From e1214e233d0f49ec56a19d1dbbfa296362a0c92c Mon Sep 17 00:00:00 2001 From: ajianaz Date: Mon, 26 Oct 2026 12:16:12 +0700 Subject: [PATCH 1/2] feat(crons): check_in ingest + monitor staleness alerts Fixes #360 --- .../migrations/postgres/007_monitors.sql | 26 +++ crates/trapfall-db/src/common.rs | 25 ++ crates/trapfall-db/src/lib.rs | 28 +++ crates/trapfall-db/src/postgres.rs | 112 +++++++++ crates/trapfall-db/src/sqlite.rs | 112 +++++++++ crates/trapfall-ingest/src/envelope.rs | 27 ++- crates/trapfall-mcp/src/lib.rs | 30 +++ crates/trapfall-proto/src/lib.rs | 61 +++++ .../migrations/20260801000001_monitors.sql | 26 +++ crates/trapfalld/src/alert.rs | 140 ++++++++--- crates/trapfalld/src/digest.rs | 9 +- crates/trapfalld/src/lib.rs | 1 + crates/trapfalld/src/main.rs | 5 +- crates/trapfalld/src/monitor.rs | 217 ++++++++++++++++++ crates/trapfalld/src/retention.rs | 12 +- crates/trapfalld/src/server.rs | 68 ++++++ 16 files changed, 865 insertions(+), 34 deletions(-) create mode 100644 crates/trapfall-db/migrations/postgres/007_monitors.sql create mode 100644 crates/trapfalld/migrations/20260801000001_monitors.sql create mode 100644 crates/trapfalld/src/monitor.rs diff --git a/crates/trapfall-db/migrations/postgres/007_monitors.sql b/crates/trapfall-db/migrations/postgres/007_monitors.sql new file mode 100644 index 0000000..052ed62 --- /dev/null +++ b/crates/trapfall-db/migrations/postgres/007_monitors.sql @@ -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); diff --git a/crates/trapfall-db/src/common.rs b/crates/trapfall-db/src/common.rs index 374b54b..aebc252 100644 --- a/crates/trapfall-db/src/common.rs +++ b/crates/trapfall-db/src/common.rs @@ -149,6 +149,31 @@ impl From 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, + /// Grace period in minutes. + pub checkin_margin: Option, + 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, + pub received_at: String, +} + /// Stored transaction row. #[derive(Debug, Clone, sqlx::FromRow)] pub struct TransactionRow { diff --git a/crates/trapfall-db/src/lib.rs b/crates/trapfall-db/src/lib.rs index 35fe491..58c21fa 100644 --- a/crates/trapfall-db/src/lib.rs +++ b/crates/trapfall-db/src/lib.rs @@ -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(()) } @@ -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(()) } @@ -273,6 +275,32 @@ pub trait Database: Send + Sync { ) -> Result)>>; async fn count_transactions(&self, project_id: &str) -> Result; + // ── 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>; + /// Monitors of all projects that have a schedule and are not already `missed`. + async fn list_schedulable_monitors(&self) -> Result>; + 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, i64)>>; + /// Delete check-ins older than `days` days (monitor rows are kept). + async fn purge_old_check_ins(&self, days: i64) -> Result; + // ── Release Health ──────────────────────────────────────────────── async fn insert_release_health( diff --git a/crates/trapfall-db/src/postgres.rs b/crates/trapfall-db/src/postgres.rs index ff37ecd..3d43e4f 100644 --- a/crates/trapfall-db/src/postgres.rs +++ b/crates/trapfall-db/src/postgres.rs @@ -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> { + 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> { + 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, i64)>> { + let owned: Option = 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 { + 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( diff --git a/crates/trapfall-db/src/sqlite.rs b/crates/trapfall-db/src/sqlite.rs index be22517..bc07a38 100644 --- a/crates/trapfall-db/src/sqlite.rs +++ b/crates/trapfall-db/src/sqlite.rs @@ -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> { + 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> { + 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, i64)>> { + let owned: Option = 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 { + 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( diff --git a/crates/trapfall-ingest/src/envelope.rs b/crates/trapfall-ingest/src/envelope.rs index 0fc3e56..47f59ae 100644 --- a/crates/trapfall-ingest/src/envelope.rs +++ b/crates/trapfall-ingest/src/envelope.rs @@ -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 ──────────────────────────────────────────────────────────────── @@ -195,6 +195,10 @@ fn parse_envelope_binary(data: &[u8], limits: &EnvelopeLimits) -> Result match serde_json::from_str::(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"), } } @@ -335,6 +339,27 @@ pub fn extract_sentry_key(auth_header: &str) -> Option { 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] diff --git a/crates/trapfall-mcp/src/lib.rs b/crates/trapfall-mcp/src/lib.rs index 8a99eec..5b0ccb3 100644 --- a/crates/trapfall-mcp/src/lib.rs +++ b/crates/trapfall-mcp/src/lib.rs @@ -278,6 +278,15 @@ fn tools_list() -> Vec { "required": ["project_slug"] }), ), + tool( + "list_monitors", + "List Sentry Crons monitors for a project with their last check-in status (ok, in_progress, error, missed)", + json!({ + "type": "object", + "properties": { "project_slug": { "type": "string", "description": "Project slug" } }, + "required": ["project_slug"] + }), + ), tool( "list_events", "List events for a specific issue", @@ -321,6 +330,7 @@ async fn call_tool(name: &str, args: Value, store: &Store) -> Result tool_get_project(args, store).await, "get_project_stats" => tool_get_project_stats(args, store).await, "list_alert_rules" => tool_list_alert_rules(args, store).await, + "list_monitors" => tool_list_monitors(args, store).await, "list_events" => tool_list_events(args, store).await, "rotate_dsn" => tool_rotate_dsn(args, store).await, "healthcheck" => tool_healthcheck(store).await, @@ -492,6 +502,26 @@ async fn tool_list_alert_rules(args: Value, store: &Store) -> Result Result { + let slug = args.get("project_slug").and_then(|v| v.as_str()).ok_or("missing project_slug")?; + let project = resolve_slug(slug, store).await?; + let monitors = store.backend().list_monitors(&project.id).await.map_err(|e| e.to_string())?; + let list: Vec = monitors + .iter() + .map(|m| { + json!({ + "id": m.id, + "slug": m.slug, + "schedule": m.schedule, + "checkin_margin": m.checkin_margin, + "last_status": m.last_status, + "last_seen": m.last_seen, + }) + }) + .collect(); + Ok(text_response(&list)) +} + async fn tool_list_events(args: Value, store: &Store) -> Result { let issue_id = args.get("issue_id").and_then(|v| v.as_str()).ok_or("missing issue_id")?; let limit = args.get("limit").and_then(|v| v.as_i64()).unwrap_or(20).clamp(1, 100); diff --git a/crates/trapfall-proto/src/lib.rs b/crates/trapfall-proto/src/lib.rs index 32f148a..dd20e6e 100644 --- a/crates/trapfall-proto/src/lib.rs +++ b/crates/trapfall-proto/src/lib.rs @@ -501,6 +501,67 @@ pub struct ParsedEnvelope { pub session_updates: Vec, pub session_aggregates: Vec, pub attachments: Vec, + pub check_ins: Vec, +} + +/// Sentry Crons check-in status as sent by SDKs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CheckInStatus { + Ok, + InProgress, + Error, +} + +impl CheckInStatus { + pub fn as_str(self) -> &'static str { + match self { + Self::Ok => "ok", + Self::InProgress => "in_progress", + Self::Error => "error", + } + } +} + +/// Monitor schedule, e.g. `{"type":"crontab","value":"0 * * * *"}`. +/// `value` is a string for crontab but a number for interval schedules. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MonitorSchedule { + #[serde(rename = "type")] + pub kind: String, + #[serde(default)] + pub value: serde_json::Value, +} + +/// Optional monitor upsert config attached to a check-in. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct MonitorConfig { + pub schedule: Option, + /// Grace period in minutes. + pub checkin_margin: Option, + /// Max runtime in minutes. + pub max_runtime: Option, + pub timezone: Option, +} + +impl MonitorConfig { + /// The crontab expression, if the schedule is a crontab. + pub fn crontab(&self) -> Option<&str> { + let s = self.schedule.as_ref().filter(|s| s.kind == "crontab")?; + s.value.as_str() + } +} + +/// Sentry Crons `check_in` envelope item. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CheckIn { + pub check_in_id: String, + pub monitor_slug: String, + pub status: CheckInStatus, + /// Seconds. + pub duration: Option, + pub timestamp: Option, + pub monitor_config: Option, } #[cfg(test)] diff --git a/crates/trapfalld/migrations/20260801000001_monitors.sql b/crates/trapfalld/migrations/20260801000001_monitors.sql new file mode 100644 index 0000000..1a976f6 --- /dev/null +++ b/crates/trapfalld/migrations/20260801000001_monitors.sql @@ -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 INTEGER, + last_seen TEXT NOT NULL, + last_status TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +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 REAL, + received_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_monitor_checkins_monitor ON monitor_checkins(monitor_id, received_at); diff --git a/crates/trapfalld/src/alert.rs b/crates/trapfalld/src/alert.rs index 8dacb18..3eae589 100644 --- a/crates/trapfalld/src/alert.rs +++ b/crates/trapfalld/src/alert.rs @@ -4,14 +4,83 @@ use tokio::sync::mpsc; use trapfall_core::Store; use trapfall_proto::{AlertRule, Issue}; +/// Input of the alert engine. +#[derive(Debug, Clone)] +pub enum AlertSignal { + Issue(Issue), + /// A cron monitor missed its expected check-in. + MonitorMissed { + project_id: String, + monitor_slug: String, + last_status: String, + last_seen: String, + schedule: Option, + }, +} + +impl AlertSignal { + fn project_id(&self) -> &str { + match self { + Self::Issue(i) => &i.project_id, + Self::MonitorMissed { project_id, .. } => project_id, + } + } + + /// Value stored in `alert_history.issue_id` (no FK on that column). + fn history_ref(&self) -> String { + match self { + Self::Issue(i) => i.id.clone(), + Self::MonitorMissed { monitor_slug, .. } => format!("monitor:{monitor_slug}"), + } + } + + fn matches(&self, rule: &AlertRule) -> bool { + match self { + Self::Issue(i) => matches_rule(rule, i), + // Issue-specific conditions can't apply to a monitor; only unconditioned + // rules fire for it. + Self::MonitorMissed { .. } => { + !["level", "count_gte", "title_contains"].iter().any(|k| rule.conditions.get(k).is_some()) + } + } + } + + fn payload(&self, rule: &AlertRule) -> serde_json::Value { + match self { + Self::Issue(issue) => serde_json::json!({ + "rule": rule.name, + "action": "webhook", + "issue": { + "id": issue.id, + "title": issue.title, + "level": format!("{:?}", issue.level).to_lowercase(), + "status": format!("{:?}", issue.status).to_lowercase(), + "count": issue.count, + "project_id": issue.project_id, + "culprit": issue.culprit, + "last_seen": issue.last_seen, + } + }), + Self::MonitorMissed { project_id, monitor_slug, last_status, last_seen, schedule } => serde_json::json!({ + "type": "monitor_missed", + "project_id": project_id, + "monitor_slug": monitor_slug, + "last_status": last_status, + "last_seen": last_seen, + "schedule": schedule, + }), + } + } +} + /// Spawn the alert engine background task. -pub fn spawn_alert_engine(store: Store, _buffer: usize) -> mpsc::UnboundedSender { - let (tx, mut rx) = mpsc::unbounded_channel::(); +pub fn spawn_alert_engine(store: Store, _buffer: usize) -> mpsc::UnboundedSender { + let (tx, mut rx) = mpsc::unbounded_channel::(); tokio::spawn(async move { - while let Some(issue) = rx.recv().await { - if let Err(e) = process_issue(&store, &issue).await { - tracing::warn!("Alert engine error for issue {}: {e}", issue.id); + while let Some(signal) = rx.recv().await { + if let Err(e) = process_signal(&store, &signal).await { + tracing::warn!("Alert engine error for {}: {e}", signal.history_ref()); } } tracing::info!("Alert engine task stopped"); @@ -20,11 +89,11 @@ pub fn spawn_alert_engine(store: Store, _buffer: usize) -> mpsc::UnboundedSender tx } -async fn process_issue(store: &Store, issue: &Issue) -> anyhow::Result<()> { - let rules = store.get_enabled_rules_for_project(&issue.project_id).await?; +async fn process_signal(store: &Store, signal: &AlertSignal) -> anyhow::Result<()> { + let rules = store.get_enabled_rules_for_project(signal.project_id()).await?; for rule in rules { - if !matches_rule(&rule, issue) { + if !signal.matches(&rule) { continue; } @@ -33,10 +102,10 @@ async fn process_issue(store: &Store, issue: &Issue) -> anyhow::Result<()> { continue; } - let history_id = store.insert_alert_history(&rule.id, &issue.project_id, &issue.id).await?; + let history_id = store.insert_alert_history(&rule.id, signal.project_id(), &signal.history_ref()).await?; let result = match rule.action_type.as_str() { - "webhook" => dispatch_webhook(&rule, issue).await, + "webhook" => dispatch_webhook(&rule, &signal.payload(&rule)).await, other => { tracing::warn!("Unknown action type: {other}"); Err(anyhow::anyhow!("unknown action type: {other}")) @@ -140,7 +209,7 @@ fn vet_addrs(addrs: &[std::net::IpAddr]) -> Result<(), String> { /// /// DNS is resolved exactly once; every address is vetted and the connection is /// pinned to the vetted addresses (no second lookup, so no rebinding window). -async fn dispatch_webhook(rule: &AlertRule, issue: &Issue) -> anyhow::Result<()> { +async fn dispatch_webhook(rule: &AlertRule, payload: &serde_json::Value) -> anyhow::Result<()> { let url = rule .action_config .get("url") @@ -179,22 +248,7 @@ async fn dispatch_webhook(rule: &AlertRule, issue: &Issue) -> anyhow::Result<()> } let client = builder.build()?; - let payload = serde_json::json!({ - "rule": rule.name, - "action": "webhook", - "issue": { - "id": issue.id, - "title": issue.title, - "level": format!("{:?}", issue.level).to_lowercase(), - "status": format!("{:?}", issue.status).to_lowercase(), - "count": issue.count, - "project_id": issue.project_id, - "culprit": issue.culprit, - "last_seen": issue.last_seen, - } - }); - - let resp = client.post(parsed_url).json(&payload).timeout(std::time::Duration::from_secs(5)).send().await?; + let resp = client.post(parsed_url).json(payload).timeout(std::time::Duration::from_secs(5)).send().await?; if resp.status().is_success() { tracing::info!("Webhook dispatched to {host} for rule '{}'", rule.name); @@ -295,6 +349,38 @@ fn dns_resolve_host(host: &str, port: u16) -> std::io::Result AlertRule { + serde_json::from_value(serde_json::json!({ + "id": "r1", "project_id": "p1", "name": "rule", "enabled": true, + "conditions": conditions, "action_type": "webhook", + "action_config": {"url": "https://example.com/h"}, "cooldown_seconds": 60, + "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z" + })) + .unwrap() + } + + #[test] + fn monitor_missed_payload_and_matching() { + let sig = AlertSignal::MonitorMissed { + project_id: "p1".into(), + monitor_slug: "nightly".into(), + last_status: "ok".into(), + last_seen: "2026-01-01T03:00:05Z".into(), + schedule: Some("0 3 * * *".into()), + }; + let rule = webhook_rule(serde_json::json!({})); + assert_eq!( + sig.payload(&rule), + serde_json::json!({ + "type": "monitor_missed", "project_id": "p1", "monitor_slug": "nightly", + "last_status": "ok", "last_seen": "2026-01-01T03:00:05Z", "schedule": "0 3 * * *" + }) + ); + assert!(sig.matches(&rule)); + assert!(!sig.matches(&webhook_rule(serde_json::json!({"level": ["error"]})))); + assert_eq!(sig.history_ref(), "monitor:nightly"); + } + #[test] fn test_ip_is_private_loopback() { assert!(ip_is_private("127.0.0.1".parse().unwrap())); diff --git a/crates/trapfalld/src/digest.rs b/crates/trapfalld/src/digest.rs index 9b20a29..63d5576 100644 --- a/crates/trapfalld/src/digest.rs +++ b/crates/trapfalld/src/digest.rs @@ -4,6 +4,7 @@ //! and commits to the database periodically or when the buffer is full. //! After processing, broadcasts ServerMessages via the WebSocket hub. +use crate::alert::AlertSignal; use tokio::sync::mpsc; use trapfall_core::Store; use trapfall_proto::{IngestEvent, Issue, ServerMessage}; @@ -18,7 +19,7 @@ pub struct DigestTask { store: Store, rx: mpsc::Receiver, ws_tx: Option>, - alert_tx: Option>, + alert_tx: Option>, } impl DigestTask { @@ -33,7 +34,7 @@ impl DigestTask { } /// Attach a channel for alert engine notifications. - pub fn with_alert_sender(mut self, tx: mpsc::UnboundedSender) -> Self { + pub fn with_alert_sender(mut self, tx: mpsc::UnboundedSender) -> Self { self.alert_tx = Some(tx); self } @@ -80,7 +81,7 @@ impl DigestTask { store: &Store, buffer: &mut Vec, ws_tx: &Option>, - alert_tx: &Option>, + alert_tx: &Option>, ) { let events = std::mem::take(buffer); let count = events.len(); @@ -97,7 +98,7 @@ impl DigestTask { let _ = tx.send(msg); } if let Some(tx) = alert_tx { - let _ = tx.send(issue.clone()); + let _ = tx.send(AlertSignal::Issue(issue.clone())); } } Err(e) => { diff --git a/crates/trapfalld/src/lib.rs b/crates/trapfalld/src/lib.rs index 41a2e22..e07a759 100644 --- a/crates/trapfalld/src/lib.rs +++ b/crates/trapfalld/src/lib.rs @@ -8,6 +8,7 @@ pub mod digest; pub mod log_time; pub mod metrics; pub mod migrate; +pub mod monitor; pub mod rate_limit; pub mod retention; pub mod scrub; diff --git a/crates/trapfalld/src/main.rs b/crates/trapfalld/src/main.rs index 295cc62..f157e3a 100644 --- a/crates/trapfalld/src/main.rs +++ b/crates/trapfalld/src/main.rs @@ -219,6 +219,7 @@ async fn run_server(store: Store, listen: String, db_url: String) -> Result<()> let alert_tx = spawn_alert_engine(store.clone(), 256); // Digest task + let retention_alert_tx = alert_tx.clone(); let digest = DigestTask::new(store.clone(), ingest_rx).with_ws_sender(ws_broadcast_tx).with_alert_sender(alert_tx); let digest_handle = tokio::spawn(async move { if let Err(e) = digest.run().await { @@ -238,7 +239,9 @@ async fn run_server(store: Store, listen: String, db_url: String) -> Result<()> let retention_handle = { let store_clone = store.clone(); let days = config.retention_days; - tokio::spawn(async move { trapfalld::retention::run_retention(&store_clone, Some(days)).await }) + tokio::spawn(async move { + trapfalld::retention::run_retention(&store_clone, Some(days), Some(retention_alert_tx)).await + }) }; // App state diff --git a/crates/trapfalld/src/monitor.rs b/crates/trapfalld/src/monitor.rs new file mode 100644 index 0000000..0208219 --- /dev/null +++ b/crates/trapfalld/src/monitor.rs @@ -0,0 +1,217 @@ +//! Sentry Crons staleness evaluation — run from the hourly retention tick. +//! +//! A monitor is *missed* when it has a crontab schedule, its last status is not +//! already `missed`, and `now` is past the next expected check-in (after +//! `last_seen`) plus the check-in margin (default 60 minutes). + +use crate::alert::AlertSignal; +use chrono::{DateTime, Datelike, Duration, Timelike, Utc}; +use tokio::sync::mpsc::UnboundedSender; +use trapfall_core::Store; +use trapfall_db::common::MonitorRow; + +/// Margin applied when a monitor does not configure `checkin_margin`. +const DEFAULT_MARGIN_MINUTES: i64 = 60; + +/// Search horizon for the next matching minute. +const MAX_LOOKAHEAD_MINUTES: i64 = 366 * 24 * 60; + +/// One cron field: does `value` match? Supports `*`, `a`, `a-b`, `a/n`, `a-b/n`, `*/n` and `,` lists. +/// `None` if the field is malformed or out of `min..=max`. +fn field_matches(field: &str, value: u32, min: u32, max: u32) -> Option { + let mut hit = false; + for part in field.split(',') { + let (range, step) = match part.split_once('/') { + Some((r, s)) => (r, s.parse::().ok().filter(|s| *s > 0)?), + None => (part, 1), + }; + let (lo, hi) = match range { + "*" => (min, max), + r => match r.split_once('-') { + Some((a, b)) => (a.parse().ok()?, b.parse().ok()?), + None => { + let a: u32 = r.parse().ok()?; + // `a/n` runs from a to max; plain `a` is just a. + (a, if part.contains('/') { max } else { a }) + } + }, + }; + if lo < min || hi > max || lo > hi { + return None; + } + hit |= value >= lo && value <= hi && (value - lo) % step == 0; + } + Some(hit) +} + +/// First minute strictly after `after` matching the 5-field UTC crontab `cron`. +/// `None` for an invalid expression or no match within a year. +// ponytail: UTC only (monitor timezone ignored), minute-by-minute scan, no +// names (JAN/MON) or `L`/`#`; swap in a cron crate if those matter. +pub fn next_run(cron: &str, after: DateTime) -> Option> { + let f: Vec<&str> = cron.split_whitespace().collect(); + let [min, hour, dom, mon, dow] = f[..] else { return None }; + // Validate every field once so a bad expression is `None`, not "never". + for (fld, lo, hi) in [(min, 0, 59), (hour, 0, 23), (dom, 1, 31), (mon, 1, 12), (dow, 0, 7)] { + field_matches(fld, lo, lo, hi)?; + } + let mut t = after.with_second(0)?.with_nanosecond(0)? + Duration::minutes(1); + for _ in 0..MAX_LOOKAHEAD_MINUTES { + let wd = t.weekday().num_days_from_sunday(); + // Day-of-week accepts 0 or 7 for Sunday. + let dow_ok = field_matches(dow, wd, 0, 7)? || (wd == 0 && field_matches(dow, 7, 0, 7)?); + let dom_ok = field_matches(dom, t.day(), 1, 31)?; + // Vixie cron: when both day fields are restricted, either may match. + let day_ok = if dom != "*" && dow != "*" { dom_ok || dow_ok } else { dom_ok && dow_ok }; + if day_ok + && field_matches(min, t.minute(), 0, 59)? + && field_matches(hour, t.hour(), 0, 23)? + && field_matches(mon, t.month(), 1, 12)? + { + return Some(t); + } + t += Duration::minutes(1); + } + None +} + +/// Has `m` missed its expected check-in as of `now`? +pub fn is_missed(m: &MonitorRow, now: DateTime) -> bool { + if m.last_status == "missed" { + return false; + } + let Some(cron) = m.schedule.as_deref() else { return false }; + let Ok(last_seen) = DateTime::parse_from_rfc3339(&m.last_seen) else { return false }; + let Some(next) = next_run(cron, last_seen.with_timezone(&Utc)) else { return false }; + now > next + Duration::minutes(m.checkin_margin.unwrap_or(DEFAULT_MARGIN_MINUTES)) +} + +/// Mark stale monitors `missed` and emit one alert signal each. Returns how many were missed. +pub async fn check_monitors( + store: &Store, + now: DateTime, + alert_tx: Option<&UnboundedSender>, +) -> anyhow::Result { + let mut missed = 0; + for m in store.backend().list_schedulable_monitors().await? { + if !is_missed(&m, now) { + continue; + } + store.backend().mark_monitor_missed(&m.id).await?; + missed += 1; + tracing::warn!(monitor = %m.slug, project = %m.project_id, "Monitor missed check-in"); + if let Some(tx) = alert_tx { + let _ = tx.send(AlertSignal::MonitorMissed { + project_id: m.project_id, + monitor_slug: m.slug, + last_status: m.last_status, + last_seen: m.last_seen, + schedule: m.schedule, + }); + } + } + Ok(missed) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(s: &str) -> DateTime { + DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc) + } + + fn monitor(schedule: Option<&str>, margin: Option, status: &str) -> MonitorRow { + MonitorRow { + id: "m1".into(), + project_id: "p1".into(), + slug: "nightly".into(), + schedule: schedule.map(Into::into), + checkin_margin: margin, + last_seen: "2026-01-01T03:00:05Z".into(), + last_status: status.into(), + created_at: "2026-01-01T03:00:05Z".into(), + } + } + + #[test] + fn next_run_basic() { + assert_eq!(next_run("0 3 * * *", at("2026-01-01T03:00:05Z")), Some(at("2026-01-02T03:00:00Z"))); + assert_eq!(next_run("*/15 * * * *", at("2026-01-01T10:07:00Z")), Some(at("2026-01-01T10:15:00Z"))); + assert_eq!(next_run("0 0 1 * *", at("2026-01-15T00:00:00Z")), Some(at("2026-02-01T00:00:00Z"))); + // Monday 09:30 — 2026-01-01 is a Thursday. + assert_eq!(next_run("30 9 * * 1", at("2026-01-01T00:00:00Z")), Some(at("2026-01-05T09:30:00Z"))); + assert_eq!(next_run("not a cron", at("2026-01-01T00:00:00Z")), None); + assert_eq!(next_run("61 * * * *", at("2026-01-01T00:00:00Z")), None); + } + + #[test] + fn staleness_with_explicit_margin() { + let m = monitor(Some("0 3 * * *"), Some(5), "ok"); + assert!(!is_missed(&m, at("2026-01-02T03:04:00Z"))); + assert!(!is_missed(&m, at("2026-01-02T03:05:00Z"))); + assert!(is_missed(&m, at("2026-01-02T03:06:00Z"))); + } + + #[test] + fn staleness_default_margin_is_60_minutes() { + let m = monitor(Some("0 3 * * *"), None, "in_progress"); + assert!(!is_missed(&m, at("2026-01-02T04:00:00Z"))); + assert!(is_missed(&m, at("2026-01-02T04:01:00Z"))); + } + + #[test] + fn staleness_skips_missed_unscheduled_and_invalid() { + let late = at("2026-03-01T00:00:00Z"); + assert!(!is_missed(&monitor(Some("0 3 * * *"), None, "missed"), late)); + assert!(!is_missed(&monitor(None, None, "ok"), late)); + assert!(!is_missed(&monitor(Some("garbage"), None, "ok"), late)); + } + + #[tokio::test] + async fn check_monitors_marks_missed_once_and_signals() { + use trapfall_proto::{CheckIn, CheckInStatus, MonitorConfig, MonitorSchedule}; + let backend = trapfall_db::open_database("sqlite::memory:").await.unwrap(); + trapfall_db::run_sqlite_migrations(backend.sqlite_pool().unwrap()).await.unwrap(); + let store = Store::new(backend); + let project = store.create_project("cron", "Cron").await.unwrap(); + let ci = CheckIn { + check_in_id: "c1".into(), + monitor_slug: "nightly".into(), + status: CheckInStatus::Ok, + duration: None, + timestamp: None, + monitor_config: Some(MonitorConfig { + schedule: Some(MonitorSchedule { kind: "crontab".into(), value: "0 3 * * *".into() }), + checkin_margin: Some(5), + ..Default::default() + }), + }; + store.backend().record_check_in(&project.id, &ci, "2026-01-01T03:00:05Z").await.unwrap(); + + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + assert_eq!(check_monitors(&store, at("2026-01-02T03:04:00Z"), Some(&tx)).await.unwrap(), 0); + assert_eq!(check_monitors(&store, at("2026-01-02T03:10:00Z"), Some(&tx)).await.unwrap(), 1); + // Already missed: no second alert. + assert_eq!(check_monitors(&store, at("2026-01-02T05:00:00Z"), Some(&tx)).await.unwrap(), 0); + match rx.try_recv().unwrap() { + AlertSignal::MonitorMissed { monitor_slug, last_status, .. } => { + assert_eq!(monitor_slug, "nightly"); + assert_eq!(last_status, "ok"); + } + _ => panic!("expected MonitorMissed"), + } + assert!(rx.try_recv().is_err()); + let monitors = store.backend().list_monitors(&project.id).await.unwrap(); + assert_eq!(monitors[0].last_status, "missed"); + + // A new check-in clears the missed state. + let ok = CheckIn { monitor_config: None, ..ci }; + store.backend().record_check_in(&project.id, &ok, "2026-01-02T03:20:00Z").await.unwrap(); + let monitors = store.backend().list_monitors(&project.id).await.unwrap(); + assert_eq!(monitors[0].last_status, "ok"); + assert_eq!(monitors[0].schedule.as_deref(), Some("0 3 * * *")); + let (rows, total) = store.backend().list_check_ins(&project.id, &monitors[0].id, 10, 0).await.unwrap().unwrap(); + assert_eq!((rows.len(), total), (2, 2)); + } +} diff --git a/crates/trapfalld/src/retention.rs b/crates/trapfalld/src/retention.rs index 49218ba..4fe3205 100644 --- a/crates/trapfalld/src/retention.rs +++ b/crates/trapfalld/src/retention.rs @@ -3,14 +3,19 @@ //! Deletes events older than the configured retention period. //! Default: 90 days. Runs every hour. +use crate::alert::AlertSignal; use std::time::Duration; +use tokio::sync::mpsc::UnboundedSender; use trapfall_core::Store; /// Default retention period in days. const DEFAULT_RETENTION_DAYS: i64 = 90; /// Run the retention task loop. -pub async fn run_retention(store: &Store, retention_days: Option) { +/// +/// Each tick also evaluates cron monitors for missed check-ins, signalling +/// `alert_tx` when one goes stale. +pub async fn run_retention(store: &Store, retention_days: Option, alert_tx: Option>) { let days = retention_days.unwrap_or(DEFAULT_RETENTION_DAYS); let mut interval = tokio::time::interval(Duration::from_secs(3600)); @@ -19,6 +24,9 @@ pub async fn run_retention(store: &Store, retention_days: Option) { if let Err(e) = purge_old_events(store, days).await { tracing::warn!("Retention purge failed: {e}"); } + if let Err(e) = crate::monitor::check_monitors(store, chrono::Utc::now(), alert_tx.as_ref()).await { + tracing::warn!("Monitor staleness check failed: {e}"); + } } } @@ -27,6 +35,8 @@ async fn purge_old_events(store: &Store, days: i64) -> anyhow::Result<()> { let db = store.backend(); let deleted = db.purge_old_events(days).await?; db.purge_orphan_issues(days).await?; + // Check-in history only; monitor state rows are kept. + db.purge_old_check_ins(days).await?; db.purge_stale_auth_attempts().await?; if deleted > 0 { diff --git a/crates/trapfalld/src/server.rs b/crates/trapfalld/src/server.rs index df5d810..ced8835 100644 --- a/crates/trapfalld/src/server.rs +++ b/crates/trapfalld/src/server.rs @@ -202,6 +202,8 @@ pub fn router(state: AppState) -> Router { .route("/api/0/projects/{slug}/transactions", get(list_transactions)) .route("/api/0/projects/{slug}/transactions/slowest", get(get_slowest_transactions)) .route("/api/0/projects/{slug}/transactions/{txn_id}", get(get_transaction)) + .route("/api/0/projects/{slug}/monitors", get(list_monitors)) + .route("/api/0/projects/{slug}/monitors/{monitor_id}/checkins", get(list_monitor_checkins)) .route("/api/0/ws", get(crate::ws::ws_handler)) // Attachment endpoints .route("/api/0/events/{event_id}/attachments", get(list_event_attachments)) @@ -480,6 +482,15 @@ async fn ingest_envelope( } } + // Persist Sentry Crons check-ins (auto-registers the monitor). Written here + // like transactions rather than via the digest channel, which is event-only. + let received_at = chrono::Utc::now().to_rfc3339(); + for ci in parsed.check_ins.iter().filter(|c| !c.monitor_slug.is_empty() && c.monitor_slug.len() <= 128) { + if let Err(e) = store.backend().record_check_in(&project.id, ci, &received_at).await { + tracing::warn!(error = %e, monitor = %ci.monitor_slug, "Failed to record check-in"); + } + } + // Persist session aggregates for agg in &parsed.session_aggregates { match store.insert_release_health(&project.id, agg).await { @@ -530,6 +541,7 @@ async fn ingest_envelope( .first() .map(|e| e.event_id.clone()) .or_else(|| parsed.transactions.first().map(|t| t.event_id.clone())) + .or_else(|| parsed.check_ins.first().map(|c| c.check_in_id.clone())) .unwrap_or_default(); if parsed.events.is_empty() && parsed.transactions.is_empty() { @@ -819,6 +831,62 @@ async fn search_issues( } } +// ── Monitor (Crons) Handlers ──────────────────────────────────────────── + +#[derive(Deserialize, Default)] +struct ListCheckInsQuery { + #[serde(default = "default_page")] + page: u32, + #[serde(default = "default_per_page")] + per_page: u32, +} + +async fn list_monitors( + State(state): State, + Path(slug): Path, +) -> Result>, StatusCode> { + let project = state + .store + .get_project_by_slug(&slug) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + let monitors = state.store.backend().list_monitors(&project.id).await.map_err(|e| { + tracing::warn!(error = %e, project_slug = %slug, "list_monitors failed"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(Json(monitors)) +} + +async fn list_monitor_checkins( + State(state): State, + Path((slug, monitor_id)): Path<(String, String)>, + Query(query): Query, +) -> Result>, StatusCode> { + let project = state + .store + .get_project_by_slug(&slug) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let limit = query.per_page.clamp(1, 100) as i64; + let page = query.page.max(1); + let offset = ((page - 1) as i64) * limit; + + let (data, total) = state + .store + .backend() + .list_check_ins(&project.id, &monitor_id, limit, offset) + .await + .map_err(|e| { + tracing::warn!(error = %e, project_slug = %slug, "list_check_ins failed"); + StatusCode::INTERNAL_SERVER_ERROR + })? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(Json(ListResponse { data, total, page, per_page: limit as u32 })) +} + // ── Transaction Handlers ──────────────────────────────────────────────── async fn list_transactions( From 35ada4d0384d4d5309b4883f1c3e748605e2ba82 Mon Sep 17 00:00:00 2001 From: ajianaz Date: Mon, 26 Oct 2026 13:38:09 +0700 Subject: [PATCH 2/2] test(crons): cover monitor endpoints, MCP list_monitors, retention purge Refs #360 --- crates/trapfall-mcp/tests/mcp_test.rs | 27 +++++++++++ crates/trapfalld/src/alert.rs | 45 +++++++++++++++++++ crates/trapfalld/src/retention.rs | 31 +++++++++++++ crates/trapfalld/tests/integration.rs | 64 +++++++++++++++++++++++++++ 4 files changed, 167 insertions(+) diff --git a/crates/trapfall-mcp/tests/mcp_test.rs b/crates/trapfall-mcp/tests/mcp_test.rs index 49b6ece..4edb629 100644 --- a/crates/trapfall-mcp/tests/mcp_test.rs +++ b/crates/trapfall-mcp/tests/mcp_test.rs @@ -279,3 +279,30 @@ async fn test_rotate_dsn_succeeds_and_masks_key() { let text = resp["result"]["content"][0]["text"].as_str().unwrap(); assert!(text.contains("New key:"), "{text}"); } + +#[tokio::test] +async fn test_list_monitors_tool() { + use trapfall_proto::{CheckIn, CheckInStatus}; + let store = setup_store().await; + let project = store.create_project("cron", "Cron").await.unwrap(); + let ci = CheckIn { + check_in_id: "c1".into(), + monitor_slug: "nightly".into(), + status: CheckInStatus::Error, + duration: None, + timestamp: None, + monitor_config: None, + }; + store.backend().record_check_in(&project.id, &ci, "2026-01-01T03:00:05Z").await.unwrap(); + + let call = |args: Value| rpc_request("tools/call", json!({"name": "list_monitors", "arguments": args})); + let resp = parse_response(&send(&store, call(json!({"project_slug": "cron"}))).await); + let monitors: Vec = serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap(); + assert_eq!(monitors.len(), 1); + assert_eq!(monitors[0]["slug"], "nightly"); + assert_eq!(monitors[0]["last_status"], "error"); + assert_eq!(monitors[0]["last_seen"], "2026-01-01T03:00:05Z"); + + let resp = parse_response(&send(&store, call(json!({"project_slug": "missing"}))).await); + assert_eq!(resp["result"]["isError"], true); +} diff --git a/crates/trapfalld/src/alert.rs b/crates/trapfalld/src/alert.rs index 3eae589..7bc6db3 100644 --- a/crates/trapfalld/src/alert.rs +++ b/crates/trapfalld/src/alert.rs @@ -381,6 +381,51 @@ mod tests { assert_eq!(sig.history_ref(), "monitor:nightly"); } + #[tokio::test] + async fn process_signal_monitor_missed_dispatch_and_cooldown() { + let backend = trapfall_db::open_database("sqlite::memory:").await.unwrap(); + trapfall_db::run_sqlite_migrations(backend.sqlite_pool().unwrap()).await.unwrap(); + let store = Store::new(backend); + let project = store.create_project("cron", "Cron").await.unwrap(); + // Plain-http URL is rejected before any network I/O, so dispatch fails + // deterministically and offline; that is enough to exercise the history path. + let rule = store + .create_alert_rule(&project.id, "r", "{}", "webhook", r#"{"url":"http://example.com/h"}"#, 3600) + .await + .unwrap(); + let sig = AlertSignal::MonitorMissed { + project_id: project.id.clone(), + monitor_slug: "nightly".into(), + last_status: "ok".into(), + last_seen: "2026-01-01T03:00:05Z".into(), + schedule: Some("0 3 * * *".into()), + }; + let history = || async { + sqlx::query_as::<_, (String, String)>("SELECT issue_id, status FROM alert_history WHERE rule_id = ?") + .bind(&rule.id) + .fetch_all(store.backend().sqlite_pool().unwrap()) + .await + .unwrap() + }; + + process_signal(&store, &sig).await.unwrap(); + assert_eq!(history().await, vec![("monitor:nightly".to_string(), "failed".to_string())]); + + // Failed sends don't start a cooldown, so a second signal dispatches again. + process_signal(&store, &sig).await.unwrap(); + assert_eq!(history().await.len(), 2); + + // A successful send puts the rule on cooldown: the next signal is skipped. + let sent: (String,) = sqlx::query_as("SELECT id FROM alert_history WHERE rule_id = ? LIMIT 1") + .bind(&rule.id) + .fetch_one(store.backend().sqlite_pool().unwrap()) + .await + .unwrap(); + store.mark_alert_sent(&sent.0).await.unwrap(); + process_signal(&store, &sig).await.unwrap(); + assert_eq!(history().await.len(), 2); + } + #[test] fn test_ip_is_private_loopback() { assert!(ip_is_private("127.0.0.1".parse().unwrap())); diff --git a/crates/trapfalld/src/retention.rs b/crates/trapfalld/src/retention.rs index 4fe3205..425dad1 100644 --- a/crates/trapfalld/src/retention.rs +++ b/crates/trapfalld/src/retention.rs @@ -53,4 +53,35 @@ mod tests { fn default_retention_is_90_days() { assert_eq!(DEFAULT_RETENTION_DAYS, 90); } + + #[tokio::test] + async fn purge_deletes_old_check_ins_but_keeps_monitors() { + use trapfall_proto::{CheckIn, CheckInStatus}; + let backend = trapfall_db::open_database("sqlite::memory:").await.unwrap(); + trapfall_db::run_sqlite_migrations(backend.sqlite_pool().unwrap()).await.unwrap(); + let store = Store::new(backend); + let project = store.create_project("cron", "Cron").await.unwrap(); + let ci = |id: &str, slug: &str| CheckIn { + check_in_id: id.into(), + monitor_slug: slug.into(), + status: CheckInStatus::Ok, + duration: None, + timestamp: None, + monitor_config: None, + }; + let db = store.backend(); + let now = chrono::Utc::now().to_rfc3339(); + db.record_check_in(&project.id, &ci("old", "mixed"), "2020-01-01T00:00:00+00:00").await.unwrap(); + db.record_check_in(&project.id, &ci("new", "mixed"), &now).await.unwrap(); + db.record_check_in(&project.id, &ci("old-only", "stale"), "2020-01-01T00:00:00+00:00").await.unwrap(); + + purge_old_events(&store, 90).await.unwrap(); + + let monitors = db.list_monitors(&project.id).await.unwrap(); + assert_eq!(monitors.len(), 2, "monitor state rows must survive purge"); + let id = |slug: &str| monitors.iter().find(|m| m.slug == slug).unwrap().id.clone(); + let (rows, total) = db.list_check_ins(&project.id, &id("mixed"), 10, 0).await.unwrap().unwrap(); + assert_eq!((total, rows[0].check_in_id.as_str()), (1, "new")); + assert_eq!(db.list_check_ins(&project.id, &id("stale"), 10, 0).await.unwrap().unwrap().1, 0); + } } diff --git a/crates/trapfalld/tests/integration.rs b/crates/trapfalld/tests/integration.rs index 7e3e845..9d69dca 100644 --- a/crates/trapfalld/tests/integration.rs +++ b/crates/trapfalld/tests/integration.rs @@ -1024,3 +1024,67 @@ async fn spoofed_forwarded_for_does_not_evade_ip_lockout() { .unwrap(); assert_eq!(app.clone().oneshot(req).await.unwrap().status(), StatusCode::UNAUTHORIZED); } + +// ── Crons: check_in ingest + monitor endpoints ───────────────────────── + +fn make_check_in_envelope_body() -> Vec { + let header = r#"{"event_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}"#; + let item_header = r#"{"type":"check_in"}"#; + let item = r#"{"check_in_id":"ci-0001","monitor_slug":"nightly-backup","status":"ok","duration":1.5,"monitor_config":{"schedule":{"type":"crontab","value":"0 3 * * *"},"checkin_margin":5}}"#; + format!("{header}\n{item_header}\n{item}").into_bytes() +} + +async fn get_json(app: &Router, cookie: &str, uri: &str) -> serde_json::Value { + let req = Request::builder().uri(uri).header("cookie", cookie).body(Body::empty()).unwrap(); + let resp = app.clone().oneshot(req).await.unwrap(); + assert_eq!(resp.status(), StatusCode::OK, "GET {uri}"); + let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024).await.unwrap(); + serde_json::from_slice(&bytes).unwrap() +} + +#[tokio::test] +async fn check_in_ingest_registers_monitor_and_lists_checkins() { + let store = test_store().await; + let project_id = seed_project(&store).await; + let app = router(make_state(store, RateLimiter::default())); + + let req = Request::builder() + .method("POST") + .uri(format!("/api/{project_id}/envelope/")) + .header("content-type", "application/octet-stream") + .header("authorization", "Bearer abc123") + .body(Body::from(make_check_in_envelope_body())) + .unwrap(); + assert_eq!(app.clone().oneshot(req).await.unwrap().status(), StatusCode::OK); + + let cookie = setup_and_get_cookie(&app).await; + + let monitors = get_json(&app, &cookie, "/api/0/projects/test-project/monitors").await; + let monitors = monitors.as_array().expect("monitors array"); + assert_eq!(monitors.len(), 1); + let m = &monitors[0]; + assert_eq!(m["slug"], "nightly-backup"); + assert_eq!(m["last_status"], "ok"); + assert_eq!(m["schedule"], "0 3 * * *"); + assert_eq!(m["checkin_margin"], 5); + assert!(!m["last_seen"].as_str().unwrap().is_empty()); + + let monitor_id = m["id"].as_str().unwrap(); + let page = get_json(&app, &cookie, &format!("/api/0/projects/test-project/monitors/{monitor_id}/checkins")).await; + assert_eq!(page["total"], 1); + assert_eq!(page["page"], 1); + assert_eq!(page["per_page"], 20); + let data = page["data"].as_array().unwrap(); + assert_eq!(data.len(), 1); + assert_eq!(data[0]["check_in_id"], "ci-0001"); + assert_eq!(data[0]["status"], "ok"); + assert_eq!(data[0]["duration"], 1.5); + + // Unknown monitor id → 404. + let req = Request::builder() + .uri("/api/0/projects/test-project/monitors/nope/checkins") + .header("cookie", &cookie) + .body(Body::empty()) + .unwrap(); + assert_eq!(app.oneshot(req).await.unwrap().status(), StatusCode::NOT_FOUND); +}