forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

notify.rs1315 lines, 39.8 KiBHistoryRawDownload
1//! Notification fan-out for issue and pull request activity.
2//!
3//! [`dispatch`] works out who hears about an activity, auto-subscribes the people involved and
4//! writes their inbox rows. It runs inline (database only) and never fails its caller: errors
5//! are logged.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use forge_core::mail::{MailKind, OutgoingMail};
10use forge_core::notifications::{Reason, SubState, WatchLevel};
11use forge_core::store::orgs::OrgMemberRole;
12use forge_core::{Action, Issue, Repo, Result, User, authorize};
13use http::HeaderMap;
14
15use crate::i18n::{self, misc};
16use crate::mail::{
17 self,
18 templates::{self, Verb, Why},
19};
20use crate::notify_hub::publish_unread;
21use crate::render::markdown::mentioned_usernames;
22use crate::state::AppState;
23use crate::web_push::{self, Alert};
24
25/// Something that happened on an issue or pull request, as far as notifications care.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum Activity {
28 Opened,
29 Comment,
30 Closed,
31 Reopened,
32 Merged,
33 Review,
34 /// The user with `assignee_id` was assigned.
35 Assigned {
36 assignee_id: String,
37 },
38 /// The user with `reviewer_id` was asked to review.
39 ReviewRequested {
40 reviewer_id: String,
41 },
42 /// The pull request head moved.
43 Pushed,
44 /// The body or a comment was edited. Only newly mentioned users hear about it.
45 Edited,
46}
47
48impl Activity {
49 /// The activity name stored on inbox rows.
50 pub fn as_str(&self) -> &'static str {
51 match self {
52 Activity::Opened => "opened",
53 Activity::Comment => "comment",
54 Activity::Closed => "closed",
55 Activity::Reopened => "reopened",
56 Activity::Merged => "merged",
57 Activity::Review => "review",
58 Activity::Assigned { .. } => "assigned",
59 Activity::ReviewRequested { .. } => "review_requested",
60 Activity::Pushed => "pushed",
61 Activity::Edited => "edited",
62 }
63 }
64
65 /// Closing, reopening and merging make subscribers hear about a state change.
66 fn changes_state(&self) -> bool {
67 matches!(
68 self,
69 Activity::Closed | Activity::Reopened | Activity::Merged
70 )
71 }
72}
73
74/// Notifies the people who should hear about `activity` on `issue` in `repo`, for the actor
75/// `actor_id` (an empty id means a system change, so nobody is excluded). `mention_text` is
76/// searched for `@mentions`. Never fails: problems are logged.
77pub async fn dispatch(
78 state: &AppState,
79 repo: &Repo,
80 issue: &Issue,
81 actor_id: &str,
82 activity: Activity,
83 mention_text: Option<&str>,
84) {
85 let mentions = mention_text.map(mentioned_usernames).unwrap_or_default();
86 fan_out(
87 state,
88 repo,
89 issue,
90 actor_id,
91 &activity,
92 &mentions,
93 mention_text,
94 )
95 .await;
96}
97
98/// Notifies the users mentioned in `new_text` but not in `old_text`. Never fails.
99pub async fn dispatch_edit(
100 state: &AppState,
101 repo: &Repo,
102 issue: &Issue,
103 actor_id: &str,
104 old_text: &str,
105 new_text: &str,
106) {
107 let before = mentioned_usernames(old_text);
108 let added: Vec<String> = mentioned_usernames(new_text)
109 .into_iter()
110 .filter(|name| !before.contains(name))
111 .collect();
112 if added.is_empty() {
113 return;
114 }
115 fan_out(
116 state,
117 repo,
118 issue,
119 actor_id,
120 &Activity::Edited,
121 &added,
122 None,
123 )
124 .await;
125}
126
127/// Sends an `Assigned` activity for each username that is in `after` but not in `before`.
128/// Never fails.
129pub async fn dispatch_assigned(
130 state: &AppState,
131 repo: &Repo,
132 issue: &Issue,
133 actor_id: &str,
134 before: &[String],
135 after: &[String],
136) {
137 for name in after.iter().filter(|name| !before.contains(name)) {
138 match state.store.user_by_username(name).await {
139 Ok(Some(user)) => {
140 let activity = Activity::Assigned {
141 assignee_id: user.id,
142 };
143 dispatch(state, repo, issue, actor_id, activity, None).await;
144 }
145 Ok(None) => {}
146 Err(e) => {
147 tracing::error!(error = %e, repo_id = %repo.id, name, "notify: assignee lookup failed");
148 }
149 }
150 }
151}
152
153/// Tells `reviewer_id` that `actor_id` asked for their review of the pull request. Never fails.
154pub async fn dispatch_review_requested(
155 state: &AppState,
156 repo: &Repo,
157 issue: &Issue,
158 actor_id: &str,
159 reviewer_id: &str,
160) {
161 let activity = Activity::ReviewRequested {
162 reviewer_id: reviewer_id.to_owned(),
163 };
164 dispatch(state, repo, issue, actor_id, activity, None).await;
165}
166
167/// Tells the admins of `repo` that a lockfile scan opened `opened` security alerts on it. The
168/// admins are the owner (for an organization, its owners) and the collaborators with the Admin
169/// role. Writes inbox rows only. Never fails: problems are logged.
170pub async fn advisories_opened(state: &AppState, repo: &Repo, opened: usize) {
171 if let Err(e) = notify_advisory_admins(state, repo, opened).await {
172 tracing::error!(error = %e, repo_id = %repo.id, "notify: advisory alert notice failed");
173 }
174}
175
176/// The users who administer `repo`, without duplicates.
177async fn advisory_admins(state: &AppState, repo: &Repo) -> Result<Vec<String>> {
178 let mut admins: BTreeSet<String> = BTreeSet::new();
179 if let Some(owner) = state.store.user_by_id(&repo.owner_id).await? {
180 if owner.is_org() {
181 for (member, role) in state.store.org_members(&owner.id).await? {
182 if role == OrgMemberRole::Owner {
183 admins.insert(member.id);
184 }
185 }
186 } else {
187 admins.insert(owner.id);
188 }
189 }
190 for (user, role) in state.store.list_collaborators(&repo.id).await? {
191 if role == forge_core::Role::Admin {
192 admins.insert(user.id);
193 }
194 }
195 Ok(admins.into_iter().collect())
196}
197
198async fn notify_advisory_admins(state: &AppState, repo: &Repo, opened: usize) -> Result<()> {
199 let count = u64::try_from(opened).unwrap_or(u64::MAX);
200 for admin in advisory_admins(state, repo).await? {
201 state
202 .store
203 .notify_new_alerts(&admin, &repo.id, count)
204 .await?;
205 publish_unread(state, &admin).await;
206 web_push::queue(
207 state,
208 &admin,
209 Alert::Advisories {
210 repo: format!("{}/{}", repo.owner_name, repo.name),
211 count,
212 url: format!("/{}/{}/security", repo.owner_name, repo.name),
213 },
214 );
215 }
216 Ok(())
217}
218
219async fn fan_out(
220 state: &AppState,
221 repo: &Repo,
222 issue: &Issue,
223 actor_id: &str,
224 activity: &Activity,
225 mentions: &[String],
226 body_text: Option<&str>,
227) {
228 if let Err(e) = run(state, repo, issue, actor_id, activity, mentions, body_text).await {
229 tracing::error!(
230 error = %e,
231 repo_id = %repo.id,
232 issue_id = %issue.id,
233 activity = activity.as_str(),
234 "notify: dispatch failed"
235 );
236 }
237}
238
239/// Keeps the stronger of the reasons already recorded for a user and `reason`.
240fn add(candidates: &mut BTreeMap<String, Reason>, user_id: String, reason: Reason) {
241 match candidates.get(&user_id) {
242 Some(prev) if prev.rank() >= reason.rank() => {}
243 _ => {
244 candidates.insert(user_id, reason);
245 }
246 }
247}
248
249fn strongest(a: Reason, b: Reason) -> Reason {
250 if a.rank() >= b.rank() { a } else { b }
251}
252
253/// The user when they exist and can Read the repo now, by their effective role (collaborator
254/// or organization).
255async fn readable_user(state: &AppState, repo: &Repo, user_id: &str) -> Result<Option<User>> {
256 let Some(user) = state.store.user_by_id(user_id).await? else {
257 return Ok(None);
258 };
259 if user.is_org() {
260 return Ok(None);
261 }
262 let role = state.store.collaborator_role(&repo.id, user_id).await?;
263 let org_role = state
264 .store
265 .org_repo_role(&repo.owner_id, user_id, &repo.id)
266 .await?;
267 Ok(authorize(Some(&user), repo, role, org_role, Action::Read)
268 .is_ok()
269 .then_some(user))
270}
271
272/// The people who hear about something addressed to `user_id`. A person hears about it when
273/// they can read the repo. An organization (for example the owner of a repo) hands it to its
274/// owners who can read the repo; the org itself never receives anything.
275async fn recipients_for(state: &AppState, repo: &Repo, user_id: &str) -> Result<Vec<String>> {
276 let Some(user) = state.store.user_by_id(user_id).await? else {
277 return Ok(Vec::new());
278 };
279 if !user.is_org() {
280 return Ok(readable_user(state, repo, user_id)
281 .await?
282 .map(|u| vec![u.id])
283 .unwrap_or_default());
284 }
285 let mut owners = Vec::new();
286 for (member, role) in state.store.org_members(&user.id).await? {
287 if role == OrgMemberRole::Owner && readable_user(state, repo, &member.id).await?.is_some() {
288 owners.push(member.id);
289 }
290 }
291 Ok(owners)
292}
293
294async fn run(
295 state: &AppState,
296 repo: &Repo,
297 issue: &Issue,
298 actor_id: &str,
299 activity: &Activity,
300 mentions: &[String],
301 body_text: Option<&str>,
302) -> Result<()> {
303 let store = &state.store;
304 let actor = (!actor_id.is_empty()).then_some(actor_id);
305 let issue_id = issue.id.as_str();
306 // Built once per run. Nothing is queued when instance mail is off.
307 let plan = match mail_plan(state, repo, issue, actor_id, activity, body_text).await {
308 Ok(plan) => plan,
309 Err(e) => {
310 tracing::error!(error = %e, issue_id, "notify: email plan failed");
311 None
312 }
313 };
314
315 // Candidates with the reason they would hear about this activity.
316 let mut candidates: BTreeMap<String, Reason> = BTreeMap::new();
317 let mut mentioned: BTreeSet<String> = BTreeSet::new();
318
319 if !matches!(
320 activity,
321 Activity::Edited | Activity::ReviewRequested { .. }
322 ) {
323 for (user_id, stored) in store.subscribers(issue_id).await? {
324 let reason = if activity.changes_state() {
325 strongest(stored, Reason::StateChange)
326 } else {
327 stored
328 };
329 add(&mut candidates, user_id, reason);
330 }
331 // Pushes reach subscribers only.
332 if *activity != Activity::Pushed {
333 for user_id in store.watchers(&repo.id).await? {
334 if is_ignored(state, &user_id, issue_id).await? {
335 continue;
336 }
337 add(&mut candidates, user_id, Reason::Watching);
338 }
339 }
340 if let Activity::Assigned { assignee_id } = activity
341 && !is_ignored(state, assignee_id, issue_id).await?
342 {
343 add(&mut candidates, assignee_id.clone(), Reason::Assign);
344 }
345 }
346
347 // A review request reaches the reviewer only, not the thread's other subscribers.
348 if let Activity::ReviewRequested { reviewer_id } = activity
349 && !is_ignored(state, reviewer_id, issue_id).await?
350 {
351 add(
352 &mut candidates,
353 reviewer_id.clone(),
354 Reason::ReviewRequested,
355 );
356 }
357
358 // Mentions reach the user whatever their watch level or subscription.
359 for name in mentions {
360 if let Some(user) = store.user_by_username(name).await? {
361 mentioned.insert(user.id.clone());
362 add(&mut candidates, user.id, Reason::Mention);
363 }
364 }
365
366 let mut recipients: BTreeMap<String, Reason> = BTreeMap::new();
367 for (user_id, reason) in candidates {
368 let is_mention = mentioned.contains(&user_id);
369 for recipient in recipients_for(state, repo, &user_id).await? {
370 if Some(recipient.as_str()) == actor {
371 continue;
372 }
373 if !is_mention && store.watch_level(&recipient, &repo.id).await? == WatchLevel::Ignoring
374 {
375 continue;
376 }
377 add(&mut recipients, recipient, reason);
378 }
379 }
380
381 // The same activity as a push for each device of a recipient. Built once, in the recipient's
382 // language when it is sent.
383 let push = if recipients.is_empty() {
384 None
385 } else {
386 match push_alert(state, repo, issue, actor_id, activity).await {
387 Ok(alert) => Some(alert),
388 Err(e) => {
389 tracing::error!(error = %e, issue_id, "notify: push text failed");
390 None
391 }
392 }
393 };
394
395 // Auto-subscribe. Existing rows, including explicit ignores, are left alone.
396 if let Some(actor_id) = actor {
397 match activity {
398 Activity::Opened => {
399 store
400 .auto_subscribe(actor_id, issue_id, Reason::Author)
401 .await?
402 }
403 Activity::Comment | Activity::Review => {
404 store
405 .auto_subscribe(actor_id, issue_id, Reason::Comment)
406 .await?;
407 }
408 _ => {}
409 }
410 }
411 if let Activity::Assigned { assignee_id } = activity
412 && readable_user(state, repo, assignee_id).await?.is_some()
413 {
414 store
415 .auto_subscribe(assignee_id, issue_id, Reason::Assign)
416 .await?;
417 }
418 if let Activity::ReviewRequested { reviewer_id } = activity
419 && readable_user(state, repo, reviewer_id).await?.is_some()
420 {
421 store
422 .auto_subscribe(reviewer_id, issue_id, Reason::ReviewRequested)
423 .await?;
424 }
425 for user_id in &mentioned {
426 if readable_user(state, repo, user_id).await?.is_some() {
427 store
428 .auto_subscribe(user_id, issue_id, Reason::Mention)
429 .await?;
430 }
431 }
432
433 for (user_id, reason) in recipients {
434 match store
435 .upsert_notification(
436 &user_id,
437 &repo.id,
438 issue_id,
439 reason,
440 activity.as_str(),
441 actor,
442 )
443 .await
444 {
445 Ok(()) => {
446 publish_unread(state, &user_id).await;
447 if let Some(alert) = &push {
448 web_push::queue(state, &user_id, alert.clone());
449 }
450 }
451 Err(e) => tracing::error!(error = %e, user_id, issue_id, "notify: inbox write failed"),
452 }
453 if let Some(plan) = &plan
454 && let Err(e) = queue_email(state, plan, &user_id, reason).await
455 {
456 tracing::error!(error = %e, user_id, issue_id, "notify: email copy failed");
457 }
458 }
459 Ok(())
460}
461
462/// What the email copies of one activity share. Built once per `run`; the reason, the address and
463/// the Message-ID depend on the recipient and are worked out in [`queue_email`].
464struct MailPlan {
465 /// The host of `base_url`, used as the Message-ID domain.
466 host: String,
467 /// The thread root, `<issue-{id}@host>`.
468 root: String,
469 /// One id per `run`, so each recipient's Message-ID is unique to this event.
470 event_id: String,
471 /// True for an opening: that mail is the root of the thread.
472 opens_thread: bool,
473 actor: Option<String>,
474 verb: Verb,
475 /// `owner/repo`.
476 repo: String,
477 number: i64,
478 title: String,
479 comment: Option<String>,
480 url: String,
481 settings_url: String,
482}
483
484/// The mail plan for this activity, or `None` when instance mail is off. Reads the mail settings
485/// once.
486async fn mail_plan(
487 state: &AppState,
488 repo: &Repo,
489 issue: &Issue,
490 actor_id: &str,
491 activity: &Activity,
492 body_text: Option<&str>,
493) -> Result<Option<MailPlan>> {
494 if !state.store.mail_settings().await?.enabled {
495 return Ok(None);
496 }
497 let base = state.config.base_url.trim_end_matches('/');
498 let host = host_of(base);
499 let actor = match actor_id {
500 "" => None,
501 id => state.store.user_by_id(id).await?.map(|u| u.username),
502 };
503 let section = if state
504 .store
505 .pull_by_number(&repo.id, issue.number)
506 .await?
507 .is_some()
508 {
509 "pulls"
510 } else {
511 "issues"
512 };
513 Ok(Some(MailPlan {
514 root: format!("<issue-{}@{host}>", issue.id),
515 host,
516 event_id: ulid::Ulid::generate().to_string(),
517 opens_thread: *activity == Activity::Opened,
518 actor,
519 verb: verb_for(activity),
520 repo: format!("{}/{}", repo.owner_name, repo.name),
521 number: issue.number,
522 title: issue.title.clone(),
523 comment: body_text.map(str::to_owned),
524 url: format!(
525 "{base}/{}/{}/{section}/{}",
526 repo.owner_name, repo.name, issue.number
527 ),
528 settings_url: format!("{base}/settings/notifications"),
529 }))
530}
531
532/// The push text for this activity: the repo, the number, the issue title and what happened.
533async fn push_alert(
534 state: &AppState,
535 repo: &Repo,
536 issue: &Issue,
537 actor_id: &str,
538 activity: &Activity,
539) -> Result<Alert> {
540 let actor = match actor_id {
541 "" => None,
542 id => state.store.user_by_id(id).await?.map(|u| u.username),
543 };
544 let section = if state
545 .store
546 .pull_by_number(&repo.id, issue.number)
547 .await?
548 .is_some()
549 {
550 "pulls"
551 } else {
552 "issues"
553 };
554 Ok(Alert::Activity {
555 repo: format!("{}/{}", repo.owner_name, repo.name),
556 number: issue.number,
557 title: issue.title.clone(),
558 verb: push_verb_for(activity),
559 actor,
560 url: format!(
561 "/{}/{}/{section}/{}",
562 repo.owner_name, repo.name, issue.number
563 ),
564 thread: issue.id.clone(),
565 })
566}
567
568fn push_verb_for(activity: &Activity) -> misc::K {
569 match activity {
570 Activity::Opened => misc::K::VerbOpened,
571 Activity::Comment => misc::K::VerbCommented,
572 Activity::Closed => misc::K::VerbClosed,
573 Activity::Reopened => misc::K::VerbReopened,
574 Activity::Merged => misc::K::VerbMerged,
575 Activity::Review => misc::K::VerbReviewed,
576 Activity::Assigned { .. } => misc::K::VerbAssigned,
577 Activity::ReviewRequested { .. } => misc::K::VerbReviewRequested,
578 Activity::Pushed => misc::K::VerbPushedTo,
579 Activity::Edited => misc::K::VerbMentionedYou,
580 }
581}
582
583fn verb_for(activity: &Activity) -> Verb {
584 match activity {
585 Activity::Opened => Verb::Opened,
586 Activity::Comment => Verb::Commented,
587 Activity::Closed => Verb::Closed,
588 Activity::Reopened => Verb::Reopened,
589 Activity::Merged => Verb::Merged,
590 Activity::Review => Verb::Reviewed,
591 Activity::Assigned { .. } => Verb::AssignedYou,
592 Activity::ReviewRequested { .. } => Verb::ReviewRequested,
593 Activity::Pushed => Verb::Pushed,
594 Activity::Edited => Verb::MentionedYou,
595 }
596}
597
598fn why_for(reason: Reason) -> Why {
599 match reason {
600 Reason::Mention => Why::Mention,
601 Reason::Assign => Why::Assign,
602 Reason::ReviewRequested => Why::ReviewRequested,
603 Reason::Author => Why::Author,
604 Reason::Comment => Why::Comment,
605 Reason::StateChange | Reason::Subscribed => Why::Subscribed,
606 Reason::Watching => Why::Watching,
607 }
608}
609
610/// Queues the email copy of one notification for `user_id`. Nothing is queued unless the user has
611/// a verified address and email notifications on. The idempotency key is per event and user, so
612/// a repeated run sends nothing twice.
613async fn queue_email(
614 state: &AppState,
615 plan: &MailPlan,
616 user_id: &str,
617 reason: Reason,
618) -> Result<()> {
619 let Some(user) = state.store.user_by_id(user_id).await? else {
620 return Ok(());
621 };
622 let Some(address) = user.email.as_deref().filter(|address| !address.is_empty()) else {
623 return Ok(());
624 };
625 if !user.email_notifications || !state.store.email_is_verified(user_id).await? {
626 return Ok(());
627 }
628 let lang = i18n::resolve(Some(user.language.as_str()), &HeaderMap::new());
629 let (subject, body) = templates::notification(
630 lang,
631 &templates::Notification {
632 actor: plan.actor.as_deref(),
633 verb: plan.verb,
634 repo: &plan.repo,
635 number: plan.number,
636 title: &plan.title,
637 comment: plan.comment.as_deref(),
638 url: &plan.url,
639 why: why_for(reason),
640 settings_url: &plan.settings_url,
641 },
642 );
643 let (message_id, in_reply_to) = if plan.opens_thread {
644 (plan.root.clone(), None)
645 } else {
646 (
647 format!("<{}.{user_id}@{}>", plan.event_id, plan.host),
648 Some(plan.root.clone()),
649 )
650 };
651 let outgoing = OutgoingMail {
652 to: address.to_owned(),
653 subject,
654 body,
655 message_id: Some(message_id),
656 in_reply_to,
657 kind: MailKind::Notification,
658 user_id: Some(user_id.to_owned()),
659 };
660 let idem_key = format!("notif:{}:{user_id}", plan.event_id);
661 mail::enqueue_message(state, &idem_key, &outgoing).await?;
662 Ok(())
663}
664
665/// The host of `base_url`, without scheme, port or path. Used as the Message-ID domain.
666fn host_of(base_url: &str) -> String {
667 let rest = base_url
668 .split_once("://")
669 .map_or(base_url, |(_, rest)| rest);
670 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
671 let host = authority
672 .rsplit_once('@')
673 .map_or(authority, |(_, host)| host);
674 let host = host.split(':').next().unwrap_or_default();
675 if host.is_empty() {
676 "localhost".to_owned()
677 } else {
678 host.to_owned()
679 }
680}
681
682/// True when the user has an explicit `ignored` subscription on the issue.
683async fn is_ignored(state: &AppState, user_id: &str, issue_id: &str) -> Result<bool> {
684 Ok(matches!(
685 state.store.subscription(user_id, issue_id).await?,
686 Some((SubState::Ignored, _))
687 ))
688}
689
690#[cfg(test)]
691mod tests {
692 use forge_core::{Notification, Role, Visibility};
693
694 use super::*;
695 use crate::test_support::test_state;
696
697 struct Fixture {
698 state: AppState,
699 repo: Repo,
700 issue: Issue,
701 owner: User,
702 tahinli: User,
703 bob: User,
704 carol: User,
705 _dir: tempfile::TempDir,
706 }
707
708 async fn fixture(visibility: Visibility) -> Fixture {
709 let dir = tempfile::tempdir().expect("tempdir");
710 let state = test_state(dir.path()).await;
711 let store = &state.store;
712 let owner = store
713 .create_user("owner", None, "unused", false)
714 .await
715 .unwrap();
716 let tahinli = store
717 .create_user("tahinli", None, "unused", false)
718 .await
719 .unwrap();
720 let bob = store
721 .create_user("bob", None, "unused", false)
722 .await
723 .unwrap();
724 let carol = store
725 .create_user("carol", None, "unused", false)
726 .await
727 .unwrap();
728 let repo = store
729 .create_repo(&owner.id, "proj", "", visibility, "main")
730 .await
731 .unwrap();
732 let issue = store
733 .create_issue(&repo.id, &owner.id, "a problem", "body")
734 .await
735 .unwrap();
736 Fixture {
737 state,
738 repo,
739 issue,
740 owner,
741 tahinli,
742 bob,
743 carol,
744 _dir: dir,
745 }
746 }
747
748 async fn inbox(fx: &Fixture, user: &User) -> Vec<Notification> {
749 fx.state
750 .store
751 .list_notifications(&user.id, false, None, 50)
752 .await
753 .unwrap()
754 }
755
756 #[test]
757 fn mentioned_usernames_cases() {
758 // (name, markdown, expected usernames): code, links, emails, HTML, dedupe and no-mention cases.
759 let cases: Vec<(&str, &str, Vec<&str>)> = vec![
760 (
761 "skips code, links and emails",
762 "hi @Tahinli and @bob. mail a@b.com `@code`\n\n\
763 ```\n@blocked\n```\n[@linked](https://x.test) @tahinli again",
764 vec!["tahinli", "bob"],
765 ),
766 (
767 "found inside html blocks",
768 "<div>\n@carol\n</div>\n",
769 vec!["carol"],
770 ),
771 ("deduped case-insensitively", "@Bob @bob @BOB", vec!["bob"]),
772 ("no mentions", "no mentions here", vec![]),
773 ];
774 for (name, text, want) in cases {
775 assert_eq!(mentioned_usernames(text), want, "case {name}");
776 }
777 }
778
779 #[tokio::test]
780 async fn comment_notifies_subscriber_not_the_commenter() {
781 let fx = fixture(Visibility::Public).await;
782 let store = &fx.state.store;
783 store
784 .subscribe(
785 &fx.bob.id,
786 &fx.issue.id,
787 SubState::Subscribed,
788 Reason::Subscribed,
789 )
790 .await
791 .unwrap();
792 store
793 .subscribe(
794 &fx.tahinli.id,
795 &fx.issue.id,
796 SubState::Subscribed,
797 Reason::Subscribed,
798 )
799 .await
800 .unwrap();
801
802 dispatch(
803 &fx.state,
804 &fx.repo,
805 &fx.issue,
806 &fx.tahinli.id,
807 Activity::Comment,
808 Some("hello"),
809 )
810 .await;
811
812 let bob_inbox = inbox(&fx, &fx.bob).await;
813 assert_eq!(bob_inbox.len(), 1);
814 assert_eq!(bob_inbox[0].reason, Reason::Subscribed);
815 assert_eq!(bob_inbox[0].last_activity, "comment");
816 assert!(
817 inbox(&fx, &fx.tahinli).await.is_empty(),
818 "the actor is never notified"
819 );
820 }
821
822 #[tokio::test]
823 async fn opened_notifies_watchers_and_auto_subscribes_the_author() {
824 let fx = fixture(Visibility::Public).await;
825 fx.state
826 .store
827 .set_watch(&fx.bob.id, &fx.repo.id, WatchLevel::Watching)
828 .await
829 .unwrap();
830
831 dispatch(
832 &fx.state,
833 &fx.repo,
834 &fx.issue,
835 &fx.owner.id,
836 Activity::Opened,
837 None,
838 )
839 .await;
840
841 let bob_inbox = inbox(&fx, &fx.bob).await;
842 assert_eq!(bob_inbox.len(), 1);
843 assert_eq!(bob_inbox[0].reason, Reason::Watching);
844 assert!(inbox(&fx, &fx.owner).await.is_empty());
845 let sub = fx
846 .state
847 .store
848 .subscription(&fx.owner.id, &fx.issue.id)
849 .await
850 .unwrap();
851 assert_eq!(sub, Some((SubState::Subscribed, Reason::Author)));
852 }
853
854 #[tokio::test]
855 async fn ignored_subscription_suppresses_watcher() {
856 let fx = fixture(Visibility::Public).await;
857 let store = &fx.state.store;
858 store
859 .set_watch(&fx.bob.id, &fx.repo.id, WatchLevel::Watching)
860 .await
861 .unwrap();
862 store
863 .subscribe(
864 &fx.bob.id,
865 &fx.issue.id,
866 SubState::Ignored,
867 Reason::Subscribed,
868 )
869 .await
870 .unwrap();
871
872 dispatch(
873 &fx.state,
874 &fx.repo,
875 &fx.issue,
876 &fx.owner.id,
877 Activity::Opened,
878 None,
879 )
880 .await;
881
882 assert!(inbox(&fx, &fx.bob).await.is_empty());
883 }
884
885 #[tokio::test]
886 async fn ignoring_repo_suppresses_but_mention_still_notifies() {
887 let fx = fixture(Visibility::Public).await;
888 let store = &fx.state.store;
889 store
890 .set_watch(&fx.tahinli.id, &fx.repo.id, WatchLevel::Ignoring)
891 .await
892 .unwrap();
893 store
894 .subscribe(
895 &fx.tahinli.id,
896 &fx.issue.id,
897 SubState::Subscribed,
898 Reason::Subscribed,
899 )
900 .await
901 .unwrap();
902
903 dispatch(
904 &fx.state,
905 &fx.repo,
906 &fx.issue,
907 &fx.bob.id,
908 Activity::Comment,
909 Some("plain"),
910 )
911 .await;
912 assert!(inbox(&fx, &fx.tahinli).await.is_empty());
913
914 dispatch(
915 &fx.state,
916 &fx.repo,
917 &fx.issue,
918 &fx.bob.id,
919 Activity::Comment,
920 Some("@tahinli look"),
921 )
922 .await;
923 let tahinli_inbox = inbox(&fx, &fx.tahinli).await;
924 assert_eq!(tahinli_inbox.len(), 1);
925 assert_eq!(tahinli_inbox[0].reason, Reason::Mention);
926 }
927
928 #[tokio::test]
929 async fn mention_without_read_access_on_private_repo_is_not_notified() {
930 let fx = fixture(Visibility::Private).await;
931 let store = &fx.state.store;
932
933 dispatch(
934 &fx.state,
935 &fx.repo,
936 &fx.issue,
937 &fx.owner.id,
938 Activity::Comment,
939 Some("@bob hi"),
940 )
941 .await;
942 assert!(inbox(&fx, &fx.bob).await.is_empty());
943 let sub = store.subscription(&fx.bob.id, &fx.issue.id).await.unwrap();
944 assert_eq!(sub, None, "an unreadable mention does not subscribe");
945
946 store
947 .set_collaborator(&fx.repo.id, &fx.bob.id, Role::Read)
948 .await
949 .unwrap();
950 dispatch(
951 &fx.state,
952 &fx.repo,
953 &fx.issue,
954 &fx.owner.id,
955 Activity::Comment,
956 Some("@bob hi"),
957 )
958 .await;
959 let bob_inbox = inbox(&fx, &fx.bob).await;
960 assert_eq!(bob_inbox.len(), 1);
961 assert_eq!(bob_inbox[0].reason, Reason::Mention);
962 }
963
964 #[tokio::test]
965 async fn assignee_is_notified_with_assign_reason() {
966 let fx = fixture(Visibility::Public).await;
967
968 dispatch(
969 &fx.state,
970 &fx.repo,
971 &fx.issue,
972 &fx.owner.id,
973 Activity::Assigned {
974 assignee_id: fx.bob.id.clone(),
975 },
976 None,
977 )
978 .await;
979
980 let bob_inbox = inbox(&fx, &fx.bob).await;
981 assert_eq!(bob_inbox.len(), 1);
982 assert_eq!(bob_inbox[0].reason, Reason::Assign);
983 assert_eq!(bob_inbox[0].last_activity, "assigned");
984 }
985
986 #[tokio::test]
987 async fn pushed_reaches_subscribers_not_watchers() {
988 let fx = fixture(Visibility::Public).await;
989 let store = &fx.state.store;
990 store
991 .set_watch(&fx.bob.id, &fx.repo.id, WatchLevel::Watching)
992 .await
993 .unwrap();
994 store
995 .subscribe(
996 &fx.carol.id,
997 &fx.issue.id,
998 SubState::Subscribed,
999 Reason::Author,
1000 )
1001 .await
1002 .unwrap();
1003
1004 dispatch(
1005 &fx.state,
1006 &fx.repo,
1007 &fx.issue,
1008 &fx.owner.id,
1009 Activity::Pushed,
1010 None,
1011 )
1012 .await;
1013
1014 assert!(inbox(&fx, &fx.bob).await.is_empty());
1015 let carol_inbox = inbox(&fx, &fx.carol).await;
1016 assert_eq!(carol_inbox.len(), 1);
1017 assert_eq!(carol_inbox[0].reason, Reason::Author);
1018 }
1019
1020 #[tokio::test]
1021 async fn edit_notifies_only_the_newly_mentioned_user() {
1022 let fx = fixture(Visibility::Public).await;
1023 fx.state
1024 .store
1025 .set_watch(&fx.bob.id, &fx.repo.id, WatchLevel::Watching)
1026 .await
1027 .unwrap();
1028
1029 dispatch_edit(
1030 &fx.state,
1031 &fx.repo,
1032 &fx.issue,
1033 &fx.owner.id,
1034 "hi @bob",
1035 "hi @bob and @carol",
1036 )
1037 .await;
1038
1039 assert!(
1040 inbox(&fx, &fx.bob).await.is_empty(),
1041 "bob was mentioned before the edit"
1042 );
1043 let carol_inbox = inbox(&fx, &fx.carol).await;
1044 assert_eq!(carol_inbox.len(), 1);
1045 assert_eq!(carol_inbox[0].reason, Reason::Mention);
1046 assert_eq!(carol_inbox[0].last_activity, "edited");
1047 }
1048
1049 #[tokio::test]
1050 async fn advisory_alerts_reach_owner_admin_collaborators_and_org_owners_only() {
1051 let dir = tempfile::tempdir().expect("tempdir");
1052 let state = test_state(dir.path()).await;
1053 let store = &state.store;
1054 let owner = store
1055 .create_user("owner", None, "unused", false)
1056 .await
1057 .unwrap();
1058 let admin = store
1059 .create_user("admin", None, "unused", false)
1060 .await
1061 .unwrap();
1062 let writer = store
1063 .create_user("writer", None, "unused", false)
1064 .await
1065 .unwrap();
1066 let repo = store
1067 .create_repo(&owner.id, "proj", "", Visibility::Private, "main")
1068 .await
1069 .unwrap();
1070 store
1071 .set_collaborator(&repo.id, &admin.id, Role::Admin)
1072 .await
1073 .unwrap();
1074 store
1075 .set_collaborator(&repo.id, &writer.id, Role::Write)
1076 .await
1077 .unwrap();
1078
1079 advisories_opened(&state, &repo, 2).await;
1080
1081 assert_eq!(advisory_rows(store, &owner.id).await, vec![2]);
1082 assert_eq!(advisory_rows(store, &admin.id).await, vec![2]);
1083 assert!(advisory_rows(store, &writer.id).await.is_empty());
1084
1085 // An org-owned repo: its owners and admin collaborators hear, its plain members do not.
1086 let org = store.create_org("acme", &owner.id).await.unwrap();
1087 let org_member = store
1088 .create_user("member", None, "unused", false)
1089 .await
1090 .unwrap();
1091 let org_owner = store
1092 .create_user("orgowner", None, "unused", false)
1093 .await
1094 .unwrap();
1095 store
1096 .add_org_member(&org.id, &org_member.id, OrgMemberRole::Member)
1097 .await
1098 .unwrap();
1099 store
1100 .add_org_member(&org.id, &org_owner.id, OrgMemberRole::Owner)
1101 .await
1102 .unwrap();
1103 let org_repo = store
1104 .create_repo(&org.id, "shared", "", Visibility::Private, "main")
1105 .await
1106 .unwrap();
1107
1108 advisories_opened(&state, &org_repo, 1).await;
1109
1110 assert_eq!(advisory_rows(store, &owner.id).await, vec![1, 2]);
1111 assert_eq!(advisory_rows(store, &org_owner.id).await, vec![1]);
1112 assert!(advisory_rows(store, &org_member.id).await.is_empty());
1113 assert!(advisory_rows(store, &org.id).await.is_empty());
1114 }
1115
1116 /// The `new_alerts` counts of a user's advisory inbox rows, sorted.
1117 async fn advisory_rows(store: &forge_core::store::Store, user_id: &str) -> Vec<u64> {
1118 let mut counts: Vec<u64> = store
1119 .list_advisory_notifications(user_id, false, None, 50)
1120 .await
1121 .unwrap()
1122 .iter()
1123 .map(|notice| notice.new_alerts)
1124 .collect();
1125 counts.sort_unstable();
1126 counts
1127 }
1128
1129 /// Instance mail on or off. Bob has a verified address and is subscribed to the issue.
1130 async fn mail_fixture(enabled: bool) -> Fixture {
1131 let fx = fixture(Visibility::Public).await;
1132 let store = &fx.state.store;
1133 store
1134 .update_mail_settings(&forge_core::mail::MailSettingsUpdate {
1135 host: "smtp.test.example",
1136 port: 587,
1137 security: forge_core::mail::Security::StartTls,
1138 username: "",
1139 from_addr: "forge@test.example",
1140 from_name: "forge",
1141 enabled,
1142 password: None,
1143 })
1144 .await
1145 .unwrap();
1146 store
1147 .set_email(&fx.bob.id, "bob@test.example")
1148 .await
1149 .unwrap();
1150 let token = store
1151 .create_verify_token(&fx.bob.id, "bob@test.example")
1152 .await
1153 .unwrap();
1154 store.redeem_verify_token(&token).await.unwrap();
1155 store
1156 .subscribe(
1157 &fx.bob.id,
1158 &fx.issue.id,
1159 SubState::Subscribed,
1160 Reason::Subscribed,
1161 )
1162 .await
1163 .unwrap();
1164 fx
1165 }
1166
1167 /// The outbox rows addressed to `address`.
1168 async fn mail_to(fx: &Fixture, address: &str) -> Vec<forge_core::mail::OutboxEntry> {
1169 fx.state
1170 .store
1171 .recent_mail(50)
1172 .await
1173 .unwrap()
1174 .into_iter()
1175 .filter(|row| row.to_addr == address)
1176 .collect()
1177 }
1178
1179 #[tokio::test]
1180 async fn comment_emails_the_subscriber_threaded_under_the_issue() {
1181 let fx = mail_fixture(true).await;
1182 dispatch(
1183 &fx.state,
1184 &fx.repo,
1185 &fx.issue,
1186 &fx.tahinli.id,
1187 Activity::Comment,
1188 Some("hello there"),
1189 )
1190 .await;
1191
1192 let rows = mail_to(&fx, "bob@test.example").await;
1193 assert_eq!(rows.len(), 1, "one mail to the subscriber");
1194 let host = host_of(&fx.state.config.base_url);
1195 assert_eq!(
1196 rows[0].in_reply_to.as_deref(),
1197 Some(format!("<issue-{}@{host}>", fx.issue.id).as_str())
1198 );
1199 let message_id = rows[0].message_id.as_deref().unwrap_or_default();
1200 assert!(message_id.starts_with('<') && message_id.ends_with(&format!("@{host}>")));
1201 assert_ne!(
1202 message_id,
1203 rows[0].in_reply_to.as_deref().unwrap_or_default()
1204 );
1205 assert!(rows[0].body.contains("hello there"), "{}", rows[0].body);
1206 assert!(
1207 rows[0].body.contains("tahinli commented on this."),
1208 "{}",
1209 rows[0].body
1210 );
1211 assert!(
1212 rows[0].idem_key.starts_with("notif:"),
1213 "{}",
1214 rows[0].idem_key
1215 );
1216 assert!(rows[0].idem_key.ends_with(&format!(":{}", fx.bob.id)));
1217 assert!(
1218 inbox(&fx, &fx.tahinli).await.is_empty(),
1219 "the actor gets no mail or inbox row"
1220 );
1221 }
1222
1223 #[tokio::test]
1224 async fn opening_mail_is_the_thread_root() {
1225 let fx = mail_fixture(true).await;
1226 dispatch(
1227 &fx.state,
1228 &fx.repo,
1229 &fx.issue,
1230 &fx.tahinli.id,
1231 Activity::Opened,
1232 Some("the body"),
1233 )
1234 .await;
1235
1236 let rows = mail_to(&fx, "bob@test.example").await;
1237 assert_eq!(rows.len(), 1);
1238 let host = host_of(&fx.state.config.base_url);
1239 let root = format!("<issue-{}@{host}>", fx.issue.id);
1240 assert_eq!(rows[0].message_id.as_deref(), Some(root.as_str()));
1241 assert_eq!(rows[0].in_reply_to, None);
1242 }
1243
1244 #[tokio::test]
1245 async fn no_mail_without_a_verified_address() {
1246 let fx = mail_fixture(true).await;
1247 fx.state
1248 .store
1249 .clear_email_verified(&fx.bob.id)
1250 .await
1251 .unwrap();
1252 dispatch(
1253 &fx.state,
1254 &fx.repo,
1255 &fx.issue,
1256 &fx.tahinli.id,
1257 Activity::Comment,
1258 Some("hi"),
1259 )
1260 .await;
1261 assert!(mail_to(&fx, "bob@test.example").await.is_empty());
1262 assert_eq!(
1263 inbox(&fx, &fx.bob).await.len(),
1264 1,
1265 "the inbox still gets it"
1266 );
1267 }
1268
1269 #[tokio::test]
1270 async fn no_mail_when_the_user_turned_email_notifications_off() {
1271 let fx = mail_fixture(true).await;
1272 fx.state
1273 .store
1274 .set_email_notifications(&fx.bob.id, false)
1275 .await
1276 .unwrap();
1277 dispatch(
1278 &fx.state,
1279 &fx.repo,
1280 &fx.issue,
1281 &fx.tahinli.id,
1282 Activity::Comment,
1283 Some("hi"),
1284 )
1285 .await;
1286 assert!(mail_to(&fx, "bob@test.example").await.is_empty());
1287 assert_eq!(inbox(&fx, &fx.bob).await.len(), 1);
1288 }
1289
1290 #[tokio::test]
1291 async fn no_mail_when_instance_mail_is_disabled() {
1292 let fx = mail_fixture(false).await;
1293 dispatch(
1294 &fx.state,
1295 &fx.repo,
1296 &fx.issue,
1297 &fx.tahinli.id,
1298 Activity::Comment,
1299 Some("hi"),
1300 )
1301 .await;
1302 assert!(mail_to(&fx, "bob@test.example").await.is_empty());
1303 }
1304
1305 #[test]
1306 fn host_of_drops_scheme_port_and_path() {
1307 assert_eq!(
1308 host_of("https://forge.example.com:8443/"),
1309 "forge.example.com"
1310 );
1311 assert_eq!(host_of("http://127.0.0.1:7660"), "127.0.0.1");
1312 assert_eq!(host_of("forge.test/x"), "forge.test");
1313 assert_eq!(host_of("https:///"), "localhost");
1314 }
1315}