Skip to content
This repository was archived by the owner on Nov 9, 2026. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions crates/trapfall-db/migrations/postgres/007_monitors.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
-- Sentry Crons: monitors (one per project+slug, auto-registered on first
-- check-in) and their check-in history.
CREATE TABLE IF NOT EXISTS monitors (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
slug TEXT NOT NULL,
schedule TEXT,
checkin_margin BIGINT,
last_seen TEXT NOT NULL,
last_status TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_monitors_project_slug ON monitors(project_id, slug);

CREATE TABLE IF NOT EXISTS monitor_checkins (
id TEXT PRIMARY KEY,
monitor_id TEXT NOT NULL REFERENCES monitors(id) ON DELETE CASCADE,
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
check_in_id TEXT NOT NULL,
status TEXT NOT NULL,
duration DOUBLE PRECISION,
received_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_monitor_checkins_monitor ON monitor_checkins(monitor_id, received_at);
25 changes: 25 additions & 0 deletions crates/trapfall-db/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,31 @@ impl From<SessionRow> for crate::StoredSession {

// ── Transaction + Span row types ─────────────────────────────────────

/// Stored Sentry Crons monitor. `schedule` is a crontab expression.
#[derive(Debug, Clone, serde::Serialize, sqlx::FromRow)]
pub struct MonitorRow {
pub id: String,
pub project_id: String,
pub slug: String,
pub schedule: Option<String>,
/// Grace period in minutes.
pub checkin_margin: Option<i64>,
pub last_seen: String,
pub last_status: String,
pub created_at: String,
}

/// Stored monitor check-in.
#[derive(Debug, Clone, serde::Serialize, sqlx::FromRow)]
pub struct CheckInRow {
pub id: String,
pub monitor_id: String,
pub check_in_id: String,
pub status: String,
pub duration: Option<f64>,
pub received_at: String,
}

/// Stored transaction row.
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct TransactionRow {
Expand Down
28 changes: 28 additions & 0 deletions crates/trapfall-db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ pub async fn run_sqlite_migrations(pool: &sqlx::SqlitePool) -> Result<()> {
if !has_seq {
sqlx::query(include_str!("../../trapfalld/migrations/20260701000001_project_seq.sql")).execute(pool).await?;
}
sqlx::query(include_str!("../../trapfalld/migrations/20260801000001_monitors.sql")).execute(pool).await?;
Ok(())
}

Expand All @@ -179,6 +180,7 @@ pub async fn run_postgres_migrations(pool: &sqlx::PgPool) -> Result<()> {
sqlx::query(include_str!("../migrations/postgres/004_release_health.sql")).execute(pool).await?;
sqlx::query(include_str!("../migrations/postgres/005_attachments.sql")).execute(pool).await?;
sqlx::query(include_str!("../migrations/postgres/006_project_seq.sql")).execute(pool).await?;
sqlx::query(include_str!("../migrations/postgres/007_monitors.sql")).execute(pool).await?;
Ok(())
}

Expand Down Expand Up @@ -273,6 +275,32 @@ pub trait Database: Send + Sync {
) -> Result<Option<(crate::common::TransactionRow, Vec<crate::common::SpanRow>)>>;
async fn count_transactions(&self, project_id: &str) -> Result<i64>;

// ── Crons / Monitors ───────────────────────────────────────────────

/// Upsert the monitor for `check_in.monitor_slug` (auto-registering it) and
/// append the check-in, in one transaction. `monitor_config` fields, when
/// present, overwrite the stored schedule/margin.
async fn record_check_in(
&self,
project_id: &str,
check_in: &trapfall_proto::CheckIn,
received_at: &str,
) -> Result<()>;
async fn list_monitors(&self, project_id: &str) -> Result<Vec<crate::common::MonitorRow>>;
/// Monitors of all projects that have a schedule and are not already `missed`.
async fn list_schedulable_monitors(&self) -> Result<Vec<crate::common::MonitorRow>>;
async fn mark_monitor_missed(&self, monitor_id: &str) -> Result<()>;
/// Newest first. `None` if the monitor does not belong to `project_id`.
async fn list_check_ins(
&self,
project_id: &str,
monitor_id: &str,
limit: i64,
offset: i64,
) -> Result<Option<(Vec<crate::common::CheckInRow>, i64)>>;
/// Delete check-ins older than `days` days (monitor rows are kept).
async fn purge_old_check_ins(&self, days: i64) -> Result<u64>;

// ── Release Health ────────────────────────────────────────────────

async fn insert_release_health(
Expand Down
112 changes: 112 additions & 0 deletions crates/trapfall-db/src/postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,118 @@ impl Database for PostgresBackend {
Ok(count)
}

// ── Crons / Monitors ───────────────────────────────────────────────

async fn record_check_in(
&self,
project_id: &str,
check_in: &trapfall_proto::CheckIn,
received_at: &str,
) -> Result<()> {
let cfg = check_in.monitor_config.as_ref();
let mut tx = self.pool.begin().await?;
let monitor_id: String = sqlx::query_scalar(
"INSERT INTO monitors (id, project_id, slug, schedule, checkin_margin, last_seen, last_status, created_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \
ON CONFLICT(project_id, slug) DO UPDATE SET last_seen = excluded.last_seen, \
last_status = excluded.last_status, \
schedule = COALESCE(excluded.schedule, monitors.schedule), \
checkin_margin = COALESCE(excluded.checkin_margin, monitors.checkin_margin) \
RETURNING id",
)
.bind(new_id())
.bind(project_id)
.bind(&check_in.monitor_slug)
.bind(cfg.and_then(|c| c.crontab()))
.bind(cfg.and_then(|c| c.checkin_margin))
.bind(received_at)
.bind(check_in.status.as_str())
.bind(received_at)
.fetch_one(&mut *tx)
.await?;
sqlx::query(
"INSERT INTO monitor_checkins (id, monitor_id, project_id, check_in_id, status, duration, received_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7)",
)
.bind(new_id())
.bind(&monitor_id)
.bind(project_id)
.bind(&check_in.check_in_id)
.bind(check_in.status.as_str())
.bind(check_in.duration)
.bind(received_at)
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(())
}

async fn list_monitors(&self, project_id: &str) -> Result<Vec<crate::common::MonitorRow>> {
Ok(sqlx::query_as::<_, crate::common::MonitorRow>(
"SELECT id, project_id, slug, schedule, checkin_margin, last_seen, last_status, created_at \
FROM monitors WHERE project_id = $1 ORDER BY slug",
)
.bind(project_id)
.fetch_all(&self.pool)
.await?)
}

async fn list_schedulable_monitors(&self) -> Result<Vec<crate::common::MonitorRow>> {
Ok(sqlx::query_as::<_, crate::common::MonitorRow>(
"SELECT id, project_id, slug, schedule, checkin_margin, last_seen, last_status, created_at \
FROM monitors WHERE schedule IS NOT NULL AND last_status != 'missed'",
)
.fetch_all(&self.pool)
.await?)
}

async fn mark_monitor_missed(&self, monitor_id: &str) -> Result<()> {
sqlx::query("UPDATE monitors SET last_status = 'missed' WHERE id = $1")
.bind(monitor_id)
.execute(&self.pool)
.await?;
Ok(())
}

async fn list_check_ins(
&self,
project_id: &str,
monitor_id: &str,
limit: i64,
offset: i64,
) -> Result<Option<(Vec<crate::common::CheckInRow>, i64)>> {
let owned: Option<i32> = sqlx::query_scalar("SELECT 1 FROM monitors WHERE id = $1 AND project_id = $2")
.bind(monitor_id)
.bind(project_id)
.fetch_optional(&self.pool)
.await?;
if owned.is_none() {
return Ok(None);
}
let rows = sqlx::query_as::<_, crate::common::CheckInRow>(
"SELECT id, monitor_id, check_in_id, status, duration, received_at FROM monitor_checkins \
WHERE monitor_id = $1 ORDER BY received_at DESC LIMIT $2 OFFSET $3",
)
.bind(monitor_id)
.bind(limit)
.bind(offset)
.fetch_all(&self.pool)
.await?;
let total = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM monitor_checkins WHERE monitor_id = $1")
.bind(monitor_id)
.fetch_one(&self.pool)
.await?;
Ok(Some((rows, total)))
}

async fn purge_old_check_ins(&self, days: i64) -> Result<u64> {
let result = sqlx::query("DELETE FROM monitor_checkins WHERE received_at < $1")
.bind(cutoff_rfc3339_days(days))
.execute(&self.pool)
.await?;
Ok(result.rows_affected())
}

// ── Release Health ────────────────────────────────────────────────

async fn insert_release_health(
Expand Down
112 changes: 112 additions & 0 deletions crates/trapfall-db/src/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,118 @@ impl Database for SqliteBackend {
Ok(count)
}

// ── Crons / Monitors ───────────────────────────────────────────────

async fn record_check_in(
&self,
project_id: &str,
check_in: &trapfall_proto::CheckIn,
received_at: &str,
) -> Result<()> {
let cfg = check_in.monitor_config.as_ref();
let mut tx = self.pool.begin().await?;
let monitor_id: String = sqlx::query_scalar(
"INSERT INTO monitors (id, project_id, slug, schedule, checkin_margin, last_seen, last_status, created_at) \
VALUES (?, ?, ?, ?, ?, ?, ?, ?) \
ON CONFLICT(project_id, slug) DO UPDATE SET last_seen = excluded.last_seen, \
last_status = excluded.last_status, \
schedule = COALESCE(excluded.schedule, monitors.schedule), \
checkin_margin = COALESCE(excluded.checkin_margin, monitors.checkin_margin) \
RETURNING id",
)
.bind(new_id())
.bind(project_id)
.bind(&check_in.monitor_slug)
.bind(cfg.and_then(|c| c.crontab()))
.bind(cfg.and_then(|c| c.checkin_margin))
.bind(received_at)
.bind(check_in.status.as_str())
.bind(received_at)
.fetch_one(&mut *tx)
.await?;
sqlx::query(
"INSERT INTO monitor_checkins (id, monitor_id, project_id, check_in_id, status, duration, received_at) \
VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.bind(new_id())
.bind(&monitor_id)
.bind(project_id)
.bind(&check_in.check_in_id)
.bind(check_in.status.as_str())
.bind(check_in.duration)
.bind(received_at)
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(())
}

async fn list_monitors(&self, project_id: &str) -> Result<Vec<crate::common::MonitorRow>> {
Ok(sqlx::query_as::<_, crate::common::MonitorRow>(
"SELECT id, project_id, slug, schedule, checkin_margin, last_seen, last_status, created_at \
FROM monitors WHERE project_id = ? ORDER BY slug",
)
.bind(project_id)
.fetch_all(&self.pool)
.await?)
}

async fn list_schedulable_monitors(&self) -> Result<Vec<crate::common::MonitorRow>> {
Ok(sqlx::query_as::<_, crate::common::MonitorRow>(
"SELECT id, project_id, slug, schedule, checkin_margin, last_seen, last_status, created_at \
FROM monitors WHERE schedule IS NOT NULL AND last_status != 'missed'",
)
.fetch_all(&self.pool)
.await?)
}

async fn mark_monitor_missed(&self, monitor_id: &str) -> Result<()> {
sqlx::query("UPDATE monitors SET last_status = 'missed' WHERE id = ?")
.bind(monitor_id)
.execute(&self.pool)
.await?;
Ok(())
}

async fn list_check_ins(
&self,
project_id: &str,
monitor_id: &str,
limit: i64,
offset: i64,
) -> Result<Option<(Vec<crate::common::CheckInRow>, i64)>> {
let owned: Option<i64> = sqlx::query_scalar("SELECT 1 FROM monitors WHERE id = ? AND project_id = ?")
.bind(monitor_id)
.bind(project_id)
.fetch_optional(&self.pool)
.await?;
if owned.is_none() {
return Ok(None);
}
let rows = sqlx::query_as::<_, crate::common::CheckInRow>(
"SELECT id, monitor_id, check_in_id, status, duration, received_at FROM monitor_checkins \
WHERE monitor_id = ? ORDER BY received_at DESC LIMIT ? OFFSET ?",
)
.bind(monitor_id)
.bind(limit)
.bind(offset)
.fetch_all(&self.pool)
.await?;
let total = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM monitor_checkins WHERE monitor_id = ?")
.bind(monitor_id)
.fetch_one(&self.pool)
.await?;
Ok(Some((rows, total)))
}

async fn purge_old_check_ins(&self, days: i64) -> Result<u64> {
let result = sqlx::query("DELETE FROM monitor_checkins WHERE received_at < ?")
.bind(cutoff_rfc3339_days(days))
.execute(&self.pool)
.await?;
Ok(result.rows_affected())
}

// ── Release Health ────────────────────────────────────────────────

async fn insert_release_health(
Expand Down
27 changes: 26 additions & 1 deletion crates/trapfall-ingest/src/envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use anyhow::{Context, Result};
use flate2::read::GzDecoder;
use std::io::Read;
use trapfall_proto::{Attachment, Event, ParsedEnvelope, SessionAggregates, SessionUpdate, Transaction};
use trapfall_proto::{Attachment, CheckIn, Event, ParsedEnvelope, SessionAggregates, SessionUpdate, Transaction};

// ── Limits ────────────────────────────────────────────────────────────────

Expand Down Expand Up @@ -195,6 +195,10 @@ fn parse_envelope_binary(data: &[u8], limits: &EnvelopeLimits) -> Result<ParsedE
tracing::warn!(item = "sessions", error = %e, "dropping session aggregates: deserialize failed")
}
},
"check_in" => match serde_json::from_str::<CheckIn>(body_text) {
Ok(c) => result.check_ins.push(c),
Err(e) => tracing::warn!(item = "check_in", error = %e, "dropping check_in: deserialize failed"),
},
_ => tracing::debug!(item_type = %hdr.item_type, "ignoring unknown envelope item type"),
}
}
Expand Down Expand Up @@ -335,6 +339,27 @@ pub fn extract_sentry_key(auth_header: &str) -> Option<String> {
mod tests {
use super::*;

#[test]
fn parse_check_in_item() {
let envelope = br#"{"sent_at":"2026-01-01T00:00:00Z"}
{"type":"check_in"}
{"check_in_id":"c1","monitor_slug":"nightly","status":"ok","duration":1.5,"monitor_config":{"schedule":{"type":"crontab","value":"0 3 * * *"},"checkin_margin":5,"max_runtime":10,"timezone":"UTC"}}
{"type":"check_in"}
{"check_in_id":"c2","monitor_slug":"nightly","status":"in_progress"}
"#;
let result = parse_envelope(envelope, None).unwrap();
assert_eq!(result.check_ins.len(), 2);
let c = &result.check_ins[0];
assert_eq!(c.monitor_slug, "nightly");
assert_eq!(c.status, trapfall_proto::CheckInStatus::Ok);
assert_eq!(c.duration, Some(1.5));
let cfg = c.monitor_config.as_ref().unwrap();
assert_eq!(cfg.crontab(), Some("0 3 * * *"));
assert_eq!(cfg.checkin_margin, Some(5));
assert_eq!(result.check_ins[1].status, trapfall_proto::CheckInStatus::InProgress);
assert!(result.check_ins[1].monitor_config.is_none());
}

// ── Existing text-based tests (backward compat) ──

#[test]
Expand Down
Loading
Loading