// Package eventconsumer runs idempotent handlers of domain events from the // event bus with at-least-once delivery. package eventconsumer import ( "context" "crypto/sha256" "errors" "fmt" "log/slog" "regexp" "runtime/debug" "strings" "time" "unicode" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/worker/retry" ) // Record outcome label values. A record ends with exactly one of them. const ( // OutcomeApplied: the handler's effect and the marker committed. OutcomeApplied = "applied" // OutcomeDuplicate: the marker existed, so the effect was skipped. OutcomeDuplicate = "duplicate" // OutcomeIgnored: the handler does not handle the event type. OutcomeIgnored = "ignored" // OutcomeDeadLettered: the record was stored as a dead letter. OutcomeDeadLettered = "dead_lettered" ) // Failure stage label values. Every failed operation is counted, including // the last handler attempt before a dead letter. const ( // StageHandler: the handler returned an error, panicked, or timed out, // or PostgreSQL refused to commit its effect. StageHandler = "handler" // StageStore: the transaction, the marker, the commit transport, or the // dead letter write failed outside the handler. StageStore = "store" // StagePoll: a poll of the event bus failed. StagePoll = "poll" // StageCommit: an offset commit failed. StageCommit = "commit" ) // maxReasonLength bounds the stored and logged failure reason. const maxReasonLength = 256 // consumerNamePattern matches the database constraint on consumer names. var consumerNamePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) // errHandlerPanic replaces the value of a handler panic, which could quote // the event. var errHandlerPanic = errors.New("handler panicked") // Metrics records consumer outcomes. Labels are the consumer name, which the // code defines, and the constants of this package. type Metrics interface { // PrepareEventConsumer exposes the consumer's series at zero, so rate // and increase queries see the first event. PrepareEventConsumer(consumer string) ObserveConsumedRecord(consumer, outcome string) ObserveConsumerFailure(consumer, stage string) } // Settings are the named consumer limits; config validates their ranges. type Settings struct { // MaxAttempts bounds the handler attempts for one event before it is // dead-lettered. A commit that PostgreSQL refuses counts as an attempt; // a database that cannot be reached does not. MaxAttempts int // Backoff is the wait after a failed attempt. Backoff retry.Backoff // HandlerTimeout bounds one attempt: the transaction with the marker, // the handler, and the commit, or one dead letter write. HandlerTimeout time.Duration // CommitTimeout bounds one offset commit. CommitTimeout time.Duration // ShutdownGrace is how long an attempt in progress may continue after // Run's context ends. When it expires the attempt is canceled, its // transaction rolls back, and its offset is not committed. ShutdownGrace time.Duration } // Consumer delivers the records of one consumer group to one handler. // Records are processed one at a time in poll order, which keeps the order // within each partition. An offset is committed only after the record's // transaction committed or its dead letter was stored, so a crash at any // point delivers the record again and the marker turns the repeat into a // duplicate. type Consumer struct { name string handler inbound.EventHandler source outbound.EventSource store outbound.EventConsumerStore metrics Metrics logger *slog.Logger settings Settings } // New checks the handler's consumer name and the settings. The name scopes // the dedup markers in the database, so an invalid one is a startup error. func New( handler inbound.EventHandler, source outbound.EventSource, store outbound.EventConsumerStore, metrics Metrics, logger *slog.Logger, settings Settings, ) (*Consumer, error) { name := handler.ConsumerName() if !consumerNamePattern.MatchString(name) { return nil, errors.New("eventconsumer.New - consumer name must be 1 to 64 lowercase letters, digits, or underscores starting with a letter") } if settings.MaxAttempts < 1 || settings.HandlerTimeout <= 0 || settings.CommitTimeout <= 0 || settings.ShutdownGrace <= 0 { return nil, fmt.Errorf("eventconsumer.New - consumer %s needs positive attempts and timeouts", name) } metrics.PrepareEventConsumer(name) return &Consumer{ name: name, handler: handler, source: source, store: store, metrics: metrics, logger: logger.With(slog.String("consumer", name)), settings: settings, }, nil } // Name returns the consumer name. func (consumer *Consumer) Name() string { return consumer.name } // Run polls and processes records until ctx ends. Failures are logged and // retried, so Run returns only after ctx ends and the record in progress // finished or ShutdownGrace canceled it. Records that were polled but not // finished are not committed; the group delivers them again. func (consumer *Consumer) Run(ctx context.Context) { workCtx, stopWork := consumer.workContext(ctx) defer stopWork() consumer.logger.Info("event consumer started") defer consumer.logger.Info("event consumer stopped") pollFailures := 0 for ctx.Err() == nil { records, err := consumer.source.Poll(ctx) if ctx.Err() != nil { // Records polled while stopping are not started. consumer.source.Release() return } if err != nil { consumer.metrics.ObserveConsumerFailure(consumer.name, StagePoll) } finished := consumer.processBatch(ctx, workCtx, records) consumer.commit(ctx, finished) consumer.source.Release() if err == nil || len(records) > 0 { pollFailures = 0 if err != nil { consumer.logger.Warn("event consumer poll reported errors", slog.Any("error", err)) } continue } pollFailures++ delay := consumer.settings.Backoff.Delay(pollFailures) consumer.logger.Warn("event consumer poll failed", slog.Int("consecutive_failures", pollFailures), slog.Duration("retry_in", delay), slog.Any("error", err), ) if !retry.Wait(ctx, delay) { return } } } // processBatch processes records in order and returns the finished prefix. // It stops at the first record that shutdown abandoned. After a record that // needed a retry or a dead letter it commits the prefix at once: a slow // batch is the one most likely to outlast the rebalance timeout, and the // member that takes over then does not repeat finished work. func (consumer *Consumer) processBatch(ctx, workCtx context.Context, records []outbound.ConsumedRecord) []outbound.ConsumedRecord { for index, record := range records { if ctx.Err() != nil { return records[:index] } finished, slow := consumer.process(ctx, workCtx, record) if !finished { return records[:index] } if slow && index < len(records)-1 { consumer.commit(ctx, records[:index+1]) } } return records } func (consumer *Consumer) commit(ctx context.Context, finished []outbound.ConsumedRecord) { if len(finished) == 0 { return } // The commit runs after shutdown began too: finished work must be // stored so the next member does not repeat it. commitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), consumer.settings.CommitTimeout) defer cancel() if err := consumer.source.Commit(commitCtx, finished); err != nil { consumer.metrics.ObserveConsumerFailure(consumer.name, StageCommit) consumer.logger.Warn("event consumer could not commit offsets; the records will be delivered again and deduplicated", slog.Int("records", len(finished)), slog.Any("error", err), ) } } // process handles one record. finished reports that it was applied, a // duplicate, ignored, or dead-lettered; it is false only when ctx ended // first. slow reports that the record needed a retry or a dead letter. func (consumer *Consumer) process(ctx, workCtx context.Context, record outbound.ConsumedRecord) (finished, slow bool) { if record.Invalid != nil { return consumer.deadLetter(ctx, workCtx, record, outbound.DeadLetterInvalidRecord, record.Invalid, 0), true } handles, err := consumer.handles(record.Event) if err != nil { consumer.metrics.ObserveConsumerFailure(consumer.name, StageHandler) return consumer.deadLetter(ctx, workCtx, record, outbound.DeadLetterHandlerPanic, err, 0), true } if !handles { consumer.metrics.ObserveConsumedRecord(consumer.name, OutcomeIgnored) return true, false } return consumer.apply(ctx, workCtx, record) } // apply runs attempts until the event is applied or a duplicate, its handler // failures end in a dead letter, or ctx ends. func (consumer *Consumer) apply(ctx, workCtx context.Context, record outbound.ConsumedRecord) (finished, slow bool) { handlerFailures, storeFailures := 0, 0 for { applied, handlerErr, storeErr := consumer.attempt(workCtx, record.Event) if handlerErr == nil && storeErr == nil { outcome := OutcomeDuplicate if applied { outcome = OutcomeApplied } consumer.metrics.ObserveConsumedRecord(consumer.name, outcome) consumer.logger.Debug("event consumed", recordAttributes(record, slog.String("outcome", outcome))...) return true, handlerFailures+storeFailures > 0 } // A failure while stopping may be the shutdown itself, so it is // neither retried nor dead-lettered; the record is delivered again. if ctx.Err() != nil { return false, true } var delay time.Duration if handlerErr != nil { consumer.metrics.ObserveConsumerFailure(consumer.name, StageHandler) handlerFailures++ if class, final := finalHandlerFailure(handlerErr, handlerFailures, consumer.settings.MaxAttempts); final { return consumer.deadLetter(ctx, workCtx, record, class, handlerErr, handlerFailures), true } delay = consumer.settings.Backoff.Delay(handlerFailures) consumer.logger.Warn("event handler failed; retrying", recordAttributes(record, slog.Int("attempt", handlerFailures), slog.Int("max_attempts", consumer.settings.MaxAttempts), slog.Duration("retry_in", delay), slog.String("reason", sanitizeReason(handlerErr)), )..., ) } else { consumer.metrics.ObserveConsumerFailure(consumer.name, StageStore) storeFailures++ delay = consumer.settings.Backoff.Delay(storeFailures) consumer.logger.Warn("event consumer could not use the database; retrying", recordAttributes(record, slog.Int("consecutive_failures", storeFailures), slog.Duration("retry_in", delay), slog.String("error", sanitizeReason(storeErr)), )..., ) } if !retry.Wait(ctx, delay) { return false, true } } } // finalHandlerFailure reports whether a handler failure ends the retries // and with which dead letter class. func finalHandlerFailure(err error, failures, maxAttempts int) (outbound.DeadLetterClass, bool) { switch { case errors.Is(err, errHandlerPanic): return outbound.DeadLetterHandlerPanic, true case errors.Is(err, inbound.ErrEventRejected): return outbound.DeadLetterHandlerRejected, true case failures >= maxAttempts: return outbound.DeadLetterRetriesExhausted, true default: return "", false } } // attempt runs one transaction. handlerErr is a failure the event causes: // the handler's own error, as the store returns it with PostgreSQL text // removed, or a commit PostgreSQL refused or aborted as a serialization // failure or deadlock. Those use up an attempt, so a handler that ignores a // failed statement ends in a dead letter instead of retrying forever. // storeErr is any other failure outside the handler, such as a lost // connection; it does not use up attempts because the event is not at fault. func (consumer *Consumer) attempt(workCtx context.Context, event outbound.ConsumedEvent) (applied bool, handlerErr, storeErr error) { ctx, cancel := context.WithTimeout(workCtx, consumer.settings.HandlerTimeout) defer cancel() handlerFailed := false applied, err := consumer.store.ApplyOnce(ctx, consumer.name, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { err := consumer.callHandler(ctx, unit, event) handlerFailed = err != nil return err }) switch { case err == nil: return applied, nil, nil case handlerFailed, errors.Is(err, outbound.ErrEventEffectRejected), errors.Is(err, outbound.ErrTransactionConflict): return false, err, nil default: return false, nil, err } } // handles asks the handler whether it applies eventType. A panic there is // treated like a panic in Handle. func (consumer *Consumer) handles(event outbound.ConsumedEvent) (handles bool, err error) { defer func() { if recovered := recover(); recovered != nil { consumer.logPanic(event) handles, err = false, errHandlerPanic } }() return consumer.handler.Handles(event.EventType), nil } // callHandler turns a panic into a final failure, so one event cannot crash // the process again on every delivery. The stack is logged; the panic value // is not, because it could quote the event. func (consumer *Consumer) callHandler(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) (err error) { defer func() { if recovered := recover(); recovered != nil { consumer.logPanic(event) err = errHandlerPanic } }() return consumer.handler.Handle(ctx, unit, event) } func (consumer *Consumer) logPanic(event outbound.ConsumedEvent) { consumer.logger.Error("event handler panicked", slog.String("event_id", event.EventID.String()), slog.String("event_type", event.EventType), slog.String("stack", string(debug.Stack())), ) } // deadLetter stores the record as a dead letter, retrying the write with // backoff until it succeeds, and reports false only when ctx ended first. // The offset is committed only after the row exists, so a database outage // never loses a record. func (consumer *Consumer) deadLetter( ctx, workCtx context.Context, record outbound.ConsumedRecord, class outbound.DeadLetterClass, cause error, attempts int, ) bool { letter := outbound.DeadLetter{ Consumer: consumer.name, Topic: record.Topic, Partition: record.Partition, Offset: record.Offset, EventID: record.EventID, ErrorClass: class, Reason: sanitizeReason(cause), Attempts: attempts, ValueSize: len(record.Value), ValueSHA256: sha256.Sum256(record.Value), } if record.Invalid == nil { letter.EventType = record.Event.EventType } for failures := 1; ; failures++ { err := consumer.writeDeadLetter(workCtx, letter) if err == nil { consumer.metrics.ObserveConsumedRecord(consumer.name, OutcomeDeadLettered) consumer.logger.Error("event dead-lettered; the offset is committed and the record needs an operator", recordAttributes(record, slog.String("error_class", string(class)), slog.Int("attempts", attempts), slog.String("reason", letter.Reason), )..., ) return true } if ctx.Err() != nil { return false } consumer.metrics.ObserveConsumerFailure(consumer.name, StageStore) delay := consumer.settings.Backoff.Delay(failures) consumer.logger.Warn("event consumer could not store a dead letter; the offset stays uncommitted", recordAttributes(record, slog.Int("consecutive_failures", failures), slog.Duration("retry_in", delay), slog.Any("error", err), )..., ) if !retry.Wait(ctx, delay) { return false } } } func (consumer *Consumer) writeDeadLetter(workCtx context.Context, letter outbound.DeadLetter) error { ctx, cancel := context.WithTimeout(workCtx, consumer.settings.HandlerTimeout) defer cancel() return consumer.store.RecordDeadLetter(ctx, letter) } // workContext returns a context for attempts that outlives ctx by at most // ShutdownGrace, so an attempt in progress at shutdown can commit. stop // releases the watcher goroutine. func (consumer *Consumer) workContext(ctx context.Context) (context.Context, func()) { workCtx, cancel := context.WithCancel(context.WithoutCancel(ctx)) stopWatching := context.AfterFunc(ctx, func() { timer := time.NewTimer(consumer.settings.ShutdownGrace) defer timer.Stop() select { case <-timer.C: cancel() case <-workCtx.Done(): } }) return workCtx, func() { stopWatching() cancel() } } // recordAttributes identifies a record in logs without its value. func recordAttributes(record outbound.ConsumedRecord, extra ...any) []any { attributes := []any{ slog.String("topic", record.Topic), slog.Int("partition", int(record.Partition)), slog.Int64("offset", record.Offset), slog.String("event_id", record.EventID.String()), } if record.Invalid == nil { attributes = append(attributes, slog.String("event_type", record.Event.EventType)) } return append(attributes, extra...) } // sanitizeReason keeps a short single-line cause. Handler errors must not // carry personal data already; this also bounds what a mistake can expose. func sanitizeReason(err error) string { reason := strings.Map(func(character rune) rune { if unicode.IsControl(character) || !unicode.IsPrint(character) { return ' ' } return character }, err.Error()) reason = strings.TrimSpace(reason) if runes := []rune(reason); len(runes) > maxReasonLength { reason = string(runes[:maxReasonLength]) } if reason == "" { return "unspecified failure" } return reason }