store.go68 lines, 2.0 KB
| 1 | package notification |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/fiston-user/payments/internal/notification/notificationdb" |
| 8 | "github.com/jackc/pgx/v5" |
| 9 | "github.com/jackc/pgx/v5/pgxpool" |
| 10 | ) |
| 11 | |
| 12 | // Store remembers what we sent, and what we gave up on. |
| 13 | type Store struct { |
| 14 | pool *pgxpool.Pool |
| 15 | q *notificationdb.Queries |
| 16 | } |
| 17 | |
| 18 | // NewStore returns a Store on pool. |
| 19 | func NewStore(pool *pgxpool.Pool) *Store { |
| 20 | return &Store{pool: pool, q: notificationdb.New(pool)} |
| 21 | } |
| 22 | |
| 23 | // Deliver records m, and calls send, in one database transaction: if send |
| 24 | // fails, the record rolls back. If m's event was handled before, it sends |
| 25 | // nothing, and returns false. |
| 26 | func (s *Store) Deliver(ctx context.Context, m Message, send func() error) (bool, error) { |
| 27 | sent := false |
| 28 | err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { |
| 29 | n, err := s.q.WithTx(tx).InsertNotification(ctx, notificationdb.InsertNotificationParams{ |
| 30 | EventID: m.EventID, |
| 31 | UserID: m.UserID, |
| 32 | Recipient: m.To, |
| 33 | Subject: m.Subject, |
| 34 | }) |
| 35 | if err != nil || n == 0 { |
| 36 | return err |
| 37 | } |
| 38 | // Until we commit, the new row is locked: the same event, delivered |
| 39 | // twice at once, waits here, and then finds it. |
| 40 | sent = true |
| 41 | return send() |
| 42 | }) |
| 43 | if err != nil { |
| 44 | return false, fmt.Errorf("deliver: %w", err) |
| 45 | } |
| 46 | return sent, nil |
| 47 | } |
| 48 | |
| 49 | // A DeadLetter is a message we gave up on. |
| 50 | type DeadLetter = notificationdb.DeadLetter |
| 51 | |
| 52 | // DeadLetter keeps a message we gave up on, and why. |
| 53 | func (s *Store) DeadLetter(ctx context.Context, d notificationdb.InsertDeadLetterParams) error { |
| 54 | if err := s.q.InsertDeadLetter(ctx, d); err != nil { |
| 55 | return fmt.Errorf("dead letter %s %d: %w", d.Stream, d.Seq, err) |
| 56 | } |
| 57 | return nil |
| 58 | } |
| 59 | |
| 60 | // DeadLetters returns the dead letters nobody has replayed yet, oldest first. |
| 61 | func (s *Store) DeadLetters(ctx context.Context) ([]DeadLetter, error) { |
| 62 | return s.q.ListDeadLetters(ctx) |
| 63 | } |
| 64 | |
| 65 | // Replayed marks a dead letter as handled after all. |
| 66 | func (s *Store) Replayed(ctx context.Context, d DeadLetter) error { |
| 67 | return s.q.MarkReplayed(ctx, notificationdb.MarkReplayedParams{Stream: d.Stream, Seq: d.Seq}) |
| 68 | } |