notifier.go64 lines, 1.8 KB
| 1 | package notification |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "log/slog" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/fiston-user/payments/internal/platform/events" |
| 11 | "github.com/google/uuid" |
| 12 | ) |
| 13 | |
| 14 | // A Notifier turns events into messages, and sends each one once. |
| 15 | type Notifier struct { |
| 16 | store *Store |
| 17 | users Users |
| 18 | sender Sender |
| 19 | logger *slog.Logger |
| 20 | MaxAttempts int // deliveries of a message, before it's a dead letter |
| 21 | Backoff time.Duration // the first retry's delay |
| 22 | } |
| 23 | |
| 24 | // NewNotifier returns a Notifier with sensible defaults. |
| 25 | func NewNotifier(store *Store, users Users, sender Sender, logger *slog.Logger) *Notifier { |
| 26 | return &Notifier{ |
| 27 | store: store, users: users, sender: sender, logger: logger, |
| 28 | MaxAttempts: 5, Backoff: time.Second, |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // Notify sends the message evt deserves, unless it was sent before. Calling |
| 33 | // it again with the same event is safe: that's what makes us idempotent. |
| 34 | func (n *Notifier) Notify(ctx context.Context, evt events.Event) error { |
| 35 | m, ok, err := compose(evt) |
| 36 | if err != nil || !ok { |
| 37 | return err |
| 38 | } |
| 39 | if m.To, err = n.users.Email(ctx, m.UserID); err != nil { |
| 40 | return err |
| 41 | } |
| 42 | sent, err := n.store.Deliver(ctx, m, func() error { return n.sender.Send(ctx, m) }) |
| 43 | if err != nil { |
| 44 | return err |
| 45 | } |
| 46 | if !sent { |
| 47 | n.logger.InfoContext(ctx, "already sent, skipping", "type", evt.Type) |
| 48 | return nil |
| 49 | } |
| 50 | n.logger.InfoContext(ctx, "notification sent", "type", evt.Type, "to", m.To) |
| 51 | return nil |
| 52 | } |
| 53 | |
| 54 | // process decodes a message's event, and notifies about it. |
| 55 | func (n *Notifier) process(ctx context.Context, data []byte) error { |
| 56 | var evt events.Event |
| 57 | if err := json.Unmarshal(data, &evt); err != nil { |
| 58 | return Permanent(fmt.Errorf("decode event: %w", err)) |
| 59 | } |
| 60 | if evt.ID == uuid.Nil { |
| 61 | return Permanent(fmt.Errorf("event %q has no ID", evt.Type)) |
| 62 | } |
| 63 | return n.Notify(ctx, evt) |
| 64 | } |