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