Skip to main content

ocre/
alerts.rs

1//! Owner alerts: an email to the app's owner when something needs attention, without flooding the inbox.
2//!
3//! [`record`] stores an [`Alert`] (a dotted reason such as
4//! `payment.failed`, an optional key such as the user's id, a detail) in
5//! the `alerts` table (`ocre g alerts` creates it) and emails it to
6//! [`ALERT_EMAIL`] at once, unless:
7//!
8//! - the same reason with the same key was emailed in the last
9//!   [`DEDUP_MINUTES`] (30): the alert is kept as `deduped`, no email;
10//! - [`HOURLY_CAP`] (20) alerts were emailed in the last hour: the alert
11//!   waits as `overflow` for the digest, one email listing what was held
12//!   back by reason ([`send_digest`], from a schedule).
13//!
14//! The decision is part of the `INSERT` (one statement), so concurrent
15//! requests cannot both email the same alert. Alerts are owner-facing:
16//! plain text, never translated, only ever sent to `ALERT_EMAIL`.
17//! [`send_digest`] also forgets alerts older than [`KEEP_DAYS`].
18//!
19//! # Free plan
20//!
21//! [`record`]: one D1 write, plus one email when it is sent (the mail
22//! adapter's own limits apply: Resend's free plan sends 100 a day, which
23//! the hourly cap keeps alerts well under). [`send_digest`]: one D1 write,
24//! one read, one delete, and an email only when alerts were held back.
25//!
26//! # Examples
27//!
28//! ```no_run
29//! use ocre::{Ctx, alerts::{self, Alert}};
30//!
31//! async fn payment_failed(ctx: &Ctx, user_id: i64, provider_message: &str) {
32//!     let alert = Alert::new("payment.failed").key(user_id).detail(format!("Provider said: {provider_message}"));
33//!     alerts::record(ctx, alert).await; // never fails the request: a problem is logged
34//! }
35//!
36//! // src/schedules/alert_digest.rs (`ocre g schedule alert_digest "every 15 minutes"`):
37//! pub async fn run(ctx: &Ctx) -> ocre::Result<()> {
38//!     alerts::send_digest(ctx).await.map(|_| ())
39//! }
40//! ```
41
42use std::fmt::Display;
43
44use serde::Deserialize;
45
46use crate::{helpers::civil_from_days, mail::Email};
47
48pub use crate::runtime::alerts::{record, send_digest};
49
50/// Worker variable holding the owner's address, where alerts go: `ALERT_EMAIL`.
51///
52/// Unset, alerts are still recorded (status `unsent`) and nothing is emailed.
53///
54/// # Examples
55///
56/// ```
57/// assert_eq!(ocre::alerts::ALERT_EMAIL, "ALERT_EMAIL");
58/// ```
59pub const ALERT_EMAIL: &str = "ALERT_EMAIL";
60
61/// Minutes during which the same reason and key are emailed once.
62pub const DEDUP_MINUTES: i64 = 30;
63
64/// Alert emails per hour at most; later alerts wait for the digest.
65pub const HOURLY_CAP: i64 = 20;
66
67/// Days alerts are kept; [`send_digest`] deletes older ones.
68pub const KEEP_DAYS: i64 = 30;
69
70/// The `alerts` table, created by the migration of `ocre g alerts`.
71///
72/// `status` is the alert's fate: `sent`, `deduped`, `overflow` (waiting for
73/// the digest), `digested`, `unsent` (no `ALERT_EMAIL`) or `failed` (the
74/// email could not be sent). Times are Unix seconds.
75pub const TABLE_SQL: &str = "CREATE TABLE alerts (
76  id INTEGER PRIMARY KEY,
77  reason TEXT NOT NULL,
78  dedup_key TEXT,
79  detail TEXT,
80  status TEXT NOT NULL CHECK (status IN ('sent', 'deduped', 'overflow', 'digested', 'unsent', 'failed')),
81  created_at INTEGER NOT NULL
82);
83CREATE INDEX index_alerts_on_reason_and_dedup_key ON alerts (reason, dedup_key, created_at);
84CREATE INDEX index_alerts_on_status_and_created_at ON alerts (status, created_at);
85";
86
87/// Something the owner should know about: a reason, what it concerns, and details.
88///
89/// # Examples
90///
91/// ```
92/// let alert = ocre::alerts::Alert::new("upload.failed").key("user:7").detail("R2 refused part 3");
93/// assert_eq!((alert.reason.as_str(), alert.key.as_deref()), ("upload.failed", Some("user:7")));
94/// ```
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct Alert {
97    /// A dotted code naming what happened (`payment.failed`); alerts group by it.
98    pub reason: String,
99    /// What it concerns (a user or record id): the same reason for another key is another alert.
100    pub key: Option<String>,
101    /// Free text shown in the email.
102    pub detail: Option<String>,
103}
104
105impl Alert {
106    /// An alert for `reason`.
107    pub fn new(reason: impl Into<String>) -> Self {
108        Self { reason: reason.into(), key: None, detail: None }
109    }
110
111    /// Sets what the alert concerns (deduplicated per reason and key).
112    pub fn key(mut self, key: impl Display) -> Self {
113        self.key = Some(key.to_string());
114        self
115    }
116
117    /// Sets the detail shown in the email.
118    pub fn detail(mut self, detail: impl Into<String>) -> Self {
119        self.detail = Some(detail.into());
120        self
121    }
122}
123
124/// The `INSERT` deciding an alert's fate: `?1` reason, `?2` key, `?3`
125/// detail, `?4` now, `?5` dedup window start, `?6` hour start, `?7` cap,
126/// `?8` whether there is a recipient.
127pub(crate) const INSERT_SQL: &str = "INSERT INTO alerts (reason, dedup_key, detail, status, created_at) \
128     VALUES (?1, ?2, ?3, CASE \
129       WHEN ?8 = 0 THEN 'unsent' \
130       WHEN EXISTS (SELECT 1 FROM alerts d WHERE d.reason = ?1 AND d.dedup_key IS ?2 AND d.status = 'sent' \
131         AND d.created_at > ?5) THEN 'deduped' \
132       WHEN (SELECT COUNT(*) FROM alerts c WHERE c.status = 'sent' AND c.created_at > ?6) >= ?7 THEN 'overflow' \
133       ELSE 'sent' END, ?4) \
134     RETURNING id, status";
135
136/// Claims the alerts waiting for the digest.
137pub(crate) const CLAIM_SQL: &str =
138    "UPDATE alerts SET status = 'digested' WHERE status = 'overflow' RETURNING id, reason, dedup_key, created_at";
139
140/// Puts claimed alerts back when the digest email failed: `?1` their ids, a JSON array.
141pub(crate) const UNCLAIM_SQL: &str =
142    "UPDATE alerts SET status = 'overflow' WHERE status = 'digested' AND id IN (SELECT value FROM json_each(?1))";
143
144/// Forgets alerts older than `?1`.
145pub(crate) const CLEANUP_SQL: &str = "DELETE FROM alerts WHERE created_at < ?1";
146
147/// A row claimed by the digest.
148#[derive(Debug, Clone, Deserialize)]
149pub(crate) struct Held {
150    pub(crate) id: i64,
151    pub(crate) reason: String,
152    pub(crate) dedup_key: Option<String>,
153    pub(crate) created_at: i64,
154}
155
156/// `2026-10-18 14:05 UTC`.
157fn utc(unix: i64) -> String {
158    let (year, month, day) = civil_from_days(unix.div_euclid(86_400));
159    let seconds = unix.rem_euclid(86_400);
160    format!("{year:04}-{month:02}-{day:02} {:02}:{:02} UTC", seconds / 3600, seconds % 3600 / 60)
161}
162
163/// The email of one alert.
164pub(crate) fn alert_email(to: &str, alert: &Alert, now: i64) -> Email {
165    let mut text = format!("{}\n\nWhen: {}\n", alert.reason, utc(now));
166    if let Some(key) = &alert.key {
167        text.push_str(&format!("About: {key}\n"));
168    }
169    if let Some(detail) = &alert.detail {
170        text.push_str(&format!("\n{detail}\n"));
171    }
172    text.push_str(&format!(
173        "\nThe same alert is emailed once per {DEDUP_MINUTES} minutes; past {HOURLY_CAP} alerts an hour, the others \
174         wait for the digest.\n"
175    ));
176    Email::new(to, format!("Alert: {}", alert.reason), text)
177}
178
179/// The digest of the alerts held back, by reason, most frequent first.
180pub(crate) fn digest_email(to: &str, held: &[Held]) -> Email {
181    let mut reasons: Vec<(&str, usize, usize, i64, i64)> = Vec::new();
182    for row in held {
183        match reasons.iter_mut().find(|(reason, ..)| *reason == row.reason) {
184            Some(entry) => {
185                entry.1 += 1;
186                entry.3 = entry.3.min(row.created_at);
187                entry.4 = entry.4.max(row.created_at);
188            }
189            None => reasons.push((&row.reason, 1, 0, row.created_at, row.created_at)),
190        }
191    }
192    for entry in &mut reasons {
193        let mut keys: Vec<&str> =
194            held.iter().filter(|row| row.reason == entry.0).filter_map(|row| row.dedup_key.as_deref()).collect();
195        keys.sort_unstable();
196        keys.dedup();
197        entry.2 = keys.len();
198    }
199    reasons.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
200    let mut text = format!("{} alerts were held back by the hourly limit of {HOURLY_CAP} emails:\n\n", held.len());
201    for (reason, count, keys, first, last) in &reasons {
202        text.push_str(&format!("- {reason}: {count} ({keys} distinct), {} to {}\n", utc(*first), utc(*last)));
203    }
204    Email::new(to, format!("Alert digest: {} alerts held back", held.len()), text)
205}
206
207#[cfg(test)]
208#[path = "../tests/alerts.rs"]
209mod tests;