feat(events): add idempotent Kafka event consumer runtime

This commit is contained in:
shira committed 2026-10-06 03:59:57 +03:00
1 parent 565ef8d4f5
commit 3adb0ef9e4
47 files changed
+5018 -105

No files matched your search

@@ -0,0 +1,481 @@
// 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
}
@@ -0,0 +1,788 @@
package eventconsumer
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"log/slog"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/retry"
)
const (
testTimeout = 5 * time.Second
testInterval = time.Millisecond
testConsumer = "test_consumer"
testTopic = "events"
handledType = "test.changed"
unhandledType = "test.other"
// testGrace is short so shutdown tests finish quickly, and far above
// the time a finished attempt needs.
testGrace = 200 * time.Millisecond
)
var (
errTransient = errors.New("transient handler failure")
errDatabase = errors.New("database unavailable")
)
// fakeSource returns its batches in order, one per poll, and then blocks
// until ctx ends. It records commits and checks that every poll is released.
type fakeSource struct {
mu sync.Mutex
batches [][]outbound.ConsumedRecord
commits [][]outbound.ConsumedRecord
polls int
releases int
pollErr error
commitErr error
drained chan struct{}
}
func newFakeSource(batches ...[]outbound.ConsumedRecord) *fakeSource {
return &fakeSource{batches: batches, drained: make(chan struct{})}
}
func (source *fakeSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) {
source.mu.Lock()
source.polls++
if source.pollErr != nil {
err := source.pollErr
source.mu.Unlock()
return nil, err
}
if len(source.batches) > 0 {
batch := source.batches[0]
source.batches = source.batches[1:]
source.mu.Unlock()
return batch, nil
}
source.mu.Unlock()
select {
case <-source.drained:
default:
close(source.drained)
}
<-ctx.Done()
return nil, ctx.Err()
}
func (source *fakeSource) Commit(_ context.Context, finished []outbound.ConsumedRecord) error {
source.mu.Lock()
defer source.mu.Unlock()
if source.commitErr != nil {
return source.commitErr
}
source.commits = append(source.commits, finished)
return nil
}
func (source *fakeSource) Release() {
source.mu.Lock()
source.releases++
source.mu.Unlock()
}
// committedOffsets returns every committed offset once, in the order of its
// first commit. A commit always repeats the prefix of its batch.
func (source *fakeSource) committedOffsets() []int64 {
source.mu.Lock()
defer source.mu.Unlock()
var offsets []int64
seen := make(map[int64]bool)
for _, commit := range source.commits {
for _, record := range commit {
if !seen[record.Offset] {
seen[record.Offset] = true
offsets = append(offsets, record.Offset)
}
}
}
return offsets
}
func (source *fakeSource) commitCount() int {
source.mu.Lock()
defer source.mu.Unlock()
return len(source.commits)
}
// fakeStore models the dedup transaction: apply runs only for a new marker,
// and the marker is kept only when apply succeeds and ctx is still live at
// commit time.
type fakeStore struct {
mu sync.Mutex
markers map[uuid.UUID]bool
deadLetters []outbound.DeadLetter
// applyFailures and letterFailures fail that many calls before the
// store reaches the handler or stores the letter.
applyFailures int
letterFailures int
applyCalls int
// commitErrors are returned, one per call, after apply returned nil, as
// a commit that PostgreSQL refused.
commitErrors []error
}
func newFakeStore() *fakeStore {
return &fakeStore{markers: make(map[uuid.UUID]bool)}
}
func (store *fakeStore) ApplyOnce(ctx context.Context, consumer string, eventID uuid.UUID, apply outbound.ApplyEvent) (bool, error) {
store.mu.Lock()
store.applyCalls++
if consumer != testConsumer {
store.mu.Unlock()
return false, fmt.Errorf("unexpected consumer %q", consumer)
}
if store.applyFailures > 0 {
store.applyFailures--
store.mu.Unlock()
return false, errDatabase
}
if store.markers[eventID] {
store.mu.Unlock()
return false, nil
}
store.mu.Unlock()
if err := apply(ctx, nil); err != nil {
return false, err
}
if err := ctx.Err(); err != nil {
return false, err
}
store.mu.Lock()
if len(store.commitErrors) > 0 {
err := store.commitErrors[0]
store.commitErrors = store.commitErrors[1:]
store.mu.Unlock()
return false, err
}
store.mu.Unlock()
store.mu.Lock()
store.markers[eventID] = true
store.mu.Unlock()
return true, nil
}
func (store *fakeStore) RecordDeadLetter(ctx context.Context, letter outbound.DeadLetter) error {
store.mu.Lock()
defer store.mu.Unlock()
if store.letterFailures > 0 {
store.letterFailures--
return errDatabase
}
if err := ctx.Err(); err != nil {
return err
}
store.deadLetters = append(store.deadLetters, letter)
return nil
}
func (store *fakeStore) letters() []outbound.DeadLetter {
store.mu.Lock()
defer store.mu.Unlock()
return append([]outbound.DeadLetter(nil), store.deadLetters...)
}
// fakeHandler applies handledType events through handle, which defaults to
// success, and records every call.
type fakeHandler struct {
mu sync.Mutex
calls []time.Time
events []uuid.UUID
handle func(ctx context.Context, event outbound.ConsumedEvent, call int) error
}
func (*fakeHandler) ConsumerName() string { return testConsumer }
func (*fakeHandler) Handles(eventType string) bool { return eventType == handledType }
func (handler *fakeHandler) Handle(ctx context.Context, _ outbound.UnitOfWork, event outbound.ConsumedEvent) error {
handler.mu.Lock()
handler.calls = append(handler.calls, time.Now())
handler.events = append(handler.events, event.EventID)
call := len(handler.calls)
handle := handler.handle
handler.mu.Unlock()
if handle == nil {
return nil
}
return handle(ctx, event, call)
}
func (handler *fakeHandler) callTimes() []time.Time {
handler.mu.Lock()
defer handler.mu.Unlock()
return append([]time.Time(nil), handler.calls...)
}
type fakeMetrics struct {
mu sync.Mutex
prepared []string
outcomes map[string]int
failures map[string]int
}
func newFakeMetrics() *fakeMetrics {
return &fakeMetrics{outcomes: make(map[string]int), failures: make(map[string]int)}
}
func (metrics *fakeMetrics) PrepareEventConsumer(consumer string) {
metrics.mu.Lock()
defer metrics.mu.Unlock()
metrics.prepared = append(metrics.prepared, consumer)
}
func (metrics *fakeMetrics) ObserveConsumedRecord(_, outcome string) {
metrics.mu.Lock()
defer metrics.mu.Unlock()
metrics.outcomes[outcome]++
}
func (metrics *fakeMetrics) ObserveConsumerFailure(_, stage string) {
metrics.mu.Lock()
defer metrics.mu.Unlock()
metrics.failures[stage]++
}
func (metrics *fakeMetrics) outcome(name string) int {
metrics.mu.Lock()
defer metrics.mu.Unlock()
return metrics.outcomes[name]
}
func (metrics *fakeMetrics) failure(stage string) int {
metrics.mu.Lock()
defer metrics.mu.Unlock()
return metrics.failures[stage]
}
type harness struct {
source *fakeSource
store *fakeStore
handler *fakeHandler
metrics *fakeMetrics
consumer *Consumer
}
func testSettings() Settings {
return Settings{
MaxAttempts: 3,
Backoff: retry.Backoff{Initial: testInterval, Max: testInterval},
HandlerTimeout: testTimeout,
CommitTimeout: testTimeout,
ShutdownGrace: testGrace,
}
}
func newHarness(t *testing.T, settings Settings, batches ...[]outbound.ConsumedRecord) *harness {
t.Helper()
h := &harness{
source: newFakeSource(batches...),
store: newFakeStore(),
handler: &fakeHandler{},
metrics: newFakeMetrics(),
}
consumer, err := New(h.handler, h.source, h.store, h.metrics, slog.New(slog.DiscardHandler), settings)
if err != nil {
t.Fatalf("New() error = %v", err)
}
h.consumer = consumer
return h
}
// run starts the consumer and returns a function that cancels it and waits
// until Run returned.
func (h *harness) run(t *testing.T) (stop func()) {
t.Helper()
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
go func() {
defer close(done)
h.consumer.Run(ctx)
}()
stopped := false
stop = func() {
t.Helper()
if stopped {
return
}
stopped = true
cancel()
select {
case <-done:
case <-time.After(testTimeout):
t.Fatal("Run() did not return after cancellation")
}
}
t.Cleanup(stop)
return stop
}
// runUntilDrained runs the consumer until the source has no batch left, then
// stops it.
func (h *harness) runUntilDrained(t *testing.T) {
t.Helper()
stop := h.run(t)
select {
case <-h.source.drained:
case <-time.After(testTimeout):
t.Fatal("the consumer did not poll every batch")
}
stop()
}
func event(offset int64, eventType string) outbound.ConsumedRecord {
eventID := uuid.New()
return outbound.ConsumedRecord{
Topic: testTopic,
Partition: 0,
Offset: offset,
EventID: eventID,
Value: []byte(fmt.Sprintf(`{"event_id":%q}`, eventID)),
Event: outbound.ConsumedEvent{
EventID: eventID,
EventType: eventType,
SchemaVersion: 1,
AggregateType: "test",
AggregateID: uuid.New(),
AggregateVersion: 1,
OccurredAt: time.Now(),
Payload: []byte(`{}`),
},
}
}
func assertOffsets(t *testing.T, got []int64, want ...int64) {
t.Helper()
if fmt.Sprint(got) != fmt.Sprint(want) {
t.Fatalf("committed offsets = %v, want %v", got, want)
}
}
func TestNewRejectsInvalidNamesAndSettings(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
for _, name := range []string{"", "Upper", "1st", "with-dash", strings.Repeat("a", 65)} {
_, err := New(namedHandler(name), newFakeSource(), newFakeStore(), newFakeMetrics(), logger, testSettings())
if err == nil {
t.Fatalf("New() accepted consumer name %q", name)
}
}
settings := testSettings()
settings.MaxAttempts = 0
if _, err := New(&fakeHandler{}, newFakeSource(), newFakeStore(), newFakeMetrics(), logger, settings); err == nil {
t.Fatal("New() accepted zero attempts")
}
}
type namedHandler string
func (handler namedHandler) ConsumerName() string { return string(handler) }
func (namedHandler) Handles(string) bool { return true }
func (namedHandler) Handle(context.Context, outbound.UnitOfWork, outbound.ConsumedEvent) error {
return nil
}
func TestConsumerAppliesSkipsDuplicatesAndCommitsInOrder(t *testing.T) {
first := event(10, handledType)
duplicate := event(11, handledType)
duplicate.EventID, duplicate.Event.EventID = first.EventID, first.EventID
ignored := event(12, unhandledType)
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{first, duplicate, ignored})
h.runUntilDrained(t)
assertOffsets(t, h.source.committedOffsets(), 10, 11, 12)
if got := len(h.handler.callTimes()); got != 1 {
t.Fatalf("handler ran %d times, want once", got)
}
for outcome, want := range map[string]int{OutcomeApplied: 1, OutcomeDuplicate: 1, OutcomeIgnored: 1, OutcomeDeadLettered: 0} {
if got := h.metrics.outcome(outcome); got != want {
t.Fatalf("outcome %s = %d, want %d", outcome, got, want)
}
}
if h.source.releases != h.source.polls {
t.Fatalf("released %d of %d polls", h.source.releases, h.source.polls)
}
if len(h.metrics.prepared) != 1 || h.metrics.prepared[0] != testConsumer {
t.Fatalf("prepared metrics for %v, want the consumer", h.metrics.prepared)
}
}
func TestConsumerRetriesStoreFailuresWithoutUsingAttemptsAndCommitsAfterSuccess(t *testing.T) {
record := event(0, handledType)
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{record})
// More failures than MaxAttempts: a database outage must not dead-letter
// a valid event.
h.store.applyFailures = 5
h.runUntilDrained(t)
assertOffsets(t, h.source.committedOffsets(), 0)
if got := h.metrics.failure(StageStore); got != 5 {
t.Fatalf("store failures = %d, want 5", got)
}
if got := h.metrics.outcome(OutcomeApplied); got != 1 {
t.Fatalf("applied = %d, want 1", got)
}
if letters := h.store.letters(); len(letters) != 0 {
t.Fatalf("a store outage produced %d dead letters", len(letters))
}
}
func TestConsumerDeadLettersAfterBoundedRetriesWithBackoff(t *testing.T) {
poison := event(0, handledType)
next := event(1, handledType)
settings := testSettings()
settings.MaxAttempts = 4
backoffFloor := 10 * time.Millisecond
// Initial equals Max, so every wait is between half the value and the
// value: at least backoffFloor.
settings.Backoff = retry.Backoff{Initial: 2 * backoffFloor, Max: 2 * backoffFloor}
h := newHarness(t, settings, []outbound.ConsumedRecord{poison, next})
var commitsBeforeNext int
h.handler.handle = func(_ context.Context, event outbound.ConsumedEvent, _ int) error {
if event.EventID == poison.EventID {
return fmt.Errorf("handler: %w", errTransient)
}
commitsBeforeNext = h.source.commitCount()
return nil
}
h.runUntilDrained(t)
calls := h.handler.callTimes()
// Four attempts for the poison event and one for the next event.
if len(calls) != settings.MaxAttempts+1 {
t.Fatalf("handler ran %d times, want %d", len(calls), settings.MaxAttempts+1)
}
for index := 1; index < settings.MaxAttempts; index++ {
if gap := calls[index].Sub(calls[index-1]); gap < backoffFloor {
t.Fatalf("attempt %d followed the previous one after %s, want at least %s", index+1, gap, backoffFloor)
}
}
letters := h.store.letters()
if len(letters) != 1 {
t.Fatalf("dead letters = %d, want 1", len(letters))
}
letter := letters[0]
if letter.ErrorClass != outbound.DeadLetterRetriesExhausted || letter.Attempts != settings.MaxAttempts ||
letter.EventID != poison.EventID || letter.EventType != handledType || letter.Offset != 0 ||
letter.Topic != testTopic || letter.ValueSize != len(poison.Value) || letter.ValueSHA256 != sha256.Sum256(poison.Value) ||
!strings.Contains(letter.Reason, errTransient.Error()) {
t.Fatalf("unexpected dead letter %+v", letter)
}
// The partition moves on: the next event is applied, and both offsets
// are committed after the dead letter was stored. The dead letter's
// offset is committed before the next record starts, so a member that
// takes over after a rebalance timeout does not repeat the retries.
assertOffsets(t, h.source.committedOffsets(), 0, 1)
if commitsBeforeNext != 1 {
t.Fatalf("commits before the next record = %d, want the prefix commit after the dead letter", commitsBeforeNext)
}
if got := h.metrics.failure(StageHandler); got != settings.MaxAttempts {
t.Fatalf("handler failures = %d, want %d", got, settings.MaxAttempts)
}
if h.metrics.outcome(OutcomeDeadLettered) != 1 || h.metrics.outcome(OutcomeApplied) != 1 {
t.Fatalf("outcomes = %v", h.metrics.outcomes)
}
}
func TestConsumerDeadLettersFinalFailuresAtOnce(t *testing.T) {
tests := []struct {
name string
handle func(context.Context, outbound.ConsumedEvent, int) error
class outbound.DeadLetterClass
}{
{
name: "rejected",
handle: func(context.Context, outbound.ConsumedEvent, int) error {
return fmt.Errorf("unsupported schema version: %w", inbound.ErrEventRejected)
},
class: outbound.DeadLetterHandlerRejected,
},
{
name: "panic",
handle: func(context.Context, outbound.ConsumedEvent, int) error {
panic("payload secret")
},
class: outbound.DeadLetterHandlerPanic,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)})
h.handler.handle = test.handle
h.runUntilDrained(t)
if got := len(h.handler.callTimes()); got != 1 {
t.Fatalf("handler ran %d times, want once", got)
}
letters := h.store.letters()
if len(letters) != 1 || letters[0].ErrorClass != test.class || letters[0].Attempts != 1 {
t.Fatalf("dead letters = %+v, want one %s", letters, test.class)
}
if strings.Contains(letters[0].Reason, "secret") {
t.Fatalf("dead letter reason %q quotes the panic value", letters[0].Reason)
}
assertOffsets(t, h.source.committedOffsets(), 0)
})
}
}
func TestConsumerDeadLettersInvalidRecordsWithoutTheHandler(t *testing.T) {
invalid := outbound.ConsumedRecord{
Topic: testTopic,
Partition: 2,
Offset: 7,
EventID: uuid.New(),
Value: []byte("not json \x00 with\nnewline"),
Invalid: fmt.Errorf("value is not a JSON event envelope\nsecond line: %w", outbound.ErrInvalidEventRecord),
}
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{invalid})
// The first write of the dead letter fails; the offset must wait for it.
h.store.letterFailures = 2
h.runUntilDrained(t)
if got := len(h.handler.callTimes()); got != 0 {
t.Fatalf("handler ran %d times for an invalid record", got)
}
letters := h.store.letters()
if len(letters) != 1 {
t.Fatalf("dead letters = %d, want 1", len(letters))
}
letter := letters[0]
if letter.ErrorClass != outbound.DeadLetterInvalidRecord || letter.Attempts != 0 || letter.EventType != "" ||
letter.EventID != invalid.EventID || letter.Partition != 2 || letter.Offset != 7 || strings.ContainsAny(letter.Reason, "\n\x00") {
t.Fatalf("unexpected dead letter %+v", letter)
}
assertOffsets(t, h.source.committedOffsets(), 7)
if got := h.metrics.failure(StageStore); got != 2 {
t.Fatalf("store failures = %d, want 2", got)
}
}
func TestConsumerShutdownAbandonsUnfinishedRecordsWithoutCommitting(t *testing.T) {
blocked := event(0, handledType)
later := event(1, handledType)
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{blocked, later})
started := make(chan struct{})
h.handler.handle = func(ctx context.Context, _ outbound.ConsumedEvent, _ int) error {
close(started)
// The effect is written but the handler outlives the grace, as a
// stuck dependency would; the transaction must roll back.
<-ctx.Done()
return ctx.Err()
}
stop := h.run(t)
<-started
stopping := time.Now()
stop()
if elapsed := time.Since(stopping); elapsed < testGrace || elapsed > testGrace+time.Second {
t.Fatalf("Run() returned %s after cancellation, want about the %s grace", elapsed, testGrace)
}
assertOffsets(t, h.source.committedOffsets())
if got := len(h.handler.callTimes()); got != 1 {
t.Fatalf("handler ran %d times, want only the abandoned record", got)
}
if letters := h.store.letters(); len(letters) != 0 {
t.Fatalf("shutdown produced dead letters: %+v", letters)
}
if h.source.releases != h.source.polls {
t.Fatalf("released %d of %d polls", h.source.releases, h.source.polls)
}
}
func TestConsumerShutdownLetsTheRecordInProgressFinishWithinTheGrace(t *testing.T) {
inProgress := event(0, handledType)
notStarted := event(1, handledType)
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{inProgress, notStarted})
started := make(chan struct{})
release := make(chan struct{})
h.handler.handle = func(_ context.Context, event outbound.ConsumedEvent, _ int) error {
if event.EventID == inProgress.EventID {
close(started)
<-release
}
return nil
}
stop := h.run(t)
<-started
go func() {
time.Sleep(testGrace / 4)
close(release)
}()
stop()
// The finished record is committed; the next one was never started.
assertOffsets(t, h.source.committedOffsets(), 0)
if got := len(h.handler.callTimes()); got != 1 {
t.Fatalf("handler ran %d times, want once", got)
}
}
func TestConsumerDoesNotRetryDuringShutdown(t *testing.T) {
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)})
settings := testSettings()
settings.Backoff = retry.Backoff{Initial: time.Hour, Max: time.Hour}
h.consumer.settings = settings
failed := make(chan struct{})
h.handler.handle = func(context.Context, outbound.ConsumedEvent, int) error {
close(failed)
return errTransient
}
stop := h.run(t)
<-failed
stopping := time.Now()
stop()
if elapsed := time.Since(stopping); elapsed > time.Second {
t.Fatalf("Run() waited %s for a backoff after cancellation", elapsed)
}
assertOffsets(t, h.source.committedOffsets())
if letters := h.store.letters(); len(letters) != 0 {
t.Fatalf("shutdown dead-lettered a retryable failure: %+v", letters)
}
}
func TestConsumerBacksOffWhenPollFails(t *testing.T) {
h := newHarness(t, testSettings())
h.source.pollErr = errors.New("broker unavailable")
settings := testSettings()
settings.Backoff = retry.Backoff{Initial: 20 * time.Millisecond, Max: 20 * time.Millisecond}
h.consumer.settings = settings
stop := h.run(t)
time.Sleep(200 * time.Millisecond)
stop()
h.source.mu.Lock()
polls := h.source.polls
h.source.mu.Unlock()
// Each failed poll waits at least 10ms, so 200ms allow about 20 polls; a
// hot loop would make thousands.
if polls < 2 || polls > 25 {
t.Fatalf("polls = %d in 200ms, want a few with backoff", polls)
}
}
func TestConsumerKeepsFinishedRecordsWhenTheCommitFails(t *testing.T) {
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)})
h.source.commitErr = errors.New("rebalance in progress")
h.runUntilDrained(t)
// The failed commit is only logged; the record is applied once and its
// redelivery would be a duplicate.
if got := h.metrics.outcome(OutcomeApplied); got != 1 {
t.Fatalf("applied = %d, want 1", got)
}
}
func TestSanitizeReasonBoundsAndFlattensTheCause(t *testing.T) {
long := strings.Repeat("é", maxReasonLength+10)
if got := []rune(sanitizeReason(errors.New(long))); len(got) != maxReasonLength {
t.Fatalf("reason has %d characters, want %d", len(got), maxReasonLength)
}
if got := sanitizeReason(errors.New("a\nb\tc\x00")); got != "a b c" {
t.Fatalf("sanitizeReason() = %q, want %q", got, "a b c")
}
if got := sanitizeReason(errors.New("\t\x00 ")); got != "unspecified failure" {
t.Fatalf("sanitizeReason() = %q for a blank cause", got)
}
}
func TestConsumerSpendsAttemptsOnCommitsThePostgreSQLRefuses(t *testing.T) {
// The handler swallowed a failed statement and returned nil, so every
// commit is refused. Without counting attempts this would retry forever.
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)})
refused := fmt.Errorf("commit: %w", outbound.ErrEventEffectRejected)
h.store.commitErrors = []error{refused, refused, refused}
h.runUntilDrained(t)
letters := h.store.letters()
if len(letters) != 1 || letters[0].ErrorClass != outbound.DeadLetterRetriesExhausted || letters[0].Attempts != 3 {
t.Fatalf("dead letters = %+v, want one retries_exhausted after 3 attempts", letters)
}
if got := len(h.handler.callTimes()); got != 3 {
t.Fatalf("handler ran %d times, want 3", got)
}
if got := h.metrics.failure(StageHandler); got != 3 {
t.Fatalf("handler failures = %d, want 3", got)
}
if got := h.metrics.failure(StageStore); got != 0 {
t.Fatalf("store failures = %d, want 0", got)
}
assertOffsets(t, h.source.committedOffsets(), 0)
}
func TestConsumerRetriesASerializationFailureAsAnAttempt(t *testing.T) {
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)})
h.store.commitErrors = []error{fmt.Errorf("commit: %w", outbound.ErrTransactionConflict)}
h.runUntilDrained(t)
if h.metrics.outcome(OutcomeApplied) != 1 || h.metrics.failure(StageHandler) != 1 || len(h.store.letters()) != 0 {
t.Fatalf("outcomes = %v, failures = %v, letters = %d; want one counted retry and the event applied",
h.metrics.outcomes, h.metrics.failures, len(h.store.letters()))
}
}
// panickyHandles panics while routing.
type panickyHandles struct{ fakeHandler }
func (*panickyHandles) Handles(string) bool { panic("routing secret") }
func TestConsumerDeadLettersAPanicWhileRouting(t *testing.T) {
source, store, metrics := newFakeSource([]outbound.ConsumedRecord{event(0, handledType)}), newFakeStore(), newFakeMetrics()
consumer, err := New(&panickyHandles{}, source, store, metrics, slog.New(slog.DiscardHandler), testSettings())
if err != nil {
t.Fatalf("New() error = %v", err)
}
h := &harness{source: source, store: store, handler: &fakeHandler{}, metrics: metrics, consumer: consumer}
h.runUntilDrained(t)
letters := store.letters()
if len(letters) != 1 || letters[0].ErrorClass != outbound.DeadLetterHandlerPanic || letters[0].Attempts != 0 ||
strings.Contains(letters[0].Reason, "secret") {
t.Fatalf("dead letters = %+v, want one handler_panic without the panic value", letters)
}
assertOffsets(t, source.committedOffsets(), 0)
}
func TestConsumerCountsPollAndCommitFailures(t *testing.T) {
h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)})
h.source.commitErr = errors.New("coordinator unavailable")
h.runUntilDrained(t)
if got := h.metrics.failure(StageCommit); got != 1 {
t.Fatalf("commit failures = %d, want 1", got)
}
polling := newHarness(t, testSettings())
polling.source.pollErr = errors.New("broker unavailable")
stop := polling.run(t)
time.Sleep(20 * time.Millisecond)
stop()
if got := polling.metrics.failure(StagePoll); got < 1 {
t.Fatalf("poll failures = %d, want at least 1", got)
}
}
+4 -19
View File
@@ -12,6 +12,7 @@ import (
"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.
@@ -27,7 +28,7 @@ type Settings struct {
// 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 Backoff
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.
@@ -155,7 +156,7 @@ func (relay *Relay) Run(ctx context.Context) {
needsPrepare = errors.Is(err, outbound.ErrEventDestinationMissing)
var delay time.Duration
delay, failures = relay.nextDelay(result, err, failures)
if !wait(ctx, delay) {
if !retry.Wait(ctx, delay) {
return
}
}
@@ -207,7 +208,7 @@ func (relay *Relay) prepare(ctx context.Context, backlog *backlogRefresher) bool
slog.Duration("retry_in", delay),
slog.Any("error", err),
)
if !wait(ctx, delay) {
if !retry.Wait(ctx, delay) {
return false
}
}
@@ -258,19 +259,3 @@ func (relay *Relay) passContext(ctx context.Context) (context.Context, func()) {
cancel()
}
}
// wait sleeps for delay and reports false when ctx ends first. A zero delay
// still reports a canceled context.
func wait(ctx context.Context, delay time.Duration) bool {
if delay <= 0 {
return ctx.Err() == nil
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}
@@ -13,6 +13,7 @@ import (
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/retry"
)
const (
@@ -136,7 +137,7 @@ func newTestRelay(store outbound.OutboxRelayStore, publisher outbound.EventPubli
return New(store, publisher, metrics, slog.New(slog.DiscardHandler), Settings{
BatchSize: 2,
PollInterval: testInterval,
Backoff: Backoff{Initial: testInterval, Max: 4 * testInterval},
Backoff: retry.Backoff{Initial: testInterval, Max: 4 * testInterval},
ShutdownTimeout: shutdownTimeout,
BacklogInterval: testInterval,
})
@@ -314,7 +315,7 @@ func TestRunStopsDuringBackoffWithoutAnotherPass(t *testing.T) {
}}, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{
BatchSize: 1,
PollInterval: testInterval,
Backoff: Backoff{Initial: time.Hour, Max: time.Hour},
Backoff: retry.Backoff{Initial: time.Hour, Max: time.Hour},
ShutdownTimeout: time.Second,
BacklogInterval: time.Hour,
})
@@ -337,7 +338,7 @@ func hourBackoffRelay(store outbound.OutboxRelayStore, publisher outbound.EventP
return New(store, publisher, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{
BatchSize: 2,
PollInterval: testInterval,
Backoff: Backoff{Initial: time.Hour, Max: time.Hour},
Backoff: retry.Backoff{Initial: time.Hour, Max: time.Hour},
ShutdownTimeout: time.Second,
BacklogInterval: backlogInterval,
})
@@ -409,7 +410,7 @@ func TestRunRefreshesTheBacklogAtMostOncePerInterval(t *testing.T) {
relay := New(store, fakePublisher{publish: acknowledgeAll}, metrics, slog.New(slog.DiscardHandler), Settings{
BatchSize: 1,
PollInterval: testInterval,
Backoff: Backoff{Initial: testInterval, Max: testInterval},
Backoff: retry.Backoff{Initial: testInterval, Max: testInterval},
ShutdownTimeout: time.Second,
BacklogInterval: time.Hour,
})
@@ -1,6 +1,9 @@
package outboxrelay
// Package retry holds the waiting rules that the background workers share:
// a capped exponential backoff with jitter and a context-aware sleep.
package retry
import (
"context"
"math/rand/v2"
"time"
)
@@ -8,8 +11,8 @@ import (
// Backoff is a capped exponential delay with equal jitter: the ceiling starts
// at Initial, doubles with every consecutive failure, and stops at Max; the
// delay is half the ceiling plus a random share of the other half. The fixed
// half keeps retries from hammering a recovering broker, and the random half
// spreads several relays apart.
// half keeps retries from hammering a recovering dependency, and the random
// half spreads several workers apart.
type Backoff struct {
Initial time.Duration
Max time.Duration
@@ -38,3 +41,19 @@ func randomJitter(limit time.Duration) time.Duration {
}
return rand.N(limit + 1) //nolint:gosec // Retry jitter needs no cryptographic randomness.
}
// Wait sleeps for delay and reports false when ctx ends first. A zero delay
// still reports a canceled context.
func Wait(ctx context.Context, delay time.Duration) bool {
if delay <= 0 {
return ctx.Err() == nil
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}
@@ -1,6 +1,7 @@
package outboxrelay
package retry
import (
"context"
"testing"
"time"
)
@@ -50,3 +51,21 @@ func TestBackoffRandomJitterStaysWithinTheCeiling(t *testing.T) {
}
}
}
func TestWaitStopsWhenTheContextEnds(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
cancel()
if Wait(ctx, 0) {
t.Fatal("Wait(canceled, 0) = true, want false")
}
started := time.Now()
if Wait(ctx, time.Hour) {
t.Fatal("Wait(canceled, 1h) = true, want false")
}
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("Wait(canceled, 1h) took %s", elapsed)
}
if !Wait(t.Context(), time.Millisecond) {
t.Fatal("Wait(live, 1ms) = false, want true")
}
}