// Package outboxrelay publishes committed transactional outbox events to the // event bus with at-least-once delivery. package outboxrelay import ( "context" "errors" "fmt" "log/slog" "time" "github.com/google/uuid" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/worker/retry" ) // Metrics records relay outcomes and the backlog without per-event labels. type Metrics interface { ObserveOutboxRelayPass(published, failed int) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) } // Settings are the named relay limits; config validates their ranges. type Settings struct { // BatchSize bounds the events one pass locks and publishes. BatchSize int // PollInterval is the wait after a pass that found no pending event. PollInterval time.Duration // Backoff is the wait after a failed pass or a failed Prepare. Backoff retry.Backoff // ShutdownTimeout bounds how long a pass in progress may continue after // Run's context ends. When it expires the pass is canceled and its // transaction rolls back, so nothing it published is marked. ShutdownTimeout time.Duration // BacklogInterval is the least time between two backlog reads for the // metrics, so a busy relay does not count the outbox on every pass. It // also bounds one read. BacklogInterval time.Duration } // Relay moves pending outbox events to the event bus. Several relays may run // against one database: each pass locks its rows with SKIP LOCKED, and only // the earliest unpublished event of an aggregate can be claimed, so one // aggregate's events are published in order. A pass marks only events the // broker acknowledged. An event acknowledged in a pass that does not commit // is published again later with the same event ID; consumers deduplicate. type Relay struct { store outbound.OutboxRelayStore publisher outbound.EventPublisher metrics Metrics logger *slog.Logger settings Settings } func New( store outbound.OutboxRelayStore, publisher outbound.EventPublisher, metrics Metrics, logger *slog.Logger, settings Settings, ) *Relay { return &Relay{store: store, publisher: publisher, metrics: metrics, logger: logger, settings: settings} } // PassResult counts the events of one pass. type PassResult struct { // Claimed events were locked and handed to the publisher. Claimed int // Published events were acknowledged and marked in a committed // transaction. Published int } // PublishPending runs one pass: it locks a batch, publishes it, and marks the // acknowledged events in the same transaction. A nil error means every // claimed event was published. On an error Published counts only events whose // mark committed. func (relay *Relay) PublishPending(ctx context.Context) (PassResult, error) { var ( result PassResult acknowledged int publishErr error ) claimErr := relay.store.ClaimPending(ctx, relay.settings.BatchSize, func(ctx context.Context, events []outbound.OutboxEvent) []uuid.UUID { result.Claimed = len(events) ids, err := relay.publish(ctx, events) acknowledged, publishErr = len(ids), err return ids }) if claimErr != nil { return result, fmt.Errorf("Relay.PublishPending - claim pending events: %w", errors.Join(claimErr, publishErr)) } result.Published = acknowledged if publishErr != nil { return result, fmt.Errorf("Relay.PublishPending - publish events: %w", publishErr) } return result, nil } // publish returns the acknowledged event IDs and, when some events were not // acknowledged, an error with their count and the first cause. The other // causes are dropped to keep one log line per pass. func (relay *Relay) publish(ctx context.Context, events []outbound.OutboxEvent) ([]uuid.UUID, error) { outcomes := relay.publisher.Publish(ctx, events) if len(outcomes) != len(events) { return nil, fmt.Errorf("Relay.publish - publisher returned %d results for %d events", len(outcomes), len(events)) } acknowledged := make([]uuid.UUID, 0, len(events)) var firstErr error for index, err := range outcomes { if err == nil { acknowledged = append(acknowledged, events[index].EventID) continue } // A missing destination wins, so Run sees it and prepares again. if firstErr == nil || (errors.Is(err, outbound.ErrEventDestinationMissing) && !errors.Is(firstErr, outbound.ErrEventDestinationMissing)) { firstErr = err } } if firstErr != nil { return acknowledged, fmt.Errorf("Relay.publish - %d of %d events not acknowledged: %w", len(events)-len(acknowledged), len(events), firstErr) } return acknowledged, nil } // Run prepares the event bus and then publishes pending events until ctx // ends. A pass that published events is followed immediately by the next one, // even when some of its events failed; an empty pass waits PollInterval; a // pass that published nothing and failed waits Backoff, which grows only // across such passes. A pass that reports a missing destination makes Run // call Prepare again first. Failures are logged and retried indefinitely, so // Run returns only after ctx ends and the pass in progress finishes or // ShutdownTimeout cancels it. func (relay *Relay) Run(ctx context.Context) { passCtx, stopPasses := relay.passContext(ctx) defer stopPasses() relay.logger.Info("outbox relay started", slog.Int("batch_size", relay.settings.BatchSize), slog.Duration("poll_interval", relay.settings.PollInterval), ) defer relay.logger.Info("outbox relay stopped") backlog := backlogRefresher{relay: relay} failures := 0 needsPrepare := true for { if needsPrepare { if !relay.prepare(ctx, &backlog) { return } } result, err := relay.PublishPending(passCtx) relay.metrics.ObserveOutboxRelayPass(result.Published, result.Claimed-result.Published) backlog.refresh(ctx) needsPrepare = errors.Is(err, outbound.ErrEventDestinationMissing) var delay time.Duration delay, failures = relay.nextDelay(result, err, failures) if !retry.Wait(ctx, delay) { return } } } // nextDelay returns the wait before the next pass and the new count of // consecutive failed passes that published nothing. func (relay *Relay) nextDelay(result PassResult, err error, failures int) (time.Duration, int) { switch { case err != nil && result.Published > 0: // The pass made progress, so the event bus works; the failed events // are retried at once instead of slowing the others down. relay.logger.Warn("outbox relay pass published part of its batch; the rest stay pending", slog.Int("claimed", result.Claimed), slog.Int("published", result.Published), slog.Any("error", err), ) return 0, 0 case err != nil: failures++ delay := relay.settings.Backoff.Delay(failures) relay.logger.Warn("outbox relay pass failed; unacknowledged events stay pending", slog.Int("claimed", result.Claimed), slog.Int("published", result.Published), slog.Int("consecutive_failures", failures), slog.Duration("retry_in", delay), slog.Any("error", err), ) return delay, failures case result.Claimed > 0: return 0, 0 default: return relay.settings.PollInterval, 0 } } // prepare repeats Prepare with backoff until it succeeds or ctx ends. The // backlog metrics keep refreshing meanwhile, so a growing outbox stays visible. func (relay *Relay) prepare(ctx context.Context, backlog *backlogRefresher) bool { for failures := 1; ; failures++ { err := relay.publisher.Prepare(ctx) if err == nil { return true } backlog.refresh(ctx) delay := relay.settings.Backoff.Delay(failures) relay.logger.Warn("outbox relay could not prepare the event bus; events stay pending", slog.Int("consecutive_failures", failures), slog.Duration("retry_in", delay), slog.Any("error", err), ) if !retry.Wait(ctx, delay) { return false } } } // backlogRefresher reads the outbox backlog for the metrics at most once per // BacklogInterval. type backlogRefresher struct { relay *Relay last time.Time } func (refresher *backlogRefresher) refresh(ctx context.Context) { interval := refresher.relay.settings.BacklogInterval if !refresher.last.IsZero() && time.Since(refresher.last) < interval { return } refresher.last = time.Now() readCtx, cancel := context.WithTimeout(ctx, interval) defer cancel() backlog, err := refresher.relay.store.Backlog(readCtx) if err != nil { // A read interrupted by shutdown is not worth a warning. if ctx.Err() == nil { refresher.relay.logger.Warn("outbox relay could not read the backlog; its metrics are stale", slog.Any("error", err)) } return } refresher.relay.metrics.ObserveOutboxBacklog(backlog) } // passContext returns a context for passes that outlives ctx by at most // ShutdownTimeout, so a pass in progress at shutdown can finish and mark what // the broker acknowledged. stop releases the watcher goroutine. func (relay *Relay) passContext(ctx context.Context) (context.Context, func()) { passCtx, cancel := context.WithCancel(context.WithoutCancel(ctx)) stopWatching := context.AfterFunc(ctx, func() { timer := time.NewTimer(relay.settings.ShutdownTimeout) defer timer.Stop() select { case <-timer.C: cancel() case <-passCtx.Done(): } }) return passCtx, func() { stopWatching() cancel() } }