Skip to content

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

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