internal/notify/notify.go
89 lines · 2710 bytes
8 symbols in this file
1// Package notify drains the notification queue: activity mail with the same
2// bounded-retry discipline as webhook delivery, so a flaky relay delays
3// feedback instead of losing it.
4package notify
5
6import (
7 "context"
8 "log/slog"
9 "regexp"
10 "time"
11
12 "gitbay.org/gitbay/internal/config"
13 "gitbay.org/gitbay/internal/mail"
14 "gitbay.org/gitbay/internal/store"
15)
16
17// DefaultMaxAttempts and DefaultRetryBase are the retry parameters gitbayd
18// wires up in production (cmd/gitbayd/main.go), named so anything that
19// needs to reason about the mailer's worst-case delivery time — such as
20// checking it against a login link's TTL — computes it from the numbers
21// actually in force rather than a copy of them.
22const (
23 DefaultMaxAttempts = 5
24 DefaultRetryBase = 30 * time.Second
25)
26
27type Mailer struct {
28 St *store.Store
29 Cfg config.Config
30 RetryBase time.Duration
31 MaxAttempts int
32}
33
34func New(st *store.Store, cfg config.Config, retryBase time.Duration) *Mailer {
35 return &Mailer{St: st, Cfg: cfg, RetryBase: retryBase, MaxAttempts: DefaultMaxAttempts}
36}
37
38// Run polls for due mail until ctx is done.
39func (m *Mailer) Run(ctx context.Context) {
40 tick := time.NewTicker(2 * time.Second)
41 defer tick.Stop()
42 for {
43 select {
44 case <-ctx.Done():
45 return
46 case <-tick.C:
47 due, err := m.St.DueMail(20)
48 if err != nil {
49 slog.Error("notify: listing due mail", "err", err)
50 continue
51 }
52 for _, q := range due {
53 m.deliver(q)
54 }
55 }
56 }
57}
58
59// deliver sends one queued mail, marking it sent, due again after a
60// backoff, or failed once it has had MaxAttempts.
61func (m *Mailer) deliver(q store.QueuedMail) {
62 err := mail.SendReplyTo(m.Cfg, q.Recipient, q.ReplyTo, q.Subject, q.Body)
63 if err == nil {
64 m.St.MarkMailSent(q.ID)
65 return
66 }
67 attempt := q.Attempts + 1
68 if attempt >= m.MaxAttempts {
69 m.St.MarkMailFailed(q.ID, err.Error(), nil)
70 slog.Warn("notification dead-lettered",
71 "mail", q.ID, "attempts", attempt, "err", redactAddresses(err.Error()))
72 return
73 }
74 next := time.Now().Add(m.RetryBase << (attempt - 1))
75 m.St.MarkMailFailed(q.ID, err.Error(), &next)
76}
77
78// A relay's rejection usually quotes the address it rejected — "550 5.1.1
79// <x@y>: Recipient address rejected" — so dropping the recipient field
80// alone would not keep an address out of the log.
81var addressPat = regexp.MustCompile(`[^\s<>@,;:"]+@[^\s<>@,;:"]+`)
82
83// redactAddresses removes mail addresses from text bound for the log. The
84// unredacted error is still recorded on the queue row, where an instance
85// admin reads it on /admin: the database holds the address, the log does
86// not (#173).
87func redactAddresses(s string) string {
88 return addressPat.ReplaceAllString(s, "<address>")
89}