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