relay.go182 lines, 5.6 KB
| 1 | // Package outbox publishes the events a service writes to its outbox table, |
| 2 | // in the same database transaction as the change each event describes. |
| 3 | package outbox |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "sync" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/fiston-user/payments/internal/platform/natsx" |
| 13 | "github.com/fiston-user/payments/internal/platform/telemetry" |
| 14 | "github.com/google/uuid" |
| 15 | "github.com/jackc/pgx/v5" |
| 16 | "github.com/jackc/pgx/v5/pgxpool" |
| 17 | "github.com/nats-io/nats.go" |
| 18 | "github.com/nats-io/nats.go/jetstream" |
| 19 | "go.opentelemetry.io/otel" |
| 20 | "go.opentelemetry.io/otel/codes" |
| 21 | "go.opentelemetry.io/otel/propagation" |
| 22 | "go.opentelemetry.io/otel/trace" |
| 23 | ) |
| 24 | |
| 25 | var tracer = otel.Tracer("github.com/fiston-user/payments/internal/platform/outbox") |
| 26 | |
| 27 | // A Relay publishes the events in the outbox table to JetStream, oldest |
| 28 | // first, and marks them published. That's two writes again, so a crash in |
| 29 | // between publishes an event twice: delivery is at least once. JetStream |
| 30 | // drops the second copy, because both carry the event's ID as Nats-Msg-Id. |
| 31 | type Relay struct { |
| 32 | pool *pgxpool.Pool |
| 33 | js jetstream.JetStream |
| 34 | logger *slog.Logger |
| 35 | BatchSize int // events per database transaction |
| 36 | MaxWait time.Duration // the longest we wait before looking again |
| 37 | } |
| 38 | |
| 39 | // NewRelay returns a Relay for the outbox table in pool's database. |
| 40 | func NewRelay(pool *pgxpool.Pool, js jetstream.JetStream, logger *slog.Logger) *Relay { |
| 41 | return &Relay{pool: pool, js: js, logger: logger, BatchSize: 100, MaxWait: 5 * time.Second} |
| 42 | } |
| 43 | |
| 44 | // message is an outbox row, waiting to be published. |
| 45 | type message struct { |
| 46 | Seq int64 |
| 47 | EventID uuid.UUID |
| 48 | Subject string |
| 49 | Payload []byte |
| 50 | TraceContext propagation.MapCarrier |
| 51 | } |
| 52 | |
| 53 | // PublishBatch publishes up to BatchSize events, and returns how many. |
| 54 | func (r *Relay) PublishBatch(ctx context.Context) (int, error) { |
| 55 | tx, err := r.pool.Begin(ctx) |
| 56 | if err != nil { |
| 57 | return 0, fmt.Errorf("outbox: begin: %w", err) |
| 58 | } |
| 59 | defer tx.Rollback(ctx) |
| 60 | |
| 61 | // FOR UPDATE locks the rows until we commit. SKIP LOCKED passes over rows |
| 62 | // another relay has locked, so several instances share the work, and |
| 63 | // never publish the same rows at the same time. |
| 64 | rows, _ := tx.Query(ctx, ` |
| 65 | SELECT seq, event_id, subject, payload, trace_context FROM outbox |
| 66 | WHERE published_at IS NULL |
| 67 | ORDER BY seq |
| 68 | LIMIT $1 |
| 69 | FOR UPDATE SKIP LOCKED`, r.BatchSize) |
| 70 | batch, err := pgx.CollectRows(rows, pgx.RowToStructByPos[message]) |
| 71 | if err != nil { |
| 72 | return 0, fmt.Errorf("outbox: read: %w", err) |
| 73 | } |
| 74 | |
| 75 | var published []int64 |
| 76 | var pubErr error |
| 77 | for _, m := range batch { |
| 78 | if pubErr = r.publish(ctx, m); pubErr != nil { |
| 79 | break // stop here, so no event overtakes this one |
| 80 | } |
| 81 | published = append(published, m.Seq) |
| 82 | } |
| 83 | if len(published) == 0 { |
| 84 | return 0, pubErr |
| 85 | } |
| 86 | // Mark what made it, even when a later event failed. |
| 87 | _, err = tx.Exec(ctx, `UPDATE outbox SET published_at = now() WHERE seq = ANY($1)`, published) |
| 88 | if err == nil { |
| 89 | err = tx.Commit(ctx) |
| 90 | } |
| 91 | if err != nil { |
| 92 | return 0, fmt.Errorf("outbox: mark published: %w", err) |
| 93 | } |
| 94 | return len(published), pubErr |
| 95 | } |
| 96 | |
| 97 | // publish sends m to JetStream, in a span that continues the trace m was |
| 98 | // written in, and passes that trace on in the message's headers. |
| 99 | func (r *Relay) publish(ctx context.Context, m message) error { |
| 100 | ctx, span := tracer.Start(telemetry.Extract(ctx, m.TraceContext), "publish "+m.Subject, |
| 101 | trace.WithSpanKind(trace.SpanKindProducer)) |
| 102 | defer span.End() |
| 103 | msg := &nats.Msg{Subject: m.Subject, Data: m.Payload, Header: nats.Header{}} |
| 104 | telemetry.Inject(ctx, natsx.HeaderCarrier{Header: msg.Header}) |
| 105 | if _, err := r.js.PublishMsg(ctx, msg, jetstream.WithMsgID(m.EventID.String())); err != nil { |
| 106 | span.SetStatus(codes.Error, err.Error()) |
| 107 | return fmt.Errorf("outbox: publish %s: %w", m.EventID, err) |
| 108 | } |
| 109 | return nil |
| 110 | } |
| 111 | |
| 112 | // Run publishes events until ctx is canceled. After a full batch, it goes |
| 113 | // again right away. Otherwise it waits: until Postgres says there are new |
| 114 | // events, or for a while that doubles each time there's nothing to do. |
| 115 | func (r *Relay) Run(ctx context.Context) { |
| 116 | r.logger.Info("outbox relay started", "batch_size", r.BatchSize) |
| 117 | wake := make(chan struct{}, 1) |
| 118 | var wg sync.WaitGroup |
| 119 | defer wg.Wait() |
| 120 | wg.Go(func() { r.listen(ctx, wake) }) |
| 121 | |
| 122 | const minWait = 50 * time.Millisecond |
| 123 | wait := minWait |
| 124 | for { |
| 125 | n, err := r.PublishBatch(ctx) |
| 126 | if err != nil && ctx.Err() == nil { |
| 127 | r.logger.Warn("outbox relay: publish failed, will retry", "err", err) |
| 128 | } |
| 129 | if n == r.BatchSize { |
| 130 | wait = minWait |
| 131 | continue |
| 132 | } |
| 133 | select { |
| 134 | case <-ctx.Done(): |
| 135 | return |
| 136 | case <-wake: |
| 137 | wait = minWait |
| 138 | case <-time.After(wait): |
| 139 | wait = min(wait*2, r.MaxWait) |
| 140 | } |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | // listen sends to wake whenever Postgres notifies the outbox channel, which |
| 145 | // a trigger does each time a transaction that wrote events commits. If the |
| 146 | // connection fails, Run still polls, and listen connects again. |
| 147 | func (r *Relay) listen(ctx context.Context, wake chan<- struct{}) { |
| 148 | for ctx.Err() == nil { |
| 149 | err := r.waitForNotifications(ctx, wake) |
| 150 | if ctx.Err() != nil { |
| 151 | return |
| 152 | } |
| 153 | r.logger.Warn("outbox relay: listen failed, polling only", "err", err) |
| 154 | select { |
| 155 | case <-ctx.Done(): |
| 156 | case <-time.After(5 * time.Second): |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | func (r *Relay) waitForNotifications(ctx context.Context, wake chan<- struct{}) error { |
| 162 | pc, err := r.pool.Acquire(ctx) |
| 163 | if err != nil { |
| 164 | return err |
| 165 | } |
| 166 | // A listening connection can't go back to the pool: it's ours for good. |
| 167 | conn := pc.Hijack() |
| 168 | defer conn.Close(context.Background()) |
| 169 | |
| 170 | if _, err := conn.Exec(ctx, "LISTEN outbox"); err != nil { |
| 171 | return err |
| 172 | } |
| 173 | for { |
| 174 | if _, err := conn.WaitForNotification(ctx); err != nil { |
| 175 | return err |
| 176 | } |
| 177 | select { |
| 178 | case wake <- struct{}{}: |
| 179 | default: // a wake-up is already waiting |
| 180 | } |
| 181 | } |
| 182 | } |