Skip to main content

ocre/runtime/
alerts.rs

1//! [`record`] and [`send_digest`]: owner alerts in D1, emailed through `ocre::mail`.
2
3use serde::Deserialize;
4
5use super::Ctx;
6use crate::{
7    Result,
8    alerts::{
9        ALERT_EMAIL, Alert, CLAIM_SQL, CLEANUP_SQL, DEDUP_MINUTES, HOURLY_CAP, Held, INSERT_SQL, KEEP_DAYS,
10        UNCLAIM_SQL, alert_email, digest_email,
11    },
12    params,
13};
14
15/// The owner's address, when set.
16fn recipient(ctx: &Ctx) -> Option<String> {
17    ctx.env().var(ALERT_EMAIL).ok().map(|value| value.to_string().trim().to_owned()).filter(|value| !value.is_empty())
18}
19
20/// Records `alert` and emails it to [`ALERT_EMAIL`](crate::alerts::ALERT_EMAIL) unless it is a repeat or over the hourly cap.
21///
22/// Never fails: an alert must not break the request that raised it, so a
23/// D1 or mail problem is logged (`[ocre alerts] ...`) instead. See the
24/// [module documentation](crate::alerts) for the rules.
25pub fn record(ctx: &Ctx, alert: Alert) -> impl Future<Output = ()> + Send + use<> {
26    let ctx = ctx.clone();
27    worker::send::SendFuture::new(async move {
28        if let Err(err) = deliver(&ctx, &alert).await {
29            ctx.log().error(format!("[ocre alerts] {} not recorded or sent: {err}", alert.reason));
30        }
31    })
32}
33
34async fn deliver(ctx: &Ctx, alert: &Alert) -> Result<()> {
35    #[derive(Deserialize)]
36    struct Row {
37        id: i64,
38        status: String,
39    }
40    let to = recipient(ctx);
41    let now = crate::now();
42    let row: Option<Row> = ctx
43        .db()?
44        .first(
45            INSERT_SQL,
46            params![
47                alert.reason.as_str(),
48                alert.key.as_deref(),
49                alert.detail.as_deref(),
50                now,
51                now - DEDUP_MINUTES * 60,
52                now - 3600,
53                HOURLY_CAP,
54                to.is_some()
55            ],
56        )
57        .await?;
58    let (Some(row), Some(to)) = (row, to) else { return Ok(()) };
59    if row.status != "sent" {
60        return Ok(());
61    }
62    if let Err(err) = crate::mail::send(ctx, alert_email(&to, alert, now)).await {
63        ctx.db()?.execute("UPDATE alerts SET status = 'failed' WHERE id = ?1", params![row.id]).await?;
64        return Err(err);
65    }
66    Ok(())
67}
68
69/// Emails one digest of the alerts held back by the hourly cap, forgets alerts older than [`KEEP_DAYS`](crate::alerts::KEEP_DAYS), and returns how many alerts the digest listed.
70///
71/// Run it from a schedule (every 15 minutes is plenty): nothing is sent
72/// when no alert was held back. Safe to run twice at once: claiming the
73/// alerts is one `UPDATE`.
74///
75/// # Errors
76///
77/// A D1 or mail error; the held alerts then wait for the next run.
78pub fn send_digest(ctx: &Ctx) -> impl Future<Output = Result<usize>> + Send + use<> {
79    let ctx = ctx.clone();
80    worker::send::SendFuture::new(async move {
81        let db = ctx.db()?;
82        db.execute(CLEANUP_SQL, params![crate::now() - KEEP_DAYS * 86_400]).await?;
83        let Some(to) = recipient(&ctx) else { return Ok(0) };
84        let held: Vec<Held> = db.all(CLAIM_SQL, params![]).await?;
85        if held.is_empty() {
86            return Ok(0);
87        }
88        if let Err(err) = crate::mail::send(&ctx, digest_email(&to, &held)).await {
89            let ids = serde_json::json!(held.iter().map(|row| row.id).collect::<Vec<_>>());
90            db.execute(UNCLAIM_SQL, params![ids]).await?;
91            return Err(err);
92        }
93        Ok(held.len())
94    })
95}