Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
2,822 linesCodeBlameRaw
1//! The inbox, kept beside the event log. See `g1t_contracts::inbox`.
2//!
3//! As each batch arrives from the bus, the events that tell someone are
4//! read against what they name (the work service's `inbox_subject`), who
5//! subscribes to it and who watches its repository (subscriptions.rs), and
6//! each person told gets their thread about it brought to the top, unread,
7//! with a line added to its history. Who is told is worked out in
8//! [`notices`], from the event, its subject and that audience alone:
9//!
10//! | Event | Who | Reason | Severity |
11//! | --- | --- | --- | --- |
12//! | `pull.stalled` | the pull request's owner, and its issue's owner and assignees | agent | warning |
13//! | `pull.review_requested` | the reviewers asked, and the people each team asked tells | review_requested | warning |
14//! | `issue.assigned`, `pull.assigned` | the people newly assigned | assign | info |
15//! | `checks.completed`, failed or errored | the pull request's owner | ci_activity | error |
16//! | `workflow.completed`, failed | the pull request's owner, or whoever pushed | ci_activity | error |
17//! | `deployment.failed` | the pull request's owner, or whoever pushed; watchers | ci_activity | error |
18//! | `deployment.succeeded` after a failure | the same | ci_activity | success |
19//! | `pull.merged`, `pull.closed`, `issue.closed`, `issue.reopened` | everyone subscribed | state_change | success for a merge, else info |
20//! | `comment.created` | everyone mentioned, the people of teams mentioned, then everyone subscribed | mention, team_mention, or why they are subscribed | info (success for an approval) |
21//! | `comment.created` by a workspace's agent | the same, shown as "Margo (agent)"; a review also tells the owner, "(advisory)" | the same, or author | the same |
22//! | `issue.opened`, `pull.opened` | whoever was assigned, asked to review or mentioned in its description (people and teams); watchers | assign, review_requested, mention, team_mention, subscribed | info |
23//! | `secret_scanning_alert.summary`, `code_scanning_alert.summary`, `vulnerability_alert.summary` | the workspace's owners and security managers, whoever pushed a refused push, and watchers who chose security and may see findings; one thread per repository and alert type | security_alert | error for critical or high (told at once), info for the rest (a digest, unless the person chose at once) |
24//! | `security_advisory.reported` | the workspace's owners and security managers | security_alert | warning |
25//! | `secret_scanning.bypass_requested`, `.bypass_reviewed` | the reviewers named; the requester | security_alert | warning; info |
26//!
27//! Watchers of a repository at `all` (or `custom`, for the kinds they
28//! chose) hear of every issue and pull request opened, commented on,
29//! closed, reopened or merged, and of deployments. Anyone who ignores the
30//! thread or the repository hears of nothing on it; anyone who
31//! unsubscribed hears only of what is asked of them.
32//!
33//! Nobody is told of what they did themselves, though an outcome they set
34//! off (checks, a workflow, a deployment, g1t's work) is theirs to hear of.
35//! g1t is never told. A failure here is logged and the batch goes on: the
36//! bus never waits on the inbox, so an item can be missed, but nothing else
37//! is held up.
38
39use std::collections::{HashMap, HashSet};
40
41use g1t_contracts::credentials::Principal;
42use g1t_contracts::events::{Event, WorkspaceRenamed};
43use g1t_contracts::identity::{AGENT_ID, UsernamesArgs};
44use g1t_contracts::inbox::*;
45use g1t_contracts::repos::{PathByIdArgs, ReadableArgs, Repo, RepoPath};
46use g1t_contracts::security::SeverityCounts;
47use g1t_contracts::security_suite::{AlertType, SecuritySummary};
48use g1t_contracts::time::rfc3339;
49use g1t_contracts::{new_id, system};
50use g1t_kit::now_ms;
51use serde::Deserialize;
52use worker::wasm_bindgen::JsValue;
53use worker::{D1Database, D1PreparedStatement, Fetcher, Result};
54
55use crate::subscriptions::{self, Audience};
56
57/// Items marked done are kept this long, then removed.
58pub const DONE_DAYS: u32 = 30;
59/// No item is kept longer than this, unless it was saved.
60pub const MAX_DAYS: u32 = 180;
61/// Unread warnings shown ahead of everything else on the first page.
62const MAX_RANKED: u32 = 20;
63const MAX_TITLE: usize = 200;
64const MAX_BODY: usize = 300;
65
66/// What the inbox asks about an event before deciding who is told.
67#[derive(Debug, PartialEq, Eq)]
68pub struct Wanted {
69 pub repo_id: String,
70 /// The issue or pull request, when the event names one.
71 pub number: Option<u32>,
72 pub comment_id: Option<String>,
73}
74
75/// One person to tell, and what.
76#[derive(Debug, PartialEq, Eq)]
77pub struct Notice {
78 pub username: String,
79 pub reason: Reason,
80 pub severity: Severity,
81 pub title: String,
82 pub body: String,
83}
84
85/// Who did it, as far as is known.
86#[derive(Debug, Default)]
87pub struct Actor {
88 pub id: Option<String>,
89 pub username: Option<String>,
90}
91
92impl Actor {
93 fn is(&self, person: &Principal) -> bool {
94 self.id.as_deref().is_some_and(|id| id == person.id) || self.is_named(&person.username)
95 }
96
97 fn is_named(&self, username: &str) -> bool {
98 self.username.as_deref().is_some_and(|name| name.eq_ignore_ascii_case(username))
99 }
100
101 /// A person's name, for a title: never g1t's ids.
102 fn name(&self) -> Option<&str> {
103 self.username.as_deref().filter(|name| !is_g1t(name))
104 }
105}
106
107pub(crate) fn is_g1t(username: &str) -> bool {
108 username.eq_ignore_ascii_case(system::USERNAME) || username.eq_ignore_ascii_case("g1t-agent")
109}
110
111pub(crate) fn is_g1t_id(id: &str) -> bool {
112 system::is_system_id(id) || id == AGENT_ID
113}
114
115/// Events that end what an agent was waiting on a person for: it picked
116/// back up, its head moved, a merge was asked for, or it is over.
117const RESUMES: [&str; 5] = ["pull.resumed", "pull.updated", "pull.merge_requested", "pull.merged", "pull.closed"];
118
119/// The issue or pull request an event names, and what to read for it.
120/// None for events the inbox does not tell anyone of.
121pub fn wants(event: &Event) -> Option<Wanted> {
122 let data = &event.data;
123 let text = |key: &str| data[key].as_str().filter(|value| !value.is_empty()).map(str::to_owned);
124 let number = |key: &str| data[key].as_u64().and_then(|n| u32::try_from(n).ok());
125 let repo_id = text("repoId").or_else(|| event.repo_id.clone())?;
126 let on = |number: Option<u32>, comment_id: Option<String>| {
127 Some(Wanted {
128 repo_id: repo_id.clone(),
129 number,
130 comment_id,
131 })
132 };
133 match event.kind.as_str() {
134 "pull.stalled" | "pull.merged" | "pull.closed" | "pull.opened"
135 | "pull.review_requested" | "pull.assigned" | "issue.opened" | "issue.closed" | "issue.reopened"
136 | "issue.assigned" => on(Some(number("number")?), None),
137 "checks.completed" => match data["status"].as_str() {
138 Some("failed" | "errored") => on(Some(number("number")?), None),
139 _ => None,
140 },
141 "workflow.completed" => match data["conclusion"].as_str() {
142 Some("failure") => on(number("pull"), None),
143 _ => None,
144 },
145 "deployment.failed" | "deployment.succeeded" => on(number("number"), None),
146 // A workflow run's jobs wait for their environment's reviewers.
147 "deployment.review_requested" => on(None, None),
148 "comment.created" => on(Some(number("number")?), Some(text("commentId")?)),
149 // Security alerts are threads of their own, not of an issue.
150 kind if SECURITY_EVENTS.contains(&kind) => on(None, None),
151 // So is a repository's mirror, told to whom its settings name.
152 kind if MIRROR_EVENTS.contains(&kind) => on(None, None),
153 _ => None,
154 }
155}
156
157/// The security service's events the inbox tells people of: each scan's
158/// summary of what it opened and fixed (one thread per repository and
159/// alert type, brought up to date by the next scan; never one item per
160/// alert), push protection bypasses asked for and decided, vulnerability
161/// reports, and advisories published. The per-alert `.created`, `.fixed`
162/// and `.dismissed` events are for webhooks.
163pub const SECURITY_EVENTS: [&str; 7] = [
164 "secret_scanning_alert.summary",
165 "code_scanning_alert.summary",
166 "vulnerability_alert.summary",
167 "secret_scanning.bypass_requested",
168 "secret_scanning.bypass_reviewed",
169 "security_advisory.reported",
170 "security_advisory.published",
171];
172
173/// The integrations service's mirroring events (see
174/// `g1t_contracts::mirrors::MirrorEvent`). People are told only when the
175/// link's settings ask for the inbox, and the event names them.
176pub const MIRROR_EVENTS: [&str; 4] = ["mirror.unreachable", "mirror.reachable", "mirror.state_changed", "mirror.moved_in"];
177
178/// Where an event's items go: which thread, what it is, and where it is.
179#[derive(Clone, Debug, PartialEq, Eq)]
180pub struct Thread {
181 pub key: String,
182 pub kind: Option<SubjectKind>,
183 pub number: Option<u32>,
184 pub run_id: Option<String>,
185 /// A path, for a subject with a page of its own.
186 pub link: Option<String>,
187}
188
189/// The thread key of an issue or pull request.
190pub fn numbered_thread(repo_id: &str, number: u32) -> String {
191 format!("{repo_id}#{number}")
192}
193
194/// The thread an event's items go to.
195pub fn thread_of(event: &Event, wanted: &Wanted, subject: Option<&InboxSubject>) -> Thread {
196 let data = &event.data;
197 let text = |key: &str| data[key].as_str().filter(|value| !value.is_empty()).map(str::to_owned);
198 match event.kind.as_str() {
199 // A project's production, or one pull request's preview.
200 "deployment.failed" | "deployment.succeeded" => {
201 let which = wanted.number.map_or_else(|| "production".to_owned(), |number| number.to_string());
202 Thread {
203 key: format!("{}/deploy/{}/{which}", wanted.repo_id, text("projectId").unwrap_or_default()),
204 kind: Some(SubjectKind::Deploy),
205 number: wanted.number,
206 run_id: text("deploymentId"),
207 link: text("path"),
208 }
209 }
210 // One run's deployment to one environment, waiting for review.
211 "deployment.review_requested" => Thread {
212 key: format!(
213 "{}/review/{}/{}",
214 wanted.repo_id,
215 text("runId").unwrap_or_default(),
216 text("environment").unwrap_or_default()
217 ),
218 kind: Some(SubjectKind::Run),
219 number: None,
220 run_id: text("runId"),
221 link: text("link"),
222 },
223 // A workflow on a branch: its next failure bumps the same thread.
224 "workflow.completed" if subject.is_none() => {
225 let branch = text("ref").unwrap_or_default();
226 let branch = branch.strip_prefix("refs/heads/").unwrap_or(&branch).to_owned();
227 let workflow = text("path").or_else(|| text("workflow")).unwrap_or_default();
228 Thread {
229 key: format!("{}/run/{workflow}@{branch}", wanted.repo_id),
230 kind: Some(SubjectKind::Run),
231 number: None,
232 run_id: text("runId"),
233 link: None,
234 }
235 }
236 // A repository's mirror: one thread, its settings page the link.
237 kind if MIRROR_EVENTS.contains(&kind) => Thread {
238 key: format!("{}/mirror", wanted.repo_id),
239 kind: None,
240 number: None,
241 run_id: None,
242 link: text("link"),
243 },
244 // A repository's alerts of one type (`rep_1/security/vulnerability`),
245 // its reports, one advisory, or one bypass request: the page is the link.
246 kind if SECURITY_EVENTS.contains(&kind) => {
247 let which = match kind {
248 "security_advisory.reported" => "reports".to_owned(),
249 "security_advisory.published" => format!("advisories/{}", text("id").unwrap_or_default()),
250 _ if kind.ends_with(".summary") => text("alertType").unwrap_or_else(|| "alerts".to_owned()),
251 _ => text("requestId").or_else(|| text("alertId")).unwrap_or_else(|| event.id.clone()),
252 };
253 Thread {
254 key: format!("{}/security/{which}", wanted.repo_id),
255 kind: None,
256 number: None,
257 run_id: None,
258 link: text("link"),
259 }
260 }
261 _ => match wanted.number {
262 Some(number) => Thread {
263 key: numbered_thread(&wanted.repo_id, number),
264 kind: subject.and_then(|subject| subject.kind),
265 number: Some(number),
266 run_id: None,
267 link: None,
268 },
269 None => Thread {
270 key: format!("event/{}", event.id),
271 kind: None,
272 number: None,
273 run_id: None,
274 link: None,
275 },
276 },
277 }
278}
279
280/// The issue or pull request whose agent threads an event closes: what an
281/// agent was waiting on a person for is over.
282pub fn resolves(event: &Event) -> Option<String> {
283 if !RESUMES.contains(&event.kind.as_str()) {
284 return None;
285 }
286 let repo_id = event.data["repoId"].as_str().map(str::to_owned).or_else(|| event.repo_id.clone())?;
287 let number = event.data["number"].as_u64().and_then(|n| u32::try_from(n).ok())?;
288 Some(numbered_thread(&repo_id, number))
289}
290
291/// Collects who is told, each once with the most specific reason, never
292/// the actor, never g1t, and never anyone ignoring the thread.
293struct Told<'a> {
294 actor: &'a Actor,
295 audience: &'a Audience,
296 notices: Vec<Notice>,
297}
298
299impl Told<'_> {
300 /// `asked`: something asked of the person directly, told even when
301 /// they unsubscribed from the thread.
302 fn tell(&mut self, username: &str, reason: Reason, severity: Severity, title: &str, body: &str, asked: bool) {
303 let username = username.trim().trim_start_matches('@').to_lowercase();
304 if username.is_empty()
305 || is_g1t(&username)
306 || self.actor.is_named(&username)
307 || self.audience.ignores(&username)
308 || (!asked && self.audience.unsubscribed(&username))
309 {
310 return;
311 }
312 let notice = Notice {
313 username,
314 reason,
315 severity,
316 title: clip(title, MAX_TITLE),
317 body: clip(body, MAX_BODY),
318 };
319 match self.notices.iter_mut().find(|told| told.username == notice.username) {
320 Some(told) if notice.reason.rank() < told.reason.rank() => *told = notice,
321 Some(_) => {}
322 None => self.notices.push(notice),
323 }
324 }
325
326 /// A person known by id as well as name, such as an author.
327 fn tell_person(&mut self, person: &Principal, reason: Reason, severity: Severity, title: &str, body: &str, asked: bool) {
328 if is_g1t_id(&person.id) || self.actor.is(person) {
329 return;
330 }
331 self.tell(&person.username, reason, severity, title, body, asked);
332 }
333
334 /// Everyone subscribed to an issue or pull request: its owner and
335 /// author, its assignees and reviewers, and whoever subscribed by
336 /// commenting, being mentioned or by hand. `reason` overrides why
337 /// each is told, as a state change does.
338 fn tell_subscribed(&mut self, subject: &InboxSubject, reason: Option<Reason>, severity: Severity, title: &str, body: &str) {
339 let why = |own: Reason| reason.unwrap_or(own);
340 self.tell_person(subject.owner(), why(Reason::Author), severity, title, body, false);
341 self.tell_person(&subject.author, why(Reason::Author), severity, title, body, false);
342 for name in &subject.assignees {
343 self.tell(name, why(Reason::Assign), severity, title, body, false);
344 }
345 for name in &subject.reviewers {
346 self.tell(name, why(Reason::ReviewRequested), severity, title, body, false);
347 }
348 let subscribed: Vec<(String, Reason)> = self.audience.subscribed().collect();
349 for (name, own) in subscribed {
350 self.tell(&name, why(own), severity, title, body, false);
351 }
352 }
353
354 /// Everyone watching the repository for this kind of activity.
355 fn tell_watchers(&mut self, kind: &str, severity: Severity, title: &str, body: &str) {
356 let watching: Vec<String> = self.audience.watching(kind).collect();
357 for name in watching {
358 self.tell(&name, Reason::Subscribed, severity, title, body, false);
359 }
360 }
361}
362
363fn clip(text: &str, max: usize) -> String {
364 let text = text.trim();
365 if text.chars().count() <= max {
366 return text.to_owned();
367 }
368 let cut: String = text.chars().take(max - 1).collect();
369 format!("{}…", cut.trim_end())
370}
371
372/// The kind of activity a watcher chooses: `issues` or `pulls`.
373fn activity_of(subject: &InboxSubject) -> &'static str {
374 match subject.kind {
375 Some(SubjectKind::Pull) => "pulls",
376 _ => "issues",
377 }
378}
379
380/// The names in an event's list field, such as the reviewers just asked.
381/// The teams an event asked to review: each `workspace/slug` with the
382/// people it tells.
383fn teams_asked(data: &serde_json::Value) -> Vec<(String, Vec<String>)> {
384 data["teams"]
385 .as_array()
386 .map(|teams| {
387 teams
388 .iter()
389 .filter_map(|team| Some((team["team"].as_str()?.to_owned(), names(team, "notified"))))
390 .collect()
391 })
392 .unwrap_or_default()
393}
394
395fn names(data: &serde_json::Value, key: &str) -> Vec<String> {
396 data[key]
397 .as_array()
398 .map(|names| names.iter().filter_map(|name| name.as_str().map(str::to_owned)).collect())
399 .unwrap_or_default()
400}
401
402/// Who is told of `event`, in `repo` (`owner/name`), given what it names
403/// and who follows it. `actor` is who caused it; outcomes nobody chose
404/// (checks, workflows, deployments, g1t stopping) are told whoever caused them.
405pub fn notices(event: &Event, repo: &str, actor: &Actor, subject: Option<&InboxSubject>, audience: &Audience) -> Vec<Notice> {
406 let nobody = Actor::default();
407 let data = &event.data;
408 // The issue or pull request, as titles name it: `acme/rocket#12`.
409 let at = match data["number"].as_u64().or(data["pull"].as_u64()) {
410 Some(number) if subject.is_some() => format!("{repo}#{number}"),
411 _ => repo.to_owned(),
412 };
413 let outcome = matches!(
414 event.kind.as_str(),
415 "checks.completed"
416 | "workflow.completed"
417 | "pull.stalled"
418 | "deployment.failed"
419 | "deployment.succeeded"
420 | "deployment.review_requested"
421 ) || SECURITY_EVENTS.contains(&event.kind.as_str())
422 || MIRROR_EVENTS.contains(&event.kind.as_str());
423 let mut told = Told {
424 actor: if outcome { &nobody } else { actor },
425 audience,
426 notices: Vec::new(),
427 };
428 // Who did it, as titles name them.
429 let who = actor.name().unwrap_or("g1t");
430
431 match (event.kind.as_str(), subject) {
432 ("pull.stalled", Some(pull)) => {
433 let detail = data["detail"].as_str().map(str::trim).filter(|detail| !detail.is_empty());
434 let (title, body) = (format!("g1t stopped on {at} and needs you"), detail.unwrap_or(&pull.title).to_owned());
435 told.tell_person(pull.owner(), Reason::Agent, Severity::Warning, &title, &body, true);
436 if let Some(issue) = &pull.issue {
437 told.tell_person(issue.owner(), Reason::Agent, Severity::Warning, &title, &body, true);
438 for name in &issue.assignees {
439 told.tell(name, Reason::Agent, Severity::Warning, &title, &body, true);
440 }
441 }
442 }
443 ("pull.review_requested", Some(pull)) => {
444 // Asked because the CODEOWNERS file says they own what changed.
445 let owned = data["codeOwners"].as_bool() == Some(true);
446 let title = if owned {
447 format!("{at} changes files you own")
448 } else {
449 format!("{who} asked you to review {at}")
450 };
451 for name in names(data, "reviewers") {
452 told.tell(&name, Reason::ReviewRequested, Severity::Warning, &title, &pull.title, true);
453 }
454 for (team, people) in teams_asked(data) {
455 let title = if owned {
456 format!("{at} changes files @{team} owns")
457 } else {
458 format!("{who} asked @{team} to review {at}")
459 };
460 for name in people {
461 told.tell(&name, Reason::ReviewRequested, Severity::Warning, &title, &pull.title, true);
462 }
463 }
464 }
465 ("issue.assigned" | "pull.assigned", Some(on)) => {
466 let title = format!("{who} assigned you to {at}");
467 for name in names(data, "added") {
468 told.tell(&name, Reason::Assign, Severity::Info, &title, &on.title, true);
469 }
470 }
471 ("issue.opened" | "pull.opened", Some(on)) => {
472 let title = format!("{who} opened {at}");
473 for name in &on.assignees {
474 told.tell(name, Reason::Assign, Severity::Info, &format!("{who} assigned you to {at}"), &on.title, true);
475 }
476 for name in &on.reviewers {
477 told.tell(name, Reason::ReviewRequested, Severity::Warning, &format!("{who} asked you to review {at}"), &on.title, true);
478 }
479 for name in &on.mentions {
480 told.tell(name, Reason::Mention, Severity::Info, &format!("{who} mentioned you on {at}"), &on.title, true);
481 }
482 for team in &on.team_mentions {
483 let title = format!("{who} mentioned @{} on {at}", team.team);
484 for name in &team.members {
485 told.tell(name, Reason::TeamMention, Severity::Info, &title, &on.title, true);
486 }
487 }
488 told.tell_watchers(activity_of(on), Severity::Info, &title, &on.title);
489 }
490 ("checks.completed", Some(pull)) => {
491 let title = match data["status"].as_str() {
492 Some("errored") => format!("Checks could not run on {at}"),
493 _ => format!("Checks failed on {at}"),
494 };
495 told.tell_person(pull.owner(), Reason::CiActivity, Severity::Error, &title, &pull.title, true);
496 }
497 ("workflow.completed", subject) => {
498 let workflow = data["workflow"].as_str().filter(|name| !name.is_empty()).unwrap_or("A workflow");
499 match subject {
500 Some(pull) => {
501 let title = format!("{workflow} failed on {at}");
502 told.tell_person(pull.owner(), Reason::CiActivity, Severity::Error, &title, &pull.title, true);
503 }
504 None => {
505 // Not on a pull request: whoever pushed the commit it ran on.
506 let branch = data["ref"].as_str().unwrap_or_default();
507 let branch = branch.strip_prefix("refs/heads/").unwrap_or(branch);
508 let title = format!("{workflow} failed on {branch} in {repo}");
509 let body = format!("Run {} at {}", data["number"], short(data["sha"].as_str().unwrap_or_default()));
510 if let Some(id) = &actor.id
511 && !is_g1t_id(id)
512 && let Some(name) = &actor.username
513 {
514 told.tell(name, Reason::CiActivity, Severity::Error, &title, &body, true);
515 }
516 }
517 }
518 }
519 ("deployment.failed" | "deployment.succeeded", subject) => {
520 let failed = event.kind == "deployment.failed";
521 let project = data["project"].as_str().filter(|name| !name.is_empty()).unwrap_or(repo);
522 let what = match subject {
523 Some(_) => format!("The preview of {at}"),
524 None => format!("Production of {project}"),
525 };
526 let (title, severity) = if failed {
527 (format!("{what} failed to deploy"), Severity::Error)
528 } else {
529 (format!("{what} is live"), Severity::Success)
530 };
531 let body = match (failed, data["error"].as_str().map(str::trim).filter(|error| !error.is_empty())) {
532 (true, Some(error)) => error.to_owned(),
533 _ => match subject {
534 Some(pull) => pull.title.clone(),
535 None => format!("Commit {}", short(data["commit"].as_str().unwrap_or_default())),
536 },
537 };
538 // A success is news to whoever answers for it only after a failure.
539 if failed || data["recovered"].as_bool() == Some(true) {
540 let title = if failed { title.clone() } else { format!("{what} is live again") };
541 match subject {
542 Some(pull) => told.tell_person(pull.owner(), Reason::CiActivity, severity, &title, &body, true),
543 None => {
544 let pusher = actor
545 .id
546 .as_deref()
547 .filter(|id| !is_g1t_id(id))
548 .and(actor.username.as_deref())
549 .or_else(|| data["triggeredBy"].as_str());
550 if let Some(name) = pusher {
551 told.tell(name, Reason::CiActivity, severity, &title, &body, true);
552 }
553 }
554 }
555 }
556 told.tell_watchers("deployments", severity, &title, &body);
557 }
558 ("pull.merged" | "pull.closed" | "issue.closed" | "issue.reopened", Some(on)) => {
559 let (verb, severity) = match event.kind.as_str() {
560 "pull.merged" => ("merged", Severity::Success),
561 "issue.reopened" => ("reopened", Severity::Info),
562 _ => ("closed", Severity::Info),
563 };
564 let title = match (actor.name(), data["resolvedBy"].as_u64()) {
565 (_, Some(pull)) if event.kind == "issue.closed" => format!("{at} was closed by #{pull}"),
566 (Some(name), _) => format!("{name} {verb} {at}"),
567 (None, _) => format!("{at} was {verb}"),
568 };
569 told.tell_subscribed(on, Some(Reason::StateChange), severity, &title, &on.title);
570 told.tell_watchers(activity_of(on), severity, &title, &on.title);
571 }
572 ("deployment.review_requested", _) => {
573 let environment = data["environment"].as_str().unwrap_or("an environment");
574 let workflow = data["workflow"].as_str().unwrap_or("A workflow");
575 let title = format!("{workflow} is waiting for your review to deploy to {environment} in {repo}");
576 let body = data["title"].as_str().unwrap_or_default();
577 // Those the actions service names: the environment's reviewers.
578 for name in names(data, "notify") {
579 told.tell(&name, Reason::ReviewRequested, Severity::Warning, &title, body, true);
580 }
581 }
582 (kind, None) if MIRROR_EVENTS.contains(&kind) => {
583 let severity = match kind {
584 "mirror.unreachable" => Severity::Warning,
585 "mirror.state_changed" if data["state"].as_str() == Some("takeover") => Severity::Warning,
586 "mirror.state_changed" if data["state"].as_str() == Some("standby") => Severity::Success,
587 _ => Severity::Info,
588 };
589 let title = data["title"].as_str().unwrap_or("A mirror changed");
590 let body = data["detail"].as_str().unwrap_or_default();
591 for name in names(data, "notify") {
592 told.tell(&name, Reason::StateChange, severity, title, body, true);
593 }
594 }
595 (kind, None) if SECURITY_EVENTS.contains(&kind) => {
596 let what = data["title"].as_str().unwrap_or("A security alert");
597 match kind {
598 "secret_scanning.bypass_requested" => {
599 let title = format!("{who} asked to bypass push protection in {repo}");
600 for name in names(data, "notify") {
601 told.tell(&name, Reason::SecurityAlert, Severity::Warning, &title, what, true);
602 }
603 }
604 "secret_scanning.bypass_reviewed" => {
605 let verdict = data["state"].as_str().unwrap_or("reviewed");
606 let title = format!("Your request to bypass push protection in {repo} was {verdict}");
607 for name in names(data, "notify") {
608 told.tell(&name, Reason::SecurityAlert, Severity::Info, &title, what, true);
609 }
610 }
611 // Something to act on: the owners and security managers, at once.
612 "security_advisory.reported" => {
613 let title = format!("A vulnerability was reported privately to {repo}");
614 for name in names(data, "notify") {
615 told.tell(&name, Reason::SecurityAlert, Severity::Warning, &title, what, true);
616 }
617 }
618 // Published for everyone: watchers who chose security.
619 "security_advisory.published" => {
620 let title = format!("{repo} published a security advisory");
621 told.tell_watchers("security", Severity::Info, &title, what);
622 }
623 // A scan's summary. One that opened nothing is no news: it
624 // brings the thread up to date instead (deliver_one). Whether
625 // what is not urgent is told now or in a digest is each
626 // person's choice, applied there too.
627 _ => {
628 let Some(summary) = security_summary(event) else {
629 return told.notices;
630 };
631 if summary.opened_count == 0 {
632 return told.notices;
633 }
634 let severity = if summary.urgent() { Severity::Error } else { Severity::Info };
635 let (title, pushed) = summary_titles(repo, &summary);
636 let body = summary.latest.clone().unwrap_or_default();
637 // Whoever pushed a refused push must act: told at once, whatever was found.
638 if let Some(pusher) = &summary.pusher {
639 told.tell(pusher, Reason::SecurityAlert, Severity::Error, &pushed, &body, true);
640 }
641 for name in &summary.notify {
642 told.tell(name, Reason::SecurityAlert, severity, &title, &body, true);
643 }
644 // Watchers who chose security alerts, if they may see findings:
645 // the service lists who may (`members`), as findings are never
646 // shown to someone who cannot change the code.
647 let members = names(data, "members");
648 let watching: Vec<String> = told.audience.watching("security").collect();
649 for name in watching.iter().filter(|name| members.iter().any(|member| member.eq_ignore_ascii_case(name))) {
650 told.tell(name, Reason::SecurityAlert, severity, &title, &body, false);
651 }
652 }
653 }
654 }
655 ("comment.created", Some(on)) => {
656 let Some(comment) = on.comment.as_ref().filter(|comment| !comment.event) else {
657 return Vec::new();
658 };
659 // Whoever wrote it is the actor, whatever the event says. One of
660 // the workspace's agents is shown by its name, marked as an
661 // agent; its handle is not a person's, so nobody is left out
662 // for sharing it, and whoever it acted for hears of it as of
663 // anything they set off.
664 let writer = match &comment.agent {
665 Some(agent) => Actor { id: Some(agent.id.clone()), username: None },
666 None => Actor {
667 id: Some(comment.author.id.clone()),
668 username: Some(comment.author.username.clone()),
669 },
670 };
671 told.actor = &writer;
672 let who = match &comment.agent {
673 Some(agent) => format!("{} (agent)", agent.display_name),
674 None => comment.author.username.clone(),
675 };
676 let advisory = if comment.advisory { " (advisory)" } else { "" };
677 let body = if comment.excerpt.is_empty() { &on.title } else { &comment.excerpt };
678 for name in &comment.mentions {
679 let title = format!("{who} mentioned you on {at}");
680 told.tell(name, Reason::Mention, Severity::Info, &title, body, true);
681 }
682 for team in &comment.team_mentions {
683 let title = format!("{who} mentioned @{} on {at}", team.team);
684 for name in &team.members {
685 told.tell(name, Reason::TeamMention, Severity::Info, &title, body, true);
686 }
687 }
688 let (severity, title) = match comment.verdict.as_deref() {
689 Some("approve") => (Severity::Success, format!("{who} approved {at}{advisory}")),
690 Some("request_changes") => (Severity::Info, format!("{who} asked for changes on {at}{advisory}")),
691 _ if comment.advisory => (Severity::Info, format!("{who} reviewed {at}{advisory}")),
692 _ => (Severity::Info, format!("{who} commented on {at}")),
693 };
694 // An approval or a request for changes (or an agent's review)
695 // is the owner's to hear of whatever they chose; the rest, as
696 // they subscribed.
697 if comment.verdict.is_some() || comment.advisory {
698 told.tell_person(on.owner(), Reason::Author, severity, &title, body, true);
699 }
700 told.tell_subscribed(on, None, severity, &title, body);
701 told.tell_watchers(activity_of(on), severity, &title, body);
702 return told.notices;
703 }
704 _ => {}
705 }
706 told.notices
707}
708
709/// Who an event subscribes to its issue or pull request without asking,
710/// and why: whoever commented, whoever they mentioned, the people assigned
711/// and the reviewers asked. Never g1t.
712pub fn subscribes(event: &Event, subject: Option<&InboxSubject>) -> Vec<(String, Reason)> {
713 let mut people: Vec<(String, Reason)> = Vec::new();
714 let mut add = |name: &str, reason: Reason| {
715 let name = name.trim().trim_start_matches('@').to_lowercase();
716 if !name.is_empty() && !is_g1t(&name) && !people.iter().any(|(had, _)| *had == name) {
717 people.push((name, reason));
718 }
719 };
720 match event.kind.as_str() {
721 "comment.created" => {
722 if let Some(comment) = subject.and_then(|subject| subject.comment.as_ref()).filter(|comment| !comment.event) {
723 // An agent is no person to subscribe; its handle may be someone's name.
724 if !is_g1t_id(&comment.author.id) && comment.agent.is_none() {
725 add(&comment.author.username, Reason::Comment);
726 }
727 for name in &comment.mentions {
728 add(name, Reason::Mention);
729 }
730 for team in &comment.team_mentions {
731 for name in &team.members {
732 add(name, Reason::TeamMention);
733 }
734 }
735 }
736 }
737 "issue.opened" | "pull.opened" => {
738 if let Some(on) = subject {
739 for name in &on.mentions {
740 add(name, Reason::Mention);
741 }
742 for team in &on.team_mentions {
743 for name in &team.members {
744 add(name, Reason::TeamMention);
745 }
746 }
747 }
748 }
749 "issue.assigned" | "pull.assigned" => {
750 for name in names(&event.data, "added") {
751 add(&name, Reason::Assign);
752 }
753 }
754 "pull.review_requested" => {
755 for name in names(&event.data, "reviewers") {
756 add(&name, Reason::ReviewRequested);
757 }
758 for (_, people) in teams_asked(&event.data) {
759 for name in people {
760 add(&name, Reason::ReviewRequested);
761 }
762 }
763 }
764 _ => {}
765 }
766 people
767}
768
769fn short(sha: &str) -> &str {
770 sha.get(..7).unwrap_or(sha)
771}
772
773// --- Security summaries ------------------------------------------------------
774
775/// The scan summary a `<type>_alert.summary` event carries.
776pub fn security_summary(event: &Event) -> Option<SecuritySummary> {
777 if !event.kind.ends_with("_alert.summary") {
778 return None;
779 }
780 serde_json::from_value(event.data.clone()).ok()
781}
782
783/// "1 critical, 2 high": the counts that are not zero, worst first.
784pub fn breakdown(counts: &SeverityCounts) -> String {
785 [("critical", counts.critical), ("high", counts.high), ("medium", counts.medium), ("low", counts.low), ("unknown", counts.unknown)]
786 .into_iter()
787 .filter(|(_, n)| *n > 0)
788 .map(|(name, n)| format!("{n} {name}"))
789 .collect::<Vec<_>>()
790 .join(", ")
791}
792
793/// "vulnerability" or "vulnerabilities", as a count wants.
794fn alerts_called(alert_type: &str, n: u32) -> &'static str {
795 match (AlertType::parse(alert_type), n) {
796 (Some(AlertType::SecretScanning), 1) => "secret",
797 (Some(AlertType::SecretScanning), _) => "secrets",
798 (Some(AlertType::CodeScanning), 1) => "code scanning alert",
799 (Some(AlertType::CodeScanning), _) => "code scanning alerts",
800 (Some(AlertType::Vulnerability), 1) => "vulnerability",
801 (Some(AlertType::Vulnerability), _) => "vulnerabilities",
802 (None, 1) => "security alert",
803 (None, _) => "security alerts",
804 }
805}
806
807/// What a scan's item says to those who look after the repository ("3 new
808/// vulnerabilities in acme/rocket: 1 critical, 2 high"), and to whoever
809/// pushed a push that was refused.
810pub fn summary_titles(repo: &str, summary: &SecuritySummary) -> (String, String) {
811 let n = summary.opened_count;
812 let counts = breakdown(&summary.new_by_severity);
813 let title = if counts.is_empty() {
814 format!("{n} new {} in {repo}", alerts_called(&summary.alert_type, n))
815 } else {
816 format!("{n} new {} in {repo}: {counts}", alerts_called(&summary.alert_type, n))
817 };
818 let pushed = match summary.blocked {
819 0 | 1 => format!("A push to {repo} was blocked: it adds a secret"),
820 n => format!("A push to {repo} was blocked: it adds {n} secrets"),
821 };
822 (title, pushed)
823}
824
825/// What a scan that opened nothing makes the thread say: how many alerts
826/// are open now ("2 open vulnerabilities in acme/rocket: 2 high"), or that
827/// none is, with what changed as the line of history.
828pub fn refreshed_text(repo: &str, summary: &SecuritySummary) -> (String, String) {
829 let open = summary.open_total();
830 let mut changes = Vec::new();
831 if summary.fixed_count > 0 {
832 changes.push(format!("{} fixed", summary.fixed_count));
833 }
834 if summary.dismissed_count > 0 {
835 changes.push(format!("{} dismissed", summary.dismissed_count));
836 }
837 let title = if open == 0 {
838 format!("No open {} in {repo}", alerts_called(&summary.alert_type, 2))
839 } else {
840 format!("{open} open {} in {repo}: {}", alerts_called(&summary.alert_type, open), breakdown(&summary.open))
841 };
842 (title, changes.join(", "))
843}
844
845/// Where a scan summary's notice goes for one person.
846#[derive(Clone, Copy, Debug, PartialEq, Eq)]
847pub enum Delivery {
848 /// Their inbox, now.
849 Now,
850 /// Their next security digest.
851 Digest,
852 /// Nowhere.
853 Never,
854}
855
856/// The policy: critical and high alerts, and a refused push, reach the
857/// people the service names (the workspace's owners and security managers,
858/// the pusher) at once whatever they chose, and watchers at once unless
859/// they turned security alerts off. Everything else waits for the person's
860/// digest, or comes at once or never, as they chose.
861pub fn security_delivery(summary: &SecuritySummary, username: &str, settings: &InboxSettings) -> Delivery {
862 if summary.urgent() {
863 let named = summary.notify.iter().any(|name| name.eq_ignore_ascii_case(username))
864 || summary.pusher.as_deref().is_some_and(|pusher| pusher.eq_ignore_ascii_case(username));
865 return if named || settings.security_alerts { Delivery::Now } else { Delivery::Never };
866 }
867 match settings.security_digest {
868 DigestCadence::AtOnce => Delivery::Now,
869 DigestCadence::Daily | DigestCadence::Weekly => Delivery::Digest,
870 DigestCadence::Off => Delivery::Never,
871 }
872}
873
874/// Brings every person's thread about a repository's alerts of one type up
875/// to date after a scan that opened nothing: the title says what is open
876/// now, a line of history says what changed, and a thread with nothing
877/// left open is done. Nobody is woken: what was read stays read, and the
878/// thread keeps its place.
879async fn refresh_security_thread(db: &D1Database, thread: &str, repo: &str, summary: &SecuritySummary, event: &Event) -> Result<()> {
880 let (title, body) = refreshed_text(repo, summary);
881 let now = now_ms();
882 let at = rfc3339(now);
883 let settled = i32::from(summary.open_total() == 0);
884 db.batch(vec![
885 db.prepare(
886 "UPDATE inbox_items SET event_id = ?1, event = ?2, title = ?3, body = ?4, updated_at = ?5, activity = activity + 1,
887 done_at = CASE WHEN ?6 = 1 THEN COALESCE(done_at, ?5) ELSE done_at END,
888 read_at = CASE WHEN ?6 = 1 THEN COALESCE(read_at, ?5) ELSE read_at END
889 WHERE thread = ?7
890 AND NOT EXISTS (SELECT 1 FROM inbox_activity a WHERE a.event_id = ?1 AND a.username = inbox_items.username)",
891 )
892 .bind(&[
893 event.id.as_str().into(),
894 event.kind.as_str().into(),
895 title.as_str().into(),
896 body.as_str().into(),
897 at.as_str().into(),
898 settled.into(),
899 thread.into(),
900 ])?,
901 db.prepare(
902 "INSERT OR IGNORE INTO inbox_activity (id, item_id, username, event_id, event, reason, severity, title, body, actor, created_at)
903 SELECT ?1 || ':' || username, id, username, ?2, ?3, 'security_alert', 'info', ?4, ?5, NULL, ?6 FROM inbox_items WHERE thread = ?7",
904 )
905 .bind(&[
906 new_id("ntf", now).into(),
907 event.id.as_str().into(),
908 event.kind.as_str().into(),
909 title.as_str().into(),
910 body.as_str().into(),
911 event.time.as_str().into(),
912 thread.into(),
913 ])?,
914 ])
915 .await?;
916 Ok(())
917}
918
919/// Where an item is on g1t.sh.
920pub fn url(repo: Option<&str>, subject: Option<SubjectKind>, number: Option<u32>, run_id: Option<&str>, link: Option<&str>) -> String {
921 if let Some(link) = link.filter(|link| link.starts_with('/')) {
922 return link.to_owned();
923 }
924 let Some(repo) = repo else {
925 return "/inbox".to_owned();
926 };
927 match (subject, number, run_id) {
928 (Some(SubjectKind::Pull), Some(number), _) => format!("/{repo}/pull/{number}"),
929 (Some(SubjectKind::Issue), Some(number), _) => format!("/{repo}/issues/{number}"),
930 (Some(SubjectKind::Run), _, Some(run)) => format!("/{repo}/actions/runs/{run}"),
931 (Some(SubjectKind::Deploy), Some(number), _) => format!("/{repo}/pull/{number}"),
932 _ => format!("/{repo}"),
933 }
934}
935
936// --- Writing ---------------------------------------------------------------
937
938/// The services the inbox reads from as events arrive.
939pub struct Sources<'a> {
940 pub work: &'a Fetcher,
941 pub repos: &'a Fetcher,
942 pub identity: &'a Fetcher,
943 /// The notify service, told of each new item for live toasts and pushes; None, nobody is.
944 pub notify: Option<&'a Fetcher>,
945}
946
947/// One notice written, and whether it was news (not a redelivery): what
948/// may be emailed.
949struct Written {
950 notice: Notice,
951 repo_id: String,
952 url: String,
953 event_id: String,
954}
955
956/// Writes the items a batch from the bus calls for. Never fails the batch:
957/// what cannot be worked out is logged and left.
958pub async fn deliver(db: &D1Database, sources: &Sources<'_>, events: &[Event]) {
959 if let Err(error) = resolve(db, events).await {
960 worker::console_error!("inbox: agent threads not closed: {error}");
961 }
962 // A workspace's own notices, about no repository (workspace_notices).
963 for event in events.iter().filter(|event| WORKSPACE_EVENTS.contains(&event.kind.as_str())) {
964 if let Err(error) = deliver_workspace(db, event).await {
965 worker::console_error!("inbox: {} {} not delivered: {error}", event.kind, event.id);
966 } else if let Some(notify) = sources.notify {
967 // Notify: the feed tells each person once per event, redelivered or not.
968 let (_, told) = workspace_notices(event, None);
969 let link = event.data["link"].as_str().filter(|link| link.starts_with('/')).unwrap_or("/inbox");
970 let live = told.iter().map(|notice| (notice.username.clone(), live_notification(&event.id, notice, link, &event.time))).collect();
971 tell_live(notify, live).await;
972 for notice in &told {
973 tell_inbox_count(db, notify, &notice.username).await;
974 }
975 }
976 }
977 let wanted: Vec<(&Event, Wanted)> = events
978 .iter()
979 .filter_map(|event| wants(event).map(|wanted| (event, wanted)))
980 .collect();
981 let created: Vec<&Event> = events.iter().filter(|event| event.kind == "repo.created").collect();
982 if wanted.is_empty() && created.is_empty() {
983 return;
984 }
985 // Everyone who caused one, named in one call.
986 let ids: Vec<String> = wanted
987 .iter()
988 .map(|(event, _)| *event)
989 .chain(created.iter().copied())
990 .filter_map(|event| event.actor.clone())
991 .filter(|id| !is_g1t_id(id))
992 .collect::<HashSet<_>>()
993 .into_iter()
994 .collect();
995 let names: HashMap<String, String> = if ids.is_empty() {
996 HashMap::new()
997 } else {
998 g1t_kit::call(sources.identity, "usernames", &UsernamesArgs { ids })
999 .await
1000 .unwrap_or_else(|error| {
1001 worker::console_error!("inbox: could not name who acted: {error}");
1002 HashMap::new()
1003 })
1004 };
1005 for event in created {
1006 if let Err(error) = subscriptions::watch_created(db, event, &names).await {
1007 worker::console_error!("inbox: {} {} not watched: {error}", event.kind, event.id);
1008 }
1009 }
1010 let mut paths: HashMap<String, Option<RepoPath>> = HashMap::new();
1011 let mut watchers: HashMap<String, Vec<subscriptions::Watcher>> = HashMap::new();
1012 let mut written: Vec<Written> = Vec::new();
1013 for (event, wanted) in wanted {
1014 match deliver_one(db, sources, &names, &mut paths, &mut watchers, event, wanted).await {
1015 Ok(mut news) => written.append(&mut news),
1016 Err(error) => worker::console_error!("inbox: {} {} not delivered: {error}", event.kind, event.id),
1017 }
1018 }
1019 // Notify: every item that was news, live in the person's tabs (services/notify).
1020 if let Some(notify) = sources.notify {
1021 let live = written
1022 .iter()
1023 .map(|item| (item.notice.username.clone(), live_notification(&item.event_id, &item.notice, &item.url, &rfc3339(now_ms()))))
1024 .collect::<Vec<_>>();
1025 tell_live(notify, live).await;
1026 let people: HashSet<&str> = written.iter().map(|item| item.notice.username.as_str()).collect();
1027 for username in people {
1028 tell_inbox_count(db, notify, username).await;
1029 }
1030 }
1031 if let Err(error) = email(db, sources.identity, written).await {
1032 worker::console_error!("inbox: emails not sent: {error}");
1033 }
1034}
1035
1036/// Events about a workspace rather than a repository, each naming who to
1037/// tell (`notify`), what to say (`title`, `body`) and where it is (`link`):
1038/// identity's personal access token approvals.
1039///
1040/// | Event | Who | Reason | Severity |
1041/// | --- | --- | --- | --- |
1042/// | `token.approval_requested` | the workspace's owners | review_requested | warning |
1043/// | `token.approval_reviewed` | the token's owner | author | info |
1044/// | `workspace_invitation.created` | the person invited | review_requested | warning |
1045/// | `workspace_invitation.accepted` | who invited them | author | success |
1046/// | `workspace_invitation.declined` | who invited them | author | info |
1047///
1048/// An invitation's item for the person invited is done once it is
1049/// accepted, declined or revoked (`workspace_invitation.revoked`, which
1050/// tells nobody).
1051pub const WORKSPACE_EVENTS: [&str; 5] = [
1052 "token.approval_requested",
1053 "token.approval_reviewed",
1054 "workspace_invitation.created",
1055 "workspace_invitation.accepted",
1056 "workspace_invitation.declined",
1057];
1058
1059/// Events that close what a workspace invitation asked of its person.
1060pub const INVITATION_ANSWERED: [&str; 3] =
1061 ["workspace_invitation.accepted", "workspace_invitation.declined", "workspace_invitation.revoked"];
1062
1063/// The notices a workspace event calls for, and the thread they go to.
1064pub fn workspace_notices(event: &Event, actor: Option<&str>) -> (String, Vec<Notice>) {
1065 let data = &event.data;
1066 let text = |key: &str| data[key].as_str().unwrap_or_default().to_owned();
1067 let (reason, severity) = match event.kind.as_str() {
1068 "token.approval_requested" | "workspace_invitation.created" => (Reason::ReviewRequested, Severity::Warning),
1069 "workspace_invitation.accepted" => (Reason::Author, Severity::Success),
1070 _ => (Reason::Author, Severity::Info),
1071 };
1072 // An invitation names its own thread; a token approval's is the token's.
1073 let thread = match data["thread"].as_str().filter(|thread| !thread.is_empty()) {
1074 Some(thread) => thread.to_owned(),
1075 None => format!("workspace:{}/token/{}", text("workspace"), text("tokenId")),
1076 };
1077 let notices = names(data, "notify")
1078 .into_iter()
1079 .map(|name| name.to_lowercase())
1080 .filter(|name| actor.is_none_or(|actor| !actor.eq_ignore_ascii_case(name)) && !is_g1t(name))
1081 .collect::<HashSet<_>>()
1082 .into_iter()
1083 .map(|username| Notice { username, reason, severity, title: text("title"), body: text("body") })
1084 .collect();
1085 (thread, notices)
1086}
1087
1088/// Writes a workspace event's notices: a thread each, with no repository.
1089async fn deliver_workspace(db: &D1Database, event: &Event) -> Result<()> {
1090 let (thread, told) = workspace_notices(event, None);
1091 if told.is_empty() {
1092 return Ok(());
1093 }
1094 let now = now_ms();
1095 let workspace = event.data["workspace"].as_str().unwrap_or_default().to_lowercase();
1096 let link = event.data["link"].as_str().filter(|link| link.starts_with('/'));
1097 let mut statements = Vec::new();
1098 for notice in &told {
1099 let username = notice.username.as_str();
1100 statements.push(db.prepare(BUMP).bind(&[
1101 new_id("ntf", now).into(),
1102 username.into(),
1103 thread.as_str().into(),
1104 event.id.as_str().into(),
1105 event.kind.as_str().into(),
1106 notice.reason.as_str().into(),
1107 notice.severity.as_str().into(),
1108 notice.title.as_str().into(),
1109 notice.body.as_str().into(),
1110 workspace.as_str().into(),
1111 JsValue::NULL,
1112 JsValue::NULL,
1113 JsValue::NULL,
1114 JsValue::NULL,
1115 JsValue::NULL,
1116 link.map_or(JsValue::NULL, JsValue::from),
1117 JsValue::NULL,
1118 event.time.as_str().into(),
1119 new_id("ntf", now).into(),
1120 ])?);
1121 statements.push(
1122 db.prepare(
1123 "INSERT OR IGNORE INTO inbox_activity (id, item_id, username, event_id, event, reason, severity, title, body, actor, created_at)
1124 SELECT ?1, id, ?2, ?4, ?5, ?6, ?7, ?8, ?9, NULL, ?10 FROM inbox_items WHERE username = ?2 AND thread = ?3",
1125 )
1126 .bind(&[
1127 new_id("ntf", now).into(),
1128 username.into(),
1129 thread.as_str().into(),
1130 event.id.as_str().into(),
1131 event.kind.as_str().into(),
1132 notice.reason.as_str().into(),
1133 notice.severity.as_str().into(),
1134 notice.title.as_str().into(),
1135 notice.body.as_str().into(),
1136 event.time.as_str().into(),
1137 ])?,
1138 );
1139 }
1140 db.batch(statements).await?;
1141 Ok(())
1142}
1143
1144/// Closes what an agent was waiting on a person for once it is over.
1145async fn resolve(db: &D1Database, events: &[Event]) -> Result<()> {
1146 let now = rfc3339(now_ms());
1147 let mut statements = Vec::new();
1148 for thread in events.iter().filter_map(resolves) {
1149 statements.push(
1150 db.prepare(
1151 "UPDATE inbox_items SET done_at = ?1, read_at = COALESCE(read_at, ?1)
1152 WHERE thread = ?2 AND reason = 'agent' AND done_at IS NULL",
1153 )
1154 .bind(&[now.as_str().into(), thread.into()])?,
1155 );
1156 }
1157 // A workspace invitation answered or revoked no longer waits on its person.
1158 for event in events.iter().filter(|event| INVITATION_ANSWERED.contains(&event.kind.as_str())) {
1159 let Some(thread) = event.data["thread"].as_str().filter(|thread| thread.starts_with("invitation:")) else {
1160 continue;
1161 };
1162 statements.push(
1163 db.prepare(
1164 "UPDATE inbox_items SET done_at = ?1, read_at = COALESCE(read_at, ?1)
1165 WHERE thread = ?2 AND reason = 'review_requested' AND done_at IS NULL",
1166 )
1167 .bind(&[now.as_str().into(), thread.into()])?,
1168 );
1169 }
1170 // Reviews no longer asked for are no longer waiting.
1171 for event in events.iter().filter(|event| event.kind == "pull.review_request_removed") {
1172 let (Some(repo_id), Some(number)) = (
1173 event.data["repoId"].as_str().map(str::to_owned).or_else(|| event.repo_id.clone()),
1174 event.data["number"].as_u64(),
1175 ) else {
1176 continue;
1177 };
1178 for name in names(&event.data, "reviewers") {
1179 statements.push(
1180 db.prepare(
1181 "UPDATE inbox_items SET done_at = ?1, read_at = COALESCE(read_at, ?1)
1182 WHERE thread = ?2 AND username = ?3 AND reason = 'review_requested' AND done_at IS NULL",
1183 )
1184 .bind(&[
1185 now.as_str().into(),
1186 format!("{repo_id}#{number}").into(),
1187 name.to_lowercase().into(),
1188 ])?,
1189 );
1190 }
1191 }
1192 if !statements.is_empty() {
1193 db.batch(statements).await?;
1194 }
1195 Ok(())
1196}
1197
1198async fn deliver_one(
1199 db: &D1Database,
1200 sources: &Sources<'_>,
1201 names: &HashMap<String, String>,
1202 paths: &mut HashMap<String, Option<RepoPath>>,
1203 watchers: &mut HashMap<String, Vec<subscriptions::Watcher>>,
1204 event: &Event,
1205 wanted: Wanted,
1206) -> Result<Vec<Written>> {
1207 if !paths.contains_key(&wanted.repo_id) {
1208 let path: Option<RepoPath> = g1t_kit::call(
1209 sources.repos,
1210 "path_by_id",
1211 &PathByIdArgs {
1212 id: wanted.repo_id.clone(),
1213 },
1214 )
1215 .await?;
1216 paths.insert(wanted.repo_id.clone(), path);
1217 }
1218 // A repository that is gone tells nobody.
1219 let Some(path) = paths.get(&wanted.repo_id).cloned().flatten() else {
1220 return Ok(Vec::new());
1221 };
1222 let subject: Option<InboxSubject> = match wanted.number {
1223 Some(number) => {
1224 let found: Option<InboxSubject> = g1t_kit::call(
1225 sources.work,
1226 "inbox_subject",
1227 &InboxSubjectArgs {
1228 repo_id: wanted.repo_id.clone(),
1229 number,
1230 comment_id: wanted.comment_id.clone(),
1231 },
1232 )
1233 .await?;
1234 if found.is_none() {
1235 return Ok(Vec::new());
1236 }
1237 found
1238 }
1239 None => None,
1240 };
1241 let actor = Actor {
1242 id: event.actor.clone(),
1243 username: match event.actor.as_deref() {
1244 Some(id) if is_g1t_id(id) => Some(system::USERNAME.to_owned()),
1245 Some(id) => names.get(id).map(|name| name.to_lowercase()),
1246 None => None,
1247 },
1248 };
1249 let thread = thread_of(event, &wanted, subject.as_ref());
1250 if !watchers.contains_key(&wanted.repo_id) {
1251 watchers.insert(wanted.repo_id.clone(), subscriptions::watchers(db, &wanted.repo_id).await?);
1252 }
1253 let audience = Audience {
1254 subscriptions: match thread.kind {
1255 Some(SubjectKind::Issue | SubjectKind::Pull) => subscriptions::of_thread(db, &thread.key).await?,
1256 _ => Vec::new(),
1257 },
1258 watchers: watchers.get(&wanted.repo_id).cloned().unwrap_or_default(),
1259 };
1260 let repo = format!("{}/{}", path.namespace, path.name).to_lowercase();
1261 let mut told = notices(event, &repo, &actor, subject.as_ref(), &audience);
1262 let mut statements = subscriptions::auto_subscribe(db, &thread.key, &wanted.repo_id, &subscribes(event, subject.as_ref()), &event.time)?;
1263 // A scan's summary: one that opened nothing brings the thread up to date
1264 // without waking anyone, and what is not urgent waits for each person's
1265 // digest, or comes at once or never, as they chose (security_delivery).
1266 if let Some(summary) = security_summary(event) {
1267 if summary.opened_count == 0 {
1268 refresh_security_thread(db, &thread.key, &repo, &summary, event).await?;
1269 return Ok(Vec::new());
1270 }
1271 let people: Vec<String> = told.iter().map(|notice| notice.username.clone()).collect();
1272 let settings = subscriptions::settings_of(db, &people).await?;
1273 let now = now_ms();
1274 let mut kept = Vec::with_capacity(told.len());
1275 for notice in told {
1276 let setting = settings.get(&notice.username).cloned().unwrap_or_default();
1277 match security_delivery(&summary, &notice.username, &setting) {
1278 Delivery::Now => kept.push(notice),
1279 Delivery::Digest => statements.push(crate::security_digest::queue(db, &notice.username, &path, &summary, &event.id, now)?),
1280 Delivery::Never => {}
1281 }
1282 }
1283 told = kept;
1284 }
1285 if told.is_empty() {
1286 if !statements.is_empty() {
1287 db.batch(statements).await?;
1288 }
1289 return Ok(Vec::new());
1290 }
1291 let now = now_ms();
1292 let link = thread.link.as_deref();
1293 let item_url = url(Some(&repo), thread.kind, thread.number, thread.run_id.as_deref(), link);
1294 // Three statements a notice: its thread brought up (unless this event
1295 // was told before), a line of history, and the history kept short.
1296 let first = statements.len();
1297 for notice in &told {
1298 let username = notice.username.as_str();
1299 let values: Vec<JsValue> = vec![
1300 new_id("ntf", now).into(),
1301 username.into(),
1302 thread.key.as_str().into(),
1303 event.id.as_str().into(),
1304 event.kind.as_str().into(),
1305 notice.reason.as_str().into(),
1306 notice.severity.as_str().into(),
1307 notice.title.as_str().into(),
1308 notice.body.as_str().into(),
1309 path.namespace.to_lowercase().into(),
1310 wanted.repo_id.as_str().into(),
1311 repo.as_str().into(),
1312 thread.kind.map_or(JsValue::NULL, |kind| kind.as_str().into()),
1313 thread.number.map_or(JsValue::NULL, JsValue::from),
1314 thread.run_id.as_deref().map_or(JsValue::NULL, JsValue::from),
1315 link.map_or(JsValue::NULL, JsValue::from),
1316 actor.username.as_deref().map_or(JsValue::NULL, JsValue::from),
1317 event.time.as_str().into(),
1318 // Same prefix as item ids, so old and new sort by time together.
1319 new_id("ntf", now).into(),
1320 ];
1321 statements.push(db.prepare(BUMP).bind(&values)?);
1322 statements.push(
1323 db.prepare(
1324 "INSERT OR IGNORE INTO inbox_activity (id, item_id, username, event_id, event, reason, severity, title, body, actor, created_at)
1325 SELECT ?1, id, ?2, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11 FROM inbox_items WHERE username = ?2 AND thread = ?3
1326 RETURNING username",
1327 )
1328 .bind(&[
1329 new_id("ntf", now).into(),
1330 username.into(),
1331 thread.key.as_str().into(),
1332 event.id.as_str().into(),
1333 event.kind.as_str().into(),
1334 notice.reason.as_str().into(),
1335 notice.severity.as_str().into(),
1336 notice.title.as_str().into(),
1337 notice.body.as_str().into(),
1338 actor.username.as_deref().map_or(JsValue::NULL, JsValue::from),
1339 event.time.as_str().into(),
1340 ])?,
1341 );
1342 statements.push(
1343 db.prepare(
1344 "DELETE FROM inbox_activity
1345 WHERE item_id = (SELECT id FROM inbox_items WHERE username = ?1 AND thread = ?2)
1346 AND id NOT IN (
1347 SELECT a.id FROM inbox_activity a
1348 WHERE a.item_id = (SELECT id FROM inbox_items WHERE username = ?1 AND thread = ?2)
1349 ORDER BY a.id DESC LIMIT ?3)",
1350 )
1351 .bind(&[username.into(), thread.key.as_str().into(), MAX_ACTIVITY.into()])?,
1352 );
1353 }
1354 let results = db.batch(statements).await?;
1355 #[derive(Deserialize)]
1356 struct Told {
1357 username: String,
1358 }
1359 // A line of history written means the event is news to that person.
1360 let mut news = HashSet::new();
1361 for (at, _) in told.iter().enumerate() {
1362 if let Some(result) = results.get(first + at * 3 + 1)
1363 && let Ok(rows) = result.results::<Told>()
1364 {
1365 news.extend(rows.into_iter().map(|row| row.username));
1366 }
1367 }
1368 Ok(told
1369 .into_iter()
1370 .filter(|notice| news.contains(&notice.username))
1371 .map(|notice| Written {
1372 notice,
1373 repo_id: wanted.repo_id.clone(),
1374 url: item_url.clone(),
1375 event_id: event.id.clone(),
1376 })
1377 .collect())
1378}
1379
1380/// Brings a person's thread up with new activity, or starts it. `?1` id,
1381/// `?2` username, `?3` thread, `?4` event id, `?5` event type, `?6` reason,
1382/// `?7` severity, `?8` title, `?9` body, `?10` workspace, `?11` repo id,
1383/// `?12` repo, `?13` subject, `?14` number, `?15` run id, `?16` link, `?17`
1384/// actor, `?18` time, `?19` the time-sortable id lists order by. Nothing
1385/// happens when the person was already told of this event. While the
1386/// thread is unread its most urgent severity is kept; done or not, it
1387/// comes back to the inbox. A snooze stands.
1388pub(crate) const BUMP: &str = "INSERT INTO inbox_items (id, username, thread, event_id, event, reason, severity, title, body,
1389 workspace, repo_id, repo, subject, number, run_id, link, actor, created_at, updated_at, bumped, activity)
1390 SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?18, ?19, 1
1391 WHERE NOT EXISTS (SELECT 1 FROM inbox_activity WHERE event_id = ?4 AND username = ?2)
1392 ON CONFLICT (username, thread) DO UPDATE SET
1393 event_id = excluded.event_id,
1394 event = excluded.event,
1395 reason = excluded.reason,
1396 severity = CASE
1397 WHEN inbox_items.read_at IS NULL AND inbox_items.done_at IS NULL
1398 AND (CASE inbox_items.severity WHEN 'warning' THEN 0 WHEN 'error' THEN 1 WHEN 'success' THEN 2 ELSE 3 END)
1399 < (CASE excluded.severity WHEN 'warning' THEN 0 WHEN 'error' THEN 1 WHEN 'success' THEN 2 ELSE 3 END)
1400 THEN inbox_items.severity ELSE excluded.severity END,
1401 title = excluded.title,
1402 body = excluded.body,
1403 workspace = excluded.workspace,
1404 repo = excluded.repo,
1405 subject = COALESCE(excluded.subject, inbox_items.subject),
1406 run_id = COALESCE(excluded.run_id, inbox_items.run_id),
1407 link = COALESCE(excluded.link, inbox_items.link),
1408 actor = excluded.actor,
1409 updated_at = excluded.updated_at,
1410 bumped = excluded.bumped,
1411 activity = inbox_items.activity + 1,
1412 read_at = NULL,
1413 done_at = NULL";
1414
1415/// What the notify service is told of an inbox item (`FeedNotification` in
1416/// @g1t/contracts): its kind from why the person was told, the workspace
1417/// from where it links, and the item's title and first line.
1418pub fn live_notification(event_id: &str, notice: &Notice, url: &str, at: &str) -> serde_json::Value {
1419 let kind = match notice.reason {
1420 Reason::ReviewRequested => "approval",
1421 Reason::Mention | Reason::TeamMention => "mention",
1422 // A critical or high alert, a refused push, a report or a bypass to
1423 // review: toasted like a mention. A digest, or what came at once by
1424 // choice, is an ordinary inbox item.
1425 Reason::SecurityAlert if notice.severity != Severity::Info => "security",
1426 _ => "inbox",
1427 };
1428 let path = url.split(['?', '#']).next().unwrap_or_default();
1429 let mut segments = path.trim_start_matches('/').split('/');
1430 let workspace = segments.next().unwrap_or_default().to_lowercase();
1431 let repo = segments.next().map(|name| format!("{workspace}/{name}"));
1432 let name = repo.unwrap_or_else(|| if workspace.is_empty() { "g1t".to_owned() } else { workspace.clone() });
1433 serde_json::json!({
1434 "id": format!("inbox:{event_id}"),
1435 "kind": kind,
1436 "workspace": workspace,
1437 "title": notice.title,
1438 "body": clip(&notice.body, 140),
1439 "href": if url.starts_with('/') { url } else { "/inbox" },
1440 "actor": { "kind": "system", "id": name, "name": name },
1441 "created_at": at,
1442 })
1443}
1444
1445/// What the notify service is told when a person's inbox count changes
1446/// (its `set_inbox`): the count as it now is, never a difference, so a
1447/// call repeated or out of order still ends right.
1448pub fn inbox_count_update(username: &str, unread: u32) -> serde_json::Value {
1449 serde_json::json!({ "username": username.to_lowercase(), "unread": unread })
1450}
1451
1452/// Tells the notify service a person's unread count as it now is, so every
1453/// tab of theirs shows it at once: after items arrive, and after marks made
1454/// anywhere (the site, the API, MCP). Logged and left when it fails.
1455pub async fn tell_inbox_count(db: &D1Database, notify: &Fetcher, username: &str) {
1456 let counted = counts(db, InboxCountsArgs { username: username.to_owned() }).await;
1457 let told: Result<serde_json::Value> = match counted {
1458 Ok(counts) => g1t_kit::call(notify, "set_inbox", &inbox_count_update(username, counts.unread)).await,
1459 Err(error) => Err(error),
1460 };
1461 if let Err(error) = told {
1462 worker::console_error!("inbox: live count not sent: {error}");
1463 }
1464}
1465
1466/// Hands items to the notify service, one call each. Logged and left when it
1467/// cannot be reached: the inbox and email do not wait on it.
1468pub(crate) async fn tell_live(notify: &Fetcher, items: Vec<(String, serde_json::Value)>) {
1469 #[derive(serde::Serialize)]
1470 struct NotifyArgs {
1471 username: String,
1472 notification: serde_json::Value,
1473 }
1474 for (username, notification) in items {
1475 let told: Result<serde_json::Value> = g1t_kit::call(notify, "notify", &NotifyArgs { username, notification }).await;
1476 if let Err(error) = told {
1477 worker::console_error!("inbox: live notification not sent: {error}");
1478 }
1479 }
1480}
1481
1482/// Emails what was news to people who asked to be emailed for its reason.
1483/// Identity sends each, only to a confirmed address and only if the person
1484/// can still read the repository.
1485async fn email(db: &D1Database, identity: &Fetcher, written: Vec<Written>) -> Result<()> {
1486 if written.is_empty() {
1487 return Ok(());
1488 }
1489 let people: Vec<String> = written
1490 .iter()
1491 .map(|item| item.notice.username.clone())
1492 .collect::<HashSet<_>>()
1493 .into_iter()
1494 .collect();
1495 let settings = subscriptions::settings_of(db, &people).await?;
1496 for item in written {
1497 let wants = settings.get(&item.notice.username).map_or(&DEFAULT_EMAIL[..], |settings| &settings.email[..]);
1498 if !wants.contains(&item.notice.reason) {
1499 continue;
1500 }
1501 let sent: Result<bool> = g1t_kit::call(
1502 identity,
1503 "notify_by_email",
1504 &NotifyByEmailArgs {
1505 username: item.notice.username.clone(),
1506 repo_id: item.repo_id.clone(),
1507 subject: item.notice.title.clone(),
1508 intro: item.notice.body.clone(),
1509 quote: None,
1510 path: item.url.clone(),
1511 reason: item.notice.reason,
1512 },
1513 )
1514 .await;
1515 if let Err(error) = sent {
1516 worker::console_error!("inbox: email to {} not sent: {error}", item.notice.username);
1517 }
1518 }
1519 Ok(())
1520}
1521
1522// --- Reading and changing ----------------------------------------------------
1523
1524#[derive(Deserialize)]
1525pub(crate) struct Row {
1526 pub(crate) id: String,
1527 reason: String,
1528 severity: String,
1529 title: String,
1530 body: String,
1531 event: Option<String>,
1532 workspace: Option<String>,
1533 pub(crate) repo_id: Option<String>,
1534 repo: Option<String>,
1535 subject: Option<String>,
1536 number: Option<f64>,
1537 run_id: Option<String>,
1538 link: Option<String>,
1539 actor: Option<String>,
1540 activity: Option<f64>,
1541 created_at: String,
1542 updated_at: Option<String>,
1543 read_at: Option<String>,
1544 done_at: Option<String>,
1545 saved: f64,
1546 snoozed_until: Option<String>,
1547 bumped: Option<String>,
1548}
1549
1550impl Row {
1551 pub(crate) fn into_item(self) -> InboxItem {
1552 let subject = self.subject.as_deref().and_then(SubjectKind::parse);
1553 let number = self.number.map(|n| n as u32);
1554 InboxItem {
1555 url: url(self.repo.as_deref(), subject, number, self.run_id.as_deref(), self.link.as_deref()),
1556 id: self.id,
1557 reason: Reason::parse(&self.reason).unwrap_or(Reason::Subscribed),
1558 severity: Severity::parse(&self.severity).unwrap_or(Severity::Info),
1559 title: self.title,
1560 body: self.body,
1561 event: self.event,
1562 repo: self.repo,
1563 workspace: self.workspace,
1564 subject,
1565 number,
1566 actor: self.actor,
1567 count: self.activity.map_or(1, |n| n as u32),
1568 updated_at: self.updated_at.unwrap_or_else(|| self.created_at.clone()),
1569 created_at: self.created_at,
1570 read_at: self.read_at,
1571 done_at: self.done_at,
1572 saved: self.saved != 0.0,
1573 snoozed_until: self.snoozed_until,
1574 }
1575 }
1576}
1577
1578pub(crate) const COLUMNS: &str = "id, reason, severity, title, body, event, workspace, repo_id, repo, subject, number, run_id,
1579 link, actor, activity, created_at, updated_at, read_at, done_at, saved, snoozed_until, bumped";
1580
1581/// The conditions that pick a view's items, after `username = ?1`; `?2` is now.
1582fn view_filter(view: InboxView) -> &'static str {
1583 match view {
1584 InboxView::Inbox => "done_at IS NULL AND (snoozed_until IS NULL OR snoozed_until <= ?2)",
1585 InboxView::Saved => "saved = 1",
1586 InboxView::Done => "done_at IS NOT NULL",
1587 }
1588}
1589
1590/// Whether a list ranks unread warnings first: the inbox itself, unfiltered.
1591fn ranked(a: &ListInboxArgs) -> bool {
1592 a.view == InboxView::Inbox
1593 && a.severity.is_none()
1594 && a.reason.is_none()
1595 && !a.participating
1596 && a.repo_id.is_none()
1597 && !a.unread
1598 && a.since.is_none()
1599 && a.updated_before.is_none()
1600}
1601
1602/// The conditions a list's filters add, and the values they bind, numbered
1603/// after the `bound` values already given.
1604fn filters(a: &ListInboxArgs, bound: usize) -> (Vec<String>, Vec<String>) {
1605 let mut conditions = Vec::new();
1606 let mut values: Vec<String> = Vec::new();
1607 let mut bind = |value: &str, condition: &str| {
1608 values.push(value.to_owned());
1609 conditions.push(condition.replace('?', &format!("?{}", bound + values.len())));
1610 };
1611 if let Some(severity) = a.severity {
1612 bind(severity.as_str(), "severity = ?");
1613 }
1614 if let Some(reason) = a.reason {
1615 bind(reason.as_str(), "reason = ?");
1616 }
1617 if let Some(repo_id) = &a.repo_id {
1618 bind(repo_id, "repo_id = ?");
1619 }
1620 if let Some(since) = &a.since {
1621 bind(since.trim(), "COALESCE(updated_at, created_at) >= ?");
1622 }
1623 if let Some(before) = &a.updated_before {
1624 bind(before.trim(), "COALESCE(updated_at, created_at) < ?");
1625 }
1626 if a.participating {
1627 conditions.push("reason NOT IN ('manual', 'subscribed')".to_owned());
1628 }
1629 if a.unread {
1630 conditions.push("read_at IS NULL".to_owned());
1631 }
1632 (conditions, values)
1633}
1634
1635pub async fn list(db: &D1Database, repos: &Fetcher, a: ListInboxArgs) -> Result<InboxPage> {
1636 let Some(viewer) = &a.viewer else {
1637 return Ok(InboxPage::default());
1638 };
1639 let username = viewer.username.to_lowercase();
1640 let now = rfc3339(now_ms());
1641 let limit = a.limit.unwrap_or(DEFAULT_INBOX_PAGE).clamp(1, MAX_INBOX_PAGE);
1642 let mut values: Vec<JsValue> = vec![username.as_str().into(), now.as_str().into()];
1643 let mut conditions = vec!["username = ?1".to_owned(), view_filter(a.view).to_owned()];
1644 let (filtered, bound) = filters(&a, values.len());
1645 conditions.extend(filtered);
1646 values.extend(bound.iter().map(|value| JsValue::from(value.as_str())));
1647 let ranked = ranked(&a);
1648 // Unread warnings lead the first page, and are left out of the rest.
1649 let leading = "severity = 'warning' AND read_at IS NULL";
1650 let mut rest = conditions.clone();
1651 let mut rest_values = values.clone();
1652 if ranked {
1653 rest.push(format!("NOT ({leading})"));
1654 }
1655 if let Some(before) = &a.before {
1656 rest_values.push(before.as_str().into());
1657 rest.push(format!("bumped < ?{}", rest_values.len()));
1658 }
1659 rest_values.push((limit + 1).into());
1660 let order = if a.view == InboxView::Done { "done_at DESC, bumped DESC" } else { "bumped DESC" };
1661 let mut statements = vec![
1662 db.prepare(format!(
1663 "SELECT {COLUMNS} FROM inbox_items WHERE {} ORDER BY {order} LIMIT ?{}",
1664 rest.join(" AND "),
1665 rest_values.len()
1666 ))
1667 .bind(&rest_values)?,
1668 ];
1669 if ranked && a.before.is_none() {
1670 statements.push(
1671 db.prepare(format!(
1672 "SELECT {COLUMNS} FROM inbox_items WHERE {} AND {leading} ORDER BY bumped DESC LIMIT ?3",
1673 conditions.join(" AND ")
1674 ))
1675 .bind(&[username.as_str().into(), now.as_str().into(), MAX_RANKED.into()])?,
1676 );
1677 }
1678 let results = db.batch(statements).await?;
1679 let mut rows = results.first().map(|result| result.results::<Row>()).transpose()?.unwrap_or_default();
1680 let next = if rows.len() > limit as usize {
1681 rows.truncate(limit as usize);
1682 rows.last().map(|row| row.bumped.clone().unwrap_or_else(|| row.id.clone()))
1683 } else {
1684 None
1685 };
1686 let mut items: Vec<Row> = results.get(1).map(|result| result.results::<Row>()).transpose()?.unwrap_or_default();
1687 items.extend(rows);
1688 let items = readable_only(db, repos, &a.viewer, &username, items).await?;
1689 Ok(InboxPage {
1690 items: items.into_iter().map(Row::into_item).collect(),
1691 next,
1692 })
1693}
1694
1695/// Rows about repositories the viewer can still read; the rest are
1696/// removed from their inbox as they are found.
1697pub(crate) async fn readable_only(db: &D1Database, repos: &Fetcher, viewer: &g1t_contracts::Viewer, username: &str, mut rows: Vec<Row>) -> Result<Vec<Row>> {
1698 let ids: Vec<String> = rows
1699 .iter()
1700 .filter_map(|row| row.repo_id.clone())
1701 .collect::<HashSet<_>>()
1702 .into_iter()
1703 .collect();
1704 if ids.is_empty() {
1705 return Ok(rows);
1706 }
1707 let readable: Vec<Repo> = g1t_kit::call(
1708 repos,
1709 "readable",
1710 &ReadableArgs {
1711 ids: ids.clone(),
1712 viewer: viewer.clone(),
1713 },
1714 )
1715 .await?;
1716 let readable: HashSet<String> = readable.into_iter().map(|repo| repo.id).collect();
1717 let gone: Vec<String> = ids.into_iter().filter(|id| !readable.contains(id)).collect();
1718 if !gone.is_empty() {
1719 forget(db, username, &gone).await?;
1720 rows.retain(|row| row.repo_id.as_ref().is_none_or(|id| !gone.contains(id)));
1721 }
1722 Ok(rows)
1723}
1724
1725/// Removes a person's items about repositories they cannot read.
1726async fn forget(db: &D1Database, username: &str, repo_ids: &[String]) -> Result<()> {
1727 let marks = vec!["?"; repo_ids.len()].join(", ");
1728 let mut values: Vec<JsValue> = vec![username.into()];
1729 values.extend(repo_ids.iter().map(|id| JsValue::from(id.as_str())));
1730 db.batch(vec![
1731 db.prepare(format!(
1732 "DELETE FROM inbox_activity WHERE item_id IN (SELECT id FROM inbox_items WHERE username = ? AND repo_id IN ({marks}))"
1733 ))
1734 .bind(&values)?,
1735 db.prepare(format!("DELETE FROM inbox_items WHERE username = ? AND repo_id IN ({marks})"))
1736 .bind(&values)?,
1737 ])
1738 .await?;
1739 Ok(())
1740}
1741
1742#[derive(Deserialize)]
1743struct CountRow {
1744 severity: String,
1745 n: f64,
1746}
1747
1748pub async fn counts(db: &D1Database, a: InboxCountsArgs) -> Result<InboxCounts> {
1749 let rows = db
1750 .prepare(
1751 "SELECT severity, count(*) AS n FROM inbox_items
1752 WHERE username = ? AND read_at IS NULL AND done_at IS NULL
1753 AND (snoozed_until IS NULL OR snoozed_until <= ?)
1754 GROUP BY severity",
1755 )
1756 .bind(&[a.username.to_lowercase().into(), rfc3339(now_ms()).into()])?
1757 .all()
1758 .await?
1759 .results::<CountRow>()?;
1760 let mut counts = InboxCounts::default();
1761 for row in rows {
1762 let n = row.n as u32;
1763 counts.unread += n;
1764 match Severity::parse(&row.severity) {
1765 Some(Severity::Error) => counts.error += n,
1766 Some(Severity::Warning) => counts.warning += n,
1767 Some(Severity::Success) => counts.success += n,
1768 Some(Severity::Info) | None => counts.info += n,
1769 }
1770 }
1771 Ok(counts)
1772}
1773
1774/// The change a mark makes, as a `SET` clause; `?1` is now.
1775fn mark_change(mark: InboxMark) -> &'static str {
1776 match mark {
1777 InboxMark::Read => "read_at = COALESCE(read_at, ?1)",
1778 InboxMark::Unread => "read_at = NULL",
1779 InboxMark::Done => "done_at = ?1, read_at = COALESCE(read_at, ?1)",
1780 InboxMark::Undone => "done_at = NULL",
1781 InboxMark::Save => "saved = 1",
1782 InboxMark::Unsave => "saved = 0",
1783 InboxMark::Snooze => "snoozed_until = ?2, read_at = COALESCE(read_at, ?1)",
1784 InboxMark::Unsnooze => "snoozed_until = NULL",
1785 }
1786}
1787
1788#[derive(Deserialize)]
1789struct IdRow {
1790 #[allow(dead_code)]
1791 id: String,
1792}
1793
1794/// Changes the person's own items. Returns how many changed.
1795pub async fn mark(db: &D1Database, a: MarkInboxArgs) -> Result<u32> {
1796 let now = rfc3339(now_ms());
1797 let until = match (a.mark, a.until.as_deref().map(str::trim)) {
1798 // Times compare as text (`g1t_contracts::time`); a snooze is for later.
1799 (InboxMark::Snooze, Some(until)) if until.len() == now.len() && until > now.as_str() => until.to_owned(),
1800 (InboxMark::Snooze, _) => return Ok(0),
1801 _ => String::new(),
1802 };
1803 let mut values: Vec<JsValue> = vec![now.as_str().into(), until.as_str().into(), a.username.to_lowercase().into()];
1804 let target = if a.all && a.ids.is_empty() {
1805 let mut target = "done_at IS NULL".to_owned();
1806 let mut bind = |values: &mut Vec<JsValue>, value: &str, condition: &str| {
1807 values.push(value.into());
1808 target.push_str(&format!(" AND {}", condition.replace('?', &format!("?{}", values.len()))));
1809 };
1810 if let Some(severity) = a.severity {
1811 bind(&mut values, severity.as_str(), "severity = ?");
1812 }
1813 if let Some(repo_id) = &a.repo_id {
1814 bind(&mut values, repo_id, "repo_id = ?");
1815 }
1816 if let Some(last_read_at) = a.last_read_at.as_deref().map(str::trim).filter(|at| !at.is_empty()) {
1817 bind(&mut values, last_read_at, "COALESCE(updated_at, created_at) <= ?");
1818 }
1819 target
1820 } else {
1821 let ids: Vec<&String> = a.ids.iter().take(MAX_MARK).collect();
1822 if ids.is_empty() {
1823 return Ok(0);
1824 }
1825 let first = values.len() + 1;
1826 values.extend(ids.iter().map(|id| JsValue::from(id.as_str())));
1827 let marks: Vec<String> = (first..values.len() + 1).map(|at| format!("?{at}")).collect();
1828 format!("id IN ({})", marks.join(", "))
1829 };
1830 let changed = db
1831 .prepare(format!(
1832 "UPDATE inbox_items SET {} WHERE username = ?3 AND {target} RETURNING id",
1833 mark_change(a.mark)
1834 ))
1835 .bind(&values)?
1836 .all()
1837 .await?
1838 .results::<IdRow>()?;
1839 Ok(changed.len() as u32)
1840}
1841
1842#[derive(Deserialize)]
1843struct ActivityRow {
1844 reason: String,
1845 severity: String,
1846 title: String,
1847 body: String,
1848 event: Option<String>,
1849 actor: Option<String>,
1850 created_at: String,
1851}
1852
1853/// One of the viewer's threads, with its history and their subscription.
1854pub async fn thread(db: &D1Database, repos: &Fetcher, work: &Fetcher, a: ThreadArgs) -> Result<Option<InboxThread>> {
1855 let Some(viewer) = &a.viewer else {
1856 return Ok(None);
1857 };
1858 let username = viewer.username.to_lowercase();
1859 let row = db
1860 .prepare(format!("SELECT {COLUMNS} FROM inbox_items WHERE id = ? AND username = ?"))
1861 .bind(&[a.id.as_str().into(), username.as_str().into()])?
1862 .first::<Row>(None)
1863 .await?;
1864 let Some(row) = readable_only(db, repos, &a.viewer, &username, row.into_iter().collect()).await?.pop() else {
1865 return Ok(None);
1866 };
1867 let activity = db
1868 .prepare(
1869 "SELECT reason, severity, title, body, event, actor, created_at FROM inbox_activity
1870 WHERE item_id = ? ORDER BY id DESC LIMIT ?",
1871 )
1872 .bind(&[row.id.as_str().into(), MAX_ACTIVITY.into()])?
1873 .all()
1874 .await?
1875 .results::<ActivityRow>()?
1876 .into_iter()
1877 .map(|row| InboxActivity {
1878 reason: Reason::parse(&row.reason).unwrap_or(Reason::Subscribed),
1879 severity: Severity::parse(&row.severity).unwrap_or(Severity::Info),
1880 title: row.title,
1881 body: row.body,
1882 event: row.event,
1883 actor: row.actor,
1884 created_at: row.created_at,
1885 })
1886 .collect();
1887 let item = row.into_item();
1888 let subscription = match (item.subject, item.number) {
1889 (Some(SubjectKind::Issue | SubjectKind::Pull), Some(_)) => {
1890 subscriptions::subscription(
1891 db,
1892 work,
1893 SubscriptionArgs {
1894 viewer: a.viewer.clone(),
1895 id: Some(item.id.clone()),
1896 ..SubscriptionArgs::default()
1897 },
1898 )
1899 .await?
1900 }
1901 _ => None,
1902 };
1903 Ok(Some(InboxThread {
1904 item,
1905 activity,
1906 subscription,
1907 }))
1908}
1909
1910// --- Keeping up ------------------------------------------------------------------
1911
1912/// Moves rows with renamed workspaces and repositories, and drops those
1913/// of purged repositories, deleted workspaces and purged accounts.
1914pub async fn follow(db: &D1Database, events: &[Event]) -> Result<()> {
1915 let mut statements = Vec::new();
1916 for event in events {
1917 let text = |key: &str| event.data[key].as_str().unwrap_or_default().to_lowercase();
1918 match event.kind.as_str() {
1919 "workspace.renamed" => {
1920 let Ok(renamed) = serde_json::from_value::<WorkspaceRenamed>(event.data.clone()) else {
1921 continue;
1922 };
1923 let (from, to) = (renamed.from.to_lowercase(), renamed.to.to_lowercase());
1924 if from == to {
1925 continue;
1926 }
1927 statements.push(
1928 db.prepare(
1929 "UPDATE inbox_items SET repo = ?2 || substr(repo, length(?1) + 1), workspace = ?2,
1930 link = CASE WHEN link LIKE '/' || ?1 || '/%' THEN '/' || ?2 || substr(link, length(?1) + 2) ELSE link END
1931 WHERE workspace = ?1",
1932 )
1933 .bind(&[from.as_str().into(), to.as_str().into()])?,
1934 );
1935 statements.push(
1936 db.prepare("UPDATE inbox_watching SET repo = ?2 || substr(repo, length(?1) + 1) WHERE repo LIKE ?1 || '/%'")
1937 .bind(&[from.as_str().into(), to.as_str().into()])?,
1938 );
1939 }
1940 "repo.renamed" => {
1941 let path = format!("{}/{}", text("namespace"), text("to"));
1942 for table in ["inbox_items", "inbox_watching"] {
1943 statements.push(
1944 db.prepare(format!("UPDATE {table} SET repo = ? WHERE repo_id = ?"))
1945 .bind(&[path.as_str().into(), text("repoId").into()])?,
1946 );
1947 }
1948 }
1949 "repo.transferred" => {
1950 let path = format!("{}/{}", text("to"), text("name"));
1951 statements.push(
1952 db.prepare("UPDATE inbox_items SET repo = ?, workspace = ? WHERE repo_id = ?")
1953 .bind(&[path.as_str().into(), text("to").into(), text("repoId").into()])?,
1954 );
1955 statements.push(
1956 db.prepare("UPDATE inbox_watching SET repo = ? WHERE repo_id = ?")
1957 .bind(&[path.as_str().into(), text("repoId").into()])?,
1958 );
1959 }
1960 "repo.purged" => {
1961 for sql in [
1962 "DELETE FROM inbox_activity WHERE item_id IN (SELECT id FROM inbox_items WHERE repo_id = ?)",
1963 "DELETE FROM inbox_items WHERE repo_id = ?",
1964 "DELETE FROM inbox_subscriptions WHERE repo_id = ?",
1965 "DELETE FROM inbox_watching WHERE repo_id = ?",
1966 ] {
1967 statements.push(db.prepare(sql).bind(&[text("repoId").into()])?);
1968 }
1969 }
1970 "workspace.deleted" => {
1971 statements.push(
1972 db.prepare("DELETE FROM inbox_items WHERE workspace = ?")
1973 .bind(&[text("slug").into()])?,
1974 );
1975 statements.push(
1976 db.prepare("DELETE FROM inbox_watching WHERE repo LIKE ? || '/%'")
1977 .bind(&[text("slug").into()])?,
1978 );
1979 }
1980 // An account purged: its inbox, what it watched and its
1981 // settings go with it (identity's account_deletion.rs).
1982 "user.deleted" => {
1983 let username = text("username");
1984 if username.is_empty() {
1985 continue;
1986 }
1987 for sql in [
1988 "DELETE FROM inbox_activity WHERE username = ?",
1989 "DELETE FROM inbox_items WHERE username = ?",
1990 "DELETE FROM inbox_subscriptions WHERE username = ?",
1991 "DELETE FROM inbox_watching WHERE username = ?",
1992 "DELETE FROM inbox_settings WHERE username = ?",
1993 ] {
1994 statements.push(db.prepare(sql).bind(&[username.as_str().into()])?);
1995 }
1996 }
1997 _ => {}
1998 }
1999 }
2000 if !statements.is_empty() {
2001 db.batch(statements).await?;
2002 }
2003 Ok(())
2004}
2005
2006/// Removes items done more than [`DONE_DAYS`] ago, and any not saved older
2007/// than [`MAX_DAYS`], with their history. Returns how many went.
2008pub async fn purge(db: &D1Database, now: u64) -> Result<u32> {
2009 let done = crate::audit::keep_from(now, DONE_DAYS);
2010 let oldest = crate::audit::keep_from(now, MAX_DAYS);
2011 let statements: Vec<D1PreparedStatement> = vec![
2012 db.prepare("DELETE FROM inbox_items WHERE saved = 0 AND done_at < ?")
2013 .bind(&[done.into()])?,
2014 db.prepare("DELETE FROM inbox_items WHERE saved = 0 AND COALESCE(updated_at, created_at) < ?")
2015 .bind(&[oldest.into()])?,
2016 db.prepare("DELETE FROM inbox_activity WHERE NOT EXISTS (SELECT 1 FROM inbox_items WHERE inbox_items.id = inbox_activity.item_id)"),
2017 ];
2018 let results = db.batch(statements).await?;
2019 let mut removed = 0;
2020 for result in results.into_iter().take(2) {
2021 removed += result.meta()?.and_then(|meta| meta.changes).unwrap_or(0) as u32;
2022 }
2023 Ok(removed)
2024}
2025
2026#[cfg(test)]
2027mod tests {
2028 use super::*;
2029 use crate::subscriptions::{State, Subscription, Watcher};
2030 use serde_json::json;
2031
2032 fn event(kind: &str, actor: Option<&str>, data: serde_json::Value) -> Event {
2033 Event {
2034 id: "evt_1".into(),
2035 kind: kind.into(),
2036 source: "work".into(),
2037 time: "2026-10-07T12:00:00.000Z".into(),
2038 repo_id: Some("rep_1".into()),
2039 actor: actor.map(str::to_owned),
2040 data,
2041 }
2042 }
2043
2044 fn person(id: &str, username: &str) -> Principal {
2045 Principal {
2046 id: id.into(),
2047 username: username.into(),
2048 }
2049 }
2050
2051 fn actor(id: &str, username: &str) -> Actor {
2052 Actor {
2053 id: Some(id.into()),
2054 username: Some(username.into()),
2055 }
2056 }
2057
2058 /// A pull request ana opened, assigned to bo, for an issue cy filed and dee is assigned.
2059 fn pull() -> InboxSubject {
2060 InboxSubject {
2061 kind: Some(SubjectKind::Pull),
2062 title: "Add the inbox".into(),
2063 author: person("usr_ana", "ana"),
2064 assignees: vec!["bo".into()],
2065 issue: Some(Box::new(InboxSubject {
2066 kind: Some(SubjectKind::Issue),
2067 title: "An inbox".into(),
2068 author: person("usr_cy", "cy"),
2069 assignees: vec!["dee".into()],
2070 ..InboxSubject::default()
2071 })),
2072 ..InboxSubject::default()
2073 }
2074 }
2075
2076 /// A change g1t made for ana.
2077 fn g1t_pull() -> InboxSubject {
2078 InboxSubject {
2079 author: person(AGENT_ID, "g1t"),
2080 requested_by: Some(person("usr_ana", "ana")),
2081 ..pull()
2082 }
2083 }
2084
2085 fn nobody() -> Audience {
2086 Audience::default()
2087 }
2088
2089 fn told(notices: &[Notice]) -> Vec<(&str, Reason, Severity)> {
2090 notices
2091 .iter()
2092 .map(|notice| (notice.username.as_str(), notice.reason, notice.severity))
2093 .collect()
2094 }
2095
2096 fn comment(author: Principal, body: &str, mentions: &[&str]) -> InboxSubject {
2097 InboxSubject {
2098 comment: Some(InboxComment {
2099 author,
2100 excerpt: body.into(),
2101 mentions: mentions.iter().map(|name| (*name).to_owned()).collect(),
2102 ..InboxComment::default()
2103 }),
2104 ..pull()
2105 }
2106 }
2107
2108 fn subscribed(rows: &[(&str, State, Option<Reason>)]) -> Audience {
2109 Audience {
2110 subscriptions: rows
2111 .iter()
2112 .map(|(name, state, reason)| Subscription {
2113 username: (*name).into(),
2114 state: *state,
2115 reason: *reason,
2116 })
2117 .collect(),
2118 watchers: Vec::new(),
2119 }
2120 }
2121
2122 fn watched(rows: &[(&str, WatchLevel, &[&str])]) -> Audience {
2123 Audience {
2124 subscriptions: Vec::new(),
2125 watchers: rows
2126 .iter()
2127 .map(|(name, level, events)| Watcher {
2128 username: (*name).into(),
2129 level: *level,
2130 events: events.iter().map(|kind| (*kind).to_owned()).collect(),
2131 })
2132 .collect(),
2133 }
2134 }
2135
2136 #[test]
2137 fn only_events_that_tell_someone_are_read() {
2138 let asked = |kind: &str, data| wants(&event(kind, None, data));
2139 assert_eq!(
2140 asked("checks.completed", json!({ "repoId": "rep_1", "number": 4, "status": "failed" })),
2141 Some(Wanted { repo_id: "rep_1".into(), number: Some(4), comment_id: None })
2142 );
2143 assert_eq!(asked("checks.completed", json!({ "repoId": "rep_1", "number": 4, "status": "passed" })), None);
2144 assert_eq!(asked("review.completed", json!({ "repoId": "rep_1", "number": 4, "verdict": "approve" })), None);
2145 assert_eq!(asked("agent.asked", json!({ "repoId": "rep_1", "number": 4 })), None);
2146 assert_eq!(asked("workflow.completed", json!({ "repoId": "rep_1", "conclusion": "success" })), None);
2147 assert_eq!(
2148 asked("workflow.completed", json!({ "repoId": "rep_1", "conclusion": "failure" })),
2149 Some(Wanted { repo_id: "rep_1".into(), number: None, comment_id: None })
2150 );
2151 assert_eq!(
2152 asked("comment.created", json!({ "repoId": "rep_1", "number": 2, "commentId": "cmt_1" })).map(|w| w.comment_id),
2153 Some(Some("cmt_1".into()))
2154 );
2155 assert_eq!(asked("git.push", json!({ "repoId": "rep_1" })), None);
2156 for kind in ["issue.opened", "pull.review_requested", "pull.stalled", "issue.assigned", "pull.closed", "issue.reopened"] {
2157 assert!(asked(kind, json!({ "repoId": "rep_1", "number": 1 })).is_some(), "{kind}");
2158 }
2159 assert_eq!(asked("deployment.failed", json!({ "repoId": "rep_1" })).map(|w| w.number), Some(None));
2160 }
2161
2162 #[test]
2163 fn a_stopped_pull_request_needs_its_people_and_its_issues_people_first() {
2164 let stalled = event("pull.stalled", None, json!({ "number": 7 }));
2165 let notices_ = notices(&stalled, "acme/rocket", &Actor::default(), Some(&pull()), &nobody());
2166 assert_eq!(
2167 told(&notices_),
2168 vec![
2169 ("ana", Reason::Agent, Severity::Warning),
2170 ("cy", Reason::Agent, Severity::Warning),
2171 ("dee", Reason::Agent, Severity::Warning),
2172 ]
2173 );
2174 assert_eq!(notices_[0].title, "g1t stopped on acme/rocket#7 and needs you");
2175 assert_eq!(notices_[0].body, "Add the inbox");
2176 // Stopping says why; even someone who unsubscribed hears of it.
2177 let stalled = event("pull.stalled", None, json!({ "number": 7, "detail": "Its checks could not be run." }));
2178 let audience = subscribed(&[("ana", State::Unsubscribed, None)]);
2179 let notices_ = notices(&stalled, "acme/rocket", &Actor::default(), Some(&g1t_pull()), &audience);
2180 assert_eq!(notices_[0].username, "ana");
2181 assert_eq!(notices_[0].title, "g1t stopped on acme/rocket#7 and needs you");
2182 assert_eq!(notices_[0].body, "Its checks could not be run.");
2183 // Ignoring the thread silences even that.
2184 let audience = subscribed(&[("ana", State::Ignored, None)]);
2185 let notices_ = notices(&stalled, "acme/rocket", &Actor::default(), Some(&g1t_pull()), &audience);
2186 assert!(!notices_.iter().any(|notice| notice.username == "ana"));
2187 }
2188
2189 #[test]
2190 fn whatever_an_agent_waits_on_closes_when_it_goes_on() {
2191 for kind in RESUMES {
2192 assert_eq!(resolves(&event(kind, None, json!({ "repoId": "rep_1", "number": 7 }))), Some("rep_1#7".into()));
2193 }
2194 assert_eq!(resolves(&event("comment.created", None, json!({ "repoId": "rep_1", "number": 7 }))), None);
2195 }
2196
2197 #[test]
2198 fn a_deployments_reviewers_are_told() {
2199 let asked = event(
2200 "deployment.review_requested",
2201 Some("usr_ana"),
2202 json!({
2203 "repoId": "rep_1", "runId": "run_7", "environment": "production", "workflow": "Deploy",
2204 "title": "Ship it", "notify": ["cy", "ana"], "link": "/acme/rocket/actions/runs/run_7"
2205 }),
2206 );
2207 let wanted = wants(&asked).unwrap();
2208 assert_eq!(wanted.number, None);
2209 let thread = thread_of(&asked, &wanted, None);
2210 assert_eq!(thread.key, "rep_1/review/run_7/production");
2211 assert_eq!(thread.link.as_deref(), Some("/acme/rocket/actions/runs/run_7"));
2212 let told = notices(&asked, "acme/rocket", &actor("usr_ana", "ana"), None, &nobody());
2213 let names: Vec<&str> = told.iter().map(|notice| notice.username.as_str()).collect();
2214 // Whoever started the run is told too, when they review it.
2215 assert_eq!(names, ["cy", "ana"]);
2216 assert!(told[0].title.contains("waiting for your review to deploy to production"));
2217 }
2218
2219 #[test]
2220 fn teams_asked_to_review_tell_the_people_they_name() {
2221 let requested = event(
2222 "pull.review_requested",
2223 Some("usr_ana"),
2224 json!({ "number": 7, "reviewers": ["cy"], "teams": [
2225 { "team": "acme/backend", "notified": ["cy", "dee", "ana"], "assigned": ["cy"] }
2226 ] }),
2227 );
2228 let notices_ = notices(&requested, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody());
2229 // cy was picked and is told as a reviewer; dee through the team;
2230 // never whoever asked.
2231 assert_eq!(
2232 told(&notices_),
2233 vec![("cy", Reason::ReviewRequested, Severity::Warning), ("dee", Reason::ReviewRequested, Severity::Warning)]
2234 );
2235 assert_eq!(notices_[0].title, "ana asked you to review acme/rocket#7");
2236 assert_eq!(notices_[1].title, "ana asked @acme/backend to review acme/rocket#7");
2237 assert_eq!(
2238 subscribes(&requested, Some(&pull())),
2239 vec![("cy".into(), Reason::ReviewRequested), ("dee".into(), Reason::ReviewRequested), ("ana".into(), Reason::ReviewRequested)]
2240 );
2241 // Asked by the CODEOWNERS file.
2242 let owned = event(
2243 "pull.review_requested",
2244 None,
2245 json!({ "number": 7, "reviewers": ["bo"], "codeOwners": true, "teams": [{ "team": "acme/docs", "notified": ["wren"], "assigned": [] }] }),
2246 );
2247 let notices_ = notices(&owned, "acme/rocket", &Actor::default(), Some(&pull()), &nobody());
2248 assert_eq!(notices_[0].title, "acme/rocket#7 changes files you own");
2249 assert_eq!(notices_[1].title, "acme/rocket#7 changes files @acme/docs owns");
2250 }
2251
2252 #[test]
2253 fn a_team_mention_tells_its_people_once_and_a_name_wins() {
2254 let mut on = comment(person("usr_bo", "bo"), "cc @ana @acme/backend", &["ana"]);
2255 if let Some(comment) = on.comment.as_mut() {
2256 comment.team_mentions = vec![TeamMentioned {
2257 team: "acme/backend".into(),
2258 members: vec!["ana".into(), "cy".into(), "bo".into()],
2259 }];
2260 }
2261 let created = event("comment.created", Some("usr_bo"), json!({ "number": 7, "commentId": "cmt_1" }));
2262 let notices_ = notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &nobody());
2263 let mentioned: Vec<(&str, Reason)> = notices_.iter().map(|n| (n.username.as_str(), n.reason)).filter(|(_, r)| matches!(r, Reason::Mention | Reason::TeamMention)).collect();
2264 assert_eq!(mentioned, vec![("ana", Reason::Mention), ("cy", Reason::TeamMention)]);
2265 assert_eq!(
2266 notices_.iter().find(|n| n.username == "cy").unwrap().title,
2267 "bo mentioned @acme/backend on acme/rocket#7"
2268 );
2269 let subscribed = subscribes(&created, Some(&on));
2270 assert!(subscribed.contains(&("cy".into(), Reason::TeamMention)));
2271 assert!(subscribed.contains(&("ana".into(), Reason::Mention)));
2272 }
2273
2274 #[test]
2275 fn a_description_tells_the_people_and_teams_it_mentions() {
2276 let mut on = pull();
2277 on.mentions = vec!["dee".into()];
2278 on.team_mentions = vec![TeamMentioned {
2279 team: "acme/web".into(),
2280 members: vec!["eve".into()],
2281 }];
2282 let opened = event("pull.opened", Some("usr_ana"), json!({ "number": 7 }));
2283 let notices_ = notices(&opened, "acme/rocket", &actor("usr_ana", "ana"), Some(&on), &nobody());
2284 assert!(told(&notices_).contains(&("dee", Reason::Mention, Severity::Info)));
2285 assert!(told(&notices_).contains(&("eve", Reason::TeamMention, Severity::Info)));
2286 assert_eq!(
2287 subscribes(&opened, Some(&on)),
2288 vec![("dee".into(), Reason::Mention), ("eve".into(), Reason::TeamMention)]
2289 );
2290 }
2291
2292 #[test]
2293 fn reviewers_and_assignees_asked_are_told_never_whoever_asked() {
2294 let requested = event("pull.review_requested", Some("usr_ana"), json!({ "number": 7, "reviewers": ["bo", "g1t", "ana"] }));
2295 let notices_ = notices(&requested, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody());
2296 assert_eq!(told(&notices_), vec![("bo", Reason::ReviewRequested, Severity::Warning)]);
2297 assert_eq!(notices_[0].title, "ana asked you to review acme/rocket#7");
2298 let assigned = event("issue.assigned", Some("usr_ana"), json!({ "number": 3, "added": ["ana", "eve"] }));
2299 let notices_ = notices(&assigned, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody());
2300 assert_eq!(told(&notices_), vec![("eve", Reason::Assign, Severity::Info)]);
2301 assert_eq!(notices_[0].title, "ana assigned you to acme/rocket#3");
2302 // Both subscribe whoever they name, never g1t.
2303 assert_eq!(subscribes(&requested, Some(&pull())), vec![("bo".into(), Reason::ReviewRequested), ("ana".into(), Reason::ReviewRequested)]);
2304 assert_eq!(subscribes(&assigned, Some(&pull())), vec![("ana".into(), Reason::Assign), ("eve".into(), Reason::Assign)]);
2305 }
2306
2307 #[test]
2308 fn failures_go_to_whoever_answers_for_the_change() {
2309 let failed = event("checks.completed", None, json!({ "number": 7, "status": "failed" }));
2310 assert_eq!(
2311 told(&notices(&failed, "acme/rocket", &Actor::default(), Some(&pull()), &nobody())),
2312 vec![("ana", Reason::CiActivity, Severity::Error)]
2313 );
2314 // g1t's change is the person's who asked for it, never g1t's.
2315 let notices_ = notices(&failed, "acme/rocket", &Actor::default(), Some(&g1t_pull()), &nobody());
2316 assert_eq!(told(&notices_), vec![("ana", Reason::CiActivity, Severity::Error)]);
2317 let errored = event("checks.completed", None, json!({ "number": 7, "status": "errored" }));
2318 assert_eq!(
2319 notices(&errored, "acme/rocket", &Actor::default(), Some(&pull()), &nobody())[0].title,
2320 "Checks could not run on acme/rocket#7"
2321 );
2322 }
2323
2324 #[test]
2325 fn a_workflow_that_fails_tells_its_pull_requests_owner_even_if_they_pushed() {
2326 let failed = event("workflow.completed", Some("usr_ana"), json!({ "pull": 7, "workflow": "CI", "conclusion": "failure" }));
2327 let notices_ = notices(&failed, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody());
2328 assert_eq!(told(&notices_), vec![("ana", Reason::CiActivity, Severity::Error)]);
2329 assert_eq!(notices_[0].title, "CI failed on acme/rocket#7");
2330 // On a branch: whoever pushed.
2331 let pushed = event(
2332 "workflow.completed",
2333 Some("usr_bo"),
2334 json!({ "workflow": "Deploy", "path": ".g1t/workflows/deploy.yml", "conclusion": "failure", "ref": "refs/heads/main", "number": 12, "sha": "abcdef0123", "runId": "run_9" }),
2335 );
2336 let notices_ = notices(&pushed, "acme/rocket", &actor("usr_bo", "bo"), None, &nobody());
2337 assert_eq!(told(&notices_), vec![("bo", Reason::CiActivity, Severity::Error)]);
2338 assert_eq!(notices_[0].title, "Deploy failed on main in acme/rocket");
2339 assert_eq!(notices_[0].body, "Run 12 at abcdef0");
2340 // Nobody to tell when g1t pushed.
2341 assert!(notices(&pushed, "acme/rocket", &actor("g1t", "g1t"), None, &nobody()).is_empty());
2342 // Every failure of a workflow on a branch is one thread.
2343 let wanted = wants(&pushed).unwrap();
2344 let thread = thread_of(&pushed, &wanted, None);
2345 assert_eq!(thread.key, "rep_1/run/.g1t/workflows/deploy.yml@main");
2346 assert_eq!(thread.run_id.as_deref(), Some("run_9"));
2347 }
2348
2349 #[test]
2350 fn deployments_tell_whoever_answers_for_them_and_watchers() {
2351 let failed = event(
2352 "deployment.failed",
2353 Some("usr_bo"),
2354 json!({ "repoId": "rep_1", "projectId": "prj_1", "project": "rocket", "deploymentId": "dpl_1", "error": "The build failed.", "path": "/acme/rocket/deployments/dpl_1" }),
2355 );
2356 let audience = watched(&[("cy", WatchLevel::Custom, &["deployments"]), ("dee", WatchLevel::Custom, &["issues"]), ("eve", WatchLevel::All, &[])]);
2357 let notices_ = notices(&failed, "acme/rocket", &actor("usr_bo", "bo"), None, &audience);
2358 assert_eq!(
2359 told(&notices_),
2360 vec![
2361 ("bo", Reason::CiActivity, Severity::Error),
2362 ("cy", Reason::Subscribed, Severity::Error),
2363 ("eve", Reason::Subscribed, Severity::Error),
2364 ]
2365 );
2366 assert_eq!(notices_[0].title, "Production of rocket failed to deploy");
2367 assert_eq!(notices_[0].body, "The build failed.");
2368 let thread = thread_of(&failed, &wants(&failed).unwrap(), None);
2369 assert_eq!(thread.key, "rep_1/deploy/prj_1/production");
2370 assert_eq!(url(Some("acme/rocket"), thread.kind, None, None, thread.link.as_deref()), "/acme/rocket/deployments/dpl_1");
2371 // A success is news to the owner only after a failure.
2372 let live = event("deployment.succeeded", Some("usr_bo"), json!({ "repoId": "rep_1", "projectId": "prj_1", "project": "rocket", "commit": "abcdef0123" }));
2373 assert!(notices(&live, "acme/rocket", &actor("usr_bo", "bo"), None, &nobody()).is_empty());
2374 let recovered = event("deployment.succeeded", Some("usr_bo"), json!({ "repoId": "rep_1", "projectId": "prj_1", "project": "rocket", "recovered": true }));
2375 let notices_ = notices(&recovered, "acme/rocket", &actor("usr_bo", "bo"), None, &nobody());
2376 assert_eq!(told(&notices_), vec![("bo", Reason::CiActivity, Severity::Success)]);
2377 assert_eq!(notices_[0].title, "Production of rocket is live again");
2378 // A preview's is the pull request's owner's.
2379 let preview = event("deployment.failed", None, json!({ "repoId": "rep_1", "projectId": "prj_1", "number": 7, "triggeredBy": "g1t" }));
2380 assert_eq!(told(&notices(&preview, "acme/rocket", &Actor::default(), Some(&pull()), &nobody())), vec![("ana", Reason::CiActivity, Severity::Error)]);
2381 assert_eq!(thread_of(&preview, &wants(&preview).unwrap(), Some(&pull())).key, "rep_1/deploy/prj_1/7");
2382 }
2383
2384 #[test]
2385 fn a_mirror_tells_only_the_people_its_settings_name() {
2386 let down = event(
2387 "mirror.unreachable",
2388 None,
2389 json!({
2390 "repoId": "rep_1", "repo": "acme/rocket", "remoteId": "rmt_1", "remote": "github.com/acme/rocket",
2391 "state": "standby", "title": "github.com/acme/rocket is not answering. acme/rocket keeps its copy.",
2392 "detail": "Take over acme/rocket to keep working on g1t until it is back.",
2393 "notify": ["ana"], "link": "/acme/rocket/settings/mirroring"
2394 }),
2395 );
2396 assert_eq!(wants(&down), Some(Wanted { repo_id: "rep_1".into(), number: None, comment_id: None }));
2397 // Watchers of everything hear nothing: only those named.
2398 let audience = watched(&[("eve", WatchLevel::All, &[])]);
2399 let notices_ = notices(&down, "acme/rocket", &Actor::default(), None, &audience);
2400 assert_eq!(told(&notices_), vec![("ana", Reason::StateChange, Severity::Warning)]);
2401 assert!(notices_[0].body.contains("Take over"));
2402 let thread = thread_of(&down, &wants(&down).unwrap(), None);
2403 assert_eq!(thread.key, "rep_1/mirror");
2404 assert_eq!(url(Some("acme/rocket"), thread.kind, None, None, thread.link.as_deref()), "/acme/rocket/settings/mirroring");
2405 // The banner-only default names nobody, so nobody is told.
2406 let quiet = event("mirror.unreachable", None, json!({ "repoId": "rep_1", "title": "x", "link": "/x" }));
2407 assert!(notices(&quiet, "acme/rocket", &Actor::default(), None, &audience).is_empty());
2408 let back = event("mirror.state_changed", None, json!({ "repoId": "rep_1", "state": "standby", "title": "handed back", "notify": ["ana"], "link": "/x" }));
2409 assert_eq!(told(&notices(&back, "acme/rocket", &Actor::default(), None, &audience)), vec![("ana", Reason::StateChange, Severity::Success)]);
2410 }
2411
2412 /// A scan's summary, as the security service publishes it.
2413 fn summary(alert_type: &str, opened: &[&str], new: (u32, u32, u32, u32), open: (u32, u32, u32, u32), pusher: Option<&str>) -> Event {
2414 let counts = |(critical, high, medium, low): (u32, u32, u32, u32)| json!({ "critical": critical, "high": high, "medium": medium, "low": low, "unknown": 0 });
2415 let worst = [(new.0, "critical"), (new.1, "high"), (new.2, "medium"), (new.3, "low")].into_iter().find(|(n, _)| *n > 0).map(|(_, name)| name);
2416 let page = match alert_type {
2417 "secret_scanning" => "secret-scanning",
2418 "code_scanning" => "code-scanning",
2419 _ => "vulnerabilities",
2420 };
2421 event(
2422 &format!("{alert_type}_alert.summary"),
2423 None,
2424 json!({
2425 "repoId": "rep_1", "alertType": alert_type, "scan": if pusher.is_some() { "push" } else { "dependencies" },
2426 "opened": opened, "openedCount": opened.len(), "fixedCount": 0, "dismissedCount": 0,
2427 "newBySeverity": counts(new), "open": counts(open), "worst": worst,
2428 "latest": if opened.is_empty() { serde_json::Value::Null } else { json!("lodash 4.17.20 in package-lock.json: GHSA-1") },
2429 "link": format!("/acme/rocket/security/{page}"),
2430 "pusher": pusher, "blocked": if pusher.is_some() { opened.len() } else { 0 },
2431 "notify": ["ana"], "members": ["ana", "bo", "cy"]
2432 }),
2433 )
2434 }
2435
2436 #[test]
2437 fn a_scan_is_one_item_per_repository_and_alert_type() {
2438 let found = summary("vulnerability", &["vul_3", "vul_2", "vul_1"], (1, 2, 0, 0), (1, 2, 0, 0), None);
2439 assert_eq!(wants(&found), Some(Wanted { repo_id: "rep_1".into(), number: None, comment_id: None }));
2440 // cy watches for security alerts and is a member; eve watches
2441 // everything but cannot see findings; dee watches issues only.
2442 let audience = watched(&[
2443 ("cy", WatchLevel::Custom, &["security"]),
2444 ("dee", WatchLevel::Custom, &["issues"]),
2445 ("eve", WatchLevel::All, &[]),
2446 ]);
2447 let notices_ = notices(&found, "acme/rocket", &Actor::default(), None, &audience);
2448 assert_eq!(told(&notices_), vec![("ana", Reason::SecurityAlert, Severity::Error), ("cy", Reason::SecurityAlert, Severity::Error)]);
2449 assert_eq!(notices_[0].title, "3 new vulnerabilities in acme/rocket: 1 critical, 2 high");
2450 assert_eq!(notices_[0].body, "lodash 4.17.20 in package-lock.json: GHSA-1");
2451 // The same thread for every scan of this type, however many alerts.
2452 let thread = thread_of(&found, &wants(&found).unwrap(), None);
2453 assert_eq!(thread.key, "rep_1/security/vulnerability");
2454 assert_eq!(url(Some("acme/rocket"), thread.kind, None, None, thread.link.as_deref()), "/acme/rocket/security/vulnerabilities");
2455 // Medium and low are news, but not urgent: an info item, or the digest.
2456 let quiet = summary("code_scanning", &["cod_1"], (0, 0, 1, 0), (0, 0, 1, 0), None);
2457 let notices_ = notices(&quiet, "acme/rocket", &Actor::default(), None, &audience);
2458 assert_eq!(told(&notices_), vec![("ana", Reason::SecurityAlert, Severity::Info), ("cy", Reason::SecurityAlert, Severity::Info)]);
2459 assert_eq!(notices_[0].title, "1 new code scanning alert in acme/rocket: 1 medium");
2460 // A scan that opened nothing tells nobody: the thread is brought up to date instead.
2461 let fixed = summary("vulnerability", &[], (0, 0, 0, 0), (0, 1, 0, 0), None);
2462 assert!(notices(&fixed, "acme/rocket", &Actor::default(), None, &audience).is_empty());
2463 let (title, body) = refreshed_text("acme/rocket", &SecuritySummary { fixed_count: 2, ..security_summary(&fixed).unwrap() });
2464 assert_eq!(title, "1 open vulnerability in acme/rocket: 1 high");
2465 assert_eq!(body, "2 fixed");
2466 let settled = SecuritySummary { fixed_count: 1, dismissed_count: 1, open: SeverityCounts::default(), ..security_summary(&fixed).unwrap() };
2467 assert_eq!(refreshed_text("acme/rocket", &settled), ("No open vulnerabilities in acme/rocket".to_owned(), "1 fixed, 1 dismissed".to_owned()));
2468 // Per-alert events are for webhooks.
2469 assert_eq!(wants(&event("vulnerability_alert.created", None, json!({ "repoId": "rep_1" }))), None);
2470 assert_eq!(wants(&event("code_scanning_alert.fixed", None, json!({ "repoId": "rep_1" }))), None);
2471 }
2472
2473 #[test]
2474 fn a_refused_push_tells_the_pusher_at_once_and_the_owners_once() {
2475 let blocked = summary("secret_scanning", &["sec_1", "sec_2"], (2, 0, 0, 0), (2, 0, 0, 0), Some("bo"));
2476 let notices_ = notices(&blocked, "acme/rocket", &Actor::default(), None, &nobody());
2477 assert_eq!(told(&notices_), vec![("bo", Reason::SecurityAlert, Severity::Error), ("ana", Reason::SecurityAlert, Severity::Error)]);
2478 assert_eq!(notices_[0].title, "A push to acme/rocket was blocked: it adds 2 secrets");
2479 assert_eq!(notices_[1].title, "2 new secrets in acme/rocket: 2 critical");
2480 assert_eq!(thread_of(&blocked, &wants(&blocked).unwrap(), None).key, "rep_1/security/secret_scanning");
2481 // Whatever bo chose, the push is theirs to fix; ana, an owner, is told whatever she chose.
2482 let summary_ = security_summary(&blocked).unwrap();
2483 let off = InboxSettings { security_alerts: false, security_digest: DigestCadence::Off, ..InboxSettings::default() };
2484 assert_eq!(security_delivery(&summary_, "bo", &off), Delivery::Now);
2485 assert_eq!(security_delivery(&summary_, "ana", &off), Delivery::Now);
2486 // A watcher who turned security alerts off hears of nothing urgent.
2487 assert_eq!(security_delivery(&summary_, "cy", &off), Delivery::Never);
2488 assert_eq!(security_delivery(&summary_, "cy", &InboxSettings::default()), Delivery::Now);
2489 }
2490
2491 #[test]
2492 fn what_is_not_urgent_waits_for_the_digest_unless_the_person_chose_otherwise() {
2493 let medium = security_summary(&summary("vulnerability", &["vul_1"], (0, 0, 1, 0), (0, 0, 1, 0), None)).unwrap();
2494 assert!(!medium.urgent());
2495 let choose = |cadence| InboxSettings { security_digest: cadence, ..InboxSettings::default() };
2496 // Owners too: a medium alert is for the digest, as they chose.
2497 assert_eq!(security_delivery(&medium, "ana", &choose(DigestCadence::Daily)), Delivery::Digest);
2498 assert_eq!(security_delivery(&medium, "cy", &choose(DigestCadence::Weekly)), Delivery::Digest);
2499 assert_eq!(security_delivery(&medium, "cy", &choose(DigestCadence::AtOnce)), Delivery::Now);
2500 assert_eq!(security_delivery(&medium, "ana", &choose(DigestCadence::Off)), Delivery::Never);
2501 let high = security_summary(&summary("vulnerability", &["vul_1"], (0, 1, 0, 0), (0, 1, 0, 0), None)).unwrap();
2502 assert_eq!(security_delivery(&high, "ana", &choose(DigestCadence::Off)), Delivery::Now);
2503 assert_eq!(breakdown(&SeverityCounts { critical: 1, low: 3, ..SeverityCounts::default() }), "1 critical, 3 low");
2504 assert_eq!(breakdown(&SeverityCounts::default()), "");
2505 }
2506
2507 #[test]
2508 fn bypass_requests_reports_and_advisories_tell_who_they_name() {
2509 let audience = watched(&[("cy", WatchLevel::Custom, &["security"]), ("eve", WatchLevel::All, &[])]);
2510 // A bypass request goes to the reviewers named, never to watchers.
2511 let requested = event(
2512 "secret_scanning.bypass_requested",
2513 Some("usr_bo"),
2514 json!({ "repoId": "rep_1", "alertId": "sec_1", "requestId": "byp_1", "title": "An AWS access key in a.env", "notify": ["ana"], "link": "/acme/-/security/bypass-requests" }),
2515 );
2516 let notices_ = notices(&requested, "acme/rocket", &actor("usr_bo", "bo"), None, &audience);
2517 assert_eq!(told(&notices_), vec![("ana", Reason::SecurityAlert, Severity::Warning)]);
2518 assert_eq!(notices_[0].title, "bo asked to bypass push protection in acme/rocket");
2519 assert_eq!(thread_of(&requested, &wants(&requested).unwrap(), None).key, "rep_1/security/byp_1");
2520 // A private report is for the owners and security managers, at once, with no reporter named.
2521 let reported = event(
2522 "security_advisory.reported",
2523 None,
2524 json!({ "repoId": "rep_1", "id": "vrp_1", "title": "XSS in the search box", "state": "new", "link": "/acme/rocket/security/reports", "notify": ["ana"], "members": ["ana", "cy"] }),
2525 );
2526 let notices_ = notices(&reported, "acme/rocket", &Actor::default(), None, &audience);
2527 assert_eq!(told(&notices_), vec![("ana", Reason::SecurityAlert, Severity::Warning)]);
2528 assert_eq!(notices_[0].title, "A vulnerability was reported privately to acme/rocket");
2529 assert_eq!(thread_of(&reported, &wants(&reported).unwrap(), None).key, "rep_1/security/reports");
2530 // A published advisory is for watchers who chose security; it is public, so no members list is needed.
2531 let published = event(
2532 "security_advisory.published",
2533 Some("usr_ana"),
2534 json!({ "repoId": "rep_1", "id": "adv_1", "g1tsaId": "G1TSA-2026-abcd-efgh", "title": "XSS in the search box", "severity": "high", "state": "published", "link": "/acme/rocket/security/advisories/G1TSA-2026-abcd-efgh" }),
2535 );
2536 let notices_ = notices(&published, "acme/rocket", &actor("usr_ana", "ana"), None, &audience);
2537 assert_eq!(told(&notices_), vec![("cy", Reason::Subscribed, Severity::Info), ("eve", Reason::Subscribed, Severity::Info)]);
2538 assert_eq!(thread_of(&published, &wants(&published).unwrap(), None).key, "rep_1/security/advisories/adv_1");
2539 }
2540
2541 #[test]
2542 fn nobody_hears_of_what_they_did_themselves() {
2543 let merged = event("pull.merged", Some("usr_ana"), json!({ "number": 7 }));
2544 let by_ana = notices(&merged, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody());
2545 // The assignee still hears; ana, who merged, does not.
2546 assert_eq!(told(&by_ana), vec![("bo", Reason::StateChange, Severity::Success)]);
2547 let by_bo = notices(&merged, "acme/rocket", &actor("usr_bo", "bo"), Some(&pull()), &nobody());
2548 assert_eq!(told(&by_bo), vec![("ana", Reason::StateChange, Severity::Success)]);
2549 assert_eq!(by_bo[0].title, "bo merged acme/rocket#7");
2550 let by_queue = notices(&merged, "acme/rocket", &Actor::default(), Some(&pull()), &nobody());
2551 assert_eq!(by_queue[0].title, "acme/rocket#7 was merged");
2552 }
2553
2554 #[test]
2555 fn closing_and_reopening_tells_everyone_subscribed_and_watchers() {
2556 let closed = event("issue.closed", Some("usr_bo"), json!({ "number": 3, "reason": "completed" }));
2557 let issue = InboxSubject {
2558 kind: Some(SubjectKind::Issue),
2559 title: "Crash".into(),
2560 author: person("usr_cy", "cy"),
2561 assignees: vec!["bo".into()],
2562 ..InboxSubject::default()
2563 };
2564 let mut audience = subscribed(&[("eve", State::Subscribed, Some(Reason::Comment)), ("fay", State::Unsubscribed, None)]);
2565 audience.watchers = watched(&[("gus", WatchLevel::All, &[]), ("hal", WatchLevel::Custom, &["pulls"])]).watchers;
2566 let notices_ = notices(&closed, "acme/rocket", &actor("usr_bo", "bo"), Some(&issue), &audience);
2567 assert_eq!(
2568 told(&notices_),
2569 vec![
2570 ("cy", Reason::StateChange, Severity::Info),
2571 ("eve", Reason::StateChange, Severity::Info),
2572 ("gus", Reason::Subscribed, Severity::Info),
2573 ]
2574 );
2575 assert_eq!(notices_[0].title, "bo closed acme/rocket#3");
2576 let by_pull = event("issue.closed", None, json!({ "number": 3, "resolvedBy": 9 }));
2577 assert_eq!(notices(&by_pull, "acme/rocket", &Actor::default(), Some(&issue), &nobody())[0].title, "acme/rocket#3 was closed by #9");
2578 let reopened = event("issue.reopened", Some("usr_cy"), json!({ "number": 3 }));
2579 assert_eq!(told(&notices(&reopened, "acme/rocket", &actor("usr_cy", "cy"), Some(&issue), &nobody())), vec![("bo", Reason::StateChange, Severity::Info)]);
2580 }
2581
2582 #[test]
2583 fn opening_tells_who_it_names_and_watchers_of_its_kind() {
2584 let opened = event("pull.opened", Some("usr_ana"), json!({ "number": 7 }));
2585 let subject = InboxSubject { reviewers: vec!["cy".into(), "g1t".into()], ..pull() };
2586 let audience = watched(&[("bo", WatchLevel::All, &[]), ("dee", WatchLevel::Custom, &["issues"]), ("eve", WatchLevel::Custom, &["pulls"]), ("fay", WatchLevel::Participating, &[])]);
2587 let notices_ = notices(&opened, "acme/rocket", &actor("usr_ana", "ana"), Some(&subject), &audience);
2588 assert_eq!(
2589 told(&notices_),
2590 vec![
2591 ("bo", Reason::Assign, Severity::Info),
2592 ("cy", Reason::ReviewRequested, Severity::Warning),
2593 ("eve", Reason::Subscribed, Severity::Info),
2594 ]
2595 );
2596 assert_eq!(notices_[2].title, "ana opened acme/rocket#7");
2597 }
2598
2599 #[test]
2600 fn ignoring_a_repository_silences_it_and_unsubscribing_keeps_only_what_is_asked() {
2601 let created = event("comment.created", Some("usr_bo"), json!({ "number": 7, "commentId": "cmt_1" }));
2602 let on = comment(person("usr_bo", "bo"), "@cy have a look", &["cy"]);
2603 let audience = watched(&[("cy", WatchLevel::Ignore, &[]), ("ana", WatchLevel::All, &[])]);
2604 assert!(notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &audience).iter().all(|notice| notice.username != "cy"));
2605 let audience = subscribed(&[("cy", State::Unsubscribed, None), ("ana", State::Unsubscribed, None)]);
2606 let notices_ = notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &audience);
2607 // cy was mentioned, which is asked of them; ana unsubscribed from the conversation.
2608 assert_eq!(told(&notices_), vec![("cy", Reason::Mention, Severity::Info)]);
2609 }
2610
2611 #[test]
2612 fn an_agent_s_review_is_shown_by_its_name_and_marked_advisory() {
2613 // Margo (@margo), acting for bo, asks for changes on ana's pull request.
2614 let created = event("comment.created", Some("usr_bo"), json!({ "number": 7, "commentId": "cmt_1" }));
2615 let mut on = comment(person("agt_1", "ana"), "Trim the name.", &[]);
2616 if let Some(said) = on.comment.as_mut() {
2617 said.agent = Some(g1t_contracts::work::AgentRef {
2618 id: "agt_1".into(),
2619 handle: "ana".into(),
2620 display_name: "Margo".into(),
2621 avatar_seed: "margo".into(),
2622 });
2623 said.acting_for = Some(person("usr_bo", "bo"));
2624 said.verdict = Some("request_changes".into());
2625 said.advisory = true;
2626 }
2627 let notices_ = notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &nobody());
2628 // Its handle sharing ana's name leaves nobody out: ana owns it and hears.
2629 assert!(told(&notices_).contains(&("ana", Reason::Author, Severity::Info)));
2630 assert_eq!(notices_[0].title, "Margo (agent) asked for changes on acme/rocket#7 (advisory)");
2631 // An agent subscribes nobody by its handle.
2632 assert!(subscribes(&created, Some(&on)).iter().all(|(name, _)| name != "ana"));
2633 }
2634
2635 #[test]
2636 fn comments_tell_those_mentioned_then_everyone_subscribed_never_the_writer() {
2637 let created = event("comment.created", Some("usr_bo"), json!({ "number": 7, "commentId": "cmt_1" }));
2638 let on = comment(person("usr_bo", "bo"), "@cy @bo have a look", &["cy", "bo", "g1t"]);
2639 let audience = subscribed(&[("eve", State::Subscribed, Some(Reason::Comment)), ("fay", State::Subscribed, Some(Reason::Manual))]);
2640 let notices_ = notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &audience);
2641 assert_eq!(
2642 told(&notices_),
2643 vec![
2644 ("cy", Reason::Mention, Severity::Info),
2645 ("ana", Reason::Author, Severity::Info),
2646 ("eve", Reason::Comment, Severity::Info),
2647 ("fay", Reason::Manual, Severity::Info),
2648 ]
2649 );
2650 assert_eq!(notices_[0].title, "bo mentioned you on acme/rocket#7");
2651 assert_eq!(notices_[1].title, "bo commented on acme/rocket#7");
2652 assert_eq!(notices_[0].body, "@cy @bo have a look");
2653 // Mentioned and the owner: told once, as mentioned.
2654 let on = comment(person("usr_bo", "bo"), "@ana", &["ana"]);
2655 assert_eq!(
2656 told(&notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &nobody())),
2657 vec![("ana", Reason::Mention, Severity::Info)]
2658 );
2659 // The owner's own comment tells the assignee, not the owner.
2660 let on = comment(person("usr_ana", "ana"), "thanks", &[]);
2661 assert_eq!(
2662 told(&notices(&created, "acme/rocket", &actor("usr_ana", "ana"), Some(&on), &nobody())),
2663 vec![("bo", Reason::Assign, Severity::Info)]
2664 );
2665 // Something that happened, not something written, tells nobody.
2666 let mut on = comment(person("usr_bo", "bo"), "assigned cy", &[]);
2667 on.comment.as_mut().unwrap().event = true;
2668 assert!(notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &nobody()).is_empty());
2669 // An approval is good news.
2670 let mut on = comment(person("usr_cy", "cy"), "", &[]);
2671 on.comment.as_mut().unwrap().verdict = Some("approve".into());
2672 let notices_ = notices(&created, "acme/rocket", &actor("usr_cy", "cy"), Some(&on), &nobody());
2673 assert_eq!(told(&notices_)[0], ("ana", Reason::Author, Severity::Success));
2674 assert_eq!(notices_[0].body, "Add the inbox");
2675 // Writing and being mentioned subscribe, never g1t.
2676 let on = comment(person("usr_bo", "bo"), "@cy", &["cy"]);
2677 assert_eq!(subscribes(&created, Some(&on)), vec![("bo".into(), Reason::Comment), ("cy".into(), Reason::Mention)]);
2678 let on = comment(person(AGENT_ID, "g1t"), "done", &[]);
2679 assert!(subscribes(&created, Some(&on)).is_empty());
2680 }
2681
2682 #[test]
2683 fn issues_and_pull_requests_are_one_thread_each() {
2684 let created = event("comment.created", Some("usr_bo"), json!({ "repoId": "rep_1", "number": 7, "commentId": "cmt_1" }));
2685 let wanted = wants(&created).unwrap();
2686 let thread = thread_of(&created, &wanted, Some(&pull()));
2687 assert_eq!(thread.key, "rep_1#7");
2688 assert_eq!(thread.kind, Some(SubjectKind::Pull));
2689 let merged = event("pull.merged", None, json!({ "repoId": "rep_1", "number": 7 }));
2690 assert_eq!(thread_of(&merged, &wants(&merged).unwrap(), Some(&pull())).key, thread.key);
2691 }
2692
2693 #[test]
2694 fn items_link_to_what_they_are_about() {
2695 assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Pull), Some(7), None, None), "/acme/rocket/pull/7");
2696 assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Issue), Some(3), None, None), "/acme/rocket/issues/3");
2697 assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Run), None, Some("run_1"), None), "/acme/rocket/actions/runs/run_1");
2698 assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Deploy), None, None, Some("/acme/site/deployments/dpl_1")), "/acme/site/deployments/dpl_1");
2699 assert_eq!(url(Some("acme/rocket"), None, None, None, None), "/acme/rocket");
2700 assert_eq!(url(None, None, None, None, None), "/inbox");
2701 }
2702
2703 #[test]
2704 fn long_titles_are_cut_to_a_line() {
2705 let long = "x".repeat(400);
2706 assert_eq!(clip(&long, MAX_TITLE).chars().count(), MAX_TITLE);
2707 assert_eq!(clip(" short ", MAX_TITLE), "short");
2708 }
2709
2710 #[test]
2711 fn marks_change_only_what_they_say() {
2712 assert_eq!(mark_change(InboxMark::Read), "read_at = COALESCE(read_at, ?1)");
2713 assert!(mark_change(InboxMark::Done).contains("done_at = ?1"));
2714 assert_eq!(mark_change(InboxMark::Unsnooze), "snoozed_until = NULL");
2715 assert!(ranked(&ListInboxArgs::default()));
2716 assert!(!ranked(&ListInboxArgs { reason: Some(Reason::Mention), ..ListInboxArgs::default() }));
2717 assert!(!ranked(&ListInboxArgs { participating: true, ..ListInboxArgs::default() }));
2718 }
2719
2720 #[test]
2721 fn filters_bind_in_order_after_what_is_bound() {
2722 let a = ListInboxArgs {
2723 reason: Some(Reason::Mention),
2724 repo_id: Some("rep_1".into()),
2725 participating: true,
2726 unread: true,
2727 ..ListInboxArgs::default()
2728 };
2729 // Two values come first: the username and now.
2730 let (conditions, values) = filters(&a, 2);
2731 assert_eq!(
2732 conditions,
2733 vec!["reason = ?3", "repo_id = ?4", "reason NOT IN ('manual', 'subscribed')", "read_at IS NULL"]
2734 );
2735 assert_eq!(values, vec!["mention", "rep_1"]);
2736 }
2737
2738 #[test]
2739 fn the_bump_keeps_whatever_is_most_urgent_while_unread() {
2740 assert!(BUMP.contains("WHERE NOT EXISTS (SELECT 1 FROM inbox_activity WHERE event_id = ?4 AND username = ?2)"));
2741 assert!(BUMP.contains("ON CONFLICT (username, thread) DO UPDATE"));
2742 assert!(BUMP.contains("activity = inbox_items.activity + 1"));
2743 // Its numbered parameters run from 1 to 19.
2744 for at in 1..=19 {
2745 assert!(BUMP.contains(&format!("?{at}")), "?{at}");
2746 }
2747 assert!(!BUMP.contains("?20"));
2748 }
2749
2750 #[test]
2751 fn live_notifications_say_what_and_where() {
2752 let notice = Notice {
2753 username: "ana".into(),
2754 reason: Reason::Agent,
2755 severity: Severity::Warning,
2756 title: "g1t needs you on acme/api#4".into(),
2757 body: "Which database?".into(),
2758 };
2759 let live = live_notification("evt_1", &notice, "/Acme/api/pull/4#c1", "2026-10-08T00:00:00Z");
2760 assert_eq!(live["id"], "inbox:evt_1");
2761 // A stop that needs a person is an ordinary inbox item.
2762 assert_eq!(live["kind"], "inbox");
2763 assert_eq!(live["workspace"], "acme");
2764 assert_eq!(live["href"], "/Acme/api/pull/4#c1");
2765 assert_eq!(live["actor"]["name"], "acme/api");
2766 let mention = Notice { reason: Reason::TeamMention, ..notice };
2767 assert_eq!(live_notification("evt_2", &mention, "https://elsewhere", "t")["href"], "/inbox");
2768 assert_eq!(live_notification("evt_2", &mention, "/x", "t")["kind"], "mention");
2769 }
2770
2771 #[test]
2772 fn inbox_counts_are_told_as_they_are_by_username() {
2773 assert_eq!(inbox_count_update("Ana", 3), serde_json::json!({ "username": "ana", "unread": 3 }));
2774 assert_eq!(inbox_count_update("bo", 0)["unread"], 0);
2775 }
2776
2777 #[test]
2778 fn token_approvals_tell_the_people_named_about_no_repository() {
2779 let mut asked = event(
2780 "token.approval_requested",
2781 Some("usr_ana"),
2782 json!({ "workspace": "acme", "tokenId": "tok_1", "notify": ["Bo", "cy", "bo", "g1t"], "title": "ana asks", "body": "ci: contents: write", "link": "/acme/-/settings/tokens" }),
2783 );
2784 asked.repo_id = None;
2785 let (thread, told) = workspace_notices(&asked, None);
2786 assert_eq!(thread, "workspace:acme/token/tok_1");
2787 let mut names: Vec<&str> = told.iter().map(|notice| notice.username.as_str()).collect();
2788 names.sort();
2789 assert_eq!(names, ["bo", "cy"], "each once, lowercased, never g1t");
2790 assert!(told.iter().all(|notice| notice.reason == Reason::ReviewRequested && notice.severity == Severity::Warning));
2791 assert!(wants(&asked).is_none(), "about no repository");
2792 let reviewed = event("token.approval_reviewed", None, json!({ "workspace": "acme", "tokenId": "tok_1", "notify": ["ana"], "title": "approved" }));
2793 let (_, told) = workspace_notices(&reviewed, None);
2794 assert_eq!(told[0].reason, Reason::Author);
2795 assert!(WORKSPACE_EVENTS.contains(&"token.approval_reviewed"));
2796 }
2797
2798 #[test]
2799 fn a_workspace_invitation_asks_its_person_and_tells_whoever_sent_it_the_answer() {
2800 let mut sent = event(
2801 "workspace_invitation.created",
2802 Some("usr_owner"),
2803 json!({ "workspace": "flagon-io", "invitationId": "inv_1", "thread": "invitation:inv_1", "notify": ["daweazl"], "title": "@syntaqx invited you to join Flagon, Inc.", "link": "/invitations" }),
2804 );
2805 sent.repo_id = None;
2806 let (thread, told) = workspace_notices(&sent, None);
2807 assert_eq!(thread, "invitation:inv_1");
2808 assert_eq!(told.len(), 1);
2809 assert_eq!((told[0].username.as_str(), told[0].reason, told[0].severity), ("daweazl", Reason::ReviewRequested, Severity::Warning));
2810 let accepted = event("workspace_invitation.accepted", None, json!({ "workspace": "flagon-io", "thread": "invitation:inv_1", "notify": ["syntaqx"] }));
2811 let (thread, told) = workspace_notices(&accepted, None);
2812 assert_eq!(thread, "invitation:inv_1");
2813 assert_eq!((told[0].reason, told[0].severity), (Reason::Author, Severity::Success));
2814 let declined = event("workspace_invitation.declined", None, json!({ "workspace": "flagon-io", "thread": "invitation:inv_1", "notify": ["syntaqx"] }));
2815 assert_eq!(workspace_notices(&declined, None).1[0].severity, Severity::Info);
2816 // Answered or revoked, the person's item is done; a revocation tells nobody.
2817 for kind in ["workspace_invitation.accepted", "workspace_invitation.declined", "workspace_invitation.revoked"] {
2818 assert!(INVITATION_ANSWERED.contains(&kind));
2819 }
2820 assert!(!WORKSPACE_EVENTS.contains(&"workspace_invitation.revoked"));
2821 }
2822}