OXYGENHUB

Coverage / crates/hub/src/notify/mod.rs 84.0%

89 of 106 lines run, 17 of 32 functions · run #483 on api-unknown-fields · run missed

1
//! Notifications (hub spec §10): who to tell about an event, the inbox
2
//! row, and email when the account asked for it and SMTP is configured.
3
4
use crate::db::{self, accounts::Account, notify as ndb};
5
use crate::Shared;
6
use std::collections::BTreeSet;
7
8
tokio::task_local! {
9
    /// The name of the agent-marked token this request came with, if any
10
    /// (oxygenhub#183): what an agent does with it is told to the token's
11
    /// owner too, though the owner is the actor.
12
    pub static AGENT: Option<String>;
13
}
14
15
/// The agent token acting now, when there is one.
16117×
pub fn agent_acting() -> Option<String> {
17117×
    AGENT.try_with(|a| a.clone()).ok().flatten()
18117×
}
19
20
/// An event worth telling people about.
21
pub struct Event<'a> {
22
    pub kind: &'a str,
23
    pub title: String,
24
    pub url: String,
25
    pub actor: &'a Account,
26
    pub repo_id: i64,
27
    /// `issue` or `proposal` and its id, for thread subscribers.
28
    pub thread: Option<(&'a str, i64)>,
29
    /// Bodies to scan for `@mentions`.
30
    pub mention_text: &'a str,
31
    /// Accounts to tell whatever their subscriptions (author, assignees).
32
    pub direct: Vec<i64>,
33
}
34
35
/// `@username` tokens in a text, unique.
36119×
pub fn mentions(text: &str) -> Vec<String> {
37119×
    let re = regex::Regex::new(r"(?:^|[^\w/])@([A-Za-z0-9][A-Za-z0-9._-]{0,63})").unwrap();
38119×
    let mut out = BTreeSet::new();
39119×
    for c in re.captures_iter(text) {
403×
        out.insert(c[1].trim_end_matches('.').to_string());
413×
    }
42119×
    out.into_iter().collect()
43119×
}
44
45
/// Deliver an event: subscribers of the thread, watchers of the
46
/// repository, mentioned accounts and direct targets, never the actor.
47117×
pub async fn deliver(app: &Shared, ev: Event<'_>) {
48117×
    let pool = &app.db;
49
    // Participants: the thread's subscribers, the mentioned, direct targets.
50
    // Watchers of the repository who are none of those are only watching.
51117×
    let mut participants: BTreeSet<i64> = BTreeSet::new();
52117×
    if let Some((kind, id)) = ev.thread {
5395×
        if let Ok(subs) = ndb::subscribers(pool, kind, id).await {
5495×
            participants.extend(subs);
5595×
        }
56
        // Acting on a thread subscribes the actor to it.
5795×
        ndb::subscribe(pool, ev.actor.id, kind, id).await.ok();
5822×
    }
59117×
    for name in mentions(ev.mention_text) {
601×
        if let Ok(Some(a)) = db::accounts::account_by_name(pool, &name).await {
611×
            participants.insert(a.id);
621×
        }
63
    }
64117×
    participants.extend(ev.direct.iter().copied());
65117×
    let mut targets: Vec<(i64, ndb::Reason)> = participants.iter().map(|id| (*id, ndb::Reason::Participating)).collect();
66117×
    if let Ok(w) = ndb::watchers(pool, ev.repo_id).await {
67123×
        targets.extend(w.into_iter().filter(|id| !participants.contains(id)).map(|id| (id, ndb::Reason::Watching)));
680×
    }
69
    // Never the actor, unless an agent acted with their token: then they
70
    // hear what their agent did.
71117×
    let agent = agent_acting();
72117×
    if agent.is_none() {
73130×
        targets.retain(|(id, _)| *id != ev.actor.id);
743×
    }
75117×
    let actor = match &agent {
763×
        Some(token) => format!("{} (agent token {token})", ev.actor.username),
77114×
        None => ev.actor.username.clone(),
78
    };
79117×
    tell(app, ev.kind, &ev.title, &ev.url, &actor, (ev.repo_id > 0).then_some(ev.repo_id), targets).await;
80117×
}
81
82
/// Tell each of `targets` about something: an inbox row, and an email
83
/// where the account asked for them and has proven its address.
84164×
pub async fn tell(app: &Shared, kind: &str, title: &str, url: &str, actor: &str, repo_id: Option<i64>, targets: Vec<(i64, ndb::Reason)>) {
85164×
    let pool = &app.db;
86164×
    for (id, reason) in targets {
87101×
        ndb::add(pool, ndb::New { account_id: id, repo_id, reason, kind, title, url, actor }).await.ok();
88101×
        app.bus.live(&crate::events::topic::user(id), "notification");
89101×
        if let Ok(Some(a)) = db::accounts::account_by_id(pool, id).await {
90
            // Only to addresses the account has proven it reads (hub spec §5.1.1).
91101×
            if a.email_notifications && a.email_verified && !a.email.is_empty() && crate::mail::enabled(app) {
920×
                email(app, &a, kind, title, url, actor).await;
93101×
            }
940×
        }
95
    }
96164×
}
97
98
/// What a kind of notification is called in an email's subject, with its
99
/// emoji, so a glance at the inbox says what happened (Andy, 2026-10-14).
10019×
pub fn label(kind: &str) -> Option<&'static str> {
10119×
    Some(match kind {
10219×
        "flow.failed" => "💥 Build Broken",
10318×
        "flow.fixed" => "🎉 Build Success",
10417×
        "flow.runner_drained" => "🛑 Runner Drained",
10517×
        "backup" => "⚠️ Backup Failed",
10617×
        "backup.recovered" => "✅ Backup Recovered",
10717×
        "backup.summary" => "📦 Daily Backup Summary",
10816×
        "proposal.opened" => "🔀 New Proposal",
10915×
        "proposal.review_requested" => "👀 Review Requested",
11014×
        "proposal.review" => "📝 New Review",
11113×
        "proposal.landed" => "🚀 Proposal Landed",
11213×
        "proposal.comment" | "issue.comment" | "drop.comment" => "💬 New Comment",
11311×
        "issue.opened" => "🐛 New Issue",
1146×
        "issue.assigned" => "📌 Issue Assigned",
1156×
        "issue.closed" => "✔️ Issue Closed",
1166×
        "account.registered" => "👋 New Sign-up",
1175×
        _ => return None,
118
    })
