internal/store/notify.go

119 lines · 4077 bytes

  1package store
  2
  3import "time"
  4
  5type QueuedMail struct {
  6	ID        int64
  7	Recipient string
  8	ReplyTo   string // "" for none
  9	Subject   string
 10	Body      string
 11	Attempts  int
 12}
 13
 14func (s *Store) EnqueueMail(recipient, subject, body string) error {
 15	return s.EnqueueMailReplyTo(recipient, "", subject, body)
 16}
 17
 18// EnqueueMailReplyTo queues mail with a Reply-To address. The address
 19// carries a reply token, so it is blanked once the row is sent or
 20// dead-lettered.
 21func (s *Store) EnqueueMailReplyTo(recipient, replyTo, subject, body string) error {
 22	_, err := s.DB.Exec(
 23		"INSERT INTO notifications (recipient, reply_to, subject, body) VALUES (?, ?, ?, ?)",
 24		recipient, replyTo, subject, body)
 25	return err
 26}
 27
 28func (s *Store) DueMail(limit int) ([]QueuedMail, error) {
 29	return queryAll(s.DB, scanQueuedMail, `
 30		SELECT id, recipient, reply_to, subject, body, attempts FROM notifications
 31		WHERE sent_at IS NULL AND failed_at IS NULL
 32		  AND (next_attempt_at IS NULL OR next_attempt_at <= ?)
 33		ORDER BY id LIMIT ?`, fmtTime(time.Now()), limit)
 34}
 35
 36func (s *Store) MarkMailSent(id int64) error {
 37	_, err := s.DB.Exec(
 38		"UPDATE notifications SET sent_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), attempts = attempts + 1, reply_to = '' WHERE id = ?", id)
 39	return err
 40}
 41
 42func (s *Store) MarkMailFailed(id int64, errMsg string, nextAt *time.Time) error {
 43	if nextAt == nil {
 44		_, err := s.DB.Exec(
 45			"UPDATE notifications SET failed_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), attempts = attempts + 1, last_error = ?, reply_to = '' WHERE id = ?",
 46			errMsg, id)
 47		return err
 48	}
 49	_, err := s.DB.Exec(
 50		"UPDATE notifications SET attempts = attempts + 1, last_error = ?, next_attempt_at = ? WHERE id = ?",
 51		errMsg, fmtTime(*nextAt), id)
 52	return err
 53}
 54
 55// IssueParticipants returns distinct user ids involved in an issue: the
 56// author, every commenter, and everyone mentioned.
 57func (s *Store) IssueParticipants(issueID int64) ([]int64, error) {
 58	return s.idQuery(`
 59		SELECT author_id FROM issues WHERE id = ?
 60		UNION SELECT author_id FROM issue_comments WHERE issue_id = ?
 61		UNION SELECT user_id FROM mentions WHERE kind = 'issue' AND item_id = ?`, issueID, issueID, issueID)
 62}
 63
 64// MRParticipants returns distinct user ids involved in an MR: author,
 65// commenters, reviewers, and everyone mentioned.
 66func (s *Store) MRParticipants(mrID int64) ([]int64, error) {
 67	return s.idQuery(`
 68		SELECT author_id FROM merge_requests WHERE id = ?
 69		UNION SELECT author_id FROM mr_comments WHERE mr_id = ?
 70		UNION SELECT reviewer_id FROM mr_reviews WHERE mr_id = ?
 71		UNION SELECT author_id FROM mr_diff_comments WHERE mr_id = ?
 72		UNION SELECT user_id FROM mentions WHERE kind = 'mr' AND item_id = ?`, mrID, mrID, mrID, mrID, mrID)
 73}
 74
 75// AddMentions records accounts mentioned in an issue or merge request
 76// (kind "issue" or "mr"); a repeat mention is not an error.
 77func (s *Store) AddMentions(repoID int64, kind string, itemID int64, userIDs []int64) error {
 78	for _, id := range userIDs {
 79		if _, err := s.DB.Exec(
 80			"INSERT INTO mentions (repo_id, kind, item_id, user_id) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING",
 81			repoID, kind, itemID, id); err != nil {
 82			return err
 83		}
 84	}
 85	return nil
 86}
 87
 88// RepoNotifyTargets returns who should hear about new activity on a repo:
 89// the owning user, or every admin of the owning org.
 90func (s *Store) RepoNotifyTargets(repo Repo) ([]int64, error) {
 91	if repo.OwnerKind == "user" {
 92		return []int64{repo.OwnerID}, nil
 93	}
 94	return s.idQuery(
 95		"SELECT user_id FROM org_members WHERE org_id = ? AND role = 'admin'", repo.OwnerID)
 96}
 97
 98func (s *Store) idQuery(q string, args ...any) ([]int64, error) {
 99	rows, err := s.DB.Query(q, args...)
100	if err != nil {
101		return nil, err
102	}
103	defer rows.Close()
104	var out []int64
105	for rows.Next() {
106		var id int64
107		if err := rows.Scan(&id); err != nil {
108			return nil, err
109		}
110		out = append(out, id)
111	}
112	return out, rows.Err()
113}
114
115func scanQueuedMail(row interface{ Scan(...any) error }) (QueuedMail, error) {
116	var m QueuedMail
117	err := row.Scan(&m.ID, &m.Recipient, &m.ReplyTo, &m.Subject, &m.Body, &m.Attempts)
118	return m, err
119}