| 1 | 1 | | //! The inbox, kept beside the event log. See `g1t_contracts::inbox`. |
| 2 | 2 | | //! |
| 3 | | − | //! As each batch arrives from the bus, the events that need a person are |
| 4 | | − | //! read against what they name (the work service's `inbox_subject`) and one |
| 5 | | − | //! item is written for each person told. Who is told is worked out in |
| 6 | | − | //! [`notices`], from the event and its subject alone: |
| 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: |
| 7 | 9 | | //! |
| 8 | | − | //! | Event | Who | Severity | |
| 9 | | − | //! | --- | --- | --- | |
| 10 | | − | //! | `agent.asked` | the pull request's owner, and its issue's owner and assignees | warning | |
| 11 | | − | //! | `checks.completed`, failed or errored | the pull request's owner | error | |
| 12 | | − | //! | `workflow.completed`, failed | the pull request's owner, or whoever pushed | error | |
| 13 | | − | //! | `review.completed` by g1t | the pull request's owner | success, or info for changes asked | |
| 14 | | − | //! | `pull.ready` for a change g1t made | whoever asked g1t for it | success | |
| 15 | | − | //! | `pull.merged` | the pull request's owner | success | |
| 16 | | − | //! | `comment.created` | everyone mentioned, then the owner | info (success for an approval) | |
| 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 | 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, then everyone subscribed | mention, or why they are subscribed | info (success for an approval) | |
| 23 | + | //! | `issue.opened`, `pull.opened` | whoever was assigned or asked to review; watchers | assign, review_requested, subscribed | info | |
| 17 | 24 | | //! |
| 18 | | − | //! Nobody is told of what they did themselves, and g1t is never told. A |
| 19 | | − | //! failure here is logged and the batch goes on: the bus never waits on |
| 20 | | − | //! the inbox, so an item can be missed, but nothing else is held up. |
| 25 | + | //! Watchers of a repository at `all` (or `custom`, for the kinds they |
| 26 | + | //! chose) hear of every issue and pull request opened, commented on, |
| 27 | + | //! closed, reopened or merged, and of deployments. Anyone who ignores the |
| 28 | + | //! thread or the repository hears of nothing on it; anyone who |
| 29 | + | //! unsubscribed hears only of what is asked of them. |
| 30 | + | //! |
| 31 | + | //! Nobody is told of what they did themselves, though an outcome they set |
| 32 | + | //! off (checks, a workflow, a deployment, g1t's work) is theirs to hear of. |
| 33 | + | //! g1t is never told. A failure here is logged and the batch goes on: the |
| 34 | + | //! bus never waits on the inbox, so an item can be missed, but nothing else |
| 35 | + | //! is held up. |
| 21 | 36 | | |
| 22 | 37 | | use std::collections::{HashMap, HashSet}; |
| 23 | 38 | | |
| ⋯ |
| 31 | 46 | | use g1t_kit::now_ms; |
| 32 | 47 | | use serde::Deserialize; |
| 33 | 48 | | use worker::wasm_bindgen::JsValue; |
| 34 | | − | use worker::{D1Database, Fetcher, Result}; |
| 49 | + | use worker::{D1Database, D1PreparedStatement, Fetcher, Result}; |
| 50 | + | |
| 51 | + | use crate::subscriptions::{self, Audience}; |
| 35 | 52 | | |
| 36 | 53 | | /// Items marked done are kept this long, then removed. |
| 37 | 54 | | pub const DONE_DAYS: u32 = 30; |
| ⋯ |
| 55 | 72 | | #[derive(Debug, PartialEq, Eq)] |
| 56 | 73 | | pub struct Notice { |
| 57 | 74 | | pub username: String, |
| 58 | | − | pub reason: &'static str, |
| 75 | + | pub reason: Reason, |
| 59 | 76 | | pub severity: Severity, |
| 60 | 77 | | pub title: String, |
| 61 | 78 | | pub body: String, |
| ⋯ |
| 76 | 93 | | fn is_named(&self, username: &str) -> bool { |
| 77 | 94 | | self.username.as_deref().is_some_and(|name| name.eq_ignore_ascii_case(username)) |
| 78 | 95 | | } |
| 96 | + | |
| 97 | + | /// A person's name, for a title: never g1t's ids. |
| 98 | + | fn name(&self) -> Option<&str> { |
| 99 | + | self.username.as_deref().filter(|name| !is_g1t(name)) |
| 100 | + | } |
| 79 | 101 | | } |
| 80 | 102 | | |
| 81 | | − | fn is_g1t(username: &str) -> bool { |
| 103 | + | pub(crate) fn is_g1t(username: &str) -> bool { |
| 82 | 104 | | username.eq_ignore_ascii_case(system::USERNAME) || username.eq_ignore_ascii_case("g1t-agent") |
| 83 | 105 | | } |
| 84 | 106 | | |
| 85 | | − | fn is_g1t_id(id: &str) -> bool { |
| 107 | + | pub(crate) fn is_g1t_id(id: &str) -> bool { |
| 86 | 108 | | system::is_system_id(id) || id == AGENT_ID |
| 87 | 109 | | } |
| 88 | 110 | | |
| 111 | + | /// Events that end what an agent was waiting on a person for: it picked |
| 112 | + | /// back up, its head moved, a merge was asked for, or it is over. |
| 113 | + | const RESUMES: [&str; 5] = ["pull.resumed", "pull.updated", "pull.merge_requested", "pull.merged", "pull.closed"]; |
| 114 | + | |
| 89 | 115 | | /// The issue or pull request an event names, and what to read for it. |
| 90 | 116 | | /// None for events the inbox does not tell anyone of. |
| 91 | 117 | | pub fn wants(event: &Event) -> Option<Wanted> { |
| ⋯ |
| 101 | 127 | | }) |
| 102 | 128 | | }; |
| 103 | 129 | | match event.kind.as_str() { |
| 104 | | − | "agent.asked" | "pull.merged" | "pull.ready" => on(Some(number("number")?), None), |
| 130 | + | "agent.asked" | "pull.stalled" | "pull.merged" | "pull.closed" | "pull.ready" | "pull.opened" |
| 131 | + | | "pull.review_requested" | "pull.assigned" | "issue.opened" | "issue.closed" | "issue.reopened" |
| 132 | + | | "issue.assigned" => on(Some(number("number")?), None), |
| 105 | 133 | | "checks.completed" => match data["status"].as_str() { |
| 106 | 134 | | Some("failed" | "errored") => on(Some(number("number")?), None), |
| 107 | 135 | | _ => None, |
| ⋯ |
| 114 | 142 | | Some("failure") => on(number("pull"), None), |
| 115 | 143 | | _ => None, |
| 116 | 144 | | }, |
| 145 | + | "deployment.failed" | "deployment.succeeded" => on(number("number"), None), |
| 117 | 146 | | "comment.created" => on(Some(number("number")?), Some(text("commentId")?)), |
| 118 | 147 | | _ => None, |
| 119 | 148 | | } |
| 120 | 149 | | } |
| 121 | 150 | | |
| 122 | | − | /// Collects who is told, each once, never the actor and never g1t. |
| 151 | + | /// Where an event's items go: which thread, what it is, and where it is. |
| 152 | + | #[derive(Clone, Debug, PartialEq, Eq)] |
| 153 | + | pub struct Thread { |
| 154 | + | pub key: String, |
| 155 | + | pub kind: Option<SubjectKind>, |
| 156 | + | pub number: Option<u32>, |
| 157 | + | pub run_id: Option<String>, |
| 158 | + | /// A path, for a subject with a page of its own. |
| 159 | + | pub link: Option<String>, |
| 160 | + | } |
| 161 | + | |
| 162 | + | /// The thread key of an issue or pull request. |
| 163 | + | pub fn numbered_thread(repo_id: &str, number: u32) -> String { |
| 164 | + | format!("{repo_id}#{number}") |
| 165 | + | } |
| 166 | + | |
| 167 | + | /// The thread an event's items go to. |
| 168 | + | pub fn thread_of(event: &Event, wanted: &Wanted, subject: Option<&InboxSubject>) -> Thread { |
| 169 | + | let data = &event.data; |
| 170 | + | let text = |key: &str| data[key].as_str().filter(|value| !value.is_empty()).map(str::to_owned); |
| 171 | + | match event.kind.as_str() { |
| 172 | + | // A project's production, or one pull request's preview. |
| 173 | + | "deployment.failed" | "deployment.succeeded" => { |
| 174 | + | let which = wanted.number.map_or_else(|| "production".to_owned(), |number| number.to_string()); |
| 175 | + | Thread { |
| 176 | + | key: format!("{}/deploy/{}/{which}", wanted.repo_id, text("projectId").unwrap_or_default()), |
| 177 | + | kind: Some(SubjectKind::Deploy), |
| 178 | + | number: wanted.number, |
| 179 | + | run_id: text("deploymentId"), |
| 180 | + | link: text("path"), |
| 181 | + | } |
| 182 | + | } |
| 183 | + | // A workflow on a branch: its next failure bumps the same thread. |
| 184 | + | "workflow.completed" if subject.is_none() => { |
| 185 | + | let branch = text("ref").unwrap_or_default(); |
| 186 | + | let branch = branch.strip_prefix("refs/heads/").unwrap_or(&branch).to_owned(); |
| 187 | + | let workflow = text("path").or_else(|| text("workflow")).unwrap_or_default(); |
| 188 | + | Thread { |
| 189 | + | key: format!("{}/run/{workflow}@{branch}", wanted.repo_id), |
| 190 | + | kind: Some(SubjectKind::Run), |
| 191 | + | number: None, |
| 192 | + | run_id: text("runId"), |
| 193 | + | link: None, |
| 194 | + | } |
| 195 | + | } |
| 196 | + | _ => match wanted.number { |
| 197 | + | Some(number) => Thread { |
| 198 | + | key: numbered_thread(&wanted.repo_id, number), |
| 199 | + | kind: subject.and_then(|subject| subject.kind), |
| 200 | + | number: Some(number), |
| 201 | + | run_id: None, |
| 202 | + | link: None, |
| 203 | + | }, |
| 204 | + | None => Thread { |
| 205 | + | key: format!("event/{}", event.id), |
| 206 | + | kind: None, |
| 207 | + | number: None, |
| 208 | + | run_id: None, |
| 209 | + | link: None, |
| 210 | + | }, |
| 211 | + | }, |
| 212 | + | } |
| 213 | + | } |
| 214 | + | |
| 215 | + | /// The issue or pull request whose agent threads an event closes: what an |
| 216 | + | /// agent was waiting on a person for is over. |
| 217 | + | pub fn resolves(event: &Event) -> Option<String> { |
| 218 | + | if !RESUMES.contains(&event.kind.as_str()) { |
| 219 | + | return None; |
| 220 | + | } |
| 221 | + | let repo_id = event.data["repoId"].as_str().map(str::to_owned).or_else(|| event.repo_id.clone())?; |
| 222 | + | let number = event.data["number"].as_u64().and_then(|n| u32::try_from(n).ok())?; |
| 223 | + | Some(numbered_thread(&repo_id, number)) |
| 224 | + | } |
| 225 | + | |
| 226 | + | /// Collects who is told, each once with the most specific reason, never |
| 227 | + | /// the actor, never g1t, and never anyone ignoring the thread. |
| 123 | 228 | | struct Told<'a> { |
| 124 | 229 | | actor: &'a Actor, |
| 230 | + | audience: &'a Audience, |
| 125 | 231 | | notices: Vec<Notice>, |
| 126 | 232 | | } |
| 127 | 233 | | |
| 128 | 234 | | impl Told<'_> { |
| 129 | | − | fn tell(&mut self, username: &str, reason: &'static str, severity: Severity, title: &str, body: &str) { |
| 235 | + | /// `asked`: something asked of the person directly, told even when |
| 236 | + | /// they unsubscribed from the thread. |
| 237 | + | fn tell(&mut self, username: &str, reason: Reason, severity: Severity, title: &str, body: &str, asked: bool) { |
| 130 | 238 | | let username = username.trim().trim_start_matches('@').to_lowercase(); |
| 131 | 239 | | if username.is_empty() |
| 132 | 240 | | || is_g1t(&username) |
| 133 | 241 | | || self.actor.is_named(&username) |
| 134 | | − | || self.notices.iter().any(|told| told.username == username) |
| 242 | + | || self.audience.ignores(&username) |
| 243 | + | || (!asked && self.audience.unsubscribed(&username)) |
| 135 | 244 | | { |
| 136 | 245 | | return; |
| 137 | 246 | | } |
| 138 | | − | self.notices.push(Notice { |
| 247 | + | let notice = Notice { |
| 139 | 248 | | username, |
| 140 | 249 | | reason, |
| 141 | 250 | | severity, |
| 142 | 251 | | title: clip(title, MAX_TITLE), |
| 143 | 252 | | body: clip(body, MAX_BODY), |
| 144 | | − | }); |
| 253 | + | }; |
| 254 | + | match self.notices.iter_mut().find(|told| told.username == notice.username) { |
| 255 | + | Some(told) if notice.reason.rank() < told.reason.rank() => *told = notice, |
| 256 | + | Some(_) => {} |
| 257 | + | None => self.notices.push(notice), |
| 258 | + | } |
| 145 | 259 | | } |
| 146 | 260 | | |
| 147 | 261 | | /// A person known by id as well as name, such as an author. |
| 148 | | − | fn tell_person(&mut self, person: &Principal, reason: &'static str, severity: Severity, title: &str, body: &str) { |
| 262 | + | fn tell_person(&mut self, person: &Principal, reason: Reason, severity: Severity, title: &str, body: &str, asked: bool) { |
| 149 | 263 | | if is_g1t_id(&person.id) || self.actor.is(person) { |
| 150 | 264 | | return; |
| 151 | 265 | | } |
| 152 | | − | self.tell(&person.username, reason, severity, title, body); |
| 266 | + | self.tell(&person.username, reason, severity, title, body, asked); |
| 267 | + | } |
| 268 | + | |
| 269 | + | /// Everyone subscribed to an issue or pull request: its owner and |
| 270 | + | /// author, its assignees and reviewers, and whoever subscribed by |
| 271 | + | /// commenting, being mentioned or by hand. `reason` overrides why |
| 272 | + | /// each is told, as a state change does. |
| 273 | + | fn tell_subscribed(&mut self, subject: &InboxSubject, reason: Option<Reason>, severity: Severity, title: &str, body: &str) { |
| 274 | + | let why = |own: Reason| reason.unwrap_or(own); |
| 275 | + | self.tell_person(subject.owner(), why(Reason::Author), severity, title, body, false); |
| 276 | + | self.tell_person(&subject.author, why(Reason::Author), severity, title, body, false); |
| 277 | + | for name in &subject.assignees { |
| 278 | + | self.tell(name, why(Reason::Assign), severity, title, body, false); |
| 279 | + | } |
| 280 | + | for name in &subject.reviewers { |
| 281 | + | self.tell(name, why(Reason::ReviewRequested), severity, title, body, false); |
| 282 | + | } |
| 283 | + | let subscribed: Vec<(String, Reason)> = self.audience.subscribed().collect(); |
| 284 | + | for (name, own) in subscribed { |
| 285 | + | self.tell(&name, why(own), severity, title, body, false); |
| 286 | + | } |
| 153 | 287 | | } |
| 288 | + | |
| 289 | + | /// Everyone watching the repository for this kind of activity. |
| 290 | + | fn tell_watchers(&mut self, kind: &str, severity: Severity, title: &str, body: &str) { |
| 291 | + | let watching: Vec<String> = self.audience.watching(kind).collect(); |
| 292 | + | for name in watching { |
| 293 | + | self.tell(&name, Reason::Subscribed, severity, title, body, false); |
| 294 | + | } |
| 295 | + | } |
| 154 | 296 | | } |
| 155 | 297 | | |
| 156 | 298 | | fn clip(text: &str, max: usize) -> String { |
| ⋯ |
| 162 | 304 | | format!("{}…", cut.trim_end()) |
| 163 | 305 | | } |
| 164 | 306 | | |
| 165 | | − | /// Who is told of `event`, in `repo` (`owner/name`), given what it names. |
| 166 | | − | /// `actor` is who caused it; outcomes nobody chose (checks, workflows, a |
| 167 | | − | /// review, an agent finishing) are told whoever caused them. |
| 168 | | − | pub fn notices(event: &Event, repo: &str, actor: &Actor, subject: Option<&InboxSubject>) -> Vec<Notice> { |
| 307 | + | /// The kind of activity a watcher chooses: `issues` or `pulls`. |
| 308 | + | fn activity_of(subject: &InboxSubject) -> &'static str { |
| 309 | + | match subject.kind { |
| 310 | + | Some(SubjectKind::Pull) => "pulls", |
| 311 | + | _ => "issues", |
| 312 | + | } |
| 313 | + | } |
| 314 | + | |
| 315 | + | /// The names in an event's list field, such as the reviewers just asked. |
| 316 | + | fn names(data: &serde_json::Value, key: &str) -> Vec<String> { |
| 317 | + | data[key] |
| 318 | + | .as_array() |
| 319 | + | .map(|names| names.iter().filter_map(|name| name.as_str().map(str::to_owned)).collect()) |
| 320 | + | .unwrap_or_default() |
| 321 | + | } |
| 322 | + | |
| 323 | + | /// Who is told of `event`, in `repo` (`owner/name`), given what it names |
| 324 | + | /// and who follows it. `actor` is who caused it; outcomes nobody chose |
| 325 | + | /// (checks, workflows, deployments, a review, an agent finishing or |
| 326 | + | /// stopping) are told whoever caused them. |
| 327 | + | pub fn notices(event: &Event, repo: &str, actor: &Actor, subject: Option<&InboxSubject>, audience: &Audience) -> Vec<Notice> { |
| 169 | 328 | | let nobody = Actor::default(); |
| 170 | 329 | | let data = &event.data; |
| 171 | 330 | | // The issue or pull request, as titles name it: `acme/rocket#12`. |
| ⋯ |
| 175 | 334 | | }; |
| 176 | 335 | | let outcome = matches!( |
| 177 | 336 | | event.kind.as_str(), |
| 178 | | − | "checks.completed" | "workflow.completed" | "review.completed" | "pull.ready" | "agent.asked" |
| 337 | + | "checks.completed" |
| 338 | + | | "workflow.completed" |
| 339 | + | | "review.completed" |
| 340 | + | | "pull.ready" |
| 341 | + | | "agent.asked" |
| 342 | + | | "pull.stalled" |
| 343 | + | | "deployment.failed" |
| 344 | + | | "deployment.succeeded" |
| 179 | 345 | | ); |
| 180 | 346 | | let mut told = Told { |
| 181 | 347 | | actor: if outcome { &nobody } else { actor }, |
| 348 | + | audience, |
| 182 | 349 | | notices: Vec::new(), |
| 183 | 350 | | }; |
| 351 | + | // Who did it, as titles name them. |
| 352 | + | let who = actor.name().unwrap_or("g1t"); |
| 184 | 353 | | |
| 185 | 354 | | match (event.kind.as_str(), subject) { |
| 186 | | − | ("agent.asked", Some(pull)) => { |
| 187 | | − | let title = format!("An agent is waiting on {}", at); |
| 188 | | − | told.tell_person(pull.owner(), "agent_asked", Severity::Warning, &title, &pull.title); |
| 355 | + | ("agent.asked" | "pull.stalled", Some(pull)) => { |
| 356 | + | let (title, body) = if event.kind == "agent.asked" { |
| 357 | + | (format!("An agent is waiting on {at}"), pull.title.clone()) |
| 358 | + | } else { |
| 359 | + | let detail = data["detail"].as_str().map(str::trim).filter(|detail| !detail.is_empty()); |
| 360 | + | (format!("g1t stopped on {at} and needs you"), detail.unwrap_or(&pull.title).to_owned()) |
| 361 | + | }; |
| 362 | + | told.tell_person(pull.owner(), Reason::Agent, Severity::Warning, &title, &body, true); |
| 189 | 363 | | if let Some(issue) = &pull.issue { |
| 190 | | − | told.tell_person(issue.owner(), "agent_asked", Severity::Warning, &title, &pull.title); |
| 364 | + | told.tell_person(issue.owner(), Reason::Agent, Severity::Warning, &title, &body, true); |
| 191 | 365 | | for name in &issue.assignees { |
| 192 | | − | told.tell(name, "agent_asked", Severity::Warning, &title, &pull.title); |
| 366 | + | told.tell(name, Reason::Agent, Severity::Warning, &title, &body, true); |
| 193 | 367 | | } |
| 194 | 368 | | } |
| 195 | 369 | | } |
| 370 | + | ("pull.review_requested", Some(pull)) => { |
| 371 | + | let title = format!("{who} asked you to review {at}"); |
| 372 | + | for name in names(data, "reviewers") { |
| 373 | + | told.tell(&name, Reason::ReviewRequested, Severity::Warning, &title, &pull.title, true); |
| 374 | + | } |
| 375 | + | } |
| 376 | + | ("issue.assigned" | "pull.assigned", Some(on)) => { |
| 377 | + | let title = format!("{who} assigned you to {at}"); |
| 378 | + | for name in names(data, "added") { |
| 379 | + | told.tell(&name, Reason::Assign, Severity::Info, &title, &on.title, true); |
| 380 | + | } |
| 381 | + | } |
| 382 | + | ("issue.opened" | "pull.opened", Some(on)) => { |
| 383 | + | let title = format!("{who} opened {at}"); |
| 384 | + | for name in &on.assignees { |
| 385 | + | told.tell(name, Reason::Assign, Severity::Info, &format!("{who} assigned you to {at}"), &on.title, true); |
| 386 | + | } |
| 387 | + | for name in &on.reviewers { |
| 388 | + | told.tell(name, Reason::ReviewRequested, Severity::Warning, &format!("{who} asked you to review {at}"), &on.title, true); |
| 389 | + | } |
| 390 | + | told.tell_watchers(activity_of(on), Severity::Info, &title, &on.title); |
| 391 | + | } |
| 196 | 392 | | ("checks.completed", Some(pull)) => { |
| 197 | 393 | | let title = match data["status"].as_str() { |
| 198 | | − | Some("errored") => format!("Checks could not run on {}", at), |
| 199 | | − | _ => format!("Checks failed on {}", at), |
| 394 | + | Some("errored") => format!("Checks could not run on {at}"), |
| 395 | + | _ => format!("Checks failed on {at}"), |
| 200 | 396 | | }; |
| 201 | | − | told.tell_person(pull.owner(), "checks_failed", Severity::Error, &title, &pull.title); |
| 397 | + | told.tell_person(pull.owner(), Reason::CiActivity, Severity::Error, &title, &pull.title, true); |
| 202 | 398 | | } |
| 203 | 399 | | ("workflow.completed", subject) => { |
| 204 | 400 | | let workflow = data["workflow"].as_str().filter(|name| !name.is_empty()).unwrap_or("A workflow"); |
| 205 | 401 | | match subject { |
| 206 | 402 | | Some(pull) => { |
| 207 | | − | let title = format!("{workflow} failed on {}", at); |
| 208 | | − | told.tell_person(pull.owner(), "workflow_failed", Severity::Error, &title, &pull.title); |
| 403 | + | let title = format!("{workflow} failed on {at}"); |
| 404 | + | told.tell_person(pull.owner(), Reason::CiActivity, Severity::Error, &title, &pull.title, true); |
| 209 | 405 | | } |
| 210 | 406 | | None => { |
| 211 | 407 | | // Not on a pull request: whoever pushed the commit it ran on. |
| ⋯ |
| 217 | 413 | | && !is_g1t_id(id) |
| 218 | 414 | | && let Some(name) = &actor.username |
| 219 | 415 | | { |
| 220 | | − | told.tell(name, "workflow_failed", Severity::Error, &title, &body); |
| 416 | + | told.tell(name, Reason::CiActivity, Severity::Error, &title, &body, true); |
| 417 | + | } |
| 418 | + | } |
| 419 | + | } |
| 420 | + | } |
| 421 | + | ("deployment.failed" | "deployment.succeeded", subject) => { |
| 422 | + | let failed = event.kind == "deployment.failed"; |
| 423 | + | let project = data["project"].as_str().filter(|name| !name.is_empty()).unwrap_or(repo); |
| 424 | + | let what = match subject { |
| 425 | + | Some(_) => format!("The preview of {at}"), |
| 426 | + | None => format!("Production of {project}"), |
| 427 | + | }; |
| 428 | + | let (title, severity) = if failed { |
| 429 | + | (format!("{what} failed to deploy"), Severity::Error) |
| 430 | + | } else { |
| 431 | + | (format!("{what} is live"), Severity::Success) |
| 432 | + | }; |
| 433 | + | let body = match (failed, data["error"].as_str().map(str::trim).filter(|error| !error.is_empty())) { |
| 434 | + | (true, Some(error)) => error.to_owned(), |
| 435 | + | _ => match subject { |
| 436 | + | Some(pull) => pull.title.clone(), |
| 437 | + | None => format!("Commit {}", short(data["commit"].as_str().unwrap_or_default())), |
| 438 | + | }, |
| 439 | + | }; |
| 440 | + | // A success is news to whoever answers for it only after a failure. |
| 441 | + | if failed || data["recovered"].as_bool() == Some(true) { |
| 442 | + | let title = if failed { title.clone() } else { format!("{what} is live again") }; |
| 443 | + | match subject { |
| 444 | + | Some(pull) => told.tell_person(pull.owner(), Reason::CiActivity, severity, &title, &body, true), |
| 445 | + | None => { |
| 446 | + | let pusher = actor |
| 447 | + | .id |
| 448 | + | .as_deref() |
| 449 | + | .filter(|id| !is_g1t_id(id)) |
| 450 | + | .and(actor.username.as_deref()) |
| 451 | + | .or_else(|| data["triggeredBy"].as_str()); |
| 452 | + | if let Some(name) = pusher { |
| 453 | + | told.tell(name, Reason::CiActivity, severity, &title, &body, true); |
| 454 | + | } |
| 221 | 455 | | } |
| 222 | 456 | | } |
| 223 | 457 | | } |
| 458 | + | told.tell_watchers("deployments", severity, &title, &body); |
| 224 | 459 | | } |
| 225 | 460 | | ("review.completed", Some(pull)) => { |
| 226 | | − | let (title, severity, reason) = match data["verdict"].as_str() { |
| 227 | | − | Some("approve") => (format!("g1t approved {}", at), Severity::Success, "approved"), |
| 228 | | − | _ => (format!("g1t asked for changes on {}", at), Severity::Info, "changes_requested"), |
| 461 | + | let (title, severity) = match data["verdict"].as_str() { |
| 462 | + | Some("approve") => (format!("g1t approved {at}"), Severity::Success), |
| 463 | + | _ => (format!("g1t asked for changes on {at}"), Severity::Info), |
| 229 | 464 | | }; |
| 230 | | − | told.tell_person(pull.owner(), reason, severity, &title, &pull.title); |
| 465 | + | told.tell_person(pull.owner(), Reason::Author, severity, &title, &pull.title, true); |
| 231 | 466 | | } |
| 232 | 467 | | ("pull.ready", Some(pull)) => { |
| 233 | 468 | | // A change g1t made is ready: the agent's run is over. |
| 234 | 469 | | if let Some(owner) = pull.requested_by.as_ref().filter(|_| is_g1t_id(&pull.author.id) || is_g1t(&pull.author.username)) { |
| 235 | | − | let title = format!("g1t finished {}", at); |
| 236 | | − | told.tell_person(owner, "agent_finished", Severity::Success, &title, &pull.title); |
| 470 | + | let title = format!("g1t finished {at}"); |
| 471 | + | told.tell_person(owner, Reason::Author, Severity::Success, &title, &pull.title, true); |
| 237 | 472 | | } |
| 238 | 473 | | } |
| 239 | | − | ("pull.merged", Some(pull)) => { |
| 240 | | − | let title = match &actor.username { |
| 241 | | − | Some(name) if !is_g1t(name) => format!("{name} merged {}", at), |
| 242 | | − | _ => format!("{} was merged", at), |
| 474 | + | ("pull.merged" | "pull.closed" | "issue.closed" | "issue.reopened", Some(on)) => { |
| 475 | + | let (verb, severity) = match event.kind.as_str() { |
| 476 | + | "pull.merged" => ("merged", Severity::Success), |
| 477 | + | "issue.reopened" => ("reopened", Severity::Info), |
| 478 | + | _ => ("closed", Severity::Info), |
| 479 | + | }; |
| 480 | + | let title = match (actor.name(), data["resolvedBy"].as_u64()) { |
| 481 | + | (_, Some(pull)) if event.kind == "issue.closed" => format!("{at} was closed by #{pull}"), |
| 482 | + | (Some(name), _) => format!("{name} {verb} {at}"), |
| 483 | + | (None, _) => format!("{at} was {verb}"), |
| 243 | 484 | | }; |
| 244 | | − | told.tell_person(pull.owner(), "merged", Severity::Success, &title, &pull.title); |
| 485 | + | told.tell_subscribed(on, Some(Reason::StateChange), severity, &title, &on.title); |
| 486 | + | told.tell_watchers(activity_of(on), severity, &title, &on.title); |
| 245 | 487 | | } |
| 246 | 488 | | ("comment.created", Some(on)) => { |
| 247 | 489 | | let Some(comment) = on.comment.as_ref().filter(|comment| !comment.event) else { |
| ⋯ |
| 256 | 498 | | let who = &comment.author.username; |
| 257 | 499 | | let body = if comment.excerpt.is_empty() { &on.title } else { &comment.excerpt }; |
| 258 | 500 | | for name in &comment.mentions { |
| 259 | | − | let title = format!("{who} mentioned you on {}", at); |
| 260 | | − | told.tell(name, "mentioned", Severity::Info, &title, body); |
| 501 | + | let title = format!("{who} mentioned you on {at}"); |
| 502 | + | told.tell(name, Reason::Mention, Severity::Info, &title, body, true); |
| 261 | 503 | | } |
| 262 | | − | let (reason, severity, title) = match comment.verdict.as_deref() { |
| 263 | | − | Some("approve") => ("approved", Severity::Success, format!("{who} approved {}", at)), |
| 264 | | − | Some("request_changes") => ("changes_requested", Severity::Info, format!("{who} asked for changes on {}", at)), |
| 265 | | − | _ => ("commented", Severity::Info, format!("{who} commented on {}", at)), |
| 504 | + | let (severity, title) = match comment.verdict.as_deref() { |
| 505 | + | Some("approve") => (Severity::Success, format!("{who} approved {at}")), |
| 506 | + | Some("request_changes") => (Severity::Info, format!("{who} asked for changes on {at}")), |
| 507 | + | _ => (Severity::Info, format!("{who} commented on {at}")), |
| 266 | 508 | | }; |
| 267 | | − | told.tell_person(on.owner(), reason, severity, &title, body); |
| 509 | + | // An approval or a request for changes is the owner's to hear |
| 510 | + | // of whatever they chose; the rest, as they subscribed. |
| 511 | + | if comment.verdict.is_some() { |
| 512 | + | told.tell_person(on.owner(), Reason::Author, severity, &title, body, true); |
| 513 | + | } |
| 514 | + | told.tell_subscribed(on, None, severity, &title, body); |
| 515 | + | told.tell_watchers(activity_of(on), severity, &title, body); |
| 268 | 516 | | return told.notices; |
| 269 | 517 | | } |
| 270 | 518 | | _ => {} |
| ⋯ |
| 272 | 520 | | told.notices |
| 273 | 521 | | } |
| 274 | 522 | | |
| 523 | + | /// Who an event subscribes to its issue or pull request without asking, |
| 524 | + | /// and why: whoever commented, whoever they mentioned, the people assigned |
| 525 | + | /// and the reviewers asked. Never g1t. |
| 526 | + | pub fn subscribes(event: &Event, subject: Option<&InboxSubject>) -> Vec<(String, Reason)> { |
| 527 | + | let mut people: Vec<(String, Reason)> = Vec::new(); |
| 528 | + | let mut add = |name: &str, reason: Reason| { |
| 529 | + | let name = name.trim().trim_start_matches('@').to_lowercase(); |
| 530 | + | if !name.is_empty() && !is_g1t(&name) && !people.iter().any(|(had, _)| *had == name) { |
| 531 | + | people.push((name, reason)); |
| 532 | + | } |
| 533 | + | }; |
| 534 | + | match event.kind.as_str() { |
| 535 | + | "comment.created" => { |
| 536 | + | if let Some(comment) = subject.and_then(|subject| subject.comment.as_ref()).filter(|comment| !comment.event) { |
| 537 | + | if !is_g1t_id(&comment.author.id) { |
| 538 | + | add(&comment.author.username, Reason::Comment); |
| 539 | + | } |
| 540 | + | for name in &comment.mentions { |
| 541 | + | add(name, Reason::Mention); |
| 542 | + | } |
| 543 | + | } |
| 544 | + | } |
| 545 | + | "issue.assigned" | "pull.assigned" => { |
| 546 | + | for name in names(&event.data, "added") { |
| 547 | + | add(&name, Reason::Assign); |
| 548 | + | } |
| 549 | + | } |
| 550 | + | "pull.review_requested" => { |
| 551 | + | for name in names(&event.data, "reviewers") { |
| 552 | + | add(&name, Reason::ReviewRequested); |
| 553 | + | } |
| 554 | + | } |
| 555 | + | _ => {} |
| 556 | + | } |
| 557 | + | people |
| 558 | + | } |
| 559 | + | |
| 275 | 560 | | fn short(sha: &str) -> &str { |
| 276 | 561 | | sha.get(..7).unwrap_or(sha) |
| 277 | 562 | | } |
| 278 | 563 | | |
| 279 | 564 | | /// Where an item is on g1t.sh. |
| 280 | | − | pub fn url(repo: Option<&str>, subject: Option<SubjectKind>, number: Option<u32>, run_id: Option<&str>) -> String { |
| 565 | + | pub fn url(repo: Option<&str>, subject: Option<SubjectKind>, number: Option<u32>, run_id: Option<&str>, link: Option<&str>) -> String { |
| 566 | + | if let Some(link) = link.filter(|link| link.starts_with('/')) { |
| 567 | + | return link.to_owned(); |
| 568 | + | } |
| 281 | 569 | | let Some(repo) = repo else { |
| 282 | 570 | | return "/inbox".to_owned(); |
| 283 | 571 | | }; |
| ⋯ |
| 285 | 573 | | (Some(SubjectKind::Pull), Some(number), _) => format!("/{repo}/pull/{number}"), |
| 286 | 574 | | (Some(SubjectKind::Issue), Some(number), _) => format!("/{repo}/issues/{number}"), |
| 287 | 575 | | (Some(SubjectKind::Run), _, Some(run)) => format!("/{repo}/actions/runs/{run}"), |
| 576 | + | (Some(SubjectKind::Deploy), Some(number), _) => format!("/{repo}/pull/{number}"), |
| 288 | 577 | | _ => format!("/{repo}"), |
| 289 | 578 | | } |
| 290 | 579 | | } |
| ⋯ |
| 298 | 587 | | pub identity: &'a Fetcher, |
| 299 | 588 | | } |
| 300 | 589 | | |
| 590 | + | /// One notice written, and whether it was news (not a redelivery): what |
| 591 | + | /// may be emailed. |
| 592 | + | struct Written { |
| 593 | + | notice: Notice, |
| 594 | + | repo_id: String, |
| 595 | + | url: String, |
| 596 | + | } |
| 597 | + | |
| 301 | 598 | | /// Writes the items a batch from the bus calls for. Never fails the batch: |
| 302 | 599 | | /// what cannot be worked out is logged and left. |
| 303 | 600 | | pub async fn deliver(db: &D1Database, sources: &Sources<'_>, events: &[Event]) { |
| 601 | + | if let Err(error) = resolve(db, events).await { |
| 602 | + | worker::console_error!("inbox: agent threads not closed: {error}"); |
| 603 | + | } |
| 304 | 604 | | let wanted: Vec<(&Event, Wanted)> = events |
| 305 | 605 | | .iter() |
| 306 | 606 | | .filter_map(|event| wants(event).map(|wanted| (event, wanted))) |
| 307 | 607 | | .collect(); |
| 308 | | − | if wanted.is_empty() { |
| 608 | + | let created: Vec<&Event> = events.iter().filter(|event| event.kind == "repo.created").collect(); |
| 609 | + | if wanted.is_empty() && created.is_empty() { |
| 309 | 610 | | return; |
| 310 | 611 | | } |
| 311 | 612 | | // Everyone who caused one, named in one call. |
| 312 | 613 | | let ids: Vec<String> = wanted |
| 313 | 614 | | .iter() |
| 314 | | − | .filter_map(|(event, _)| event.actor.clone()) |
| 615 | + | .map(|(event, _)| *event) |
| 616 | + | .chain(created.iter().copied()) |
| 617 | + | .filter_map(|event| event.actor.clone()) |
| 315 | 618 | | .filter(|id| !is_g1t_id(id)) |
| 316 | 619 | | .collect::<HashSet<_>>() |
| 317 | 620 | | .into_iter() |
| ⋯ |
| 326 | 629 | | HashMap::new() |
| 327 | 630 | | }) |
| 328 | 631 | | }; |
| 632 | + | for event in created { |
| 633 | + | if let Err(error) = subscriptions::watch_created(db, event, &names).await { |
| 634 | + | worker::console_error!("inbox: {} {} not watched: {error}", event.kind, event.id); |
| 635 | + | } |
| 636 | + | } |
| 329 | 637 | | let mut paths: HashMap<String, Option<RepoPath>> = HashMap::new(); |
| 638 | + | let mut watchers: HashMap<String, Vec<subscriptions::Watcher>> = HashMap::new(); |
| 639 | + | let mut written: Vec<Written> = Vec::new(); |
| 330 | 640 | | for (event, wanted) in wanted { |
| 331 | | − | if let Err(error) = deliver_one(db, sources, &names, &mut paths, event, wanted).await { |
| 332 | | − | worker::console_error!("inbox: {} {} not delivered: {error}", event.kind, event.id); |
| 641 | + | match deliver_one(db, sources, &names, &mut paths, &mut watchers, event, wanted).await { |
| 642 | + | Ok(mut news) => written.append(&mut news), |
| 643 | + | Err(error) => worker::console_error!("inbox: {} {} not delivered: {error}", event.kind, event.id), |
| 644 | + | } |
| 645 | + | } |
| 646 | + | if let Err(error) = email(db, sources.identity, written).await { |
| 647 | + | worker::console_error!("inbox: emails not sent: {error}"); |
| 648 | + | } |
| 649 | + | } |
| 650 | + | |
| 651 | + | /// Closes what an agent was waiting on a person for once it is over. |
| 652 | + | async fn resolve(db: &D1Database, events: &[Event]) -> Result<()> { |
| 653 | + | let now = rfc3339(now_ms()); |
| 654 | + | let mut statements = Vec::new(); |
| 655 | + | for thread in events.iter().filter_map(resolves) { |
| 656 | + | statements.push( |
| 657 | + | db.prepare( |
| 658 | + | "UPDATE inbox_items SET done_at = ?1, read_at = COALESCE(read_at, ?1) |
| 659 | + | WHERE thread = ?2 AND reason = 'agent' AND done_at IS NULL", |
| 660 | + | ) |
| 661 | + | .bind(&[now.as_str().into(), thread.into()])?, |
| 662 | + | ); |
| 663 | + | } |
| 664 | + | // Reviews no longer asked for are no longer waiting. |
| 665 | + | for event in events.iter().filter(|event| event.kind == "pull.review_request_removed") { |
| 666 | + | let (Some(repo_id), Some(number)) = ( |
| 667 | + | event.data["repoId"].as_str().map(str::to_owned).or_else(|| event.repo_id.clone()), |
| 668 | + | event.data["number"].as_u64(), |
| 669 | + | ) else { |
| 670 | + | continue; |
| 671 | + | }; |
| 672 | + | for name in names(&event.data, "reviewers") { |
| 673 | + | statements.push( |
| 674 | + | db.prepare( |
| 675 | + | "UPDATE inbox_items SET done_at = ?1, read_at = COALESCE(read_at, ?1) |
| 676 | + | WHERE thread = ?2 AND username = ?3 AND reason = 'review_requested' AND done_at IS NULL", |
| 677 | + | ) |
| 678 | + | .bind(&[ |
| 679 | + | now.as_str().into(), |
| 680 | + | format!("{repo_id}#{number}").into(), |
| 681 | + | name.to_lowercase().into(), |
| 682 | + | ])?, |
| 683 | + | ); |
| 333 | 684 | | } |
| 334 | 685 | | } |
| 686 | + | if !statements.is_empty() { |
| 687 | + | db.batch(statements).await?; |
| 688 | + | } |
| 689 | + | Ok(()) |
| 335 | 690 | | } |
| 336 | 691 | | |
| 337 | 692 | | async fn deliver_one( |
| ⋯ |
| 339 | 694 | | sources: &Sources<'_>, |
| 340 | 695 | | names: &HashMap<String, String>, |
| 341 | 696 | | paths: &mut HashMap<String, Option<RepoPath>>, |
| 697 | + | watchers: &mut HashMap<String, Vec<subscriptions::Watcher>>, |
| 342 | 698 | | event: &Event, |
| 343 | 699 | | wanted: Wanted, |
| 344 | | − | ) -> Result<()> { |
| 700 | + | ) -> Result<Vec<Written>> { |
| 345 | 701 | | if !paths.contains_key(&wanted.repo_id) { |
| 346 | 702 | | let path: Option<RepoPath> = g1t_kit::call( |
| 347 | 703 | | sources.repos, |
| ⋯ |
| 355 | 711 | | } |
| 356 | 712 | | // A repository that is gone tells nobody. |
| 357 | 713 | | let Some(path) = paths.get(&wanted.repo_id).cloned().flatten() else { |
| 358 | | − | return Ok(()); |
| 714 | + | return Ok(Vec::new()); |
| 359 | 715 | | }; |
| 360 | 716 | | let subject: Option<InboxSubject> = match wanted.number { |
| 361 | 717 | | Some(number) => { |
| ⋯ |
| 370 | 726 | | ) |
| 371 | 727 | | .await?; |
| 372 | 728 | | if found.is_none() { |
| 373 | | − | return Ok(()); |
| 729 | + | return Ok(Vec::new()); |
| 374 | 730 | | } |
| 375 | 731 | | found |
| 376 | 732 | | } |
| ⋯ |
| 384 | 740 | | None => None, |
| 385 | 741 | | }, |
| 386 | 742 | | }; |
| 743 | + | let thread = thread_of(event, &wanted, subject.as_ref()); |
| 744 | + | if !watchers.contains_key(&wanted.repo_id) { |
| 745 | + | watchers.insert(wanted.repo_id.clone(), subscriptions::watchers(db, &wanted.repo_id).await?); |
| 746 | + | } |
| 747 | + | let audience = Audience { |
| 748 | + | subscriptions: match thread.kind { |
| 749 | + | Some(SubjectKind::Issue | SubjectKind::Pull) => subscriptions::of_thread(db, &thread.key).await?, |
| 750 | + | _ => Vec::new(), |
| 751 | + | }, |
| 752 | + | watchers: watchers.get(&wanted.repo_id).cloned().unwrap_or_default(), |
| 753 | + | }; |
| 387 | 754 | | let repo = format!("{}/{}", path.namespace, path.name).to_lowercase(); |
| 388 | | − | let told = notices(event, &repo, &actor, subject.as_ref()); |
| 755 | + | let told = notices(event, &repo, &actor, subject.as_ref(), &audience); |
| 756 | + | let mut statements = subscriptions::auto_subscribe(db, &thread.key, &wanted.repo_id, &subscribes(event, subject.as_ref()), &event.time)?; |
| 389 | 757 | | if told.is_empty() { |
| 390 | | − | return Ok(()); |
| 758 | + | if !statements.is_empty() { |
| 759 | + | db.batch(statements).await?; |
| 760 | + | } |
| 761 | + | return Ok(Vec::new()); |
| 391 | 762 | | } |
| 392 | | − | let (kind, number, run_id) = match (&subject, event.kind.as_str()) { |
| 393 | | − | (Some(subject), _) => (subject.kind, wanted.number, None), |
| 394 | | − | (None, "workflow.completed") => (Some(SubjectKind::Run), None, event.data["runId"].as_str()), |
| 395 | | − | (None, _) => (None, None, None), |
| 396 | | − | }; |
| 397 | 763 | | let now = now_ms(); |
| 398 | | − | let mut statements = Vec::with_capacity(told.len()); |
| 399 | | − | for notice in told { |
| 764 | + | let link = thread.link.as_deref(); |
| 765 | + | let item_url = url(Some(&repo), thread.kind, thread.number, thread.run_id.as_deref(), link); |
| 766 | + | // Three statements a notice: its thread brought up (unless this event |
| 767 | + | // was told before), a line of history, and the history kept short. |
| 768 | + | let first = statements.len(); |
| 769 | + | for notice in &told { |
| 770 | + | let username = notice.username.as_str(); |
| 771 | + | let values: Vec<JsValue> = vec![ |
| 772 | + | new_id("ntf", now).into(), |
| 773 | + | username.into(), |
| 774 | + | thread.key.as_str().into(), |
| 775 | + | event.id.as_str().into(), |
| 776 | + | event.kind.as_str().into(), |
| 777 | + | notice.reason.as_str().into(), |
| 778 | + | notice.severity.as_str().into(), |
| 779 | + | notice.title.as_str().into(), |
| 780 | + | notice.body.as_str().into(), |
| 781 | + | path.namespace.to_lowercase().into(), |
| 782 | + | wanted.repo_id.as_str().into(), |
| 783 | + | repo.as_str().into(), |
| 784 | + | thread.kind.map_or(JsValue::NULL, |kind| kind.as_str().into()), |
| 785 | + | thread.number.map_or(JsValue::NULL, JsValue::from), |
| 786 | + | thread.run_id.as_deref().map_or(JsValue::NULL, JsValue::from), |
| 787 | + | link.map_or(JsValue::NULL, JsValue::from), |
| 788 | + | actor.username.as_deref().map_or(JsValue::NULL, JsValue::from), |
| 789 | + | event.time.as_str().into(), |
| 790 | + | // Same prefix as item ids, so old and new sort by time together. |
| 791 | + | new_id("ntf", now).into(), |
| 792 | + | ]; |
| 793 | + | statements.push(db.prepare(BUMP).bind(&values)?); |
| 400 | 794 | | statements.push( |
| 401 | 795 | | db.prepare( |
| 402 | | − | // A redelivered event finds its rows there already. |
| 403 | | − | "INSERT OR IGNORE INTO inbox_items (id, username, event_id, reason, severity, title, body, |
| 404 | | − | workspace, repo_id, repo, subject, number, run_id, actor, created_at) |
| 405 | | − | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", |
| 796 | + | "INSERT OR IGNORE INTO inbox_activity (id, item_id, username, event_id, event, reason, severity, title, body, actor, created_at) |
| 797 | + | SELECT ?1, id, ?2, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11 FROM inbox_items WHERE username = ?2 AND thread = ?3 |
| 798 | + | RETURNING username", |
| 406 | 799 | | ) |
| 407 | 800 | | .bind(&[ |
| 408 | 801 | | new_id("ntf", now).into(), |
| 409 | | − | notice.username.as_str().into(), |
| 802 | + | username.into(), |
| 803 | + | thread.key.as_str().into(), |
| 410 | 804 | | event.id.as_str().into(), |
| 411 | | − | notice.reason.into(), |
| 805 | + | event.kind.as_str().into(), |
| 806 | + | notice.reason.as_str().into(), |
| 412 | 807 | | notice.severity.as_str().into(), |
| 413 | 808 | | notice.title.as_str().into(), |
| 414 | 809 | | notice.body.as_str().into(), |
| 415 | | − | path.namespace.to_lowercase().into(), |
| 416 | | − | wanted.repo_id.as_str().into(), |
| 417 | | − | repo.as_str().into(), |
| 418 | | − | kind.map_or(JsValue::NULL, |kind| kind.as_str().into()), |
| 419 | | − | number.map_or(JsValue::NULL, JsValue::from), |
| 420 | | − | run_id.map_or(JsValue::NULL, JsValue::from), |
| 421 | 810 | | actor.username.as_deref().map_or(JsValue::NULL, JsValue::from), |
| 422 | 811 | | event.time.as_str().into(), |
| 423 | 812 | | ])?, |
| 424 | 813 | | ); |
| 814 | + | statements.push( |
| 815 | + | db.prepare( |
| 816 | + | "DELETE FROM inbox_activity |
| 817 | + | WHERE item_id = (SELECT id FROM inbox_items WHERE username = ?1 AND thread = ?2) |
| 818 | + | AND id NOT IN ( |
| 819 | + | SELECT a.id FROM inbox_activity a |
| 820 | + | WHERE a.item_id = (SELECT id FROM inbox_items WHERE username = ?1 AND thread = ?2) |
| 821 | + | ORDER BY a.id DESC LIMIT ?3)", |
| 822 | + | ) |
| 823 | + | .bind(&[username.into(), thread.key.as_str().into(), MAX_ACTIVITY.into()])?, |
| 824 | + | ); |
| 825 | + | } |
| 826 | + | let results = db.batch(statements).await?; |
| 827 | + | #[derive(Deserialize)] |
| 828 | + | struct Told { |
| 829 | + | username: String, |
| 425 | 830 | | } |
| 426 | | − | db.batch(statements).await?; |
| 831 | + | // A line of history written means the event is news to that person. |
| 832 | + | let mut news = HashSet::new(); |
| 833 | + | for (at, _) in told.iter().enumerate() { |
| 834 | + | if let Some(result) = results.get(first + at * 3 + 1) |
| 835 | + | && let Ok(rows) = result.results::<Told>() |
| 836 | + | { |
| 837 | + | news.extend(rows.into_iter().map(|row| row.username)); |
| 838 | + | } |
| 839 | + | } |
| 840 | + | Ok(told |
| 841 | + | .into_iter() |
| 842 | + | .filter(|notice| news.contains(¬ice.username)) |
| 843 | + | .map(|notice| Written { |
| 844 | + | notice, |
| 845 | + | repo_id: wanted.repo_id.clone(), |
| 846 | + | url: item_url.clone(), |
| 847 | + | }) |
| 848 | + | .collect()) |
| 849 | + | } |
| 850 | + | |
| 851 | + | /// Brings a person's thread up with new activity, or starts it. `?1` id, |
| 852 | + | /// `?2` username, `?3` thread, `?4` event id, `?5` event type, `?6` reason, |
| 853 | + | /// `?7` severity, `?8` title, `?9` body, `?10` workspace, `?11` repo id, |
| 854 | + | /// `?12` repo, `?13` subject, `?14` number, `?15` run id, `?16` link, `?17` |
| 855 | + | /// actor, `?18` time, `?19` the time-sortable id lists order by. Nothing |
| 856 | + | /// happens when the person was already told of this event. While the |
| 857 | + | /// thread is unread its most urgent severity is kept; done or not, it |
| 858 | + | /// comes back to the inbox. A snooze stands. |
| 859 | + | const BUMP: &str = "INSERT INTO inbox_items (id, username, thread, event_id, event, reason, severity, title, body, |
| 860 | + | workspace, repo_id, repo, subject, number, run_id, link, actor, created_at, updated_at, bumped, activity) |
| 861 | + | SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?18, ?19, 1 |
| 862 | + | WHERE NOT EXISTS (SELECT 1 FROM inbox_activity WHERE event_id = ?4 AND username = ?2) |
| 863 | + | ON CONFLICT (username, thread) DO UPDATE SET |
| 864 | + | event_id = excluded.event_id, |
| 865 | + | event = excluded.event, |
| 866 | + | reason = excluded.reason, |
| 867 | + | severity = CASE |
| 868 | + | WHEN inbox_items.read_at IS NULL AND inbox_items.done_at IS NULL |
| 869 | + | AND (CASE inbox_items.severity WHEN 'warning' THEN 0 WHEN 'error' THEN 1 WHEN 'success' THEN 2 ELSE 3 END) |
| 870 | + | < (CASE excluded.severity WHEN 'warning' THEN 0 WHEN 'error' THEN 1 WHEN 'success' THEN 2 ELSE 3 END) |
| 871 | + | THEN inbox_items.severity ELSE excluded.severity END, |
| 872 | + | title = excluded.title, |
| 873 | + | body = excluded.body, |
| 874 | + | workspace = excluded.workspace, |
| 875 | + | repo = excluded.repo, |
| 876 | + | subject = COALESCE(excluded.subject, inbox_items.subject), |
| 877 | + | run_id = COALESCE(excluded.run_id, inbox_items.run_id), |
| 878 | + | link = COALESCE(excluded.link, inbox_items.link), |
| 879 | + | actor = excluded.actor, |
| 880 | + | updated_at = excluded.updated_at, |
| 881 | + | bumped = excluded.bumped, |
| 882 | + | activity = inbox_items.activity + 1, |
| 883 | + | read_at = NULL, |
| 884 | + | done_at = NULL"; |
| 885 | + | |
| 886 | + | /// Emails what was news to people who asked to be emailed for its reason. |
| 887 | + | /// Identity sends each, only to a confirmed address and only if the person |
| 888 | + | /// can still read the repository. |
| 889 | + | async fn email(db: &D1Database, identity: &Fetcher, written: Vec<Written>) -> Result<()> { |
| 890 | + | if written.is_empty() { |
| 891 | + | return Ok(()); |
| 892 | + | } |
| 893 | + | let people: Vec<String> = written |
| 894 | + | .iter() |
| 895 | + | .map(|item| item.notice.username.clone()) |
| 896 | + | .collect::<HashSet<_>>() |
| 897 | + | .into_iter() |
| 898 | + | .collect(); |
| 899 | + | let settings = subscriptions::settings_of(db, &people).await?; |
| 900 | + | for item in written { |
| 901 | + | let wants = settings.get(&item.notice.username).map_or(&DEFAULT_EMAIL[..], |settings| &settings.email[..]); |
| 902 | + | if !wants.contains(&item.notice.reason) { |
| 903 | + | continue; |
| 904 | + | } |
| 905 | + | let sent: Result<bool> = g1t_kit::call( |
| 906 | + | identity, |
| 907 | + | "notify_by_email", |
| 908 | + | &NotifyByEmailArgs { |
| 909 | + | username: item.notice.username.clone(), |
| 910 | + | repo_id: item.repo_id.clone(), |
| 911 | + | subject: item.notice.title.clone(), |
| 912 | + | intro: item.notice.body.clone(), |
| 913 | + | quote: None, |
| 914 | + | path: item.url.clone(), |
| 915 | + | reason: item.notice.reason, |
| 916 | + | }, |
| 917 | + | ) |
| 918 | + | .await; |
| 919 | + | if let Err(error) = sent { |
| 920 | + | worker::console_error!("inbox: email to {} not sent: {error}", item.notice.username); |
| 921 | + | } |
| 922 | + | } |
| 427 | 923 | | Ok(()) |
| 428 | 924 | | } |
| 429 | 925 | | |
| 430 | 926 | | // --- Reading and changing ---------------------------------------------------- |
| 431 | 927 | | |
| 432 | 928 | | #[derive(Deserialize)] |
| 433 | | − | struct Row { |
| 434 | | − | id: String, |
| 929 | + | pub(crate) struct Row { |
| 930 | + | pub(crate) id: String, |
| 435 | 931 | | reason: String, |
| 436 | 932 | | severity: String, |
| 437 | 933 | | title: String, |
| 438 | 934 | | body: String, |
| 935 | + | event: Option<String>, |
| 439 | 936 | | workspace: Option<String>, |
| 440 | | − | repo_id: Option<String>, |
| 937 | + | pub(crate) repo_id: Option<String>, |
| 441 | 938 | | repo: Option<String>, |
| 442 | 939 | | subject: Option<String>, |
| 443 | 940 | | number: Option<f64>, |
| 444 | 941 | | run_id: Option<String>, |
| 942 | + | link: Option<String>, |
| 445 | 943 | | actor: Option<String>, |
| 944 | + | activity: Option<f64>, |
| 446 | 945 | | created_at: String, |
| 946 | + | updated_at: Option<String>, |
| 447 | 947 | | read_at: Option<String>, |
| 448 | 948 | | done_at: Option<String>, |
| 449 | 949 | | saved: f64, |
| 450 | 950 | | snoozed_until: Option<String>, |
| 951 | + | bumped: Option<String>, |
| 451 | 952 | | } |
| 452 | 953 | | |
| 453 | 954 | | impl Row { |
| 454 | | − | fn into_item(self) -> InboxItem { |
| 955 | + | pub(crate) fn into_item(self) -> InboxItem { |
| 455 | 956 | | let subject = self.subject.as_deref().and_then(SubjectKind::parse); |
| 456 | 957 | | let number = self.number.map(|n| n as u32); |
| 457 | 958 | | InboxItem { |
| 458 | | − | url: url(self.repo.as_deref(), subject, number, self.run_id.as_deref()), |
| 959 | + | url: url(self.repo.as_deref(), subject, number, self.run_id.as_deref(), self.link.as_deref()), |
| 459 | 960 | | id: self.id, |
| 460 | | − | reason: self.reason, |
| 961 | + | reason: Reason::parse(&self.reason).unwrap_or(Reason::Subscribed), |
| 461 | 962 | | severity: Severity::parse(&self.severity).unwrap_or(Severity::Info), |
| 462 | 963 | | title: self.title, |
| 463 | 964 | | body: self.body, |
| 965 | + | event: self.event, |
| 464 | 966 | | repo: self.repo, |
| 465 | 967 | | workspace: self.workspace, |
| 466 | 968 | | subject, |
| 467 | 969 | | number, |
| 468 | 970 | | actor: self.actor, |
| 971 | + | count: self.activity.map_or(1, |n| n as u32), |
| 972 | + | updated_at: self.updated_at.unwrap_or_else(|| self.created_at.clone()), |
| 469 | 973 | | created_at: self.created_at, |
| 470 | 974 | | read_at: self.read_at, |
| 471 | 975 | | done_at: self.done_at, |
| ⋯ |
| 475 | 979 | | } |
| 476 | 980 | | } |
| 477 | 981 | | |
| 478 | | − | const COLUMNS: &str = "id, reason, severity, title, body, workspace, repo_id, repo, subject, number, run_id, actor, |
| 479 | | − | created_at, read_at, done_at, saved, snoozed_until"; |
| 982 | + | pub(crate) const COLUMNS: &str = "id, reason, severity, title, body, event, workspace, repo_id, repo, subject, number, run_id, |
| 983 | + | link, actor, activity, created_at, updated_at, read_at, done_at, saved, snoozed_until, bumped"; |
| 480 | 984 | | |
| 481 | 985 | | /// The conditions that pick a view's items, after `username = ?1`; `?2` is now. |
| 482 | 986 | | fn view_filter(view: InboxView) -> &'static str { |
| ⋯ |
| 489 | 993 | | |
| 490 | 994 | | /// Whether a list ranks unread warnings first: the inbox itself, unfiltered. |
| 491 | 995 | | fn ranked(a: &ListInboxArgs) -> bool { |
| 492 | | − | a.view == InboxView::Inbox && a.severity.is_none() && !a.unread |
| 996 | + | a.view == InboxView::Inbox |
| 997 | + | && a.severity.is_none() |
| 998 | + | && a.reason.is_none() |
| 999 | + | && !a.participating |
| 1000 | + | && a.repo_id.is_none() |
| 1001 | + | && !a.unread |
| 1002 | + | && a.since.is_none() |
| 1003 | + | && a.updated_before.is_none() |
| 493 | 1004 | | } |
| 494 | 1005 | | |
| 1006 | + | /// The conditions a list's filters add, and the values they bind, numbered |
| 1007 | + | /// after the `bound` values already given. |
| 1008 | + | fn filters(a: &ListInboxArgs, bound: usize) -> (Vec<String>, Vec<String>) { |
| 1009 | + | let mut conditions = Vec::new(); |
| 1010 | + | let mut values: Vec<String> = Vec::new(); |
| 1011 | + | let mut bind = |value: &str, condition: &str| { |
| 1012 | + | values.push(value.to_owned()); |
| 1013 | + | conditions.push(condition.replace('?', &format!("?{}", bound + values.len()))); |
| 1014 | + | }; |
| 1015 | + | if let Some(severity) = a.severity { |
| 1016 | + | bind(severity.as_str(), "severity = ?"); |
| 1017 | + | } |
| 1018 | + | if let Some(reason) = a.reason { |
| 1019 | + | bind(reason.as_str(), "reason = ?"); |
| 1020 | + | } |
| 1021 | + | if let Some(repo_id) = &a.repo_id { |
| 1022 | + | bind(repo_id, "repo_id = ?"); |
| 1023 | + | } |
| 1024 | + | if let Some(since) = &a.since { |
| 1025 | + | bind(since.trim(), "COALESCE(updated_at, created_at) >= ?"); |
| 1026 | + | } |
| 1027 | + | if let Some(before) = &a.updated_before { |
| 1028 | + | bind(before.trim(), "COALESCE(updated_at, created_at) < ?"); |
| 1029 | + | } |
| 1030 | + | if a.participating { |
| 1031 | + | conditions.push("reason NOT IN ('manual', 'subscribed')".to_owned()); |
| 1032 | + | } |
| 1033 | + | if a.unread { |
| 1034 | + | conditions.push("read_at IS NULL".to_owned()); |
| 1035 | + | } |
| 1036 | + | (conditions, values) |
| 1037 | + | } |
| 1038 | + | |
| 495 | 1039 | | pub async fn list(db: &D1Database, repos: &Fetcher, a: ListInboxArgs) -> Result<InboxPage> { |
| 496 | 1040 | | let Some(viewer) = &a.viewer else { |
| 497 | 1041 | | return Ok(InboxPage::default()); |
| ⋯ |
| 499 | 1043 | | let username = viewer.username.to_lowercase(); |
| 500 | 1044 | | let now = rfc3339(now_ms()); |
| 501 | 1045 | | let limit = a.limit.unwrap_or(DEFAULT_INBOX_PAGE).clamp(1, MAX_INBOX_PAGE); |
| 502 | | − | let mut conditions = vec!["username = ?1".to_owned(), view_filter(a.view).to_owned()]; |
| 503 | 1046 | | let mut values: Vec<JsValue> = vec![username.as_str().into(), now.as_str().into()]; |
| 504 | | − | if let Some(severity) = a.severity { |
| 505 | | − | values.push(severity.as_str().into()); |
| 506 | | − | conditions.push(format!("severity = ?{}", values.len())); |
| 507 | | − | } |
| 508 | | − | if a.unread { |
| 509 | | − | conditions.push("read_at IS NULL".to_owned()); |
| 510 | | − | } |
| 1047 | + | let mut conditions = vec!["username = ?1".to_owned(), view_filter(a.view).to_owned()]; |
| 1048 | + | let (filtered, bound) = filters(&a, values.len()); |
| 1049 | + | conditions.extend(filtered); |
| 1050 | + | values.extend(bound.iter().map(|value| JsValue::from(value.as_str()))); |
| 511 | 1051 | | let ranked = ranked(&a); |
| 512 | 1052 | | // Unread warnings lead the first page, and are left out of the rest. |
| 513 | 1053 | | let leading = "severity = 'warning' AND read_at IS NULL"; |
| 514 | 1054 | | let mut rest = conditions.clone(); |
| 1055 | + | let mut rest_values = values.clone(); |
| 515 | 1056 | | if ranked { |
| 516 | 1057 | | rest.push(format!("NOT ({leading})")); |
| 517 | 1058 | | } |
| 518 | 1059 | | if let Some(before) = &a.before { |
| 519 | | − | values.push(before.as_str().into()); |
| 520 | | − | rest.push(format!("id < ?{}", values.len())); |
| 1060 | + | rest_values.push(before.as_str().into()); |
| 1061 | + | rest.push(format!("bumped < ?{}", rest_values.len())); |
| 521 | 1062 | | } |
| 522 | | − | values.push((limit + 1).into()); |
| 523 | | − | let order = if a.view == InboxView::Done { "done_at DESC, id DESC" } else { "id DESC" }; |
| 1063 | + | rest_values.push((limit + 1).into()); |
| 1064 | + | let order = if a.view == InboxView::Done { "done_at DESC, bumped DESC" } else { "bumped DESC" }; |
| 524 | 1065 | | let mut statements = vec![ |
| 525 | 1066 | | db.prepare(format!( |
| 526 | 1067 | | "SELECT {COLUMNS} FROM inbox_items WHERE {} ORDER BY {order} LIMIT ?{}", |
| 527 | 1068 | | rest.join(" AND "), |
| 528 | | − | values.len() |
| 1069 | + | rest_values.len() |
| 529 | 1070 | | )) |
| 530 | | − | .bind(&values)?, |
| 1071 | + | .bind(&rest_values)?, |
| 531 | 1072 | | ]; |
| 532 | 1073 | | if ranked && a.before.is_none() { |
| 533 | 1074 | | statements.push( |
| 534 | 1075 | | db.prepare(format!( |
| 535 | | − | "SELECT {COLUMNS} FROM inbox_items WHERE {} AND {leading} ORDER BY id DESC LIMIT ?3" |
| 536 | | − | , conditions.join(" AND ") |
| 1076 | + | "SELECT {COLUMNS} FROM inbox_items WHERE {} AND {leading} ORDER BY bumped DESC LIMIT ?3", |
| 1077 | + | conditions.join(" AND ") |
| 537 | 1078 | | )) |
| 538 | 1079 | | .bind(&[username.as_str().into(), now.as_str().into(), MAX_RANKED.into()])?, |
| 539 | 1080 | | ); |
| ⋯ |
| 542 | 1083 | | let mut rows = results.first().map(|result| result.results::<Row>()).transpose()?.unwrap_or_default(); |
| 543 | 1084 | | let next = if rows.len() > limit as usize { |
| 544 | 1085 | | rows.truncate(limit as usize); |
| 545 | | − | rows.last().map(|row| row.id.clone()) |
| 1086 | + | rows.last().map(|row| row.bumped.clone().unwrap_or_else(|| row.id.clone())) |
| 546 | 1087 | | } else { |
| 547 | 1088 | | None |
| 548 | 1089 | | }; |
| 549 | 1090 | | let mut items: Vec<Row> = results.get(1).map(|result| result.results::<Row>()).transpose()?.unwrap_or_default(); |
| 550 | 1091 | | items.extend(rows); |
| 1092 | + | let items = readable_only(db, repos, &a.viewer, &username, items).await?; |
| 1093 | + | Ok(InboxPage { |
| 1094 | + | items: items.into_iter().map(Row::into_item).collect(), |
| 1095 | + | next, |
| 1096 | + | }) |
| 1097 | + | } |
| 551 | 1098 | | |
| 552 | | − | // What is about a repository they can no longer read is dropped. |
| 553 | | − | let ids: Vec<String> = items |
| 1099 | + | /// Rows about repositories the viewer can still read; the rest are |
| 1100 | + | /// removed from their inbox as they are found. |
| 1101 | + | pub(crate) async fn readable_only(db: &D1Database, repos: &Fetcher, viewer: &g1t_contracts::Viewer, username: &str, mut rows: Vec<Row>) -> Result<Vec<Row>> { |
| 1102 | + | let ids: Vec<String> = rows |
| 554 | 1103 | | .iter() |
| 555 | 1104 | | .filter_map(|row| row.repo_id.clone()) |
| 556 | 1105 | | .collect::<HashSet<_>>() |
| 557 | 1106 | | .into_iter() |
| 558 | 1107 | | .collect(); |
| 559 | | − | if !ids.is_empty() { |
| 560 | | − | let readable: Vec<Repo> = g1t_kit::call( |
| 561 | | − | repos, |
| 562 | | − | "readable", |
| 563 | | − | &ReadableArgs { |
| 564 | | − | ids: ids.clone(), |
| 565 | | − | viewer: a.viewer.clone(), |
| 566 | | − | }, |
| 567 | | − | ) |
| 568 | | − | .await?; |
| 569 | | − | let readable: HashSet<String> = readable.into_iter().map(|repo| repo.id).collect(); |
| 570 | | − | let gone: Vec<String> = ids.into_iter().filter(|id| !readable.contains(id)).collect(); |
| 571 | | − | if !gone.is_empty() { |
| 572 | | − | forget(db, &username, &gone).await?; |
| 573 | | − | items.retain(|row| row.repo_id.as_ref().is_none_or(|id| !gone.contains(id))); |
| 574 | | − | } |
| 1108 | + | if ids.is_empty() { |
| 1109 | + | return Ok(rows); |
| 1110 | + | } |
| 1111 | + | let readable: Vec<Repo> = g1t_kit::call( |
| 1112 | + | repos, |
| 1113 | + | "readable", |
| 1114 | + | &ReadableArgs { |
| 1115 | + | ids: ids.clone(), |
| 1116 | + | viewer: viewer.clone(), |
| 1117 | + | }, |
| 1118 | + | ) |
| 1119 | + | .await?; |
| 1120 | + | let readable: HashSet<String> = readable.into_iter().map(|repo| repo.id).collect(); |
| 1121 | + | let gone: Vec<String> = ids.into_iter().filter(|id| !readable.contains(id)).collect(); |
| 1122 | + | if !gone.is_empty() { |
| 1123 | + | forget(db, username, &gone).await?; |
| 1124 | + | rows.retain(|row| row.repo_id.as_ref().is_none_or(|id| !gone.contains(id))); |
| 575 | 1125 | | } |
| 576 | | − | Ok(InboxPage { |
| 577 | | − | items: items.into_iter().map(Row::into_item).collect(), |
| 578 | | − | next, |
| 579 | | − | }) |
| 1126 | + | Ok(rows) |
| 580 | 1127 | | } |
| 581 | 1128 | | |
| 582 | 1129 | | /// Removes a person's items about repositories they cannot read. |
| ⋯ |
| 584 | 1131 | | let marks = vec!["?"; repo_ids.len()].join(", "); |
| 585 | 1132 | | let mut values: Vec<JsValue> = vec![username.into()]; |
| 586 | 1133 | | values.extend(repo_ids.iter().map(|id| JsValue::from(id.as_str()))); |
| 587 | | − | db.prepare(format!("DELETE FROM inbox_items WHERE username = ? AND repo_id IN ({marks})")) |
| 588 | | − | .bind(&values)? |
| 589 | | − | .run() |
| 590 | | − | .await?; |
| 1134 | + | db.batch(vec![ |
| 1135 | + | db.prepare(format!( |
| 1136 | + | "DELETE FROM inbox_activity WHERE item_id IN (SELECT id FROM inbox_items WHERE username = ? AND repo_id IN ({marks}))" |
| 1137 | + | )) |
| 1138 | + | .bind(&values)?, |
| 1139 | + | db.prepare(format!("DELETE FROM inbox_items WHERE username = ? AND repo_id IN ({marks})")) |
| 1140 | + | .bind(&values)?, |
| 1141 | + | ]) |
| 1142 | + | .await?; |
| 591 | 1143 | | Ok(()) |
| 592 | 1144 | | } |
| 593 | 1145 | | |
| ⋯ |
| 633 | 1185 | | InboxMark::Save => "saved = 1", |
| 634 | 1186 | | InboxMark::Unsave => "saved = 0", |
| 635 | 1187 | | InboxMark::Snooze => "snoozed_until = ?2, read_at = COALESCE(read_at, ?1)", |
| 1188 | + | InboxMark::Unsnooze => "snoozed_until = NULL", |
| 636 | 1189 | | } |
| 637 | 1190 | | } |
| 638 | 1191 | | |
| ⋯ |
| 654 | 1207 | | let mut values: Vec<JsValue> = vec![now.as_str().into(), until.as_str().into(), a.username.to_lowercase().into()]; |
| 655 | 1208 | | let target = if a.all && a.ids.is_empty() { |
| 656 | 1209 | | let mut target = "done_at IS NULL".to_owned(); |
| 1210 | + | let mut bind = |values: &mut Vec<JsValue>, value: &str, condition: &str| { |
| 1211 | + | values.push(value.into()); |
| 1212 | + | target.push_str(&format!(" AND {}", condition.replace('?', &format!("?{}", values.len())))); |
| 1213 | + | }; |
| 657 | 1214 | | if let Some(severity) = a.severity { |
| 658 | | − | values.push(severity.as_str().into()); |
| 659 | | − | target.push_str(&format!(" AND severity = ?{}", values.len())); |
| 1215 | + | bind(&mut values, severity.as_str(), "severity = ?"); |
| 1216 | + | } |
| 1217 | + | if let Some(repo_id) = &a.repo_id { |
| 1218 | + | bind(&mut values, repo_id, "repo_id = ?"); |
| 1219 | + | } |
| 1220 | + | if let Some(last_read_at) = a.last_read_at.as_deref().map(str::trim).filter(|at| !at.is_empty()) { |
| 1221 | + | bind(&mut values, last_read_at, "COALESCE(updated_at, created_at) <= ?"); |
| 660 | 1222 | | } |
| 661 | 1223 | | target |
| 662 | 1224 | | } else { |
| ⋯ |
| 681 | 1243 | | Ok(changed.len() as u32) |
| 682 | 1244 | | } |
| 683 | 1245 | | |
| 1246 | + | #[derive(Deserialize)] |
| 1247 | + | struct ActivityRow { |
| 1248 | + | reason: String, |
| 1249 | + | severity: String, |
| 1250 | + | title: String, |
| 1251 | + | body: String, |
| 1252 | + | event: Option<String>, |
| 1253 | + | actor: Option<String>, |
| 1254 | + | created_at: String, |
| 1255 | + | } |
| 1256 | + | |
| 1257 | + | /// One of the viewer's threads, with its history and their subscription. |
| 1258 | + | pub async fn thread(db: &D1Database, repos: &Fetcher, work: &Fetcher, a: ThreadArgs) -> Result<Option<InboxThread>> { |
| 1259 | + | let Some(viewer) = &a.viewer else { |
| 1260 | + | return Ok(None); |
| 1261 | + | }; |
| 1262 | + | let username = viewer.username.to_lowercase(); |
| 1263 | + | let row = db |
| 1264 | + | .prepare(format!("SELECT {COLUMNS} FROM inbox_items WHERE id = ? AND username = ?")) |
| 1265 | + | .bind(&[a.id.as_str().into(), username.as_str().into()])? |
| 1266 | + | .first::<Row>(None) |
| 1267 | + | .await?; |
| 1268 | + | let Some(row) = readable_only(db, repos, &a.viewer, &username, row.into_iter().collect()).await?.pop() else { |
| 1269 | + | return Ok(None); |
| 1270 | + | }; |
| 1271 | + | let activity = db |
| 1272 | + | .prepare( |
| 1273 | + | "SELECT reason, severity, title, body, event, actor, created_at FROM inbox_activity |
| 1274 | + | WHERE item_id = ? ORDER BY id DESC LIMIT ?", |
| 1275 | + | ) |
| 1276 | + | .bind(&[row.id.as_str().into(), MAX_ACTIVITY.into()])? |
| 1277 | + | .all() |
| 1278 | + | .await? |
| 1279 | + | .results::<ActivityRow>()? |
| 1280 | + | .into_iter() |
| 1281 | + | .map(|row| InboxActivity { |
| 1282 | + | reason: Reason::parse(&row.reason).unwrap_or(Reason::Subscribed), |
| 1283 | + | severity: Severity::parse(&row.severity).unwrap_or(Severity::Info), |
| 1284 | + | title: row.title, |
| 1285 | + | body: row.body, |
| 1286 | + | event: row.event, |
| 1287 | + | actor: row.actor, |
| 1288 | + | created_at: row.created_at, |
| 1289 | + | }) |
| 1290 | + | .collect(); |
| 1291 | + | let item = row.into_item(); |
| 1292 | + | let subscription = match (item.subject, item.number) { |
| 1293 | + | (Some(SubjectKind::Issue | SubjectKind::Pull), Some(_)) => { |
| 1294 | + | subscriptions::subscription( |
| 1295 | + | db, |
| 1296 | + | work, |
| 1297 | + | SubscriptionArgs { |
| 1298 | + | viewer: a.viewer.clone(), |
| 1299 | + | id: Some(item.id.clone()), |
| 1300 | + | ..SubscriptionArgs::default() |
| 1301 | + | }, |
| 1302 | + | ) |
| 1303 | + | .await? |
| 1304 | + | } |
| 1305 | + | _ => None, |
| 1306 | + | }; |
| 1307 | + | Ok(Some(InboxThread { |
| 1308 | + | item, |
| 1309 | + | activity, |
| 1310 | + | subscription, |
| 1311 | + | })) |
| 1312 | + | } |
| 1313 | + | |
| 684 | 1314 | | // --- Keeping up ------------------------------------------------------------------ |
| 685 | 1315 | | |
| 686 | 1316 | | /// Moves rows with renamed workspaces and repositories, and drops those |
| ⋯ |
| 700 | 1330 | | } |
| 701 | 1331 | | statements.push( |
| 702 | 1332 | | db.prepare( |
| 703 | | − | "UPDATE inbox_items SET repo = ?2 || substr(repo, length(?1) + 1), workspace = ?2 |
| 1333 | + | "UPDATE inbox_items SET repo = ?2 || substr(repo, length(?1) + 1), workspace = ?2, |
| 1334 | + | link = CASE WHEN link LIKE '/' || ?1 || '/%' THEN '/' || ?2 || substr(link, length(?1) + 2) ELSE link END |
| 704 | 1335 | | WHERE workspace = ?1", |
| 705 | 1336 | | ) |
| 706 | 1337 | | .bind(&[from.as_str().into(), to.as_str().into()])?, |
| 707 | 1338 | | ); |
| 1339 | + | statements.push( |
| 1340 | + | db.prepare("UPDATE inbox_watching SET repo = ?2 || substr(repo, length(?1) + 1) WHERE repo LIKE ?1 || '/%'") |
| 1341 | + | .bind(&[from.as_str().into(), to.as_str().into()])?, |
| 1342 | + | ); |
| 708 | 1343 | | } |
| 709 | | − | "repo.renamed" => statements.push( |
| 710 | | − | db.prepare("UPDATE inbox_items SET repo = ? WHERE repo_id = ?").bind(&[ |
| 711 | | − | format!("{}/{}", text("namespace"), text("to")).into(), |
| 712 | | − | text("repoId").into(), |
| 713 | | − | ])?, |
| 714 | | − | ), |
| 715 | | − | "repo.transferred" => statements.push( |
| 716 | | − | db.prepare("UPDATE inbox_items SET repo = ?, workspace = ? WHERE repo_id = ?") |
| 717 | | − | .bind(&[ |
| 718 | | − | format!("{}/{}", text("to"), text("name")).into(), |
| 719 | | − | text("to").into(), |
| 720 | | − | text("repoId").into(), |
| 721 | | − | ])?, |
| 722 | | − | ), |
| 723 | | − | "repo.purged" => statements.push( |
| 724 | | − | db.prepare("DELETE FROM inbox_items WHERE repo_id = ?") |
| 725 | | − | .bind(&[text("repoId").into()])?, |
| 726 | | − | ), |
| 727 | | − | "workspace.deleted" => statements.push( |
| 728 | | − | db.prepare("DELETE FROM inbox_items WHERE workspace = ?") |
| 729 | | − | .bind(&[text("slug").into()])?, |
| 730 | | − | ), |
| 1344 | + | "repo.renamed" => { |
| 1345 | + | let path = format!("{}/{}", text("namespace"), text("to")); |
| 1346 | + | for table in ["inbox_items", "inbox_watching"] { |
| 1347 | + | statements.push( |
| 1348 | + | db.prepare(format!("UPDATE {table} SET repo = ? WHERE repo_id = ?")) |
| 1349 | + | .bind(&[path.as_str().into(), text("repoId").into()])?, |
| 1350 | + | ); |
| 1351 | + | } |
| 1352 | + | } |
| 1353 | + | "repo.transferred" => { |
| 1354 | + | let path = format!("{}/{}", text("to"), text("name")); |
| 1355 | + | statements.push( |
| 1356 | + | db.prepare("UPDATE inbox_items SET repo = ?, workspace = ? WHERE repo_id = ?") |
| 1357 | + | .bind(&[path.as_str().into(), text("to").into(), text("repoId").into()])?, |
| 1358 | + | ); |
| 1359 | + | statements.push( |
| 1360 | + | db.prepare("UPDATE inbox_watching SET repo = ? WHERE repo_id = ?") |
| 1361 | + | .bind(&[path.as_str().into(), text("repoId").into()])?, |
| 1362 | + | ); |
| 1363 | + | } |
| 1364 | + | "repo.purged" => { |
| 1365 | + | for sql in [ |
| 1366 | + | "DELETE FROM inbox_activity WHERE item_id IN (SELECT id FROM inbox_items WHERE repo_id = ?)", |
| 1367 | + | "DELETE FROM inbox_items WHERE repo_id = ?", |
| 1368 | + | "DELETE FROM inbox_subscriptions WHERE repo_id = ?", |
| 1369 | + | "DELETE FROM inbox_watching WHERE repo_id = ?", |
| 1370 | + | ] { |
| 1371 | + | statements.push(db.prepare(sql).bind(&[text("repoId").into()])?); |
| 1372 | + | } |
| 1373 | + | } |
| 1374 | + | "workspace.deleted" => { |
| 1375 | + | statements.push( |
| 1376 | + | db.prepare("DELETE FROM inbox_items WHERE workspace = ?") |
| 1377 | + | .bind(&[text("slug").into()])?, |
| 1378 | + | ); |
| 1379 | + | statements.push( |
| 1380 | + | db.prepare("DELETE FROM inbox_watching WHERE repo LIKE ? || '/%'") |
| 1381 | + | .bind(&[text("slug").into()])?, |
| 1382 | + | ); |
| 1383 | + | } |
| 731 | 1384 | | _ => {} |
| 732 | 1385 | | } |
| 733 | 1386 | | } |
| ⋯ |
| 738 | 1391 | | } |
| 739 | 1392 | | |
| 740 | 1393 | | /// Removes items done more than [`DONE_DAYS`] ago, and any not saved older |
| 741 | | − | /// than [`MAX_DAYS`]. Returns how many went. |
| 1394 | + | /// than [`MAX_DAYS`], with their history. Returns how many went. |
| 742 | 1395 | | pub async fn purge(db: &D1Database, now: u64) -> Result<u32> { |
| 743 | 1396 | | let done = crate::audit::keep_from(now, DONE_DAYS); |
| 744 | 1397 | | let oldest = crate::audit::keep_from(now, MAX_DAYS); |
| 745 | | − | let results = db |
| 746 | | − | .batch(vec![ |
| 747 | | − | db.prepare("DELETE FROM inbox_items WHERE saved = 0 AND done_at < ?") |
| 748 | | − | .bind(&[done.into()])?, |
| 749 | | − | db.prepare("DELETE FROM inbox_items WHERE saved = 0 AND created_at < ?") |
| 750 | | − | .bind(&[oldest.into()])?, |
| 751 | | − | ]) |
| 752 | | − | .await?; |
| 1398 | + | let statements: Vec<D1PreparedStatement> = vec![ |
| 1399 | + | db.prepare("DELETE FROM inbox_items WHERE saved = 0 AND done_at < ?") |
| 1400 | + | .bind(&[done.into()])?, |
| 1401 | + | db.prepare("DELETE FROM inbox_items WHERE saved = 0 AND COALESCE(updated_at, created_at) < ?") |
| 1402 | + | .bind(&[oldest.into()])?, |
| 1403 | + | db.prepare("DELETE FROM inbox_activity WHERE NOT EXISTS (SELECT 1 FROM inbox_items WHERE inbox_items.id = inbox_activity.item_id)"), |
| 1404 | + | ]; |
| 1405 | + | let results = db.batch(statements).await?; |
| 753 | 1406 | | let mut removed = 0; |
| 754 | | − | for result in results { |
| 1407 | + | for result in results.into_iter().take(2) { |
| 755 | 1408 | | removed += result.meta()?.and_then(|meta| meta.changes).unwrap_or(0) as u32; |
| 756 | 1409 | | } |
| 757 | 1410 | | Ok(removed) |
| ⋯ |
| 760 | 1413 | | #[cfg(test)] |
| 761 | 1414 | | mod tests { |
| 762 | 1415 | | use super::*; |
| 1416 | + | use crate::subscriptions::{State, Subscription, Watcher}; |
| 763 | 1417 | | use serde_json::json; |
| 764 | 1418 | | |
| 765 | 1419 | | fn event(kind: &str, actor: Option<&str>, data: serde_json::Value) -> Event { |
| ⋯ |
| 815 | 1469 | | } |
| 816 | 1470 | | } |
| 817 | 1471 | | |
| 818 | | − | fn told(notices: &[Notice]) -> Vec<(&str, &str, Severity)> { |
| 1472 | + | fn nobody() -> Audience { |
| 1473 | + | Audience::default() |
| 1474 | + | } |
| 1475 | + | |
| 1476 | + | fn told(notices: &[Notice]) -> Vec<(&str, Reason, Severity)> { |
| 819 | 1477 | | notices |
| 820 | 1478 | | .iter() |
| 821 | 1479 | | .map(|notice| (notice.username.as_str(), notice.reason, notice.severity)) |
| ⋯ |
| 834 | 1492 | | } |
| 835 | 1493 | | } |
| 836 | 1494 | | |
| 1495 | + | fn subscribed(rows: &[(&str, State, Option<Reason>)]) -> Audience { |
| 1496 | + | Audience { |
| 1497 | + | subscriptions: rows |
| 1498 | + | .iter() |
| 1499 | + | .map(|(name, state, reason)| Subscription { |
| 1500 | + | username: (*name).into(), |
| 1501 | + | state: *state, |
| 1502 | + | reason: *reason, |
| 1503 | + | }) |
| 1504 | + | .collect(), |
| 1505 | + | watchers: Vec::new(), |
| 1506 | + | } |
| 1507 | + | } |
| 1508 | + | |
| 1509 | + | fn watched(rows: &[(&str, WatchLevel, &[&str])]) -> Audience { |
| 1510 | + | Audience { |
| 1511 | + | subscriptions: Vec::new(), |
| 1512 | + | watchers: rows |
| 1513 | + | .iter() |
| 1514 | + | .map(|(name, level, events)| Watcher { |
| 1515 | + | username: (*name).into(), |
| 1516 | + | level: *level, |
| 1517 | + | events: events.iter().map(|kind| (*kind).to_owned()).collect(), |
| 1518 | + | }) |
| 1519 | + | .collect(), |
| 1520 | + | } |
| 1521 | + | } |
| 1522 | + | |
| 837 | 1523 | | #[test] |
| 838 | 1524 | | fn only_events_that_tell_someone_are_read() { |
| 839 | 1525 | | let asked = |kind: &str, data| wants(&event(kind, None, data)); |
| ⋯ |
| 853 | 1539 | | Some(Some("cmt_1".into())) |
| 854 | 1540 | | ); |
| 855 | 1541 | | assert_eq!(asked("git.push", json!({ "repoId": "rep_1" })), None); |
| 856 | | − | assert_eq!(asked("issue.opened", json!({ "repoId": "rep_1", "number": 1 })), None); |
| 1542 | + | for kind in ["issue.opened", "pull.review_requested", "pull.stalled", "issue.assigned", "pull.closed", "issue.reopened"] { |
| 1543 | + | assert!(asked(kind, json!({ "repoId": "rep_1", "number": 1 })).is_some(), "{kind}"); |
| 1544 | + | } |
| 1545 | + | assert_eq!(asked("deployment.failed", json!({ "repoId": "rep_1" })).map(|w| w.number), Some(None)); |
| 857 | 1546 | | } |
| 858 | 1547 | | |
| 859 | 1548 | | #[test] |
| 860 | | − | fn a_waiting_agent_needs_the_pull_requests_and_the_issues_people_first() { |
| 1549 | + | fn a_waiting_or_stopped_agent_needs_the_pull_requests_and_the_issues_people_first() { |
| 861 | 1550 | | let asked = event("agent.asked", Some("usr_agent"), json!({ "number": 7 })); |
| 862 | | − | let notices = notices(&asked, "acme/rocket", &Actor::default(), Some(&pull())); |
| 1551 | + | let notices_ = notices(&asked, "acme/rocket", &Actor::default(), Some(&pull()), &nobody()); |
| 863 | 1552 | | assert_eq!( |
| 864 | | − | told(¬ices), |
| 1553 | + | told(¬ices_), |
| 865 | 1554 | | vec![ |
| 866 | | − | ("ana", "agent_asked", Severity::Warning), |
| 867 | | − | ("cy", "agent_asked", Severity::Warning), |
| 868 | | − | ("dee", "agent_asked", Severity::Warning), |
| 1555 | + | ("ana", Reason::Agent, Severity::Warning), |
| 1556 | + | ("cy", Reason::Agent, Severity::Warning), |
| 1557 | + | ("dee", Reason::Agent, Severity::Warning), |
| 869 | 1558 | | ] |
| 870 | 1559 | | ); |
| 871 | | − | assert_eq!(notices[0].title, "An agent is waiting on acme/rocket#7"); |
| 872 | | − | assert_eq!(notices[0].body, "Add the inbox"); |
| 1560 | + | assert_eq!(notices_[0].title, "An agent is waiting on acme/rocket#7"); |
| 1561 | + | assert_eq!(notices_[0].body, "Add the inbox"); |
| 1562 | + | // Stopping says why; even someone who unsubscribed hears of it. |
| 1563 | + | let stalled = event("pull.stalled", None, json!({ "number": 7, "detail": "Its checks could not be run." })); |
| 1564 | + | let audience = subscribed(&[("ana", State::Unsubscribed, None)]); |
| 1565 | + | let notices_ = notices(&stalled, "acme/rocket", &Actor::default(), Some(&g1t_pull()), &audience); |
| 1566 | + | assert_eq!(notices_[0].username, "ana"); |
| 1567 | + | assert_eq!(notices_[0].title, "g1t stopped on acme/rocket#7 and needs you"); |
| 1568 | + | assert_eq!(notices_[0].body, "Its checks could not be run."); |
| 1569 | + | // Ignoring the thread silences even that. |
| 1570 | + | let audience = subscribed(&[("ana", State::Ignored, None)]); |
| 1571 | + | let notices_ = notices(&stalled, "acme/rocket", &Actor::default(), Some(&g1t_pull()), &audience); |
| 1572 | + | assert!(!notices_.iter().any(|notice| notice.username == "ana")); |
| 1573 | + | } |
| 1574 | + | |
| 1575 | + | #[test] |
| 1576 | + | fn whatever_an_agent_waits_on_closes_when_it_goes_on() { |
| 1577 | + | for kind in RESUMES { |
| 1578 | + | assert_eq!(resolves(&event(kind, None, json!({ "repoId": "rep_1", "number": 7 }))), Some("rep_1#7".into())); |
| 1579 | + | } |
| 1580 | + | assert_eq!(resolves(&event("comment.created", None, json!({ "repoId": "rep_1", "number": 7 }))), None); |
| 873 | 1581 | | } |
| 874 | 1582 | | |
| 875 | 1583 | | #[test] |
| 1584 | + | fn reviewers_and_assignees_asked_are_told_never_whoever_asked() { |
| 1585 | + | let requested = event("pull.review_requested", Some("usr_ana"), json!({ "number": 7, "reviewers": ["bo", "g1t", "ana"] })); |
| 1586 | + | let notices_ = notices(&requested, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody()); |
| 1587 | + | assert_eq!(told(¬ices_), vec![("bo", Reason::ReviewRequested, Severity::Warning)]); |
| 1588 | + | assert_eq!(notices_[0].title, "ana asked you to review acme/rocket#7"); |
| 1589 | + | let assigned = event("issue.assigned", Some("usr_ana"), json!({ "number": 3, "added": ["ana", "eve"] })); |
| 1590 | + | let notices_ = notices(&assigned, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody()); |
| 1591 | + | assert_eq!(told(¬ices_), vec![("eve", Reason::Assign, Severity::Info)]); |
| 1592 | + | assert_eq!(notices_[0].title, "ana assigned you to acme/rocket#3"); |
| 1593 | + | // Both subscribe whoever they name, never g1t. |
| 1594 | + | assert_eq!(subscribes(&requested, Some(&pull())), vec![("bo".into(), Reason::ReviewRequested), ("ana".into(), Reason::ReviewRequested)]); |
| 1595 | + | assert_eq!(subscribes(&assigned, Some(&pull())), vec![("ana".into(), Reason::Assign), ("eve".into(), Reason::Assign)]); |
| 1596 | + | } |
| 1597 | + | |
| 1598 | + | #[test] |
| 876 | 1599 | | fn failures_go_to_whoever_answers_for_the_change() { |
| 877 | 1600 | | let failed = event("checks.completed", None, json!({ "number": 7, "status": "failed" })); |
| 878 | | − | assert_eq!(told(¬ices(&failed, "acme/rocket", &Actor::default(), Some(&pull()))), vec![("ana", "checks_failed", Severity::Error)]); |
| 1601 | + | assert_eq!( |
| 1602 | + | told(¬ices(&failed, "acme/rocket", &Actor::default(), Some(&pull()), &nobody())), |
| 1603 | + | vec![("ana", Reason::CiActivity, Severity::Error)] |
| 1604 | + | ); |
| 879 | 1605 | | // g1t's change is the person's who asked for it, never g1t's. |
| 880 | | − | let notices_ = notices(&failed, "acme/rocket", &Actor::default(), Some(&g1t_pull())); |
| 881 | | − | assert_eq!(told(¬ices_), vec![("ana", "checks_failed", Severity::Error)]); |
| 1606 | + | let notices_ = notices(&failed, "acme/rocket", &Actor::default(), Some(&g1t_pull()), &nobody()); |
| 1607 | + | assert_eq!(told(¬ices_), vec![("ana", Reason::CiActivity, Severity::Error)]); |
| 882 | 1608 | | let errored = event("checks.completed", None, json!({ "number": 7, "status": "errored" })); |
| 883 | | − | assert_eq!(notices(&errored, "acme/rocket", &Actor::default(), Some(&pull()))[0].title, "Checks could not run on acme/rocket#7"); |
| 1609 | + | assert_eq!( |
| 1610 | + | notices(&errored, "acme/rocket", &Actor::default(), Some(&pull()), &nobody())[0].title, |
| 1611 | + | "Checks could not run on acme/rocket#7" |
| 1612 | + | ); |
| 884 | 1613 | | } |
| 885 | 1614 | | |
| 886 | 1615 | | #[test] |
| 887 | 1616 | | fn a_workflow_that_fails_tells_its_pull_requests_owner_even_if_they_pushed() { |
| 888 | 1617 | | let failed = event("workflow.completed", Some("usr_ana"), json!({ "pull": 7, "workflow": "CI", "conclusion": "failure" })); |
| 889 | | − | let notices_ = notices(&failed, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull())); |
| 890 | | − | assert_eq!(told(¬ices_), vec![("ana", "workflow_failed", Severity::Error)]); |
| 1618 | + | let notices_ = notices(&failed, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody()); |
| 1619 | + | assert_eq!(told(¬ices_), vec![("ana", Reason::CiActivity, Severity::Error)]); |
| 891 | 1620 | | assert_eq!(notices_[0].title, "CI failed on acme/rocket#7"); |
| 892 | 1621 | | // On a branch: whoever pushed. |
| 893 | 1622 | | let pushed = event( |
| 894 | 1623 | | "workflow.completed", |
| 895 | 1624 | | Some("usr_bo"), |
| 896 | | − | json!({ "workflow": "Deploy", "conclusion": "failure", "ref": "refs/heads/main", "number": 12, "sha": "abcdef0123" }), |
| 1625 | + | json!({ "workflow": "Deploy", "path": ".g1t/workflows/deploy.yml", "conclusion": "failure", "ref": "refs/heads/main", "number": 12, "sha": "abcdef0123", "runId": "run_9" }), |
| 897 | 1626 | | ); |
| 898 | | − | let notices_ = notices(&pushed, "acme/rocket", &actor("usr_bo", "bo"), None); |
| 899 | | − | assert_eq!(told(¬ices_), vec![("bo", "workflow_failed", Severity::Error)]); |
| 1627 | + | let notices_ = notices(&pushed, "acme/rocket", &actor("usr_bo", "bo"), None, &nobody()); |
| 1628 | + | assert_eq!(told(¬ices_), vec![("bo", Reason::CiActivity, Severity::Error)]); |
| 900 | 1629 | | assert_eq!(notices_[0].title, "Deploy failed on main in acme/rocket"); |
| 901 | 1630 | | assert_eq!(notices_[0].body, "Run 12 at abcdef0"); |
| 902 | 1631 | | // Nobody to tell when g1t pushed. |
| 903 | | − | assert!(notices(&pushed, "acme/rocket", &actor("g1t", "g1t"), None).is_empty()); |
| 1632 | + | assert!(notices(&pushed, "acme/rocket", &actor("g1t", "g1t"), None, &nobody()).is_empty()); |
| 1633 | + | // Every failure of a workflow on a branch is one thread. |
| 1634 | + | let wanted = wants(&pushed).unwrap(); |
| 1635 | + | let thread = thread_of(&pushed, &wanted, None); |
| 1636 | + | assert_eq!(thread.key, "rep_1/run/.g1t/workflows/deploy.yml@main"); |
| 1637 | + | assert_eq!(thread.run_id.as_deref(), Some("run_9")); |
| 1638 | + | } |
| 1639 | + | |
| 1640 | + | #[test] |
| 1641 | + | fn deployments_tell_whoever_answers_for_them_and_watchers() { |
| 1642 | + | let failed = event( |
| 1643 | + | "deployment.failed", |
| 1644 | + | Some("usr_bo"), |
| 1645 | + | json!({ "repoId": "rep_1", "projectId": "prj_1", "project": "rocket", "deploymentId": "dpl_1", "error": "The build failed.", "path": "/acme/rocket/deployments/dpl_1" }), |
| 1646 | + | ); |
| 1647 | + | let audience = watched(&[("cy", WatchLevel::Custom, &["deployments"]), ("dee", WatchLevel::Custom, &["issues"]), ("eve", WatchLevel::All, &[])]); |
| 1648 | + | let notices_ = notices(&failed, "acme/rocket", &actor("usr_bo", "bo"), None, &audience); |
| 1649 | + | assert_eq!( |
| 1650 | + | told(¬ices_), |
| 1651 | + | vec![ |
| 1652 | + | ("bo", Reason::CiActivity, Severity::Error), |
| 1653 | + | ("cy", Reason::Subscribed, Severity::Error), |
| 1654 | + | ("eve", Reason::Subscribed, Severity::Error), |
| 1655 | + | ] |
| 1656 | + | ); |
| 1657 | + | assert_eq!(notices_[0].title, "Production of rocket failed to deploy"); |
| 1658 | + | assert_eq!(notices_[0].body, "The build failed."); |
| 1659 | + | let thread = thread_of(&failed, &wants(&failed).unwrap(), None); |
| 1660 | + | assert_eq!(thread.key, "rep_1/deploy/prj_1/production"); |
| 1661 | + | assert_eq!(url(Some("acme/rocket"), thread.kind, None, None, thread.link.as_deref()), "/acme/rocket/deployments/dpl_1"); |
| 1662 | + | // A success is news to the owner only after a failure. |
| 1663 | + | let live = event("deployment.succeeded", Some("usr_bo"), json!({ "repoId": "rep_1", "projectId": "prj_1", "project": "rocket", "commit": "abcdef0123" })); |
| 1664 | + | assert!(notices(&live, "acme/rocket", &actor("usr_bo", "bo"), None, &nobody()).is_empty()); |
| 1665 | + | let recovered = event("deployment.succeeded", Some("usr_bo"), json!({ "repoId": "rep_1", "projectId": "prj_1", "project": "rocket", "recovered": true })); |
| 1666 | + | let notices_ = notices(&recovered, "acme/rocket", &actor("usr_bo", "bo"), None, &nobody()); |
| 1667 | + | assert_eq!(told(¬ices_), vec![("bo", Reason::CiActivity, Severity::Success)]); |
| 1668 | + | assert_eq!(notices_[0].title, "Production of rocket is live again"); |
| 1669 | + | // A preview's is the pull request's owner's. |
| 1670 | + | let preview = event("deployment.failed", None, json!({ "repoId": "rep_1", "projectId": "prj_1", "number": 7, "triggeredBy": "g1t" })); |
| 1671 | + | assert_eq!(told(¬ices(&preview, "acme/rocket", &Actor::default(), Some(&pull()), &nobody())), vec![("ana", Reason::CiActivity, Severity::Error)]); |
| 1672 | + | assert_eq!(thread_of(&preview, &wants(&preview).unwrap(), Some(&pull())).key, "rep_1/deploy/prj_1/7"); |
| 904 | 1673 | | } |
| 905 | 1674 | | |
| 906 | 1675 | | #[test] |
| 907 | 1676 | | fn nobody_hears_of_what_they_did_themselves() { |
| 908 | 1677 | | let merged = event("pull.merged", Some("usr_ana"), json!({ "number": 7 })); |
| 909 | | − | assert!(notices(&merged, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull())).is_empty()); |
| 910 | | − | let by_bo = notices(&merged, "acme/rocket", &actor("usr_bo", "bo"), Some(&pull())); |
| 911 | | − | assert_eq!(told(&by_bo), vec![("ana", "merged", Severity::Success)]); |
| 1678 | + | let by_ana = notices(&merged, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody()); |
| 1679 | + | // The assignee still hears; ana, who merged, does not. |
| 1680 | + | assert_eq!(told(&by_ana), vec![("bo", Reason::StateChange, Severity::Success)]); |
| 1681 | + | let by_bo = notices(&merged, "acme/rocket", &actor("usr_bo", "bo"), Some(&pull()), &nobody()); |
| 1682 | + | assert_eq!(told(&by_bo), vec![("ana", Reason::StateChange, Severity::Success)]); |
| 912 | 1683 | | assert_eq!(by_bo[0].title, "bo merged acme/rocket#7"); |
| 913 | | − | let by_queue = notices(&merged, "acme/rocket", &Actor::default(), Some(&pull())); |
| 1684 | + | let by_queue = notices(&merged, "acme/rocket", &Actor::default(), Some(&pull()), &nobody()); |
| 914 | 1685 | | assert_eq!(by_queue[0].title, "acme/rocket#7 was merged"); |
| 915 | 1686 | | } |
| 916 | 1687 | | |
| 917 | 1688 | | #[test] |
| 1689 | + | fn closing_and_reopening_tells_everyone_subscribed_and_watchers() { |
| 1690 | + | let closed = event("issue.closed", Some("usr_bo"), json!({ "number": 3, "reason": "completed" })); |
| 1691 | + | let issue = InboxSubject { |
| 1692 | + | kind: Some(SubjectKind::Issue), |
| 1693 | + | title: "Crash".into(), |
| 1694 | + | author: person("usr_cy", "cy"), |
| 1695 | + | assignees: vec!["bo".into()], |
| 1696 | + | ..InboxSubject::default() |
| 1697 | + | }; |
| 1698 | + | let mut audience = subscribed(&[("eve", State::Subscribed, Some(Reason::Comment)), ("fay", State::Unsubscribed, None)]); |
| 1699 | + | audience.watchers = watched(&[("gus", WatchLevel::All, &[]), ("hal", WatchLevel::Custom, &["pulls"])]).watchers; |
| 1700 | + | let notices_ = notices(&closed, "acme/rocket", &actor("usr_bo", "bo"), Some(&issue), &audience); |
| 1701 | + | assert_eq!( |
| 1702 | + | told(¬ices_), |
| 1703 | + | vec![ |
| 1704 | + | ("cy", Reason::StateChange, Severity::Info), |
| 1705 | + | ("eve", Reason::StateChange, Severity::Info), |
| 1706 | + | ("gus", Reason::Subscribed, Severity::Info), |
| 1707 | + | ] |
| 1708 | + | ); |
| 1709 | + | assert_eq!(notices_[0].title, "bo closed acme/rocket#3"); |
| 1710 | + | let by_pull = event("issue.closed", None, json!({ "number": 3, "resolvedBy": 9 })); |
| 1711 | + | assert_eq!(notices(&by_pull, "acme/rocket", &Actor::default(), Some(&issue), &nobody())[0].title, "acme/rocket#3 was closed by #9"); |
| 1712 | + | let reopened = event("issue.reopened", Some("usr_cy"), json!({ "number": 3 })); |
| 1713 | + | assert_eq!(told(¬ices(&reopened, "acme/rocket", &actor("usr_cy", "cy"), Some(&issue), &nobody())), vec![("bo", Reason::StateChange, Severity::Info)]); |
| 1714 | + | } |
| 1715 | + | |
| 1716 | + | #[test] |
| 1717 | + | fn opening_tells_who_it_names_and_watchers_of_its_kind() { |
| 1718 | + | let opened = event("pull.opened", Some("usr_ana"), json!({ "number": 7 })); |
| 1719 | + | let subject = InboxSubject { reviewers: vec!["cy".into(), "g1t".into()], ..pull() }; |
| 1720 | + | let audience = watched(&[("bo", WatchLevel::All, &[]), ("dee", WatchLevel::Custom, &["issues"]), ("eve", WatchLevel::Custom, &["pulls"]), ("fay", WatchLevel::Participating, &[])]); |
| 1721 | + | let notices_ = notices(&opened, "acme/rocket", &actor("usr_ana", "ana"), Some(&subject), &audience); |
| 1722 | + | assert_eq!( |
| 1723 | + | told(¬ices_), |
| 1724 | + | vec![ |
| 1725 | + | ("bo", Reason::Assign, Severity::Info), |
| 1726 | + | ("cy", Reason::ReviewRequested, Severity::Warning), |
| 1727 | + | ("eve", Reason::Subscribed, Severity::Info), |
| 1728 | + | ] |
| 1729 | + | ); |
| 1730 | + | assert_eq!(notices_[2].title, "ana opened acme/rocket#7"); |
| 1731 | + | } |
| 1732 | + | |
| 1733 | + | #[test] |
| 1734 | + | fn ignoring_a_repository_silences_it_and_unsubscribing_keeps_only_what_is_asked() { |
| 1735 | + | let created = event("comment.created", Some("usr_bo"), json!({ "number": 7, "commentId": "cmt_1" })); |
| 1736 | + | let on = comment(person("usr_bo", "bo"), "@cy have a look", &["cy"]); |
| 1737 | + | let audience = watched(&[("cy", WatchLevel::Ignore, &[]), ("ana", WatchLevel::All, &[])]); |
| 1738 | + | assert!(notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &audience).iter().all(|notice| notice.username != "cy")); |
| 1739 | + | let audience = subscribed(&[("cy", State::Unsubscribed, None), ("ana", State::Unsubscribed, None)]); |
| 1740 | + | let notices_ = notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &audience); |
| 1741 | + | // cy was mentioned, which is asked of them; ana unsubscribed from the conversation. |
| 1742 | + | assert_eq!(told(¬ices_), vec![("cy", Reason::Mention, Severity::Info)]); |
| 1743 | + | } |
| 1744 | + | |
| 1745 | + | #[test] |
| 918 | 1746 | | fn g1t_finishing_or_reviewing_tells_the_person_it_worked_for() { |
| 919 | 1747 | | // The agent acts as the person it works for: still an outcome they hear of. |
| 920 | 1748 | | let ready = event("pull.ready", Some("usr_ana"), json!({ "number": 7 })); |
| 921 | | − | let notices_ = notices(&ready, "acme/rocket", &actor("usr_ana", "ana"), Some(&g1t_pull())); |
| 922 | | − | assert_eq!(told(¬ices_), vec![("ana", "agent_finished", Severity::Success)]); |
| 1749 | + | let notices_ = notices(&ready, "acme/rocket", &actor("usr_ana", "ana"), Some(&g1t_pull()), &nobody()); |
| 1750 | + | assert_eq!(told(¬ices_), vec![("ana", Reason::Author, Severity::Success)]); |
| 923 | 1751 | | assert_eq!(notices_[0].title, "g1t finished acme/rocket#7"); |
| 924 | 1752 | | // A person's draft marked ready is not news to them. |
| 925 | | − | assert!(notices(&ready, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull())).is_empty()); |
| 1753 | + | assert!(notices(&ready, "acme/rocket", &actor("usr_ana", "ana"), Some(&pull()), &nobody()).is_empty()); |
| 926 | 1754 | | |
| 927 | 1755 | | let approve = event("review.completed", None, json!({ "number": 7, "verdict": "approve" })); |
| 928 | | − | assert_eq!(told(¬ices(&approve, "acme/rocket", &Actor::default(), Some(&pull()))), vec![("ana", "approved", Severity::Success)]); |
| 1756 | + | assert_eq!( |
| 1757 | + | told(¬ices(&approve, "acme/rocket", &Actor::default(), Some(&pull()), &nobody())), |
| 1758 | + | vec![("ana", Reason::Author, Severity::Success)] |
| 1759 | + | ); |
| 929 | 1760 | | let changes = event("review.completed", None, json!({ "number": 7, "verdict": "request_changes" })); |
| 930 | 1761 | | assert_eq!( |
| 931 | | − | told(¬ices(&changes, "acme/rocket", &Actor::default(), Some(&pull()))), |
| 932 | | − | vec![("ana", "changes_requested", Severity::Info)] |
| 1762 | + | told(¬ices(&changes, "acme/rocket", &Actor::default(), Some(&pull()), &nobody())), |
| 1763 | + | vec![("ana", Reason::Author, Severity::Info)] |
| 933 | 1764 | | ); |
| 934 | 1765 | | } |
| 935 | 1766 | | |
| 936 | 1767 | | #[test] |
| 937 | | − | fn comments_tell_those_mentioned_then_the_owner_never_the_writer() { |
| 1768 | + | fn comments_tell_those_mentioned_then_everyone_subscribed_never_the_writer() { |
| 938 | 1769 | | let created = event("comment.created", Some("usr_bo"), json!({ "number": 7, "commentId": "cmt_1" })); |
| 939 | 1770 | | let on = comment(person("usr_bo", "bo"), "@cy @bo have a look", &["cy", "bo", "g1t"]); |
| 940 | | − | let notices_ = notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on)); |
| 1771 | + | let audience = subscribed(&[("eve", State::Subscribed, Some(Reason::Comment)), ("fay", State::Subscribed, Some(Reason::Manual))]); |
| 1772 | + | let notices_ = notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &audience); |
| 941 | 1773 | | assert_eq!( |
| 942 | 1774 | | told(¬ices_), |
| 943 | | − | vec![("cy", "mentioned", Severity::Info), ("ana", "commented", Severity::Info)] |
| 1775 | + | vec![ |
| 1776 | + | ("cy", Reason::Mention, Severity::Info), |
| 1777 | + | ("ana", Reason::Author, Severity::Info), |
| 1778 | + | ("eve", Reason::Comment, Severity::Info), |
| 1779 | + | ("fay", Reason::Manual, Severity::Info), |
| 1780 | + | ] |
| 944 | 1781 | | ); |
| 945 | 1782 | | assert_eq!(notices_[0].title, "bo mentioned you on acme/rocket#7"); |
| 1783 | + | assert_eq!(notices_[1].title, "bo commented on acme/rocket#7"); |
| 946 | 1784 | | assert_eq!(notices_[0].body, "@cy @bo have a look"); |
| 947 | 1785 | | // Mentioned and the owner: told once, as mentioned. |
| 948 | 1786 | | let on = comment(person("usr_bo", "bo"), "@ana", &["ana"]); |
| 949 | | − | assert_eq!(told(¬ices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on))), vec![("ana", "mentioned", Severity::Info)]); |
| 950 | | − | // The owner's own comment tells nobody but those they mention. |
| 1787 | + | assert_eq!( |
| 1788 | + | told(¬ices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &nobody())), |
| 1789 | + | vec![("ana", Reason::Mention, Severity::Info)] |
| 1790 | + | ); |
| 1791 | + | // The owner's own comment tells the assignee, not the owner. |
| 951 | 1792 | | let on = comment(person("usr_ana", "ana"), "thanks", &[]); |
| 952 | | − | assert!(notices(&created, "acme/rocket", &actor("usr_ana", "ana"), Some(&on)).is_empty()); |
| 1793 | + | assert_eq!( |
| 1794 | + | told(¬ices(&created, "acme/rocket", &actor("usr_ana", "ana"), Some(&on), &nobody())), |
| 1795 | + | vec![("bo", Reason::Assign, Severity::Info)] |
| 1796 | + | ); |
| 953 | 1797 | | // Something that happened, not something written, tells nobody. |
| 954 | 1798 | | let mut on = comment(person("usr_bo", "bo"), "assigned cy", &[]); |
| 955 | 1799 | | on.comment.as_mut().unwrap().event = true; |
| 956 | | − | assert!(notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on)).is_empty()); |
| 1800 | + | assert!(notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on), &nobody()).is_empty()); |
| 957 | 1801 | | // An approval is good news. |
| 958 | | − | let mut on = comment(person("usr_bo", "bo"), "", &[]); |
| 1802 | + | let mut on = comment(person("usr_cy", "cy"), "", &[]); |
| 959 | 1803 | | on.comment.as_mut().unwrap().verdict = Some("approve".into()); |
| 960 | | − | let notices_ = notices(&created, "acme/rocket", &actor("usr_bo", "bo"), Some(&on)); |
| 961 | | − | assert_eq!(told(¬ices_), vec![("ana", "approved", Severity::Success)]); |
| 1804 | + | let notices_ = notices(&created, "acme/rocket", &actor("usr_cy", "cy"), Some(&on), &nobody()); |
| 1805 | + | assert_eq!(told(¬ices_)[0], ("ana", Reason::Author, Severity::Success)); |
| 962 | 1806 | | assert_eq!(notices_[0].body, "Add the inbox"); |
| 1807 | + | // Writing and being mentioned subscribe, never g1t. |
| 1808 | + | let on = comment(person("usr_bo", "bo"), "@cy", &["cy"]); |
| 1809 | + | assert_eq!(subscribes(&created, Some(&on)), vec![("bo".into(), Reason::Comment), ("cy".into(), Reason::Mention)]); |
| 1810 | + | let on = comment(person(AGENT_ID, "g1t"), "done", &[]); |
| 1811 | + | assert!(subscribes(&created, Some(&on)).is_empty()); |
| 1812 | + | } |
| 1813 | + | |
| 1814 | + | #[test] |
| 1815 | + | fn issues_and_pull_requests_are_one_thread_each() { |
| 1816 | + | let created = event("comment.created", Some("usr_bo"), json!({ "repoId": "rep_1", "number": 7, "commentId": "cmt_1" })); |
| 1817 | + | let wanted = wants(&created).unwrap(); |
| 1818 | + | let thread = thread_of(&created, &wanted, Some(&pull())); |
| 1819 | + | assert_eq!(thread.key, "rep_1#7"); |
| 1820 | + | assert_eq!(thread.kind, Some(SubjectKind::Pull)); |
| 1821 | + | let merged = event("pull.merged", None, json!({ "repoId": "rep_1", "number": 7 })); |
| 1822 | + | assert_eq!(thread_of(&merged, &wants(&merged).unwrap(), Some(&pull())).key, thread.key); |
| 963 | 1823 | | } |
| 964 | 1824 | | |
| 965 | 1825 | | #[test] |
| 966 | 1826 | | fn items_link_to_what_they_are_about() { |
| 967 | | − | assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Pull), Some(7), None), "/acme/rocket/pull/7"); |
| 968 | | − | assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Issue), Some(3), None), "/acme/rocket/issues/3"); |
| 969 | | − | assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Run), None, Some("run_1")), "/acme/rocket/actions/runs/run_1"); |
| 970 | | − | assert_eq!(url(Some("acme/rocket"), None, None, None), "/acme/rocket"); |
| 971 | | − | assert_eq!(url(None, None, None, None), "/inbox"); |
| 1827 | + | assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Pull), Some(7), None, None), "/acme/rocket/pull/7"); |
| 1828 | + | assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Issue), Some(3), None, None), "/acme/rocket/issues/3"); |
| 1829 | + | assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Run), None, Some("run_1"), None), "/acme/rocket/actions/runs/run_1"); |
| 1830 | + | assert_eq!(url(Some("acme/rocket"), Some(SubjectKind::Deploy), None, None, Some("/acme/site/deployments/dpl_1")), "/acme/site/deployments/dpl_1"); |
| 1831 | + | assert_eq!(url(Some("acme/rocket"), None, None, None, None), "/acme/rocket"); |
| 1832 | + | assert_eq!(url(None, None, None, None, None), "/inbox"); |
| 972 | 1833 | | } |
| 973 | 1834 | | |
| 974 | 1835 | | #[test] |
| ⋯ |
| 982 | 1843 | | fn marks_change_only_what_they_say() { |
| 983 | 1844 | | assert_eq!(mark_change(InboxMark::Read), "read_at = COALESCE(read_at, ?1)"); |
| 984 | 1845 | | assert!(mark_change(InboxMark::Done).contains("done_at = ?1")); |
| 985 | | − | assert!(ranked(&ListInboxArgs { |
| 986 | | − | viewer: None, |
| 987 | | − | view: InboxView::Inbox, |
| 988 | | − | severity: None, |
| 989 | | − | unread: false, |
| 990 | | − | before: None, |
| 991 | | − | limit: None, |
| 992 | | − | })); |
| 1846 | + | assert_eq!(mark_change(InboxMark::Unsnooze), "snoozed_until = NULL"); |
| 1847 | + | assert!(ranked(&ListInboxArgs::default())); |
| 1848 | + | assert!(!ranked(&ListInboxArgs { reason: Some(Reason::Mention), ..ListInboxArgs::default() })); |
| 1849 | + | assert!(!ranked(&ListInboxArgs { participating: true, ..ListInboxArgs::default() })); |
| 1850 | + | } |
| 1851 | + | |
| 1852 | + | #[test] |
| 1853 | + | fn filters_bind_in_order_after_what_is_bound() { |
| 1854 | + | let a = ListInboxArgs { |
| 1855 | + | reason: Some(Reason::Mention), |
| 1856 | + | repo_id: Some("rep_1".into()), |
| 1857 | + | participating: true, |
| 1858 | + | unread: true, |
| 1859 | + | ..ListInboxArgs::default() |
| 1860 | + | }; |
| 1861 | + | // Two values come first: the username and now. |
| 1862 | + | let (conditions, values) = filters(&a, 2); |
| 1863 | + | assert_eq!( |
| 1864 | + | conditions, |
| 1865 | + | vec!["reason = ?3", "repo_id = ?4", "reason NOT IN ('manual', 'subscribed')", "read_at IS NULL"] |
| 1866 | + | ); |
| 1867 | + | assert_eq!(values, vec!["mention", "rep_1"]); |
| 1868 | + | } |
| 1869 | + | |
| 1870 | + | #[test] |
| 1871 | + | fn the_bump_keeps_whatever_is_most_urgent_while_unread() { |
| 1872 | + | assert!(BUMP.contains("WHERE NOT EXISTS (SELECT 1 FROM inbox_activity WHERE event_id = ?4 AND username = ?2)")); |
| 1873 | + | assert!(BUMP.contains("ON CONFLICT (username, thread) DO UPDATE")); |
| 1874 | + | assert!(BUMP.contains("activity = inbox_items.activity + 1")); |
| 1875 | + | // Its numbered parameters run from 1 to 19. |
| 1876 | + | for at in 1..=19 { |
| 1877 | + | assert!(BUMP.contains(&format!("?{at}")), "?{at}"); |
| 1878 | + | } |
| 1879 | + | assert!(!BUMP.contains("?20")); |
| 993 | 1880 | | } |
| 994 | 1881 | | } |