11919×
}
120
121
/// A notification's email subject: its label, then what happened.
1224×
pub fn subject(kind: &str, title: &str) -> String {
1234×
    match label(kind) {
1243×
        Some(l) => format!("{l}: {title}"),
1251×
        None => title.to_string(),
126
    }
1274×
}
128
1290×
async fn email(app: &Shared, to: &Account, kind: &str, title: &str, url: &str, actor: &str) {
1300×
    let unsubscribe = format!("{}/settings/notifications?unsubscribe={}", app.config.base_url(), to.unsubscribe_key);
1310×
    let link = format!("{}{url}", app.config.base_url());
1320×
    let body = format!("{actor}: {title}\n\n{link}\n\nStop these emails: {unsubscribe}\n");
1330×
    let action = crate::mail::Action { label: "Open it", url: &link };
1340×
    let subject = subject(kind, title);
1350×
    if let Err(e) = crate::mail::send_letter(app, to.name(), &to.email, &subject, &body, Some(action), Some(&unsubscribe)).await {
1360×
        tracing::warn!("email to {}: {e}", to.email);
137
        // Sent again from the work queue (#276), when mail is on at all.
1380×
        if crate::mail::enabled(app) {
1390×
            crate::queue::queue_mail(app, to.name(), &to.email, &subject, &body, Some(("Open it", &link)), Some(&unsubscribe)).await;
1400×
        }
1410×
    }
1420×
}
143
144
#[cfg(test)]
145
mod tests {
146
    use super::*;
147
148
    #[test]
1491×
    fn subjects_say_what_happened() {
1501×
        assert_eq!(
1511×
            subject("flow.failed", "andy/demo: run #4 on main failed (test)"),
152
            "💥 Build Broken: andy/demo: run #4 on main failed (test)"
153
        );
1541×
        assert_eq!(
1551×
            subject("flow.fixed", "andy/demo: run #5 on main passed: fixed"),
156
            "🎉 Build Success: andy/demo: run #5 on main passed: fixed"
157
        );
1581×
        assert_eq!(subject("backup.summary", "x"), "📦 Daily Backup Summary: x");
1591×
        assert_eq!(subject("something.new", "x"), "x", "a kind without a label keeps its title");
1601×
    }
161
162
    #[test]
1631×
    fn finds_mentions() {
1641×
        assert_eq!(mentions("cc @andy and @bob. not an email [email protected], nor /@path"), vec!["andy", "bob"]);
1651×
        assert!(mentions("nothing here").is_empty());
1661×
    }
167
}