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.

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