From b61fe17a01a998ed90020eb218b8193628699752 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 6 Nov 2026 09:06:10 -0500 Subject: [PATCH 1/2] Alert routes: post a firing alarm once until it really clears A route (and any CloudWatch alarm by name) can post every time (default, and what routes saved before the setting do), once until it clears, or once with a daily reminder. Each alert's episode is stored per route and alarm ARN and changed only by version-conditioned writes, so concurrent deliveries post once. An OK starts a quiet window (30 min, or two of the alarm's evaluation spans, up to 6 h); an ALARM inside it is the same episode. The worker checks the window and the daily reminder later through chained SQS delays. Held repeats start no run and are recorded as suppressed with their episode. --- docs/self-host/integrations.md | 2 + services/common/contract/worker_messages.json | 3 +- services/common/src/alert_episodes.rs | 1360 +++++++++++++++++ services/common/src/alert_notify.rs | 107 ++ services/common/src/dlq.rs | 2 + services/common/src/lib.rs | 1 + services/common/src/messages.rs | 27 +- services/gateway/src/routes/alerts.rs | 636 ++++++-- services/gateway/src/routes/deliveries.rs | 2 +- services/worker/src/main.rs | 3 + services/worker/src/passes/alert_episodes.rs | 134 ++ services/worker/src/passes/mod.rs | 1 + 12 files changed, 2155 insertions(+), 123 deletions(-) create mode 100644 services/common/src/alert_episodes.rs create mode 100644 services/worker/src/passes/alert_episodes.rs diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index 02fbb2c1b..30093b584 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -26,6 +26,8 @@ Teams connect their own AWS accounts so CoderHelm can read CloudWatch logs, alar Each AWS connection shows **Permissions up to date** or **Update needed: N new read-only permissions**. The check runs live: it asks IAM's policy simulator about the role (`iam:SimulatePrincipalPolicy` on that one role), or, for roles made before that, tries the cheapest read of each kind. **Update in AWS** opens a stack (`CoderHelmLogReaderUpdate-`) that adds exactly this release's permissions to the existing role. Sign in to the role's account, review it and press **Create stack**. When you come back, the page checks again by itself. If something went wrong, it names the reason and the fix: the stack failed, it isn't in the role's account, a permissions boundary or an organization policy (SCP) blocks the permissions. Once a day the install checks every account, and each team's Slack or Teams channel hears once per release that needs an update. Until then, features that need a missing permission say so where they are used, skip that step and keep working with the rest. - **Alert routes (SNS)**\ **Settings, Alerts** shows the subscription endpoint, `https://coderhelm.example.com/webhooks/alerts/sns`. Save and turn on the route before you subscribe the topic: CoderHelm only confirms subscriptions for topics with a route that's on. If you subscribed first, press **Request confirmation** on the subscription in SNS. Every message's signature is checked before anything else. +- **Alarms that keep firing**\ + Each route has a repeat setting under **When an alarm keeps firing**: **Every time it fires** (the default, and how routes saved before the setting behave), **Once, until it clears**, or **Once, then a daily reminder**. A CloudWatch alarm can have its own setting by name. While an alarm keeps firing it posts once and starts no second fix run; flipping to OK and back doesn't count as clearing. It has cleared once it stays OK for a quiet window of 30 minutes, or two of the alarm's own evaluation spans (period times evaluation periods) when that is longer, up to 6 hours. Then the recovery posts once (on routes that post recoveries) and the next alarm posts at once. The daily reminder says since when it has been firing and how many times. Every delivery is still recorded, and the Alerts page shows a firing alarm as one row with a count. The quiet window and reminders are checked later by the worker through the ticket queue, so no new infrastructure is needed. - **With hybrid**\ No change: AWS accounts always connect to your install directly. diff --git a/services/common/contract/worker_messages.json b/services/common/contract/worker_messages.json index c54bc22cd..02ff787a8 100644 --- a/services/common/contract/worker_messages.json +++ b/services/common/contract/worker_messages.json @@ -31,7 +31,8 @@ "usage_record": {"type":"usage_record","call_id":"req_011","team_id":"TEAM#team-a","at_ms":1792416387000,"feature":"run","model":"claude-opus-5-5","billed_to":"team","estimated":true,"usage":{"uncached_input":10,"cache_read":2000,"cache_write_5m":300,"cache_write_1h":0,"output":42}}, "plugin_run": {"type":"plugin_run","team_id":"TEAM#team-a","run_id":"01hzzrun","plugin_id":"marketing","hash":"abc","trigger":"manual","inputs":{"brief":"Launch post for 2.0","channels":["linkedin"]},"requested_by":"someone@example.com"}, "plugin_publish": {"type":"plugin_publish","team_id":"TEAM#team-a","artifact_id":"01hzzart","version":2,"approval_id":"01hzzapp"}, - "plugin_sync": {"type":"plugin_sync","team_id":"TEAM#team-a","source_id":"acme-plugins-abc123","plugin_id":"","force":false,"reason":"webhook"} + "plugin_sync": {"type":"plugin_sync","team_id":"TEAM#team-a","source_id":"acme-plugins-abc123","plugin_id":"","force":false,"reason":"webhook"}, + "alert_episode_check": {"type":"alert_episode_check","team_id":"TEAM#team-a","topic_arn":"arn:aws:sns:us-east-1:111122223333:example-alarms","fingerprint":"arn:aws:cloudwatch:us-east-1:111122223333:alarm:example-queue-depth","check":"clear","token":"01JBALERT3K8P2N6Q9R1S4T7V0","delay_remaining_secs":1800} }, "scheduled": { "review_reminder": {"type":"review_reminder"}, diff --git a/services/common/src/alert_episodes.rs b/services/common/src/alert_episodes.rs new file mode 100644 index 000000000..7c8c13974 --- /dev/null +++ b/services/common/src/alert_episodes.rs @@ -0,0 +1,1360 @@ +//! Repeat settings for alert routes: post an alarm once, not every time it +//! fires. +//! +//! A route (and, by name, one of its alarms) says how often a firing alert +//! posts to chat: +//! +//! - [`Repeat::EveryTime`]: every ALARM posts, as before this setting existed. +//! Routes saved without it behave this way. +//! - [`Repeat::UntilClear`]: the first ALARM posts; repeats stay quiet until +//! the alarm has really cleared. +//! - [`Repeat::Daily`]: as `UntilClear`, plus one reminder a day while it is +//! still firing. +//! +//! The span from the first ALARM to the real clear is an **episode**, stored +//! per route and alert (the CloudWatch alarm's ARN carries its account, +//! region and name). An OK starts a quiet window ([`quiet_window_secs`]): an +//! ALARM inside it is the same episode (the alarm is flapping), and only when +//! the window passes without one has the alarm cleared. Then the recovery +//! posts (on routes that post recoveries) and the next ALARM posts again. +//! +//! Every change to an episode is a read, a pure decision ([`step`]) and a +//! write conditioned on the version read ([`apply`]), so two deliveries at the +//! same moment can't both post: the loser reads the winner's episode and +//! decides again. + +use std::collections::BTreeMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use aws_sdk_dynamodb::Client as DynamoClient; +use serde_json::Value; +use tracing::warn; + +use crate::mcp_credentials::Cipher; +use crate::notify::{self, Poster}; + +/// How often a firing alert posts to chat. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Repeat { + /// Every ALARM posts (the behaviour before this setting). + #[default] + EveryTime, + /// The first ALARM posts; repeats stay quiet until it clears. + UntilClear, + /// As `UntilClear`, plus one reminder a day while it keeps firing. + Daily, +} + +pub const EVERY_TIME: &str = "every_time"; +pub const UNTIL_CLEAR: &str = "until_clear"; +pub const DAILY: &str = "daily"; + +impl Repeat { + /// The stored value. `""` (a route saved before this setting) is + /// `EveryTime`; anything else unknown is `None`. + pub fn parse(v: &str) -> Option { + match v.trim() { + "" | EVERY_TIME => Some(Self::EveryTime), + UNTIL_CLEAR => Some(Self::UntilClear), + DAILY => Some(Self::Daily), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::EveryTime => EVERY_TIME, + Self::UntilClear => UNTIL_CLEAR, + Self::Daily => DAILY, + } + } +} + +/// Most alarms one route may give their own repeat setting. +pub const MAX_ALARM_OVERRIDES: usize = 200; + +/// Shortest quiet window: an OK must hold this long, with no ALARM, before +/// the alarm counts as cleared. Most alarms are evaluated every 1 to 5 +/// minutes, so a flapping alarm swings back within a few periods; half an hour +/// is six 5-minute periods of calm, long enough to call it settled and short +/// enough that the recovery post is still news. +pub const CLEAR_QUIET_MIN_SECS: u64 = 30 * 60; +/// An alarm evaluated over a longer span gets this many of its own spans +/// (period x evaluation periods, from the alarm's own SNS message): it can't +/// swing back sooner than its next evaluation, so one span of OK proves +/// little and two say it stayed clear. +pub const CLEAR_QUIET_PERIODS: u64 = 2; +/// Longest quiet window, whatever the alarm's span (an hourly or daily alarm +/// would otherwise hold its recovery for days). +pub const CLEAR_QUIET_MAX_SECS: u64 = 6 * 3600; +/// A reminder at most this often while an episode stays open. +pub const REMINDER_EVERY_SECS: u64 = 24 * 3600; +/// An episode's record lives this long after its last change. +const EPISODE_TTL_SECS: u64 = 30 * 86_400; +/// Most of the alert's text kept on the episode, for the cards posted later. +const MAX_EPISODE_BODY: usize = 6_000; +/// SQS delays a message at most this long; longer waits chain. +pub const SQS_MAX_DELAY_SECS: u64 = 900; + +/// Pure: the quiet window for an OK, from the CloudWatch message when it has +/// the alarm's period and evaluation periods. See [`CLEAR_QUIET_MIN_SECS`]. +pub fn quiet_window_secs(message: &str) -> u64 { + let v: Value = serde_json::from_str(message).unwrap_or(Value::Null); + let t = &v["Trigger"]; + let num = |x: &Value| { + x.as_u64() + .or_else(|| x.as_str().and_then(|s| s.parse().ok())) + }; + let span = match (num(&t["Period"]), num(&t["EvaluationPeriods"])) { + (Some(p), Some(e)) => p.saturating_mul(e.max(1)), + (Some(p), None) => p, + _ => 0, + }; + span.saturating_mul(CLEAR_QUIET_PERIODS) + .clamp(CLEAR_QUIET_MIN_SECS, CLEAR_QUIET_MAX_SECS) +} + +/// Pure: the CloudWatch alarm an alert title names (`: `). +pub fn alarm_name<'a>(kind: &str, title: &'a str) -> Option<&'a str> { + (kind == "cloudwatch_alarm") + .then(|| title.split_once(": ").map(|(_, n)| n)) + .flatten() +} + +/// Pure: the setting that applies to an alert. An alarm named in the route's +/// overrides uses its own; other CloudWatch alarms and plain messages (which +/// clear with a `Recovers:` line) use the route's. Alerts that never send a +/// recovery (custom notifications, EventBridge events) always post every +/// time: with no clear, "until it clears" would mean never again. +pub fn effective( + route: Repeat, + overrides: &BTreeMap, + kind: &str, + title: &str, +) -> Repeat { + match kind { + "cloudwatch_alarm" => alarm_name(kind, title) + .and_then(|n| overrides.get(n).copied()) + .unwrap_or(route), + "message" | "recovery" => route, + _ => Repeat::EveryTime, + } +} + +/// The route's setting and its per-alarm overrides, as stored on its item. +pub fn route_setting( + item: &std::collections::HashMap, +) -> (Repeat, BTreeMap) { + let route = item + .get("repeat") + .and_then(|v| v.as_s().ok()) + .and_then(|s| Repeat::parse(s)) + .unwrap_or_default(); + let overrides = item + .get("alarm_repeat") + .and_then(|v| v.as_m().ok()) + .map(|m| { + m.iter() + .filter_map(|(k, v)| Some((k.clone(), Repeat::parse(v.as_s().ok()?)?))) + .collect() + }) + .unwrap_or_default(); + (route, overrides) +} + +/// Settings-table sort key of an alert's episode on a route. +pub fn episode_sk(topic_arn: &str, fingerprint: &str) -> String { + format!( + "ALERT_EPISODE#{}", + crate::content_hash(&format!("{topic_arn}\n{fingerprint}")) + ) +} + +/// One alert's run of firing on one route, from its first ALARM to its real +/// clear. Times are epoch seconds. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Episode { + pub topic_arn: String, + pub fingerprint: String, + /// The latest firing alert, for the cards posted later. + pub kind: String, + pub title: String, + pub body: String, + /// From the first ALARM until it has really cleared. + pub open: bool, + pub first_at: i64, + /// The alert record that opened it: every alert in it points here. + pub first_alert_id: String, + /// When it last posted: the first card or the latest reminder. + pub last_notified_at: i64, + /// ALARMs received in it, the first included. + pub fires: u64, + pub reminders: u64, + pub last_event_id: String, + /// When an OK started the quiet window, while it is running. + pub clearing_since: Option, + /// The OK's alert record, and the window it started. + pub clear_event_id: String, + pub quiet_secs: u64, + /// The OK itself, for the recovery card. + pub clear_kind: String, + pub clear_title: String, + pub clear_body: String, + /// Bumped on every write; each write is conditioned on the one read. + pub ver: u64, +} + +/// What happened, as [`step`] sees it. +#[derive(Debug, Clone, Copy)] +pub enum Input<'a> { + /// The alert fired (an ALARM, or a plain message). + Fire { + event_id: &'a str, + at: i64, + kind: &'a str, + title: &'a str, + body: &'a str, + }, + /// Its recovery (an OK) arrived. + Clear { + event_id: &'a str, + at: i64, + quiet_secs: u64, + kind: &'a str, + title: &'a str, + body: &'a str, + }, + /// The quiet window an OK started should have passed. + ClearCheck { clear_event_id: &'a str, now: i64 }, + /// A day since the last post should have passed. + RemindCheck { notified_at: i64, now: i64 }, +} + +/// What to do about it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Decision { + /// A new episode: post as usual. + Opened, + /// The previous episode had cleared (its quiet window passed before this + /// ALARM) but its recovery hadn't posted yet: post it, then post this + /// alarm as a new episode. + Reopened(Box), + /// Still firing and a day since the last post: post a reminder. + Remind, + /// Still firing: record it, post nothing, start no run. + Suppressed, + /// A delivery already counted (an SNS redelivery). + Redelivered, + /// An OK started the quiet window (`schedule`: queue the check; false + /// when a window was already running). + Clearing { schedule: bool }, + /// The window passed with no ALARM: the episode ended. Post its recovery. + Cleared(Box), + /// Too early: check again after this many seconds. + Wait(u64), + /// No open episode (or a check about one that moved on): nothing to do. + Nothing, +} + +impl Decision { + /// For logs. + pub fn name(&self) -> &'static str { + match self { + Decision::Opened => "opened", + Decision::Reopened(_) => "reopened", + Decision::Remind => "remind", + Decision::Suppressed => "suppressed", + Decision::Redelivered => "redelivered", + Decision::Clearing { .. } => "clearing", + Decision::Cleared(_) => "cleared", + Decision::Wait(_) => "wait", + Decision::Nothing => "nothing", + } + } +} + +fn trimmed(s: &str) -> String { + crate::truncate_str(s, MAX_EPISODE_BODY).to_string() +} + +/// Pure: the decision for `input` given the stored episode, and the episode +/// to write (None = no write). +pub fn step(prev: Option<&Episode>, input: Input, mode: Repeat) -> (Decision, Option) { + let open = prev.filter(|p| p.open); + match input { + Input::Fire { + event_id, + at, + kind, + title, + body, + } => { + let fresh = || Episode { + topic_arn: prev.map(|p| p.topic_arn.clone()).unwrap_or_default(), + fingerprint: prev.map(|p| p.fingerprint.clone()).unwrap_or_default(), + kind: kind.to_string(), + title: title.to_string(), + body: trimmed(body), + open: true, + first_at: at, + first_alert_id: event_id.to_string(), + last_notified_at: at, + fires: 1, + last_event_id: event_id.to_string(), + ver: prev.map(|p| p.ver).unwrap_or(0) + 1, + ..Episode::default() + }; + let Some(p) = open else { + return (Decision::Opened, Some(fresh())); + }; + if p.last_event_id == event_id || p.first_alert_id == event_id { + return (Decision::Redelivered, None); + } + if let Some(since) = p.clearing_since { + if at.saturating_sub(since) >= p.quiet_secs as i64 { + return (Decision::Reopened(Box::new(p.clone())), Some(fresh())); + } + } + // Still the same episode. An OK in its window is undone. + let mut next = Episode { + kind: kind.to_string(), + title: title.to_string(), + body: trimmed(body), + fires: p.fires + 1, + last_event_id: event_id.to_string(), + clearing_since: None, + clear_event_id: String::new(), + clear_kind: String::new(), + clear_title: String::new(), + clear_body: String::new(), + ver: p.ver + 1, + ..p.clone() + }; + let due = at.saturating_sub(p.last_notified_at) >= REMINDER_EVERY_SECS as i64; + if mode == Repeat::Daily && due { + next.last_notified_at = at; + next.reminders += 1; + (Decision::Remind, Some(next)) + } else { + (Decision::Suppressed, Some(next)) + } + } + Input::Clear { + event_id, + at, + quiet_secs, + kind, + title, + body, + } => { + let Some(p) = open else { + return (Decision::Nothing, None); + }; + if p.clearing_since.is_some() { + return (Decision::Clearing { schedule: false }, None); + } + let next = Episode { + clearing_since: Some(at), + clear_event_id: event_id.to_string(), + quiet_secs, + clear_kind: kind.to_string(), + clear_title: title.to_string(), + clear_body: trimmed(body), + ver: p.ver + 1, + ..p.clone() + }; + (Decision::Clearing { schedule: true }, Some(next)) + } + Input::ClearCheck { + clear_event_id, + now, + } => { + let Some(p) = open.filter(|p| p.clear_event_id == clear_event_id) else { + return (Decision::Nothing, None); + }; + let Some(since) = p.clearing_since else { + return (Decision::Nothing, None); + }; + let waited = now.saturating_sub(since).max(0) as u64; + if waited < p.quiet_secs { + return (Decision::Wait(p.quiet_secs - waited), None); + } + let next = Episode { + open: false, + clearing_since: None, + ver: p.ver + 1, + ..p.clone() + }; + (Decision::Cleared(Box::new(p.clone())), Some(next)) + } + Input::RemindCheck { notified_at, now } => { + let Some(p) = open.filter(|p| p.last_notified_at == notified_at) else { + return (Decision::Nothing, None); + }; + // Clearing: the window decides. A real clear ends it; an ALARM + // inside the window reminds then if a day has passed. + if mode != Repeat::Daily || p.clearing_since.is_some() { + return (Decision::Nothing, None); + } + let waited = now.saturating_sub(notified_at).max(0) as u64; + if waited < REMINDER_EVERY_SECS { + return (Decision::Wait(REMINDER_EVERY_SECS - waited), None); + } + let next = Episode { + last_notified_at: now, + reminders: p.reminders + 1, + ver: p.ver + 1, + ..p.clone() + }; + (Decision::Remind, Some(next)) + } + } +} + +// ─── Storage ──────────────────────────────────────────────────────────────── + +/// Where episodes live. `put` writes only when the stored version is still +/// `expect` (None = no record yet) and says whether it did. +#[async_trait::async_trait] +pub trait EpisodeStore: Send + Sync { + async fn get(&self, team_id: &str, sk: &str) -> Result, String>; + async fn put( + &self, + team_id: &str, + sk: &str, + ep: &Episode, + expect: Option, + ) -> Result; + /// Remove the record. With `first_alert_id`, only while that alert still + /// opened it. + async fn delete( + &self, + team_id: &str, + sk: &str, + first_alert_id: Option<&str>, + ) -> Result<(), String>; +} + +/// The result of [`apply`]: the decision, and the episode as now stored. +#[derive(Debug, Clone)] +pub struct Applied { + pub decision: Decision, + pub episode: Option, +} + +/// Read, decide, write. A write that loses to a concurrent one reads again +/// and decides again, so of two deliveries at once only one opens the +/// episode (or reminds); the other sees it and stays quiet. +pub async fn apply( + store: &dyn EpisodeStore, + team_id: &str, + topic_arn: &str, + fingerprint: &str, + input: Input<'_>, + mode: Repeat, +) -> Result { + let sk = episode_sk(topic_arn, fingerprint); + for _ in 0..5 { + let prev = store.get(team_id, &sk).await?; + let (decision, write) = step(prev.as_ref(), input, mode); + let Some(mut next) = write else { + return Ok(Applied { + decision, + episode: prev, + }); + }; + next.topic_arn = topic_arn.to_string(); + next.fingerprint = fingerprint.to_string(); + if store + .put(team_id, &sk, &next, prev.as_ref().map(|p| p.ver)) + .await? + { + return Ok(Applied { + decision, + episode: Some(next), + }); + } + } + Err("the episode kept changing under us".into()) +} + +/// Episodes in the settings table, under the team's partition. +pub struct DynamoStore<'a> { + pub client: &'a DynamoClient, + pub table: &'a str, +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn n(v: impl ToString) -> AttributeValue { + AttributeValue::N(v.to_string()) +} + +/// The episode as a settings item (without its keys). +pub fn to_item(ep: &Episode) -> Vec<(&'static str, AttributeValue)> { + let mut out = vec![ + ("topic_arn", s(&ep.topic_arn)), + ("fingerprint", s(&ep.fingerprint)), + ("kind", s(&ep.kind)), + ("title", s(crate::truncate_str(&ep.title, 300))), + ("body", s(&ep.body)), + ("open", AttributeValue::Bool(ep.open)), + ("first_at", n(ep.first_at)), + ("first_alert_id", s(&ep.first_alert_id)), + ("last_notified_at", n(ep.last_notified_at)), + ("fires", n(ep.fires)), + ("reminders", n(ep.reminders)), + ("last_event_id", s(&ep.last_event_id)), + ("clear_event_id", s(&ep.clear_event_id)), + ("quiet_secs", n(ep.quiet_secs)), + ("clear_kind", s(&ep.clear_kind)), + ("clear_title", s(crate::truncate_str(&ep.clear_title, 300))), + ("clear_body", s(&ep.clear_body)), + ("ver", n(ep.ver)), + ]; + if let Some(since) = ep.clearing_since { + out.push(("clearing_since", n(since))); + } + out +} + +/// The episode a settings item holds. +pub fn from_item(item: &std::collections::HashMap) -> Episode { + let st = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let num = |k: &str| { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + }; + Episode { + topic_arn: st("topic_arn"), + fingerprint: st("fingerprint"), + kind: st("kind"), + title: st("title"), + body: st("body"), + open: item + .get("open") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false), + first_at: num("first_at").unwrap_or(0), + first_alert_id: st("first_alert_id"), + last_notified_at: num("last_notified_at").unwrap_or(0), + fires: num("fires").unwrap_or(0).max(0) as u64, + reminders: num("reminders").unwrap_or(0).max(0) as u64, + last_event_id: st("last_event_id"), + clearing_since: num("clearing_since"), + clear_event_id: st("clear_event_id"), + quiet_secs: num("quiet_secs").unwrap_or(0).max(0) as u64, + clear_kind: st("clear_kind"), + clear_title: st("clear_title"), + clear_body: st("clear_body"), + ver: num("ver").unwrap_or(0).max(0) as u64, + } +} + +#[async_trait::async_trait] +impl EpisodeStore for DynamoStore<'_> { + async fn get(&self, team_id: &str, sk: &str) -> Result, String> { + let out = self + .client + .get_item() + .table_name(self.table) + .key("pk", s(team_id)) + .key("sk", s(sk)) + .consistent_read(true) + .send() + .await + .map_err(|e| e.to_string())?; + Ok(out.item().map(from_item)) + } + + async fn put( + &self, + team_id: &str, + sk: &str, + ep: &Episode, + expect: Option, + ) -> Result { + let ttl = chrono::Utc::now().timestamp().max(0) as u64 + EPISODE_TTL_SECS; + let mut put = self + .client + .put_item() + .table_name(self.table) + .item("pk", s(team_id)) + .item("sk", s(sk)) + .item("ttl", n(ttl)); + for (k, v) in to_item(ep) { + put = put.item(k, v); + } + put = match expect { + None => put.condition_expression("attribute_not_exists(pk)"), + Some(v) => put + .condition_expression("ver = :v") + .expression_attribute_values(":v", n(v)), + }; + match put.send().await { + Ok(_) => Ok(true), + Err(e) + if e.as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()) => + { + Ok(false) + } + Err(e) => Err(e.to_string()), + } + } + + async fn delete( + &self, + team_id: &str, + sk: &str, + first_alert_id: Option<&str>, + ) -> Result<(), String> { + let mut del = self + .client + .delete_item() + .table_name(self.table) + .key("pk", s(team_id)) + .key("sk", s(sk)); + if let Some(id) = first_alert_id { + del = del + .condition_expression("first_alert_id = :id") + .expression_attribute_values(":id", s(id)); + } + match del.send().await { + Ok(_) => Ok(()), + Err(e) + if e.as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()) => + { + Ok(()) + } + Err(e) => Err(e.to_string()), + } + } +} + +// ─── Words ────────────────────────────────────────────────────────────────── + +fn utc(secs: i64) -> String { + chrono::DateTime::from_timestamp(secs, 0) + .map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string()) + .unwrap_or_else(|| "earlier".to_string()) +} + +/// Pure: "45 min", "3 hours", "2 days". +pub fn span(secs: u64) -> String { + let m = (secs + 30) / 60; + if m < 1 { + return "under a minute".into(); + } + if m < 90 { + return format!("{m} min"); + } + let h = (m + 30) / 60; + if h < 48 { + return format!("{h} hours"); + } + format!("{} days", (h + 12) / 24) +} + +fn times(n: u64) -> String { + if n == 1 { + "once".into() + } else { + format!("{n} times") + } +} + +/// Pure: the reminder card's line: still firing, since when, how often. +pub fn reminder_line(ep: &Episode, now: i64) -> String { + format!( + "Still firing. It started {} ({} ago) and has fired {} since. One reminder a day until it clears.", + utc(ep.first_at), + span(now.saturating_sub(ep.first_at).max(0) as u64), + times(ep.fires), + ) +} + +/// Pure: the line on a new episode's card when a run for the alert started +/// in the last few hours, so no new run starts. +pub fn reopened_without_run_line() -> &'static str { + "Fired again after it cleared. A fix for this alert started a few hours ago, so no new run." +} + +/// Pure: the recovery card's line for an episode that really cleared. +pub fn cleared_line(ep: &Episode, opened: &crate::alert_notify::OpenAlert, base: &str) -> String { + let link = crate::alert_notify::recovered_line(opened, base); + format!( + "{link} It stayed clear for {}; it fired {} while open.", + span(ep.quiet_secs), + times(ep.fires), + ) +} + +// ─── Checks after a wait ──────────────────────────────────────────────────── + +/// What the worker checks later: the quiet window of an OK, or a day since an +/// episode last posted. +pub const CHECK_CLEAR: &str = "clear"; +pub const CHECK_REMIND: &str = "remind"; + +/// Queue a check for `secs` from now (chained past SQS's 15 minute limit). +/// Best effort: false when it couldn't be queued. +pub async fn schedule_check( + sqs: &aws_sdk_sqs::Client, + queue_url: &str, + mut msg: crate::messages::AlertEpisodeCheckMessage, + secs: u64, +) -> bool { + if queue_url.is_empty() { + return false; + } + msg.delay_remaining_secs = secs; + let delay = secs.min(SQS_MAX_DELAY_SECS); + let body = match serde_json::to_string(&crate::messages::WorkerMessage::AlertEpisodeCheck(msg)) + { + Ok(b) => b, + Err(e) => { + warn!(error = %e, "Could not serialize an alert episode check"); + return false; + } + }; + match sqs + .send_message() + .queue_url(queue_url) + .message_body(body) + .delay_seconds(delay as i32) + .send() + .await + { + Ok(_) => true, + Err(e) => { + warn!(error = %e, "Could not queue an alert episode check"); + false + } + } +} + +/// What posting a card needs: the settings table, the key that opens saved +/// webhooks, a poster and the dashboard's address. +pub struct Posting<'a> { + pub dynamo: &'a DynamoClient, + pub table: &'a str, + pub cipher: &'a dyn Cipher, + pub poster: &'a dyn Poster, + pub base: &'a str, +} + +/// The route's item for `topic_arn` when it belongs to `team_id`. +pub async fn route_item( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + topic_arn: &str, +) -> Option> { + let item = dynamo + .get_item() + .table_name(table) + .key("pk", s(&format!("ALERTTOPIC#{topic_arn}"))) + .key("sk", s("ROUTE")) + .send() + .await + .ok()? + .item() + .cloned()?; + (item + .get("team_id") + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + == Some(team_id)) + .then_some(item) +} + +fn flag(item: &std::collections::HashMap, k: &str) -> bool { + item.get(k) + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false) +} + +async fn post( + p: &Posting<'_>, + team_id: &str, + topic_arn: &str, + card: crate::alert_notify::AlertCard<'_>, +) -> bool { + let channels = + crate::alert_notify::notify_target(p.dynamo, p.cipher, p.table, team_id, topic_arn).await; + if channels.is_empty() { + return false; + } + let msg = crate::alert_notify::alert_message(&card); + notify::deliver_recorded( + p.poster, &channels, &msg, "alert", p.dynamo, p.table, team_id, + ) + .await + .any_ok() +} + +/// An episode ended: close its open card and, on a route that posts +/// recoveries, post one recovery card linking it. The OK's own record says +/// whether it posted. Returns whether a card went out. +pub async fn post_cleared(p: &Posting<'_>, team_id: &str, ended: &Episode) -> bool { + let opened = + crate::alert_notify::close_open_alert(p.dynamo, p.table, team_id, &ended.fingerprint).await; + let route = route_item(p.dynamo, p.table, team_id, &ended.topic_arn).await; + let posts = route + .as_ref() + .is_some_and(|r| flag(r, "enabled") && flag(r, "post_recoveries")); + let mut sent = false; + if let (Some(o), true) = (&opened, posts) { + let line = cleared_line(ended, o, p.base); + let at = ended.clearing_since.unwrap_or(ended.first_at); + let context = crate::alert_notify::card_context(&ended.topic_arn, &utc_rfc3339(at)); + let alert_url = format!("{}/alerts/detail?id={}", p.base, ended.clear_event_id); + let kind = Some(ended.clear_kind.as_str()) + .filter(|k| !k.is_empty()) + .unwrap_or(&ended.kind); + let console = console_url(&ended.topic_arn, kind, &ended.clear_title); + sent = post( + p, + team_id, + &ended.topic_arn, + crate::alert_notify::AlertCard { + kind, + title: &ended.clear_title, + body: &ended.clear_body, + outcome: &line, + alert_url: &alert_url, + console_url: console.as_deref(), + context: &context, + }, + ) + .await; + } + if !ended.clear_event_id.is_empty() { + let outcome = if opened.is_some() { + "recovered" + } else { + "no_open_alert" + }; + let written = p + .dynamo + .update_item() + .table_name(p.table) + .key("pk", s(team_id)) + .key("sk", s(&format!("ALERT_EVENT#{}", ended.clear_event_id))) + .update_expression("SET outcome = :o") + .condition_expression("attribute_exists(pk)") + .expression_attribute_values(":o", s(outcome)) + .send() + .await; + if let Err(e) = written { + if !e + .as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()) + { + warn!(team_id, error = %e, "Could not mark the recovery on its record"); + } + } + } + sent +} + +/// Post the daily reminder for a still open episode: the alert's own card, +/// saying it is still firing, since when and how often. +pub async fn post_reminder(p: &Posting<'_>, team_id: &str, ep: &Episode, now: i64) -> bool { + let line = reminder_line(ep, now); + let context = crate::alert_notify::card_context(&ep.topic_arn, &utc_rfc3339(now)); + let alert_url = format!("{}/alerts/detail?id={}", p.base, ep.last_event_id); + let console = console_url(&ep.topic_arn, &ep.kind, &ep.title); + post( + p, + team_id, + &ep.topic_arn, + crate::alert_notify::AlertCard { + kind: &ep.kind, + title: &ep.title, + body: &ep.body, + outcome: &line, + alert_url: &alert_url, + console_url: console.as_deref(), + context: &context, + }, + ) + .await +} + +fn utc_rfc3339(secs: i64) -> String { + chrono::DateTime::from_timestamp(secs, 0) + .map(|t| t.to_rfc3339()) + .unwrap_or_default() +} + +fn console_url(topic_arn: &str, kind: &str, title: &str) -> Option { + let region = topic_arn.split(':').nth(3).unwrap_or(""); + alarm_name(kind, title).and_then(|n| crate::alert_notify::cloudwatch_console_url(region, n)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + const T0: i64 = 1_790_000_000; + const MIN: i64 = 60; + const HOUR: i64 = 3600; + const TEAM: &str = "TEAM#t"; + const TOPIC: &str = "arn:aws:sns:us-east-1:111122223333:example-alarms"; + const FP: &str = "arn:aws:cloudwatch:us-east-1:111122223333:alarm:example-queue-depth"; + + fn fire(id: &str, at: i64) -> Input<'_> { + Input::Fire { + event_id: id, + at, + kind: "cloudwatch_alarm", + title: "ALARM: example-queue-depth", + body: "- Reason: Threshold crossed", + } + } + + fn clear(id: &str, at: i64) -> Input<'_> { + Input::Clear { + event_id: id, + at, + quiet_secs: CLEAR_QUIET_MIN_SECS, + kind: "cloudwatch_alarm", + title: "OK: example-queue-depth", + body: "- Reason: back under", + } + } + + /// Feeds inputs through `step` as `apply` would, returning each decision. + fn run(mode: Repeat, inputs: &[Input]) -> (Vec, Option) { + let mut ep: Option = None; + let mut out = vec![]; + for i in inputs { + let (d, next) = step(ep.as_ref(), *i, mode); + if next.is_some() { + ep = next; + } + out.push(d); + } + (out, ep) + } + + fn posts(ds: &[Decision]) -> usize { + ds.iter() + .filter(|d| { + matches!( + d, + Decision::Opened | Decision::Reopened(_) | Decision::Remind + ) + }) + .count() + } + + #[test] + fn a_flapping_alarm_inside_the_quiet_window_posts_once() { + let (ds, ep) = run( + Repeat::UntilClear, + &[ + fire("a1", T0), + clear("o1", T0 + 3 * MIN), + fire("a2", T0 + 6 * MIN), + clear("o2", T0 + 9 * MIN), + fire("a3", T0 + 12 * MIN), + // The check of the first OK finds its window undone. + Input::ClearCheck { + clear_event_id: "o1", + now: T0 + 40 * MIN, + }, + ], + ); + assert_eq!(posts(&ds), 1, "{ds:?}"); + assert_eq!(ds[0], Decision::Opened); + assert_eq!(ds[2], Decision::Suppressed); + assert_eq!(ds[5], Decision::Nothing); + let ep = ep.unwrap(); + assert!(ep.open && ep.clearing_since.is_none()); + assert_eq!(ep.fires, 3); + assert_eq!(ep.first_alert_id, "a1"); + } + + #[test] + fn a_real_clear_ends_the_episode_once_and_the_next_alarm_posts_at_once() { + let (ds, ep) = run( + Repeat::UntilClear, + &[ + fire("a1", T0), + clear("o1", T0 + 5 * MIN), + // A second OK in the window doesn't start a second check. + clear("o1b", T0 + 6 * MIN), + // Checked too early (SQS delays are approximate): wait more. + Input::ClearCheck { + clear_event_id: "o1", + now: T0 + 20 * MIN, + }, + Input::ClearCheck { + clear_event_id: "o1", + now: T0 + 35 * MIN, + }, + // The same check delivered twice ends nothing more. + Input::ClearCheck { + clear_event_id: "o1", + now: T0 + 36 * MIN, + }, + fire("a2", T0 + 50 * MIN), + ], + ); + assert_eq!(ds[1], Decision::Clearing { schedule: true }); + assert_eq!(ds[2], Decision::Clearing { schedule: false }); + assert_eq!(ds[3], Decision::Wait(15 * 60)); + let Decision::Cleared(ended) = &ds[4] else { + panic!("{ds:?}") + }; + assert_eq!(ended.clear_event_id, "o1"); + assert_eq!(ended.fires, 1); + assert_eq!(ds[5], Decision::Nothing); + assert_eq!(ds[6], Decision::Opened); + let ep = ep.unwrap(); + assert_eq!(ep.first_alert_id, "a2"); + assert_eq!(ep.fires, 1); + } + + #[test] + fn an_alarm_after_the_window_ends_the_old_episode_even_before_its_check() { + let (ds, ep) = run( + Repeat::UntilClear, + &[ + fire("a1", T0), + clear("o1", T0 + MIN), + fire("a2", T0 + 45 * MIN), + ], + ); + let Decision::Reopened(old) = &ds[2] else { + panic!("{ds:?}") + }; + assert_eq!(old.first_alert_id, "a1"); + assert_eq!(ep.as_ref().unwrap().first_alert_id, "a2"); + // The late check then finds nothing to end. + let (d, _) = step( + ep.as_ref(), + Input::ClearCheck { + clear_event_id: "o1", + now: T0 + 50 * MIN, + }, + Repeat::UntilClear, + ); + assert_eq!(d, Decision::Nothing); + } + + #[test] + fn daily_reminds_once_per_24_hours_while_open_and_never_after_clear() { + let mut inputs = vec![fire("a0", T0)]; + let ids: Vec = (1..=60).map(|i| format!("a{i}")).collect(); + // Fires every hour for 60 hours. + for (i, id) in ids.iter().enumerate() { + inputs.push(fire(id, T0 + (i as i64 + 1) * HOUR)); + } + let (ds, ep) = run(Repeat::Daily, &inputs); + let reminders: Vec = ds + .iter() + .enumerate() + .filter(|(_, d)| **d == Decision::Remind) + .map(|(i, _)| i) + .collect(); + assert_eq!(reminders, vec![24, 48], "one at 24h and one at 48h"); + let ep = ep.unwrap(); + assert_eq!(ep.reminders, 2); + assert_eq!(ep.fires, 61); + + // A stuck alarm (no new fires) is reminded by the scheduled check, + // once: a second check for the same post finds it moved on. + let (ds, ep) = run( + Repeat::Daily, + &[ + fire("a1", T0), + Input::RemindCheck { + notified_at: T0, + now: T0 + 10 * HOUR, + }, + Input::RemindCheck { + notified_at: T0, + now: T0 + 24 * HOUR, + }, + Input::RemindCheck { + notified_at: T0, + now: T0 + 25 * HOUR, + }, + ], + ); + assert_eq!(ds[1], Decision::Wait(14 * 3600)); + assert_eq!(ds[2], Decision::Remind); + assert_eq!(ds[3], Decision::Nothing); + assert_eq!(ep.unwrap().last_notified_at, T0 + 24 * HOUR); + + // After a real clear: no reminder, whatever arrives. + let (ds, _) = run( + Repeat::Daily, + &[ + fire("a1", T0), + clear("o1", T0 + HOUR), + Input::ClearCheck { + clear_event_id: "o1", + now: T0 + 2 * HOUR, + }, + Input::RemindCheck { + notified_at: T0, + now: T0 + 30 * HOUR, + }, + ], + ); + assert!(matches!(ds[2], Decision::Cleared(_))); + assert_eq!(ds[3], Decision::Nothing); + // Until clear never reminds. + let (ds, _) = run( + Repeat::UntilClear, + &[ + fire("a1", T0), + fire("a2", T0 + 30 * HOUR), + Input::RemindCheck { + notified_at: T0, + now: T0 + 30 * HOUR, + }, + ], + ); + assert_eq!(ds[1], Decision::Suppressed); + assert_eq!(ds[2], Decision::Nothing); + } + + #[test] + fn a_redelivery_counts_once() { + let (ds, ep) = run( + Repeat::UntilClear, + &[ + fire("a1", T0), + fire("a1", T0), + fire("a2", T0 + MIN), + fire("a2", T0 + MIN), + ], + ); + assert_eq!(ds[1], Decision::Redelivered); + assert_eq!(ds[3], Decision::Redelivered); + assert_eq!(ep.unwrap().fires, 2); + } + + #[test] + fn an_ok_with_nothing_open_changes_nothing() { + let (ds, ep) = run(Repeat::UntilClear, &[clear("o1", T0)]); + assert_eq!(ds, vec![Decision::Nothing]); + assert!(ep.is_none()); + } + + #[test] + fn the_quiet_window_is_two_of_the_alarms_spans_within_bounds() { + let msg = |p: u64, e: u64| { + serde_json::json!({"AlarmName": "x", "NewStateValue": "OK", + "Trigger": {"Period": p, "EvaluationPeriods": e}}) + .to_string() + }; + // 1 minute x 3: six minutes is under the floor. + assert_eq!(quiet_window_secs(&msg(60, 3)), CLEAR_QUIET_MIN_SECS); + // 15 minutes x 2 = 30 min span, two of them = an hour. + assert_eq!(quiet_window_secs(&msg(900, 2)), 3600); + // A daily alarm is capped. + assert_eq!(quiet_window_secs(&msg(86_400, 1)), CLEAR_QUIET_MAX_SECS); + assert_eq!(quiet_window_secs("plain text"), CLEAR_QUIET_MIN_SECS); + } + + #[test] + fn an_alarms_own_setting_beats_the_routes() { + let o = BTreeMap::from([ + ("example-queue-depth".to_string(), Repeat::Daily), + ("example-disk".to_string(), Repeat::EveryTime), + ]); + let r = Repeat::UntilClear; + assert_eq!( + effective(r, &o, "cloudwatch_alarm", "ALARM: example-queue-depth"), + Repeat::Daily + ); + assert_eq!( + effective(r, &o, "cloudwatch_alarm", "OK: example-queue-depth"), + Repeat::Daily, + "its OK finds the same setting" + ); + assert_eq!( + effective(r, &o, "cloudwatch_alarm", "ALARM: example-disk"), + Repeat::EveryTime + ); + assert_eq!( + effective(r, &o, "cloudwatch_alarm", "ALARM: example-cpu"), + Repeat::UntilClear + ); + assert_eq!(effective(r, &o, "message", "Nightly load failed"), r); + // Alerts that never clear post every time. + assert_eq!(effective(r, &o, "eventbridge", "x"), Repeat::EveryTime); + assert_eq!(effective(r, &o, "chatbot_custom", "x"), Repeat::EveryTime); + } + + #[test] + fn routes_saved_before_the_setting_post_every_time() { + let (r, o) = route_setting(&std::collections::HashMap::new()); + assert_eq!(r, Repeat::EveryTime); + assert!(o.is_empty()); + assert_eq!(Repeat::parse(""), Some(Repeat::EveryTime)); + assert_eq!(Repeat::parse("weekly"), None); + let item = std::collections::HashMap::from([ + ("repeat".to_string(), s("daily")), + ( + "alarm_repeat".to_string(), + AttributeValue::M(std::collections::HashMap::from([ + ("a".to_string(), s("until_clear")), + ("bad".to_string(), s("weekly")), + ])), + ), + ]); + let (r, o) = route_setting(&item); + assert_eq!(r, Repeat::Daily); + assert_eq!(o, BTreeMap::from([("a".to_string(), Repeat::UntilClear)])); + } + + #[test] + fn episodes_round_trip_through_their_item() { + let (_, ep) = run(Repeat::Daily, &[fire("a1", T0), clear("o1", T0 + MIN)]); + let mut ep = ep.unwrap(); + ep.topic_arn = TOPIC.into(); + ep.fingerprint = FP.into(); + let item: std::collections::HashMap = to_item(&ep) + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + assert_eq!(from_item(&item), ep); + assert_ne!(episode_sk(TOPIC, FP), episode_sk("arn:other", FP)); + } + + #[test] + fn the_reminder_says_since_when_and_how_often() { + let ep = Episode { + first_at: 1_793_871_120, // 2026-11-05 09:32 UTC + fires: 14, + ..Episode::default() + }; + assert_eq!( + reminder_line(&ep, 1_793_871_120 + 25 * 3600), + "Still firing. It started 2026-11-05 09:32 UTC (25 hours ago) and has fired 14 times since. One reminder a day until it clears." + ); + assert_eq!(span(45 * 60), "45 min"); + assert_eq!(span(3 * 86_400), "3 days"); + } + + /// An in-memory store whose reads wait for each other, so two callers + /// both read before either writes: the race SNS can cause. + struct Racing { + items: Mutex>, + barrier: tokio::sync::Barrier, + first_reads: std::sync::atomic::AtomicUsize, + } + + #[async_trait::async_trait] + impl EpisodeStore for Racing { + async fn get(&self, _t: &str, sk: &str) -> Result, String> { + let v = self.items.lock().unwrap().get(sk).cloned(); + if self + .first_reads + .fetch_add(1, std::sync::atomic::Ordering::SeqCst) + < 2 + { + self.barrier.wait().await; + } + Ok(v) + } + async fn put( + &self, + _t: &str, + sk: &str, + ep: &Episode, + expect: Option, + ) -> Result { + let mut items = self.items.lock().unwrap(); + if items.get(sk).map(|e| e.ver) != expect { + return Ok(false); + } + items.insert(sk.to_string(), ep.clone()); + Ok(true) + } + async fn delete(&self, _t: &str, sk: &str, first: Option<&str>) -> Result<(), String> { + let mut items = self.items.lock().unwrap(); + if first.is_none() || items.get(sk).map(|e| e.first_alert_id.as_str()) == first { + items.remove(sk); + } + Ok(()) + } + } + + #[tokio::test] + async fn two_deliveries_at_once_post_once() { + let store = Racing { + items: Mutex::new(Default::default()), + barrier: tokio::sync::Barrier::new(2), + first_reads: Default::default(), + }; + let (a, b) = tokio::join!( + apply(&store, TEAM, TOPIC, FP, fire("a1", T0), Repeat::UntilClear), + apply( + &store, + TEAM, + TOPIC, + FP, + fire("a2", T0 + 1), + Repeat::UntilClear + ), + ); + let ds = [a.unwrap().decision, b.unwrap().decision]; + assert_eq!( + ds.iter().filter(|d| **d == Decision::Opened).count(), + 1, + "{ds:?}" + ); + assert!(ds.contains(&Decision::Suppressed), "{ds:?}"); + let ep = store + .get(TEAM, &episode_sk(TOPIC, FP)) + .await + .unwrap() + .unwrap(); + assert_eq!(ep.fires, 2); + assert_eq!(ep.topic_arn, TOPIC); + assert_eq!(ep.fingerprint, FP); + } + + #[tokio::test] + async fn a_failed_start_forgets_the_episode_so_the_retry_opens_it() { + let store = Racing { + items: Mutex::new(Default::default()), + barrier: tokio::sync::Barrier::new(1), + first_reads: std::sync::atomic::AtomicUsize::new(2), + }; + let a = apply(&store, TEAM, TOPIC, FP, fire("a1", T0), Repeat::UntilClear) + .await + .unwrap(); + assert_eq!(a.decision, Decision::Opened); + let sk = episode_sk(TOPIC, FP); + // Another alert's rollback leaves it alone. + store.delete(TEAM, &sk, Some("zz")).await.unwrap(); + assert!(store.get(TEAM, &sk).await.unwrap().is_some()); + store.delete(TEAM, &sk, Some("a1")).await.unwrap(); + let retry = apply(&store, TEAM, TOPIC, FP, fire("a1", T0), Repeat::UntilClear) + .await + .unwrap(); + assert_eq!(retry.decision, Decision::Opened); + } +} diff --git a/services/common/src/alert_notify.rs b/services/common/src/alert_notify.rs index 1519a78d6..e651d2d89 100644 --- a/services/common/src/alert_notify.rs +++ b/services/common/src/alert_notify.rs @@ -367,6 +367,113 @@ pub fn fix_message( } } +/// Pure: a card's context line, "us-east-1 · 123456789012 · 2026-10-10 04:00 +/// UTC", from the topic and when the alert was sent. +pub fn card_context(topic_arn: &str, at_rfc3339: &str) -> String { + let parts: Vec<&str> = topic_arn.split(':').collect(); + let region = parts.get(3).copied().unwrap_or(""); + let account = parts + .get(4) + .copied() + .filter(|a| a.len() == 12 && a.chars().all(|c| c.is_ascii_digit())) + .unwrap_or(""); + let when = chrono::DateTime::parse_from_rfc3339(at_rfc3339) + .map(|t| { + t.with_timezone(&chrono::Utc) + .format("%Y-%m-%d %H:%M UTC") + .to_string() + }) + .unwrap_or_default(); + [region, account, when.as_str()] + .iter() + .filter(|s| !s.is_empty()) + .copied() + .collect::>() + .join(" · ") +} + +// ─── Open alerts ──────────────────────────────────────────────────────────── +// +// Chat webhooks (Teams Workflows, Slack incoming webhooks) can't reply in a +// thread, so a recovery is its own card that links the alert it resolves. To +// keep recoveries from spamming the channel, a posted alert card is "open" +// until one recovery closes it: the first recovery posts (on a route that +// posts recoveries), later ones (SNS retries, a job that keeps succeeding, an +// alarm flapping back to OK) don't, until a new alert card opens it again. + +/// Settings-table sort key of an alert's open card. +pub fn open_alert_sk(fingerprint: &str) -> String { + format!("ALERT_OPEN#{}", crate::content_hash(fingerprint)) +} + +/// The first card of an open alert, linked from its recovery card. +#[derive(Debug, PartialEq, Eq)] +pub struct OpenAlert { + pub id: String, + pub posted_at: String, +} + +/// Pure: the recovery card's line, linking the alert card it resolves. +pub fn recovered_line(o: &OpenAlert, base: &str) -> String { + let when = chrono::DateTime::parse_from_rfc3339(&o.posted_at) + .map(|t| { + t.with_timezone(&chrono::Utc) + .format("%Y-%m-%d %H:%M UTC") + .to_string() + }) + .unwrap_or_else(|_| "earlier".to_string()); + if ulid::Ulid::from_string(&o.id).is_ok() { + format!( + "Recovered. Resolves [the alert posted {when}]({base}/alerts/detail?id={}).", + o.id + ) + } else { + format!("Recovered. Resolves the alert posted {when}.") + } +} + +/// Close an open alert, returning its first card. Only one caller can close +/// it, so concurrent or repeated recoveries post at most one card. `None` when +/// nothing was open, or on an error (no card beats a duplicate). +pub async fn close_open_alert( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + fingerprint: &str, +) -> Option { + let out = dynamo + .delete_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(open_alert_sk(fingerprint))) + .condition_expression("attribute_exists(pk)") + .return_values(aws_sdk_dynamodb::types::ReturnValue::AllOld) + .send() + .await; + let old = match out { + Ok(o) => o.attributes, + Err(e) => { + let missing = e + .as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()); + if !missing { + tracing::warn!(team_id, error = %e, "Could not close the open alert; not posting its recovery"); + } + return None; + } + }?; + let s = |k: &str| { + old.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + Some(OpenAlert { + id: s("alert_id"), + posted_at: s("posted_at"), + }) +} + /// Pure: the alarm's page in the CloudWatch console. pub fn cloudwatch_console_url(region: &str, alarm_name: &str) -> Option { let ok_region = !region.is_empty() diff --git a/services/common/src/dlq.rs b/services/common/src/dlq.rs index acdb897cc..c10534559 100644 --- a/services/common/src/dlq.rs +++ b/services/common/src/dlq.rs @@ -82,6 +82,8 @@ pub const WORKER_MESSAGE_TYPES: &[&str] = &[ "hybrid_name_check", // Self-hosted support tickets to CoderHelm, and answers back. "support_sync", + // An alert episode's quiet window or daily reminder, checked later. + "alert_episode_check", ]; /// Scheduled jobs that act on every team (EventBridge puts them on the ticket diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 0fbc5f103..1620d0ac8 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -46,6 +46,7 @@ pub mod webhooks; /// asks before every call, approval cards, sign-in prompts and the pause. pub mod agent_policy; /// Alert notifications: which channels an alert posts to, and its messages. +pub mod alert_episodes; pub mod alert_notify; /// Chat notifications (Teams and Slack): one message model, a renderer per /// channel, sealed webhook URLs. diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 4b84a7b27..87083d7a6 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -204,6 +204,29 @@ pub enum WorkerMessage { /// Read a published draft's numbers back, as a lesson for later runs. #[serde(rename = "plugin_results")] PluginResults(PluginResultsMessage), + /// An alert episode's later check (self-scheduled with SQS delay): did + /// the alarm stay clear through its quiet window, or is a daily reminder + /// due (`crate::alert_episodes`). + #[serde(rename = "alert_episode_check")] + AlertEpisodeCheck(AlertEpisodeCheckMessage), +} + +/// One later check of an alert episode. A wait longer than SQS allows chains: +/// each hop waits up to 900s and lowers `delay_remaining_secs`. +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct AlertEpisodeCheckMessage { + pub team_id: String, + pub topic_arn: String, + /// The alert's identity on the topic (a CloudWatch alarm's ARN). + pub fingerprint: String, + /// `clear` or `remind`. + pub check: String, + /// What the check is about: the OK's alert id (`clear`), or when the + /// episode last posted, in epoch seconds (`remind`). A check whose + /// episode moved on does nothing. + pub token: String, + #[serde(default)] + pub delay_remaining_secs: u64, } /// One plugin run. `hash` is the plugin version it was asked against; the @@ -388,7 +411,8 @@ impl WorkerMessage { | WorkerMessage::LogAutofix | WorkerMessage::AwsPermissionsSweep | WorkerMessage::HybridNameCheck - | WorkerMessage::SupportSync => f::OTHER, + | WorkerMessage::SupportSync + | WorkerMessage::AlertEpisodeCheck(_) => f::OTHER, WorkerMessage::PluginRun(_) | WorkerMessage::PluginPublish(_) | WorkerMessage::PluginSync(_) @@ -459,6 +483,7 @@ impl WorkerMessage { | WorkerMessage::PluginSweep | WorkerMessage::HybridNameCheck | WorkerMessage::SupportSync + | WorkerMessage::AlertEpisodeCheck(_) | WorkerMessage::PluginTrigger(_) | WorkerMessage::PluginResults(_) => None, } diff --git a/services/gateway/src/routes/alerts.rs b/services/gateway/src/routes/alerts.rs index f8d79684d..ed8b15ad4 100644 --- a/services/gateway/src/routes/alerts.rs +++ b/services/gateway/src/routes/alerts.rs @@ -16,6 +16,8 @@ //! for it), so nobody can route someone else's alerts into their runs. //! - Alert text is treated as data, never as instructions: alerts often quote //! attacker-controlled values (user agents, request paths). +//! - A route's repeat setting (`common::alert_episodes`) can post a firing +//! alarm once until it really clears; a repeat inside it never starts a run. //! - Repeats of the same alert are collapsed, each rule has a daily run cap, //! and alert runs stop for the day once their tokens reach the team's daily //! alert token budget. @@ -29,14 +31,17 @@ use axum::{ }; use serde::Deserialize; use serde_json::{json, Value}; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; use tracing::{error, info, warn}; use super::sns::{self, SnsMessage}; use crate::models::{Claims, TicketMessage, TicketSource, WorkerMessage}; use crate::AppState; -use common::alert_notify; +use common::alert_episodes::{self as episodes, Decision, Episode, Repeat}; +#[cfg(test)] +use common::alert_notify::OpenAlert; +use common::alert_notify::{self, recovered_line}; use common::notify::{self, store, ChannelKind, Channels}; /// Same alert (same fingerprint) within this window is one alert. @@ -421,6 +426,11 @@ struct Route { /// Post recoveries and other non-alarm state changes to chat. Off by /// default: they are still recorded on the alert's page. post_recoveries: bool, + /// How often a firing alert posts (`common::alert_episodes`). Routes + /// saved before the setting post every time. + repeat: Repeat, + /// Alarms with their own setting, by exact alarm name. + alarm_repeat: BTreeMap, } fn strings(v: Option<&AttributeValue>) -> Vec { @@ -493,9 +503,12 @@ fn route_from_item(item: &HashMap) -> Option { }], None => vec![], }; + let (repeat, alarm_repeat) = episodes::route_setting(item); Some(Route { team_id, rules, + repeat, + alarm_repeat, enabled: item .get("enabled") .and_then(|v| v.as_bool().ok()) @@ -694,6 +707,14 @@ pub enum Outcome { InFlight, Misconfigured, Error, + /// The alarm is still firing in an episode that already posted: recorded, + /// not posted, no run (the route's repeat setting). + Suppressed, + /// Still firing a day after the last post: one reminder posted. + Reminded, + /// An OK started the quiet window: the recovery posts once the alarm has + /// stayed clear through it. + Clearing, } impl Outcome { @@ -713,6 +734,9 @@ impl Outcome { Outcome::InFlight => "in_flight", Outcome::Misconfigured => "misconfigured", Outcome::Error => "error", + Outcome::Suppressed => "suppressed", + Outcome::Reminded => "reminded", + Outcome::Clearing => "clearing", } } } @@ -749,32 +773,292 @@ async fn handle_notification( let alert = normalize(msg.subject.as_deref(), &msg.message); let tid = ticket_id(&alert.fingerprint); let rule = pick_rule(&route.rules, &alert); - let (result, opened) = match &alert.recovers { - Some(fp) if route.enabled => { - let opened = close_open_alert(state, &route.team_id, fp).await; + let id = event_id(&msg.timestamp, &msg.message_id); + let mode = episodes::effective(route.repeat, &route.alarm_repeat, alert.kind, &alert.title); + let tracked = if route.enabled && mode != Repeat::EveryTime { + track_episode(state, msg, route, &alert, &id, mode).await + } else { + if route.enabled { + if let Some(fp) = &alert.recovers { + // It cleared on a route that posts every time: an episode + // left from another setting must not hold the next alarm. + forget_episode(state, &route.team_id, &msg.topic_arn, fp, None).await; + } + } + None + }; + let mut line_override: Option = None; + let decision = tracked.as_ref().map(|t| &t.decision); + let result = match plan(decision, alert.recovers.is_some(), route.enabled) { + Plan::Hold => { + info!(topic = %msg.topic_arn, ticket = %tid, "Alert still firing — recorded, not posted"); + Ok(Outcome::Suppressed) + } + Plan::WaitForClear => { + info!(topic = %msg.topic_arn, ticket = %tid, "Alert OK — waiting out the quiet window"); + Ok(Outcome::Clearing) + } + Plan::Remind => { + let ep = &tracked + .as_ref() + .expect("a reminder has its episode") + .episode; + line_override = Some(episodes::reminder_line(ep, ep.last_notified_at)); + Ok(Outcome::Reminded) + } + Plan::Decide => { + if let Some(Decision::Reopened(old)) = decision { + // Its quiet window passed before this ALARM: the previous + // episode ended, so its recovery goes first. + let kms = cipher(state); + let http = notify::Http(&state.http); + let posting = episodes::Posting { + dynamo: &state.dynamo, + table: &state.config.settings_table_name, + cipher: &kms, + poster: &http, + base: dashboard_base(state), + }; + episodes::post_cleared(&posting, &route.team_id, old).await; + } + let opens_episode = matches!(decision, Some(Decision::Opened | Decision::Reopened(_))); + let decided = decide(state, msg, route, rule, &alert, &tid).await; + match &decided { + Err(_) if opens_episode => { + // SNS retries this delivery: let it open the episode again. + forget_episode( + state, + &route.team_id, + &msg.topic_arn, + &alert.fingerprint, + Some(&id), + ) + .await; + } + Ok(Outcome::Duplicate) if opens_episode => { + line_override = Some(episodes::reopened_without_run_line().to_string()); + } + _ => {} + } + decided + } + Plan::Recover => { + let fp = alert.recovers.as_deref().unwrap_or_default(); + let opened = alert_notify::close_open_alert( + &state.dynamo, + &state.config.settings_table_name, + &route.team_id, + fp, + ) + .await; let outcome = if opened.is_some() { Outcome::Recovered } else { Outcome::NoOpenAlert }; info!(topic = %msg.topic_arn, ticket = %tid, outcome = outcome.as_str(), "Alert recovery"); - (Ok(outcome), opened) + line_override = opened.map(|o| recovered_line(&o, dashboard_base(state))); + Ok(outcome) } - _ => (decide(state, msg, route, rule, &alert, &tid).await, None), }; let outcome = match &result { Ok(o) => *o, Err(_) => Outcome::Error, }; let repo = rule.map(|r| r.repo.as_str()).unwrap_or(""); - record_event(state, msg, route, repo, &alert, &tid, outcome).await; - if alert.actionable && alert.recovers.is_none() && !repo.is_empty() { + let tag = tracked.as_ref().map(|t| EpisodeTag { + id: t.episode.first_alert_id.clone(), + fires: t.episode.fires, + suppressed: outcome == Outcome::Suppressed, + }); + record_event(state, msg, route, repo, &alert, outcome, tag.as_ref()).await; + if alert.actionable + && alert.recovers.is_none() + && !repo.is_empty() + && outcome != Outcome::Suppressed + { link_incident(state, &route.team_id, repo, &alert).await; } - notify_channels(state, msg, route, repo, &alert, outcome, opened.as_ref()).await; + notify_channels(state, msg, route, repo, &alert, outcome, line_override).await; + if let Some(t) = &tracked { + schedule_episode_checks(state, route, t, outcome, mode).await; + } result.map(|_| StatusCode::OK) } +/// What a delivery leads to, before any run or post. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Plan { + /// Still firing in an episode that already posted: record it only. No + /// card, and no run (so a fix route never starts a second run for it). + Hold, + /// An OK on a route that posts once: the quiet window decides later. + WaitForClear, + /// The daily reminder: a card, no run. + Remind, + /// As before the repeat setting: a run for a rule that takes it, or a + /// card (repeat runs stay deduplicated by `decide`). + Decide, + /// A recovery posting at once (routes that post every time, or nothing + /// open on a route that posts once). + Recover, +} + +/// Pure: the plan for a delivery, from its episode's decision (None = the +/// route posts every time, or the episode couldn't be tracked). +pub fn plan(decision: Option<&Decision>, recovers: bool, route_enabled: bool) -> Plan { + match decision { + Some(Decision::Suppressed | Decision::Redelivered) => Plan::Hold, + Some(Decision::Clearing { .. }) => Plan::WaitForClear, + Some(Decision::Remind) => Plan::Remind, + _ if recovers && route_enabled => Plan::Recover, + _ => Plan::Decide, + } +} + +/// An alert's episode after this delivery, and what it decided. +struct Tracked { + decision: Decision, + episode: Episode, +} + +/// What an alert's record says about its episode, so the alerts page can +/// group a firing alarm's deliveries under the one that posted. +struct EpisodeTag { + /// The alert record that opened the episode. + id: String, + fires: u64, + suppressed: bool, +} + +fn sns_epoch(timestamp: &str) -> i64 { + chrono::DateTime::parse_from_rfc3339(timestamp) + .map(|t| t.timestamp()) + .unwrap_or_else(|_| chrono::Utc::now().timestamp()) +} + +/// Count this delivery in its alert's episode. `None` (post as if the route +/// posted every time) when the alert isn't a fire or a clear, or the episode +/// couldn't be read or written: a duplicate card beats a lost alert. +async fn track_episode( + state: &AppState, + msg: &SnsMessage, + route: &Route, + alert: &Alert, + id: &str, + mode: Repeat, +) -> Option { + let at = sns_epoch(&msg.timestamp); + let (fingerprint, input) = match &alert.recovers { + Some(fp) => ( + fp.as_str(), + episodes::Input::Clear { + event_id: id, + at, + quiet_secs: episodes::quiet_window_secs(&msg.message), + kind: alert.kind, + title: &alert.title, + body: &alert.body, + }, + ), + None if alert.actionable => ( + alert.fingerprint.as_str(), + episodes::Input::Fire { + event_id: id, + at, + kind: alert.kind, + title: &alert.title, + body: &alert.body, + }, + ), + None => return None, + }; + let store = episodes::DynamoStore { + client: &state.dynamo, + table: &state.config.settings_table_name, + }; + match episodes::apply( + &store, + &route.team_id, + &msg.topic_arn, + fingerprint, + input, + mode, + ) + .await + { + Ok(a) => { + info!(topic = %msg.topic_arn, decision = a.decision.name(), "Alert episode"); + Some(Tracked { + decision: a.decision, + episode: a.episode?, + }) + } + Err(e) => { + warn!(topic = %msg.topic_arn, error = %e, "Could not track the alert's episode; posting it as every time"); + None + } + } +} + +/// Drop an alert's episode (only while `first_alert_id` opened it, when +/// given). Best effort. +async fn forget_episode( + state: &AppState, + team_id: &str, + topic_arn: &str, + fingerprint: &str, + first_alert_id: Option<&str>, +) { + use episodes::EpisodeStore; + let store = episodes::DynamoStore { + client: &state.dynamo, + table: &state.config.settings_table_name, + }; + let sk = episodes::episode_sk(topic_arn, fingerprint); + if let Err(e) = store.delete(team_id, &sk, first_alert_id).await { + warn!(team_id, error = %e, "Could not drop the alert's episode"); + } +} + +/// Queue what this delivery leaves for later: the check of the quiet window +/// an OK started, or the next daily reminder of an episode that just posted. +async fn schedule_episode_checks( + state: &AppState, + route: &Route, + t: &Tracked, + outcome: Outcome, + mode: Repeat, +) { + let ep = &t.episode; + let check = |check: &str, token: String| common::messages::AlertEpisodeCheckMessage { + team_id: route.team_id.clone(), + topic_arn: ep.topic_arn.clone(), + fingerprint: ep.fingerprint.clone(), + check: check.to_string(), + token, + delay_remaining_secs: 0, + }; + let (msg, secs) = match &t.decision { + Decision::Clearing { schedule: true } => ( + check(episodes::CHECK_CLEAR, ep.clear_event_id.clone()), + ep.quiet_secs, + ), + Decision::Opened | Decision::Reopened(_) | Decision::Remind + if mode == Repeat::Daily && outcome != Outcome::Error => + { + ( + check(episodes::CHECK_REMIND, ep.last_notified_at.to_string()), + episodes::REMINDER_EVERY_SECS, + ) + } + _ => return, + }; + if !episodes::schedule_check(&state.sqs, &state.config.ticket_queue_url, msg, secs).await { + warn!(team_id = %route.team_id, "Alert episode check not queued; the next alarm decides instead"); + } +} + /// When an alert names a merged CoderHelm pull request of `repo` (its URL /// or its merge commit, as deploy markers print them), records the incident /// against that change. Only runs the repo's latest 50 are looked at. @@ -866,7 +1150,13 @@ pub fn notify_line(outcome: Outcome, repo: &str, post_recoveries: bool) -> Optio } Outcome::DailyCap => "No fix started: this rule reached its daily limit.".to_string(), Outcome::Misconfigured => "No fix started: the rule's repo is invalid.".to_string(), - Outcome::Duplicate | Outcome::RoutePaused | Outcome::Error => return None, + // The reminder's line is built from its episode. + Outcome::Reminded => String::new(), + Outcome::Duplicate + | Outcome::RoutePaused + | Outcome::Error + | Outcome::Suppressed + | Outcome::Clearing => return None, }) } @@ -899,6 +1189,8 @@ async fn route_channels(state: &AppState, route: &Route) -> Channels { } /// Post the alert to the route's channels (Teams, Slack). Best effort. +/// `line_override` replaces the card's line on what CoderHelm did (a +/// recovery's link to its alert, a reminder, a new episode with no new run). async fn notify_channels( state: &AppState, msg: &SnsMessage, @@ -906,9 +1198,13 @@ async fn notify_channels( repo: &str, alert: &Alert, outcome: Outcome, - opened: Option<&OpenAlert>, + line_override: Option, ) { - let Some(mut line) = notify_line(outcome, repo, route.post_recoveries) else { + let new_episode = outcome == Outcome::Duplicate && line_override.is_some(); + let Some(line) = notify_line(outcome, repo, route.post_recoveries) + .or_else(|| new_episode.then(String::new)) + .map(|l| line_override.unwrap_or(l)) + else { return; }; let channels = route_channels(state, route).await; @@ -916,28 +1212,10 @@ async fn notify_channels( return; } let region = msg.topic_arn.split(':').nth(3).unwrap_or(""); - let account = topic_account(&msg.topic_arn).unwrap_or(""); - let when = chrono::DateTime::parse_from_rfc3339(&msg.timestamp) - .map(|t| { - t.with_timezone(&chrono::Utc) - .format("%Y-%m-%d %H:%M UTC") - .to_string() - }) - .unwrap_or_default(); - let context = [region, account, when.as_str()] - .iter() - .filter(|s| !s.is_empty()) - .copied() - .collect::>() - .join(" · "); + let context = alert_notify::card_context(&msg.topic_arn, &msg.timestamp); let id = event_id(&msg.timestamp, &msg.message_id); let alert_url = format!("{}/alerts/detail?id={id}", dashboard_base(state)); - if let Some(o) = opened { - line = recovered_line(o, dashboard_base(state)); - } - let console = (alert.kind == "cloudwatch_alarm") - .then(|| alert.title.split_once(": ").map(|(_, name)| name)) - .flatten() + let console = episodes::alarm_name(alert.kind, &alert.title) .and_then(|name| alert_notify::cloudwatch_console_url(region, name)); let card = alert_notify::alert_message(&alert_notify::AlertCard { kind: alert.kind, @@ -967,46 +1245,12 @@ async fn notify_channels( // ─── Open alerts ──────────────────────────────────────────────────────────── // -// Chat webhooks (Teams Workflows, Slack incoming webhooks) can't reply in a thread, so a recovery is its own -// card that links the alert it resolves. To keep recoveries from spamming the -// channel, a posted alert card is "open" until one recovery closes it: the -// first recovery posts (on a route that posts recoveries), later ones (SNS -// retries, a DAG that keeps succeeding, an alarm flapping back to OK) don't, -// until a new alert card opens it again. +// A posted alert card stays "open" until one recovery closes it, so a +// recovery posts once (see `common::alert_notify::close_open_alert`). /// Days an unrecovered alert stays open; each repeat of the alert renews it. const OPEN_ALERT_SECS: u64 = 30 * DAY_SECS; -fn open_alert_sk(fingerprint: &str) -> String { - format!("ALERT_OPEN#{}", common::content_hash(fingerprint)) -} - -/// The first card of an open alert, linked from its recovery card. -#[derive(Debug, PartialEq, Eq)] -pub struct OpenAlert { - pub id: String, - pub posted_at: String, -} - -/// Pure: the recovery card's line, linking the alert card it resolves. -pub fn recovered_line(o: &OpenAlert, base: &str) -> String { - let when = chrono::DateTime::parse_from_rfc3339(&o.posted_at) - .map(|t| { - t.with_timezone(&chrono::Utc) - .format("%Y-%m-%d %H:%M UTC") - .to_string() - }) - .unwrap_or_else(|_| "earlier".to_string()); - if is_event_id(&o.id) { - format!( - "Recovered. Resolves [the alert posted {when}]({base}/alerts/detail?id={}).", - o.id - ) - } else { - format!("Recovered. Resolves the alert posted {when}.") - } -} - /// Mark an alert's card open. A repeat keeps the first card's link and renews /// how long it stays open. Best effort. async fn open_alert(state: &AppState, team_id: &str, alert: &Alert, id: &str, posted_at: &str) { @@ -1016,7 +1260,7 @@ async fn open_alert(state: &AppState, team_id: &str, alert: &Alert, id: &str, po .update_item() .table_name(&state.config.settings_table_name) .key("pk", attr_s(team_id)) - .key("sk", attr_s(&open_alert_sk(&alert.fingerprint))) + .key("sk", attr_s(&alert_notify::open_alert_sk(&alert.fingerprint))) .update_expression( "SET alert_id = if_not_exists(alert_id, :id), posted_at = if_not_exists(posted_at, :at), \ title = :title, #ttl = :ttl", @@ -1033,44 +1277,6 @@ async fn open_alert(state: &AppState, team_id: &str, alert: &Alert, id: &str, po } } -/// Close an open alert, returning its first card. Only one caller can close -/// it, so concurrent or repeated recoveries post at most one card. `None` when -/// nothing was open, or on an error (no card beats a duplicate). -async fn close_open_alert(state: &AppState, team_id: &str, fingerprint: &str) -> Option { - let out = state - .dynamo - .delete_item() - .table_name(&state.config.settings_table_name) - .key("pk", attr_s(team_id)) - .key("sk", attr_s(&open_alert_sk(fingerprint))) - .condition_expression("attribute_exists(pk)") - .return_values(aws_sdk_dynamodb::types::ReturnValue::AllOld) - .send() - .await; - let old = match out { - Ok(o) => o.attributes, - Err(e) => { - let missing = e - .as_service_error() - .is_some_and(|se| se.is_conditional_check_failed_exception()); - if !missing { - warn!(team_id, error = %e, "Could not close the open alert; not posting its recovery"); - } - return None; - } - }?; - let s = |k: &str| { - old.get(k) - .and_then(|v| v.as_s().ok()) - .cloned() - .unwrap_or_default() - }; - Some(OpenAlert { - id: s("alert_id"), - posted_at: s("posted_at"), - }) -} - /// The team's alert channel setting: whether it is on, and the raw item /// (its webhooks are sealed; see [`store`]). pub(crate) struct TeamNotify { @@ -1274,9 +1480,11 @@ async fn record_event( route: &Route, repo: &str, alert: &Alert, - tid: &str, outcome: Outcome, + episode: Option<&EpisodeTag>, ) { + let tid = ticket_id(&alert.fingerprint); + let tid = tid.as_str(); let id = event_id(&msg.timestamp, &msg.message_id); let now = chrono::Utc::now(); let received_at = chrono::DateTime::parse_from_rfc3339(&msg.timestamp) @@ -1305,18 +1513,28 @@ async fn record_event( // A recovery names the ticket of the alert it resolves, so the dashboard // can show the two together (a plain `Recovers:` message has a ticket of // its own). - let written = match &alert.recovers { + let put = match &alert.recovers { Some(fp) => put.item("recovers_ticket", attr_s(&ticket_id(fp))), None => put, - } - .item("ttl", AttributeValue::N(ttl.to_string())) - .item( - common::deliveries_rollup::ROLLED, - AttributeValue::N("1".into()), - ) - .return_values(aws_sdk_dynamodb::types::ReturnValue::AllOld) - .send() - .await; + }; + // Every delivery is recorded, held ones too: they carry the episode they + // belong to, so history shows a firing alarm as one group with a count. + let put = match episode { + Some(e) => put + .item("episode", attr_s(&e.id)) + .item("episode_fires", AttributeValue::N(e.fires.to_string())) + .item("suppressed", AttributeValue::Bool(e.suppressed)), + None => put, + }; + let written = put + .item("ttl", AttributeValue::N(ttl.to_string())) + .item( + common::deliveries_rollup::ROLLED, + AttributeValue::N("1".into()), + ) + .return_values(aws_sdk_dynamodb::types::ReturnValue::AllOld) + .send() + .await; match written { Ok(r) => { // The Deliveries overview counts alerts too. An SNS redelivery @@ -1548,6 +1766,8 @@ pub async fn list_routes( "notify_mode": r.notify_mode, "webhooks": store::view(&r.webhooks), "post_recoveries": r.post_recoveries, + "repeat": r.repeat.as_str(), + "alarm_repeat": r.alarm_repeat.iter().map(|(k, v)| (k.clone(), json!(v.as_str()))).collect::>(), "updated_at": it.get("updated_at").and_then(|v| v.as_s().ok()), })) }) @@ -1599,6 +1819,36 @@ pub struct PutRouteRequest { /// Post recoveries (default off). #[serde(default)] post_recoveries: bool, + /// How often a firing alert posts: "every_time" (default), "until_clear" + /// or "daily". + #[serde(default)] + repeat: String, + /// Alarms with their own repeat setting, by exact alarm name. + #[serde(default)] + alarm_repeat: BTreeMap, +} + +/// Pure: the repeat setting a request saves, and its per-alarm overrides, +/// checked. Err = bad request. +pub fn repeat_from_request( + req: &PutRouteRequest, +) -> Result<(Repeat, BTreeMap), StatusCode> { + let route = Repeat::parse(&req.repeat).ok_or(StatusCode::BAD_REQUEST)?; + if req.alarm_repeat.len() > episodes::MAX_ALARM_OVERRIDES { + return Err(StatusCode::BAD_REQUEST); + } + let mut out = BTreeMap::new(); + for (name, v) in &req.alarm_repeat { + let name = name.trim(); + if name.is_empty() || name.len() > 255 { + return Err(StatusCode::BAD_REQUEST); + } + out.insert( + name.to_string(), + Repeat::parse(v).ok_or(StatusCode::BAD_REQUEST)?, + ); + } + Ok((route, out)) } fn notify_mode_of(req: &PutRouteRequest) -> Option<&'static str> { @@ -1697,6 +1947,7 @@ pub async fn put_route( let topic = req.topic_arn.trim(); let account = topic_account(topic).ok_or(StatusCode::BAD_REQUEST)?; let rules = rules_from_request(&req)?; + let (repeat, alarm_repeat) = repeat_from_request(&req)?; if rules.is_empty() && notify_mode_of(&req) == Some(alert_notify::MODE_OFF) { // A route that neither fixes nor notifies would do nothing. return Err(StatusCode::BAD_REQUEST); @@ -1747,6 +1998,12 @@ pub async fn put_route( vec![] }; let rules_attr = AttributeValue::L(rules.iter().map(rule_to_attr).collect()); + let alarm_repeat_attr = AttributeValue::M( + alarm_repeat + .iter() + .map(|(k, v)| (k.clone(), attr_s(v.as_str()))) + .collect(), + ); let now = chrono::Utc::now().to_rfc3339(); let fields = |pk: &str, sk: &str| { let mut b = Put::builder() @@ -1759,6 +2016,8 @@ pub async fn put_route( .item("enabled", AttributeValue::Bool(req.enabled)) .item("notify_mode", attr_s(notify_mode)) .item("post_recoveries", AttributeValue::Bool(req.post_recoveries)) + .item("repeat", attr_s(repeat.as_str())) + .item("alarm_repeat", alarm_repeat_attr.clone()) .item("updated_at", attr_s(&now)) .item("updated_by", attr_s(&claims.email)); for (k, v) in &webhooks { @@ -2285,6 +2544,11 @@ fn event_summary(it: &HashMap) -> Value { "outcome": s("outcome"), "ticket_id": s("ticket_id"), "recovers_ticket": s("recovers_ticket"), + // The alert record that opened this alert's episode, on routes that + // post once (absent when the route posts every time). + "episode": s("episode"), + "episode_fires": it.get("episode_fires").and_then(|v| v.as_n().ok()).and_then(|n| n.parse::().ok()), + "suppressed": it.get("suppressed").and_then(|v| v.as_bool().ok()).copied().unwrap_or(false), }) } @@ -2309,7 +2573,7 @@ pub async fn list_events( .expression_attribute_values(":pk", attr_s(&claims.team_id)) .expression_attribute_values(":p", attr_s("ALERT_EVENT#")) .projection_expression( - "id, received_at, topic_arn, repo, kind, title, outcome, ticket_id, recovers_ticket", + "id, received_at, topic_arn, repo, kind, title, outcome, ticket_id, recovers_ticket, episode, episode_fires, suppressed", ) .scan_index_forward(false) .limit(50); @@ -2928,4 +3192,136 @@ mod tests { assert_eq!(v["outcome"], "recovered"); assert!(event_summary(&HashMap::new())["recovers_ticket"].is_null()); } + + #[test] + fn a_held_repeat_never_starts_a_run_or_posts() { + // Still firing in an open episode: recorded only, so a fix rule + // can't start a second run for it. + assert_eq!(plan(Some(&Decision::Suppressed), false, true), Plan::Hold); + assert_eq!(plan(Some(&Decision::Redelivered), false, true), Plan::Hold); + assert_eq!(plan(Some(&Decision::Remind), false, true), Plan::Remind); + // A new episode goes through the run decision as before, where the + // existing repeat window still folds repeated runs into one. + assert_eq!(plan(Some(&Decision::Opened), false, true), Plan::Decide); + assert_eq!( + plan(Some(&Decision::Reopened(Box::default())), false, true), + Plan::Decide + ); + // An OK on a route that posts once waits out the quiet window; + // with nothing open it recovers as before. + assert_eq!( + plan(Some(&Decision::Clearing { schedule: true }), true, true), + Plan::WaitForClear + ); + assert_eq!(plan(Some(&Decision::Nothing), true, true), Plan::Recover); + // Routes that post every time track nothing: unchanged. + assert_eq!(plan(None, false, true), Plan::Decide); + assert_eq!(plan(None, true, true), Plan::Recover); + assert_eq!( + plan(None, true, false), + Plan::Decide, + "paused: recorded as paused" + ); + } + + #[test] + fn routes_saved_before_the_repeat_setting_post_every_time() { + for item in [route_item(None, "o/r"), route_item(Some(ACTION_NOTIFY), "")] { + let r = route_from_item(&item).unwrap(); + assert_eq!(r.repeat, Repeat::EveryTime); + assert!(r.alarm_repeat.is_empty()); + assert_eq!( + episodes::effective( + r.repeat, + &r.alarm_repeat, + "cloudwatch_alarm", + "ALARM: example-cpu" + ), + Repeat::EveryTime + ); + } + // A saved setting and its per-alarm override read back. + let mut item = route_item(Some(ACTION_NOTIFY), ""); + item.insert("repeat".into(), attr_s("until_clear")); + item.insert( + "alarm_repeat".into(), + AttributeValue::M(HashMap::from([( + "example-queue-depth".to_string(), + attr_s("daily"), + )])), + ); + let r = route_from_item(&item).unwrap(); + assert_eq!( + episodes::effective( + r.repeat, + &r.alarm_repeat, + "cloudwatch_alarm", + "ALARM: example-queue-depth" + ), + Repeat::Daily, + "the alarm's own setting beats the route's" + ); + assert_eq!( + episodes::effective( + r.repeat, + &r.alarm_repeat, + "cloudwatch_alarm", + "ALARM: example-cpu" + ), + Repeat::UntilClear + ); + } + + #[test] + fn the_repeat_setting_and_alarm_overrides_are_checked() { + let req = |repeat: &str, alarms: &[(&str, &str)]| PutRouteRequest { + repeat: repeat.into(), + alarm_repeat: alarms + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + ..Default::default() + }; + let (r, o) = repeat_from_request(&req("", &[])).unwrap(); + assert_eq!(r, Repeat::EveryTime, "absent = every time"); + assert!(o.is_empty()); + let (r, o) = + repeat_from_request(&req("daily", &[(" example-cpu ", "every_time")])).unwrap(); + assert_eq!(r, Repeat::Daily); + assert_eq!(o.get("example-cpu"), Some(&Repeat::EveryTime)); + assert!(repeat_from_request(&req("weekly", &[])).is_err()); + assert!(repeat_from_request(&req("daily", &[("x", "hourly")])).is_err()); + assert!(repeat_from_request(&req("daily", &[(" ", "daily")])).is_err()); + let many: Vec<(String, String)> = (0..=episodes::MAX_ALARM_OVERRIDES) + .map(|i| (format!("a{i}"), "daily".to_string())) + .collect(); + let too_many = PutRouteRequest { + alarm_repeat: many.into_iter().collect(), + ..Default::default() + }; + assert!(repeat_from_request(&too_many).is_err()); + } + + #[test] + fn held_and_waiting_alerts_post_nothing_and_reminders_post() { + assert!(notify_line(Outcome::Suppressed, "o/r", true).is_none()); + assert!(notify_line(Outcome::Clearing, "", true).is_none()); + assert_eq!( + notify_line(Outcome::Reminded, "", false).as_deref(), + Some("") + ); + assert_eq!(Outcome::Suppressed.as_str(), "suppressed"); + let mut item = HashMap::new(); + item.insert("id".to_string(), attr_s("01J0000000000000000000000B")); + item.insert("episode".to_string(), attr_s("01J0000000000000000000000A")); + item.insert("episode_fires".to_string(), AttributeValue::N("7".into())); + item.insert("suppressed".to_string(), AttributeValue::Bool(true)); + let v = event_summary(&item); + assert_eq!(v["episode"], "01J0000000000000000000000A"); + assert_eq!(v["episode_fires"], 7); + assert_eq!(v["suppressed"], true); + let plain = event_summary(&HashMap::new()); + assert!(plain["episode"].is_null()); + assert_eq!(plain["suppressed"], false); + } } diff --git a/services/gateway/src/routes/deliveries.rs b/services/gateway/src/routes/deliveries.rs index 6eafce551..0e5865f2c 100644 --- a/services/gateway/src/routes/deliveries.rs +++ b/services/gateway/src/routes/deliveries.rs @@ -88,7 +88,7 @@ pub fn alert_to_delivery( let outcome = g("outcome"); d.status = match outcome.as_str() { "error" => Status::Failed, - "duplicate" | "ignored" | "muted" => Status::Ignored, + "duplicate" | "ignored" | "muted" | "suppressed" => Status::Ignored, _ => Status::Handled, }; if d.status == Status::Failed { diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index addb8cd93..394b357db 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -549,6 +549,9 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) error!("Hybrid name check failed: {e:?}"); } } + models::WorkerMessage::AlertEpisodeCheck(msg) => { + passes::alert_episodes::run(&state, msg).await; + } models::WorkerMessage::PluginSweep => { info!("Plugin source poll"); if let Err(e) = passes::plugins::sweep(&state).await { diff --git a/services/worker/src/passes/alert_episodes.rs b/services/worker/src/passes/alert_episodes.rs new file mode 100644 index 000000000..6c93b33ad --- /dev/null +++ b/services/worker/src/passes/alert_episodes.rs @@ -0,0 +1,134 @@ +//! The later half of an alert route's repeat setting +//! (`common::alert_episodes`): once an OK's quiet window has passed with no +//! ALARM, end the episode and post its recovery; once a day has passed since +//! an open episode last posted, post its reminder. + +use common::alert_episodes::{self as episodes, Decision, Input}; +use common::messages::AlertEpisodeCheckMessage; +use tracing::{info, warn}; + +use crate::WorkerState; + +pub async fn run(state: &WorkerState, msg: AlertEpisodeCheckMessage) { + // Still waiting: one more hop (a single SQS delay is capped). + if msg.delay_remaining_secs > episodes::SQS_MAX_DELAY_SECS { + let rest = msg.delay_remaining_secs - episodes::SQS_MAX_DELAY_SECS; + episodes::schedule_check(&state.sqs, &state.config.ticket_queue_url, msg, rest).await; + return; + } + let table = &state.config.settings_table_name; + let Some(route) = + episodes::route_item(&state.dynamo, table, &msg.team_id, &msg.topic_arn).await + else { + info!(team_id = %msg.team_id, "Alert episode check: the route is gone"); + return; + }; + let store = episodes::DynamoStore { + client: &state.dynamo, + table, + }; + let now = chrono::Utc::now().timestamp(); + let sk = episodes::episode_sk(&msg.topic_arn, &msg.fingerprint); + // The setting as it is now: a route switched away from daily reminders + // stops reminding. + let mode = match ::get( + &store, + &msg.team_id, + &sk, + ) + .await + { + Ok(Some(ep)) => { + let (r, o) = episodes::route_setting(&route); + episodes::effective(r, &o, &ep.kind, &ep.title) + } + Ok(None) => return, + Err(e) => { + warn!(team_id = %msg.team_id, error = %e, "Alert episode check: could not read the episode"); + return; + } + }; + let notified_at: i64 = msg.token.parse().unwrap_or(-1); + let input = match msg.check.as_str() { + episodes::CHECK_CLEAR => Input::ClearCheck { + clear_event_id: &msg.token, + now, + }, + episodes::CHECK_REMIND => Input::RemindCheck { notified_at, now }, + other => { + warn!(check = other, "Alert episode check: unknown check"); + return; + } + }; + let applied = match episodes::apply( + &store, + &msg.team_id, + &msg.topic_arn, + &msg.fingerprint, + input, + mode, + ) + .await + { + Ok(a) => a, + Err(e) => { + warn!(team_id = %msg.team_id, error = %e, "Alert episode check failed"); + return; + } + }; + info!(team_id = %msg.team_id, check = %msg.check, decision = applied.decision.name(), "Alert episode check"); + let cipher = common::mcp_credentials::Kms { + client: &state.kms, + key_id: "", + }; + let http = common::notify::Http(&state.http); + let base = super::skills::app_url(&state.config.stage); + let posting = episodes::Posting { + dynamo: &state.dynamo, + table, + cipher: &cipher, + poster: &http, + base, + }; + let enabled = route + .get("enabled") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false); + match applied.decision { + Decision::Cleared(ended) => { + episodes::post_cleared(&posting, &msg.team_id, &ended).await; + } + Decision::Remind => { + let Some(ep) = applied.episode else { return }; + if enabled { + episodes::post_reminder(&posting, &msg.team_id, &ep, now).await; + } + let next = AlertEpisodeCheckMessage { + token: ep.last_notified_at.to_string(), + delay_remaining_secs: 0, + ..msg + }; + episodes::schedule_check( + &state.sqs, + &state.config.ticket_queue_url, + next, + episodes::REMINDER_EVERY_SECS, + ) + .await; + } + Decision::Wait(secs) => { + episodes::schedule_check( + &state.sqs, + &state.config.ticket_queue_url, + AlertEpisodeCheckMessage { + delay_remaining_secs: 0, + ..msg + }, + secs, + ) + .await; + } + _ => {} + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index cddd4d366..09549a901 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -786,6 +786,7 @@ fn has_time_for_remediation(start: &Instant) -> bool { } pub mod agent_tools; +pub mod alert_episodes; pub mod await_merge; pub mod aws_permissions; mod branch_update; From 1d509c8e25cefb5ef4c46817bb20207aa202b2a6 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 6 Nov 2026 09:15:08 -0500 Subject: [PATCH 2/2] Pin the dashboard with the alert repeat setting --- selfhost/versions.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/selfhost/versions.json b/selfhost/versions.json index 405a90baa..582df5089 100644 --- a/selfhost/versions.json +++ b/selfhost/versions.json @@ -1,4 +1,4 @@ { "about": "The dashboard commit each platform release ships: a full 40-character commit SHA of CoderHelm/coderhelm, never a branch or tag (scripts/check-dashboard-ref.mjs fails CI and the release otherwise). The release workflow builds exactly this commit (dashboard/) into dashboard.tar.gz. Move it with scripts/bump-dashboard.sh in a reviewed PR, in the same PR as any API change the dashboard needs.", - "dashboardRef": "d2df18677bb2cebd0a8b9a33e93900180f6d63d9" + "dashboardRef": "f4ebcbdb04525641f9f64e4c3901a25b909e4cbb" }