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,290 @@
package kafka
import (
"context"
"errors"
"fmt"
"log/slog"
"slices"
"sync"
"time"
"github.com/twmb/franz-go/pkg/kerr"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/twmb/franz-go/pkg/kmsg"
"lincodex/backend/config"
"lincodex/backend/internal/port/outbound"
)
// leaveGroupMargin is added to CONSUMER_COMMIT_TIMEOUT to bound leaving the
// group at close: the leave revokes the partitions, and the revocation may
// commit finished records whose earlier commit failed. A broker that does not
// answer in time cannot hold shutdown; a member that could not leave is
// removed by the broker after the session timeout.
const leaveGroupMargin = 2 * time.Second
// EventSource implements outbound.EventSource with a franz-go consumer group
// member. Autocommit is off and rebalancing is blocked from a poll until
// Release, so an offset is committed only for records the consumer finished
// and only while this member still owns their partitions.
type EventSource struct {
client *kgo.Client
logger *slog.Logger
maxPollRecords int
commitTimeout time.Duration
leaveTimeout time.Duration
mu sync.Mutex
// epochs holds the leader epoch of every record of the last poll, which
// the commit carries for log truncation detection.
epochs map[recordPosition]int32
// polled holds the offsets of the last poll per partition in order, so
// Commit can refuse finished records that skip one.
polled map[topicPartition][]int64
// pending holds, per partition, the position after the last finished
// record that is not committed yet: a commit failed, and a later commit
// or the revocation of the partition retries it.
pending map[string]map[int32]kgo.EpochOffset
}
type topicPartition struct {
topic string
partition int32
}
type recordPosition struct {
topic string
partition int32
offset int64
}
var _ outbound.EventSource = (*EventSource)(nil)
// NewEventSource creates a member of group that consumes KAFKA_EVENTS_TOPIC
// without connecting; franz-go dials brokers on first poll. A group without
// a committed offset starts at the earliest retained record, so a new
// consumer never skips an event. The returned cleanup leaves the group and
// closes the client; call it only after the consumer stopped polling.
func NewEventSource(settings config.Config, group string, logger *slog.Logger) (*EventSource, func(), error) {
source := &EventSource{
logger: logger,
maxPollRecords: settings.ConsumerMaxPollRecords,
commitTimeout: settings.ConsumerCommitTimeout,
leaveTimeout: settings.ConsumerCommitTimeout + leaveGroupMargin,
epochs: make(map[recordPosition]int32),
polled: make(map[topicPartition][]int64),
pending: make(map[string]map[int32]kgo.EpochOffset),
}
client, err := kgo.NewClient(
kgo.SeedBrokers(settings.KafkaBrokers...),
kgo.ConsumerGroup(group),
kgo.ConsumeTopics(settings.KafkaEventsTopic),
kgo.DisableAutoCommit(),
kgo.BlockRebalanceOnPoll(),
// Set explicitly: config checks that the slowest record fits in it.
kgo.RebalanceTimeout(settings.ConsumerRebalanceTimeout),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
kgo.OnPartitionsRevoked(source.onRevoked),
kgo.OnPartitionsLost(source.onLost),
)
if err != nil {
return nil, nil, fmt.Errorf("kafka.NewEventSource - create Kafka client: %w", err)
}
source.client = client
return source, source.close, nil
}
// Poll returns the records of the next fetch in partition order. Fetch
// errors of single partitions are joined into the error; records of other
// partitions are still returned.
func (source *EventSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) {
fetches := source.client.PollRecords(ctx, source.maxPollRecords)
if err := ctx.Err(); err != nil {
return nil, err
}
if fetches.IsClientClosed() {
return nil, errors.New("EventSource.Poll - Kafka client is closed")
}
var fetchErr error
fetches.EachError(func(topic string, partition int32, err error) {
fetchErr = errors.Join(fetchErr, fmt.Errorf("EventSource.Poll - fetch %s partition %d: %w", topic, partition, err))
})
records := make([]outbound.ConsumedRecord, 0, fetches.NumRecords())
source.mu.Lock()
clear(source.epochs)
clear(source.polled)
fetches.EachRecord(func(record *kgo.Record) {
source.epochs[recordPosition{topic: record.Topic, partition: record.Partition, offset: record.Offset}] = record.LeaderEpoch
partition := topicPartition{topic: record.Topic, partition: record.Partition}
source.polled[partition] = append(source.polled[partition], record.Offset)
records = append(records, decodeRecord(record))
})
source.mu.Unlock()
return records, fetchErr
}
// Commit commits the position after the last finished record of each
// partition, together with any earlier position whose commit failed.
func (source *EventSource) Commit(ctx context.Context, finished []outbound.ConsumedRecord) error {
source.mu.Lock()
if err := source.checkPrefix(finished); err != nil {
source.mu.Unlock()
return err
}
for _, record := range finished {
epoch := source.epochs[recordPosition{topic: record.Topic, partition: record.Partition, offset: record.Offset}]
partitions := source.pending[record.Topic]
if partitions == nil {
partitions = make(map[int32]kgo.EpochOffset)
source.pending[record.Topic] = partitions
}
next := kgo.EpochOffset{Epoch: epoch, Offset: record.Offset + 1}
if current, ok := partitions[record.Partition]; !ok || current.Less(next) {
partitions[record.Partition] = next
}
}
offsets := clonePending(source.pending, nil)
source.mu.Unlock()
if err := source.commitOffsets(ctx, offsets); err != nil {
return err
}
source.forgetCommitted(offsets)
return nil
}
// checkPrefix verifies that, for every partition, the finished records are
// the first records of the last poll in order without a gap, so a commit can
// never move a partition past a record that was not finished. The caller
// holds mu.
func (source *EventSource) checkPrefix(finished []outbound.ConsumedRecord) error {
seen := make(map[topicPartition]int, len(source.polled))
for _, record := range finished {
partition := topicPartition{topic: record.Topic, partition: record.Partition}
polled, index := source.polled[partition], seen[partition]
if index >= len(polled) || polled[index] != record.Offset {
return fmt.Errorf("EventSource.Commit - record at %s partition %d offset %d is not the next record of the last poll", record.Topic, record.Partition, record.Offset)
}
seen[partition] = index + 1
}
return nil
}
// Release allows the group to rebalance until the next poll.
func (source *EventSource) Release() {
source.client.AllowRebalance()
}
// onRevoked commits finished records of the revoked partitions whose
// earlier commit failed. Unfinished records were never marked finished, so
// they are not committed and the next owner processes them.
func (source *EventSource) onRevoked(ctx context.Context, _ *kgo.Client, revoked map[string][]int32) {
source.mu.Lock()
offsets := clonePending(source.pending, revoked)
source.dropPending(revoked)
source.mu.Unlock()
if len(offsets) == 0 {
return
}
commitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), source.commitTimeout)
defer cancel()
if err := source.commitOffsets(commitCtx, offsets); err != nil {
source.logger.Warn("event consumer could not commit finished records of revoked partitions; the next owner processes them again",
slog.Any("error", err))
}
}
// onLost drops pending positions: the member no longer belongs to the group
// generation, so a commit would fail, and the next owner starts from the
// last committed offset.
func (source *EventSource) onLost(_ context.Context, _ *kgo.Client, lost map[string][]int32) {
source.mu.Lock()
source.dropPending(lost)
source.mu.Unlock()
if len(lost) > 0 {
source.logger.Warn("event consumer lost its partitions; uncommitted records will be processed again")
}
}
func (source *EventSource) commitOffsets(ctx context.Context, offsets map[string]map[int32]kgo.EpochOffset) error {
if len(offsets) == 0 {
return nil
}
var commitErr error
source.client.CommitOffsetsSync(ctx, offsets, func(_ *kgo.Client, _ *kmsg.OffsetCommitRequest, response *kmsg.OffsetCommitResponse, err error) {
if err != nil {
commitErr = err
return
}
for _, topic := range response.Topics {
for _, partition := range topic.Partitions {
if err := kerr.ErrorForCode(partition.ErrorCode); err != nil {
commitErr = errors.Join(commitErr, fmt.Errorf("partition %d: %w", partition.Partition, err))
}
}
}
})
if commitErr != nil {
return fmt.Errorf("EventSource.commitOffsets - commit offsets: %w", commitErr)
}
return nil
}
// forgetCommitted removes pending positions that the commit covered and that
// did not advance meanwhile.
func (source *EventSource) forgetCommitted(committed map[string]map[int32]kgo.EpochOffset) {
source.mu.Lock()
defer source.mu.Unlock()
for topic, partitions := range committed {
for partition, offset := range partitions {
if source.pending[topic][partition] == offset {
delete(source.pending[topic], partition)
}
}
if len(source.pending[topic]) == 0 {
delete(source.pending, topic)
}
}
}
func (source *EventSource) dropPending(partitions map[string][]int32) {
for topic, numbers := range partitions {
for _, partition := range numbers {
delete(source.pending[topic], partition)
}
if len(source.pending[topic]) == 0 {
delete(source.pending, topic)
}
}
}
// close leaves the group, which revokes the partitions and commits finished
// records whose commit failed, and closes the client.
func (source *EventSource) close() {
ctx, cancel := context.WithTimeout(context.Background(), source.leaveTimeout)
defer cancel()
if err := source.client.LeaveGroupContext(ctx); err != nil {
source.logger.Warn("event consumer could not leave its group; the broker removes it after the session timeout",
slog.Any("error", err))
}
source.client.CloseAllowingRebalance()
}
// clonePending copies the pending positions, limited to the partitions in
// only when only is not nil.
func clonePending(pending map[string]map[int32]kgo.EpochOffset, only map[string][]int32) map[string]map[int32]kgo.EpochOffset {
result := make(map[string]map[int32]kgo.EpochOffset)
for topic, partitions := range pending {
for partition, offset := range partitions {
if only != nil && !slices.Contains(only[topic], partition) {
continue
}
if result[topic] == nil {
result[topic] = make(map[int32]kgo.EpochOffset)
}
result[topic][partition] = offset
}
}
return result
}
@@ -0,0 +1,78 @@
package kafka
import (
"testing"
"github.com/twmb/franz-go/pkg/kgo"
"lincodex/backend/internal/port/outbound"
)
func TestEventSourceCommitAcceptsOnlyAPrefixOfTheLastPollPerPartition(t *testing.T) {
newSource := func() *EventSource {
source := &EventSource{
epochs: make(map[recordPosition]int32),
polled: make(map[topicPartition][]int64),
pending: make(map[string]map[int32]kgo.EpochOffset),
}
// The last poll returned offsets 4, 5, 6 of partition 0 and 9 of
// partition 1.
for partition, offsets := range map[int32][]int64{0: {4, 5, 6}, 1: {9}} {
for _, offset := range offsets {
source.epochs[recordPosition{topic: testTopic, partition: partition, offset: offset}] = 1
key := topicPartition{topic: testTopic, partition: partition}
source.polled[key] = append(source.polled[key], offset)
}
}
return source
}
record := func(partition int32, offset int64) outbound.ConsumedRecord {
return outbound.ConsumedRecord{Topic: testTopic, Partition: partition, Offset: offset}
}
rejected := map[string][]outbound.ConsumedRecord{
"not from the last poll": {record(0, 7)},
"gap": {record(0, 4), record(0, 6)},
"skips the first record": {record(0, 5)},
"out of order": {record(0, 5), record(0, 4)},
"repeated record": {record(0, 4), record(0, 4)},
"another topic": {{Topic: "other", Partition: 0, Offset: 4}},
}
for name, finished := range rejected {
t.Run(name, func(t *testing.T) {
source := newSource()
if err := source.Commit(t.Context(), finished); err == nil {
t.Fatal("Commit() accepted records that are not a prefix of the last poll")
}
if len(source.pending) != 0 {
t.Fatalf("Commit() kept a pending position for rejected records: %v", source.pending)
}
})
}
// Interleaved partitions are fine as long as each one is a prefix.
source := newSource()
if err := source.checkPrefix([]outbound.ConsumedRecord{record(0, 4), record(1, 9), record(0, 5)}); err != nil {
t.Fatalf("checkPrefix() rejected a valid prefix: %v", err)
}
}
func TestPendingPositionsAreLimitedAndForgottenPerPartition(t *testing.T) {
source := &EventSource{pending: map[string]map[int32]kgo.EpochOffset{
testTopic: {0: {Epoch: 1, Offset: 10}, 1: {Epoch: 1, Offset: 20}},
}}
revoked := clonePending(source.pending, map[string][]int32{testTopic: {1}})
if len(revoked[testTopic]) != 1 || revoked[testTopic][1].Offset != 20 {
t.Fatalf("clonePending() = %v, want only partition 1", revoked)
}
committed := clonePending(source.pending, nil)
// Partition 0 advanced while the commit was in flight, so it stays.
source.pending[testTopic][0] = kgo.EpochOffset{Epoch: 1, Offset: 11}
source.forgetCommitted(committed)
if len(source.pending[testTopic]) != 1 || source.pending[testTopic][0].Offset != 11 {
t.Fatalf("pending after forgetCommitted() = %v, want only the advanced partition 0", source.pending)
}
source.dropPending(map[string][]int32{testTopic: {0}})
if len(source.pending) != 0 {
t.Fatalf("pending after dropPending() = %v, want none", source.pending)
}
}
@@ -1,6 +1,7 @@
package kafka
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
@@ -9,6 +10,7 @@ import (
"github.com/google/uuid"
"github.com/twmb/franz-go/pkg/kgo"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
@@ -74,3 +76,96 @@ func newRecord(topic string, event outbound.OutboxEvent) (*kgo.Record, error) {
},
}, nil
}
// decodeRecord turns a consumed record into an event. A value that is not a
// valid envelope yields a record whose Invalid error matches
// outbound.ErrInvalidEventRecord; the error names the broken rule and never
// quotes the value. EventID then comes from the event_id header when it holds
// a UUID, so an operator can still find the event.
func decodeRecord(record *kgo.Record) outbound.ConsumedRecord {
consumed := outbound.ConsumedRecord{
Topic: record.Topic,
Partition: record.Partition,
Offset: record.Offset,
Value: record.Value,
}
headerID, headerErr := uuid.Parse(recordHeader(record, headerEventID))
if headerErr == nil {
consumed.EventID = headerID
}
event, err := decodeEnvelope(record.Value)
if err == nil && headerErr == nil && headerID != event.EventID {
// A consumer that deduplicated by the header would disagree with one
// that reads the value, so the record is not trusted.
err = invalidRecord("event_id header differs from the envelope")
}
if err != nil {
consumed.Invalid = err
return consumed
}
consumed.Event = event
consumed.EventID = event.EventID
return consumed
}
func decodeEnvelope(value []byte) (outbound.ConsumedEvent, error) {
var decoded envelope
// The json error is dropped: its text can quote part of the value.
if err := json.Unmarshal(value, &decoded); err != nil {
return outbound.ConsumedEvent{}, invalidRecord("value is not a JSON event envelope")
}
if decoded.EnvelopeVersion != EnvelopeVersion {
return outbound.ConsumedEvent{}, invalidRecord("unsupported envelope_version")
}
if decoded.EventID == uuid.Nil {
return outbound.ConsumedEvent{}, invalidRecord("event_id is missing")
}
identity := domain.DomainEventInput{
EventType: decoded.EventType,
SchemaVersion: decoded.SchemaVersion,
AggregateType: decoded.AggregateType,
AggregateID: decoded.AggregateID,
AggregateVersion: decoded.AggregateVersion,
}
if err := identity.ValidateIdentity(); err != nil {
return outbound.ConsumedEvent{}, fmt.Errorf("kafka.decodeEnvelope - %w: %w", outbound.ErrInvalidEventRecord, err)
}
if decoded.OccurredAt.IsZero() {
return outbound.ConsumedEvent{}, invalidRecord("occurred_at is missing")
}
if !isJSONObject(decoded.Payload) {
return outbound.ConsumedEvent{}, invalidRecord("payload is not a JSON object")
}
return outbound.ConsumedEvent{
EventID: decoded.EventID,
EventType: decoded.EventType,
SchemaVersion: decoded.SchemaVersion,
AggregateType: decoded.AggregateType,
AggregateID: decoded.AggregateID,
AggregateVersion: decoded.AggregateVersion,
OccurredAt: decoded.OccurredAt,
Payload: decoded.Payload,
}, nil
}
// isJSONObject reports whether raw, which json.Unmarshal already checked, is
// an object rather than another value or null.
func isJSONObject(raw json.RawMessage) bool {
trimmed := bytes.TrimLeft(raw, " \t\r\n")
return len(trimmed) > 0 && trimmed[0] == '{'
}
func invalidRecord(reason string) error {
return fmt.Errorf("kafka.decodeEnvelope - %s: %w", reason, outbound.ErrInvalidEventRecord)
}
// recordHeader returns the last value of the header key, or "" without one.
func recordHeader(record *kgo.Record, key string) string {
value := ""
for _, header := range record.Headers {
if header.Key == key {
value = string(header.Value)
}
}
return value
}
@@ -2,11 +2,13 @@ package kafka
import (
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/twmb/franz-go/pkg/kgo"
"lincodex/backend/internal/port/outbound"
)
@@ -103,3 +105,106 @@ func TestNewRecordRejectsAnInvalidPayloadWithoutQuotingIt(t *testing.T) {
t.Fatalf("newRecord() error = %v, want the event ID", err)
}
}
func TestDecodeRecordReadsWhatNewRecordWrites(t *testing.T) {
want := testEvent()
record, err := newRecord(testTopic, want)
if err != nil {
t.Fatalf("newRecord() error = %v", err)
}
record.Partition, record.Offset = 2, 41
consumed := decodeRecord(record)
if consumed.Invalid != nil {
t.Fatalf("decodeRecord() Invalid = %v", consumed.Invalid)
}
got := consumed.Event
if consumed.Topic != testTopic || consumed.Partition != 2 || consumed.Offset != 41 || consumed.EventID != want.EventID ||
got.EventID != want.EventID || got.EventType != want.EventType || got.SchemaVersion != want.SchemaVersion ||
got.AggregateType != want.AggregateType || got.AggregateID != want.AggregateID ||
got.AggregateVersion != want.AggregateVersion || !got.OccurredAt.Equal(want.OccurredAt) {
t.Fatalf("decodeRecord() = %+v, want the fields of %+v", consumed, want)
}
if string(got.Payload) != `{"user_id":"6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a","nested":{"n":1}}` {
t.Fatalf("payload = %s", got.Payload)
}
if string(consumed.Value) != string(record.Value) {
t.Fatal("decodeRecord() did not keep the raw value")
}
}
func TestDecodeRecordRejectsInvalidEnvelopesWithoutQuotingThem(t *testing.T) {
valid, err := newRecord(testTopic, testEvent())
if err != nil {
t.Fatalf("newRecord() error = %v", err)
}
headerID := testEvent().EventID
withField := func(field string, value any) []byte {
var fields map[string]any
if err := json.Unmarshal(valid.Value, &fields); err != nil {
t.Fatalf("decode test envelope: %v", err)
}
if value == nil {
delete(fields, field)
} else {
fields[field] = value
}
encoded, err := json.Marshal(fields)
if err != nil {
t.Fatalf("encode test envelope: %v", err)
}
return encoded
}
tests := []struct {
name string
value []byte
headers []kgo.RecordHeader
want string
}{
{name: "not JSON", value: []byte("secret-value"), want: "value is not a JSON event envelope"},
{name: "wrong type", value: withField("event_id", "secret-value"), want: "value is not a JSON event envelope"},
{name: "future envelope", value: withField("envelope_version", 2), want: "unsupported envelope_version"},
{name: "no event ID", value: withField("event_id", nil), want: "event_id is missing"},
{name: "bad event type", value: withField("event_type", "Secret Value"), want: "event type must be"},
{name: "zero schema", value: withField("schema_version", 0), want: "schema version must be positive"},
{name: "no aggregate", value: withField("aggregate_id", nil), want: "aggregate ID must not be nil"},
{name: "zero version", value: withField("aggregate_version", 0), want: "aggregate version must be positive"},
{name: "no time", value: withField("occurred_at", nil), want: "occurred_at is missing"},
{name: "array payload", value: withField("payload", []string{"secret-value"}), want: "payload is not a JSON object"},
{name: "null payload", value: withField("payload", nil), want: "payload is not a JSON object"},
{
name: "header mismatch",
value: valid.Value,
headers: []kgo.RecordHeader{{Key: "event_id", Value: []byte(uuid.NewString())}},
want: "event_id header differs from the envelope",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
headers := test.headers
if headers == nil {
headers = []kgo.RecordHeader{{Key: "event_id", Value: []byte(headerID.String())}}
}
consumed := decodeRecord(&kgo.Record{Topic: testTopic, Value: test.value, Headers: headers})
if !errors.Is(consumed.Invalid, outbound.ErrInvalidEventRecord) {
t.Fatalf("Invalid = %v, want ErrInvalidEventRecord", consumed.Invalid)
}
if !strings.Contains(consumed.Invalid.Error(), test.want) {
t.Fatalf("Invalid = %v, want %q", consumed.Invalid, test.want)
}
if strings.Contains(consumed.Invalid.Error(), "secret") || strings.Contains(consumed.Invalid.Error(), "Secret") {
t.Fatalf("Invalid quotes the value: %v", consumed.Invalid)
}
if test.headers == nil && consumed.EventID != headerID {
t.Fatalf("EventID = %s, want the header event ID", consumed.EventID)
}
})
}
}
func TestDecodeRecordWithoutAnEventIDHeaderLeavesItNil(t *testing.T) {
consumed := decodeRecord(&kgo.Record{Topic: testTopic, Value: []byte("{}"), Headers: []kgo.RecordHeader{{Key: "event_id", Value: []byte("not-a-uuid")}}})
if consumed.Invalid == nil || consumed.EventID != uuid.Nil {
t.Fatalf("decodeRecord() = %+v, want an invalid record without an event ID", consumed)
}
}
@@ -0,0 +1,206 @@
package postgres
import (
"context"
"errors"
"fmt"
"math"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/port/outbound"
)
// SQLSTATE classes that classifyCommitError separates.
const (
sqlStateClassLength = 2
integrityConstraintClass = "23"
transactionRollbackClass = "40"
)
// EventConsumerStore implements outbound.EventConsumerStore with a pgx pool
// owned by the caller. Each ApplyOnce holds one connection and one
// transaction for the duration of the handler.
type EventConsumerStore struct {
pool *pgxpool.Pool
// transactionTimeout is set as statement_timeout and
// idle_in_transaction_session_timeout of every ApplyOnce transaction.
transactionTimeout time.Duration
}
var _ outbound.EventConsumerStore = (*EventConsumerStore)(nil)
// NewEventConsumerStore bounds each transaction on the server by
// transactionTimeout, the consumer's handler timeout. The caller's context
// already cancels the work of a live process; the server-side limits also
// end the transaction of a process that froze or lost the network, so the
// marker it holds does not block a concurrent duplicate indefinitely.
func NewEventConsumerStore(pool *pgxpool.Pool, transactionTimeout time.Duration) *EventConsumerStore {
return &EventConsumerStore{pool: pool, transactionTimeout: transactionTimeout}
}
// ApplyOnce inserts the marker first and runs apply only when the insert
// added it. INSERT ... ON CONFLICT DO NOTHING is used rather than a plain
// INSERT that fails on the unique key: it waits for a concurrent transaction
// holding the same key exactly as the plain insert would, but a duplicate
// then reports zero rows instead of aborting the transaction with SQLSTATE
// 23505, so no error decides control flow and PostgreSQL logs no error for
// an expected duplicate.
func (store *EventConsumerStore) ApplyOnce(ctx context.Context, consumer string, eventID uuid.UUID, apply outbound.ApplyEvent) (bool, error) {
// PostgreSQL reads 0 as no limit, so a value below one millisecond would
// silently remove the bound.
if store.transactionTimeout < time.Millisecond {
return false, errors.New("EventConsumerStore.ApplyOnce - transaction timeout must be at least 1ms")
}
if ctx.Value(transactionContextKey{}) != nil {
return false, fmt.Errorf("EventConsumerStore.ApplyOnce - begin transaction: %w", outbound.ErrNestedTransaction)
}
tx, err := store.pool.BeginTx(ctx, transactionOptions)
if err != nil {
return false, fmt.Errorf("EventConsumerStore.ApplyOnce - begin transaction: %w", sanitizeConnectError(err))
}
finished := false
defer func() {
// Runs only when apply panics; the panic keeps its stack and the
// rollback error cannot change that outcome.
if !finished {
_ = rollback(ctx, tx)
}
}()
applied, applyErr := store.applyInTransaction(ctx, tx, consumer, eventID, apply)
finished = true
if applyErr != nil || !applied {
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
return false, errors.Join(applyErr, fmt.Errorf("EventConsumerStore.ApplyOnce - roll back transaction: %w", rollbackErr))
}
return false, applyErr
}
if err := tx.Commit(ctx); err != nil {
return false, fmt.Errorf("EventConsumerStore.ApplyOnce - commit transaction: %w", classifyCommitError(err))
}
return true, nil
}
// classifyCommitError separates a commit that PostgreSQL refused from one
// that failed in transport. A refusal is deterministic or caused by
// concurrent writers, so the consumer counts it as a handler attempt instead
// of retrying it as a database outage forever:
//
// - pgx.ErrTxCommitRollback: a statement of the handler failed and the
// handler returned nil anyway, so PostgreSQL rolled the aborted
// transaction back;
// - SQLSTATE class 23: a deferred integrity constraint failed at commit;
// - SQLSTATE class 40: a serialization failure or deadlock, which a retry
// usually resolves, so it matches outbound.ErrTransactionConflict.
//
// Connection and network errors pass through as store failures.
func classifyCommitError(err error) error {
if errors.Is(err, pgx.ErrTxCommitRollback) {
return fmt.Errorf("postgres.classifyCommitError - transaction was aborted by a failed statement: %w", outbound.ErrEventEffectRejected)
}
var pgError *pgconn.PgError
if errors.As(err, &pgError) && len(pgError.Code) == len(deadlockDetectedCode) {
safe := &databaseError{code: pgError.Code, constraint: pgError.ConstraintName}
switch pgError.Code[:sqlStateClassLength] {
case integrityConstraintClass:
return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrEventEffectRejected, safe)
case transactionRollbackClass:
return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrTransactionConflict, safe)
}
}
return sanitizedDatabaseError(err)
}
// sanitizedApplyError keeps the identity of a handler error for errors.Is
// and errors.As but replaces the text of a PostgreSQL error inside it, whose
// message can quote row values, with its SQLSTATE and constraint. The
// consumer logs this text and stores it with a dead letter.
type sanitizedApplyError struct {
text string
cause error
}
func (err *sanitizedApplyError) Error() string { return err.text }
func (err *sanitizedApplyError) Unwrap() error { return err.cause }
func sanitizeApplyError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return err
}
safe := (&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}).Error()
text := strings.ReplaceAll(err.Error(), pgError.Error(), safe)
// A handler that formatted the message itself may still carry it.
if pgError.Message != "" && strings.Contains(text, pgError.Message) {
text = "handler failed: " + safe
}
return &sanitizedApplyError{text: text, cause: err}
}
func (store *EventConsumerStore) applyInTransaction(
ctx context.Context,
tx pgx.Tx,
consumer string,
eventID uuid.UUID,
apply outbound.ApplyEvent,
) (bool, error) {
queries := sqlc.New(tx)
timeout := milliseconds(store.transactionTimeout)
err := queries.SetConsumerTransactionTimeouts(ctx, sqlc.SetConsumerTransactionTimeoutsParams{
StatementTimeoutMs: timeout,
IdleTimeoutMs: timeout,
})
if err != nil {
return false, fmt.Errorf("postgres.applyInTransaction - set transaction timeouts: %w", sanitizedDatabaseError(err))
}
inserted, err := queries.InsertProcessedEventMarker(ctx, sqlc.InsertProcessedEventMarkerParams{
ConsumerName: consumer,
EventID: pgtype.UUID{Bytes: eventID, Valid: true},
})
if err != nil {
return false, fmt.Errorf("postgres.applyInTransaction - insert processed event marker: %w", sanitizedDatabaseError(err))
}
if inserted == 0 {
return false, nil
}
unit := &UnitOfWork{tx: tx, queries: queries}
// The error of apply is returned without a store location, so the caller
// keeps its identity; only PostgreSQL text inside it is replaced.
if err := apply(context.WithValue(ctx, transactionContextKey{}, true), unit); err != nil {
return false, sanitizeApplyError(markTransactionConflict(err))
}
return true, nil
}
// RecordDeadLetter stores letter outside any consumer transaction.
func (store *EventConsumerStore) RecordDeadLetter(ctx context.Context, letter outbound.DeadLetter) error {
if letter.Attempts < 0 || letter.Attempts > math.MaxInt32 || letter.ValueSize < 0 || letter.ValueSize > math.MaxInt32 {
return errors.New("EventConsumerStore.RecordDeadLetter - attempts and value size must fit a non-negative int32")
}
params := sqlc.InsertConsumerDeadLetterParams{
ConsumerName: letter.Consumer,
Topic: letter.Topic,
KafkaPartition: letter.Partition,
KafkaOffset: letter.Offset,
EventID: pgtype.UUID{Bytes: letter.EventID, Valid: letter.EventID != uuid.Nil},
EventType: pgtype.Text{String: letter.EventType, Valid: letter.EventType != ""},
ErrorClass: string(letter.ErrorClass),
Reason: letter.Reason,
Attempts: int32(letter.Attempts),
ValueSize: int32(letter.ValueSize),
ValueSha256: letter.ValueSHA256[:],
}
if err := sqlc.New(store.pool).InsertConsumerDeadLetter(ctx, params); err != nil {
return fmt.Errorf("EventConsumerStore.RecordDeadLetter - insert dead letter: %w", sanitizedDatabaseError(err))
}
return nil
}
@@ -0,0 +1,80 @@
package postgres
import (
"errors"
"fmt"
"net"
"strings"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
func TestClassifyCommitErrorSeparatesRefusalsFromTransportFailures(t *testing.T) {
tests := []struct {
name string
err error
rejected bool
conflict bool
forbidText string
}{
{name: "aborted transaction", err: pgx.ErrTxCommitRollback, rejected: true},
{
name: "deferred unique violation",
err: &pgconn.PgError{Code: "23505", ConstraintName: "effects_key", Message: "duplicate key secret-value"},
rejected: true,
forbidText: "secret-value",
},
{name: "serialization failure", err: &pgconn.PgError{Code: "40001", Message: "could not serialize"}, conflict: true},
{name: "deadlock", err: &pgconn.PgError{Code: "40P01"}, conflict: true},
{name: "network", err: &net.OpError{Op: "read", Err: errors.New("connection reset")}},
{name: "server shutdown", err: &pgconn.PgError{Code: "57P01", Message: "terminating connection secret-value"}, forbidText: "secret-value"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := classifyCommitError(test.err)
if got := errors.Is(err, outbound.ErrEventEffectRejected); got != test.rejected {
t.Fatalf("classifyCommitError() = %v, rejected = %t, want %t", err, got, test.rejected)
}
if got := errors.Is(err, outbound.ErrTransactionConflict); got != test.conflict {
t.Fatalf("classifyCommitError() = %v, conflict = %t, want %t", err, got, test.conflict)
}
if test.forbidText != "" && strings.Contains(err.Error(), test.forbidText) {
t.Fatalf("classifyCommitError() kept the PostgreSQL message: %v", err)
}
})
}
}
func TestSanitizeApplyErrorKeepsIdentityButDropsThePostgreSQLMessage(t *testing.T) {
pgError := &pgconn.PgError{Severity: "ERROR", Code: "22P02", Message: `invalid input syntax for type uuid: "secret-value"`}
wrapped := fmt.Errorf("apply effect: %w: %w", inbound.ErrEventRejected, pgError)
err := sanitizeApplyError(wrapped)
if strings.Contains(err.Error(), "secret-value") {
t.Fatalf("sanitizeApplyError() kept the message: %v", err)
}
if !strings.Contains(err.Error(), "apply effect") || !strings.Contains(err.Error(), "22P02") {
t.Fatalf("sanitizeApplyError() = %q, want the handler context and the SQLSTATE", err)
}
var found *pgconn.PgError
if !errors.Is(err, inbound.ErrEventRejected) || !errors.As(err, &found) {
t.Fatalf("sanitizeApplyError() lost the error identity: %v", err)
}
// A handler that copied only the message into its own text.
copied := fmt.Errorf("apply effect failed with %s: %w", pgError.Message, errors.New("cause"))
copied = fmt.Errorf("%w (%w)", copied, pgError)
if err := sanitizeApplyError(copied); strings.Contains(err.Error(), "secret-value") {
t.Fatalf("sanitizeApplyError() kept a copied message: %v", err)
}
plain := errors.New("plain handler failure")
if err := sanitizeApplyError(plain); err != plain { //nolint:errorlint // The same value proves the pass-through.
t.Fatalf("sanitizeApplyError() changed an error without PostgreSQL text: %v", err)
}
}
@@ -81,7 +81,7 @@ func (store *OutboxRelayStore) ClaimPending(ctx context.Context, limit int, publ
return claimErr
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("OutboxRelayStore.ClaimPending - commit transaction: %w", relayDatabaseError(err))
return fmt.Errorf("OutboxRelayStore.ClaimPending - commit transaction: %w", sanitizedDatabaseError(err))
}
return nil
}
@@ -93,11 +93,11 @@ func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRe
IdleTimeoutMs: milliseconds(timeouts.IdleInTransaction),
})
if err != nil {
return fmt.Errorf("postgres.claimPending - set transaction timeouts: %w", relayDatabaseError(err))
return fmt.Errorf("postgres.claimPending - set transaction timeouts: %w", sanitizedDatabaseError(err))
}
rows, err := queries.LockPendingOutboxEvents(ctx, limit)
if err != nil {
return fmt.Errorf("postgres.claimPending - lock pending events: %w", relayDatabaseError(err))
return fmt.Errorf("postgres.claimPending - lock pending events: %w", sanitizedDatabaseError(err))
}
if len(rows) == 0 {
return nil
@@ -130,7 +130,7 @@ func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRe
}
count, err := queries.MarkOutboxEventsPublished(ctx, marked)
if err != nil {
return fmt.Errorf("postgres.claimPending - mark published events: %w", relayDatabaseError(err))
return fmt.Errorf("postgres.claimPending - mark published events: %w", sanitizedDatabaseError(err))
}
if count != int64(len(marked)) {
return fmt.Errorf("postgres.claimPending - marked %d events, want %d", count, len(marked))
@@ -142,7 +142,7 @@ func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRe
func (store *OutboxRelayStore) Backlog(ctx context.Context) (outbound.OutboxBacklog, error) {
row, err := sqlc.New(store.pool).GetOutboxBacklog(ctx)
if err != nil {
return outbound.OutboxBacklog{}, fmt.Errorf("OutboxRelayStore.Backlog - read backlog: %w", relayDatabaseError(err))
return outbound.OutboxBacklog{}, fmt.Errorf("OutboxRelayStore.Backlog - read backlog: %w", sanitizedDatabaseError(err))
}
return outbound.OutboxBacklog{
Pending: row.PendingEvents,
@@ -169,10 +169,11 @@ func outboxEventFromRow(row sqlc.LockPendingOutboxEventsRow) outbound.OutboxEven
}
}
// relayDatabaseError keeps only the SQLSTATE of a PostgreSQL error, whose
// message or detail could quote an event payload, and drops the connection
// prefix of a connect error.
func relayDatabaseError(err error) error {
// sanitizedDatabaseError keeps only the SQLSTATE and constraint of a
// PostgreSQL error, whose message or detail could quote an event payload, and
// drops the connection prefix of a connect error. The relay and the event
// consumers use it.
func sanitizedDatabaseError(err error) error {
var pgError *pgconn.PgError
if errors.As(err, &pgError) {
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
@@ -43,15 +43,15 @@ func TestRelayDatabaseErrorKeepsOnlyTheSQLState(t *testing.T) {
Message: `invalid input syntax for type json: "secret-payload"`,
Detail: `Token "secret-payload" is invalid.`,
}
err := relayDatabaseError(original)
err := sanitizedDatabaseError(original)
if strings.Contains(err.Error(), "secret-payload") {
t.Fatalf("relayDatabaseError() kept the message: %v", err)
t.Fatalf("sanitizedDatabaseError() kept the message: %v", err)
}
var stateError sqlStateError
if !errors.As(err, &stateError) || stateError.SQLState() != "22P02" {
t.Fatalf("relayDatabaseError() = %v, want SQLSTATE 22P02", err)
t.Fatalf("sanitizedDatabaseError() = %v, want SQLSTATE 22P02", err)
}
if conflict := relayDatabaseError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(conflict, outbound.ErrTransactionConflict) {
t.Fatalf("relayDatabaseError(deadlock) = %v, want ErrTransactionConflict", conflict)
if conflict := sanitizedDatabaseError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(conflict, outbound.ErrTransactionConflict) {
t.Fatalf("sanitizedDatabaseError(deadlock) = %v, want ErrTransactionConflict", conflict)
}
}
@@ -0,0 +1,133 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: event_consumer.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const insertConsumerDeadLetter = `-- name: InsertConsumerDeadLetter :exec
INSERT INTO consumer_dead_letters (
consumer_name,
topic,
kafka_partition,
kafka_offset,
event_id,
event_type,
error_class,
reason,
attempts,
value_size,
value_sha256
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11
)
ON CONFLICT (
consumer_name, topic, kafka_partition, kafka_offset, value_sha256
) DO UPDATE SET
event_id = excluded.event_id,
event_type = excluded.event_type,
error_class = excluded.error_class,
reason = excluded.reason,
attempts = excluded.attempts,
dead_lettered_at = clock_timestamp()
`
type InsertConsumerDeadLetterParams struct {
ConsumerName string
Topic string
KafkaPartition int32
KafkaOffset int64
EventID pgtype.UUID
EventType pgtype.Text
ErrorClass string
Reason string
Attempts int32
ValueSize int32
ValueSha256 []byte
}
// Stores a record that a consumer could not apply. A second delivery of the
// same record (same position and value) refreshes the outcome of its row:
// after a rewind the handler may fail differently. A different value at a
// reused position, after the topic was recreated, gets its own row.
func (q *Queries) InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error {
_, err := q.db.Exec(ctx, insertConsumerDeadLetter,
arg.ConsumerName,
arg.Topic,
arg.KafkaPartition,
arg.KafkaOffset,
arg.EventID,
arg.EventType,
arg.ErrorClass,
arg.Reason,
arg.Attempts,
arg.ValueSize,
arg.ValueSha256,
)
return err
}
const insertProcessedEventMarker = `-- name: InsertProcessedEventMarker :execrows
INSERT INTO consumer_processed_events (consumer_name, event_id)
VALUES ($1, $2)
ON CONFLICT (consumer_name, event_id) DO NOTHING
`
type InsertProcessedEventMarkerParams struct {
ConsumerName string
EventID pgtype.UUID
}
// Records that a consumer applies an event, in the transaction of the effect.
// It returns 0 rows when the marker exists. While another transaction holds
// an uncommitted marker for the same key, the insert waits for it: after a
// commit it returns 0, after a rollback it inserts. So a concurrent duplicate
// never runs the effect at the same time as the first delivery.
func (q *Queries) InsertProcessedEventMarker(ctx context.Context, arg InsertProcessedEventMarkerParams) (int64, error) {
result, err := q.db.Exec(ctx, insertProcessedEventMarker, arg.ConsumerName, arg.EventID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const setConsumerTransactionTimeouts = `-- name: SetConsumerTransactionTimeouts :exec
SELECT
set_config('statement_timeout', $1::text, true),
set_config(
'idle_in_transaction_session_timeout',
$2::text,
true
)
`
type SetConsumerTransactionTimeoutsParams struct {
StatementTimeoutMs string
IdleTimeoutMs string
}
// Bounds a consumer transaction on the server, local to the transaction.
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
// ends the session of a process that froze or lost the network inside the
// handler, which releases the processed-event marker that a concurrent
// duplicate waits for.
func (q *Queries) SetConsumerTransactionTimeouts(ctx context.Context, arg SetConsumerTransactionTimeoutsParams) error {
_, err := q.db.Exec(ctx, setConsumerTransactionTimeouts, arg.StatementTimeoutMs, arg.IdleTimeoutMs)
return err
}
@@ -8,6 +8,28 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
type ConsumerDeadLetter struct {
ID int64
ConsumerName string
Topic string
KafkaPartition int32
KafkaOffset int64
EventID pgtype.UUID
EventType pgtype.Text
ErrorClass string
Reason string
Attempts int32
ValueSize int32
ValueSha256 []byte
DeadLetteredAt pgtype.Timestamptz
}
type ConsumerProcessedEvent struct {
ConsumerName string
EventID pgtype.UUID
ProcessedAt pgtype.Timestamptz
}
type EmailToken struct {
ID pgtype.UUID
UserID pgtype.UUID
@@ -49,6 +49,11 @@ type Querier interface {
GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
// Stores a record that a consumer could not apply. A second delivery of the
// same record (same position and value) refreshes the outcome of its row:
// after a rewind the handler may fail differently. A different value at a
// reused position, after the topic was recreated, gets its own row.
InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
// Stores a version and returns the stored row with the publication time and
@@ -57,6 +62,12 @@ type Querier interface {
// surrounding transaction. created_at is never taken from the caller, and a
// NULL effective_at means "at publication".
InsertPolicyVersion(ctx context.Context, arg InsertPolicyVersionParams) (PolicyVersion, error)
// Records that a consumer applies an event, in the transaction of the effect.
// It returns 0 rows when the marker exists. While another transaction holds
// an uncommitted marker for the same key, the insert waits for it: after a
// commit it returns 0, after a rollback it inserts. So a concurrent duplicate
// never runs the effect at the same time as the first delivery.
InsertProcessedEventMarker(ctx context.Context, arg InsertProcessedEventMarkerParams) (int64, error)
InsertSession(ctx context.Context, arg InsertSessionParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
@@ -82,6 +93,12 @@ type Querier interface {
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
// Bounds a consumer transaction on the server, local to the transaction.
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
// ends the session of a process that froze or lost the network inside the
// handler, which releases the processed-event marker that a concurrent
// duplicate waits for.
SetConsumerTransactionTimeouts(ctx context.Context, arg SetConsumerTransactionTimeoutsParams) error
// Bounds the claim transaction on the server. statement_timeout stops a
// statement that runs too long; idle_in_transaction_session_timeout ends the
// session, and with it the transaction and its row locks, when the client
@@ -25,6 +25,12 @@ type Metrics struct {
// so dashboards aggregate them with max, not sum.
relayPending client.Gauge
relayOldestAge client.Gauge
// consumerRecords counts consumed records by consumer and final
// outcome; every record ends with exactly one outcome.
consumerRecords *client.CounterVec
// consumerFailures counts every failed consumer operation, including the
// last handler attempt before a dead letter, by the stage that failed.
consumerFailures *client.CounterVec
}
// Outbox relay outcome label values.
@@ -33,6 +39,13 @@ const (
relayOutcomeFailed = "failed"
)
// Event consumer label values. They mirror the eventconsumer constants, which
// this adapter does not import; PrepareEventConsumer creates these series.
var (
consumerOutcomes = []string{"applied", "duplicate", "ignored", "dead_lettered"}
consumerStages = []string{"handler", "store", "poll", "commit"}
)
func New() *Metrics {
registry := client.NewRegistry()
requests := client.NewCounterVec(client.CounterOpts{
@@ -56,10 +69,19 @@ func New() *Metrics {
Name: "lincodex_outbox_relay_oldest_pending_age_seconds",
Help: "Age of the earliest unpublished outbox event at the last backlog read by the relay; 0 without pending events.",
})
consumerRecords := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_event_consumer_records_total",
Help: "Event bus records finished by a consumer, by outcome: applied, duplicate, ignored, or dead_lettered.",
}, []string{"consumer", "outcome"})
consumerFailures := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_event_consumer_failures_total",
Help: "Failed event consumer operations, including the last handler attempt before a dead letter, by stage: handler, store, poll, or commit.",
}, []string{"consumer", "stage"})
registry.MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
requests, latency, relayEvents, relayPending, relayOldestAge,
consumerRecords, consumerFailures,
)
// Expose both series from the start so rate queries see zero, not absence.
relayEvents.WithLabelValues(relayOutcomePublished)
@@ -71,9 +93,34 @@ func New() *Metrics {
relayEvents: relayEvents,
relayPending: relayPending,
relayOldestAge: relayOldestAge,
consumerRecords: consumerRecords,
consumerFailures: consumerFailures,
}
}
// PrepareEventConsumer exposes every series of consumer at zero, so an alert
// on the first dead letter sees an increase instead of a new series.
func (metrics *Metrics) PrepareEventConsumer(consumer string) {
for _, outcome := range consumerOutcomes {
metrics.consumerRecords.WithLabelValues(consumer, outcome)
}
for _, stage := range consumerStages {
metrics.consumerFailures.WithLabelValues(consumer, stage)
}
}
// ObserveConsumedRecord counts one finished record.
func (metrics *Metrics) ObserveConsumedRecord(consumer, outcome string) {
metrics.consumerRecords.WithLabelValues(consumer, outcome).Inc()
}
// ObserveConsumerFailure counts one failed handler attempt, store
// operation, poll, or offset commit.
func (metrics *Metrics) ObserveConsumerFailure(consumer, stage string) {
metrics.consumerFailures.WithLabelValues(consumer, stage).Inc()
}
// ObserveOutboxBacklog records the latest backlog read.
func (metrics *Metrics) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) {
metrics.relayPending.Set(float64(backlog.Pending))
@@ -58,3 +58,31 @@ func TestMetricsHandlerExposesTheOutboxBacklog(t *testing.T) {
}
}
}
func TestMetricsHandlerExposesEventConsumerOutcomes(t *testing.T) {
metrics := New()
metrics.PrepareEventConsumer("audit_log")
metrics.ObserveConsumedRecord("audit_log", "applied")
metrics.ObserveConsumedRecord("audit_log", "applied")
metrics.ObserveConsumedRecord("audit_log", "dead_lettered")
metrics.ObserveConsumerFailure("audit_log", "handler")
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
body := response.Body.String()
for _, want := range []string{
`lincodex_event_consumer_records_total{consumer="audit_log",outcome="applied"} 2`,
`lincodex_event_consumer_records_total{consumer="audit_log",outcome="dead_lettered"} 1`,
// Prepared series are exposed at zero before the first observation.
`lincodex_event_consumer_records_total{consumer="audit_log",outcome="duplicate"} 0`,
`lincodex_event_consumer_records_total{consumer="audit_log",outcome="ignored"} 0`,
`lincodex_event_consumer_failures_total{consumer="audit_log",stage="handler"} 1`,
`lincodex_event_consumer_failures_total{consumer="audit_log",stage="store"} 0`,
`lincodex_event_consumer_failures_total{consumer="audit_log",stage="poll"} 0`,
`lincodex_event_consumer_failures_total{consumer="audit_log",stage="commit"} 0`,
} {
if !strings.Contains(body, want) {
t.Fatalf("metrics output is missing %s:\n%s", want, body)
}
}
}
+26 -13
View File
@@ -9,6 +9,7 @@ import (
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
@@ -36,6 +37,9 @@ type Application struct {
// relay publishes outbox events while the servers run. It is nil when
// the relay is disabled or the database is not configured.
relay *outboxrelay.Relay
// consumers apply events from the event bus while the servers run. The
// list is empty until a handler is registered in eventHandlers.
consumers eventConsumers
}
func NewApplication(
@@ -45,6 +49,7 @@ func NewApplication(
logger *slog.Logger,
mailSender outbound.MailSender,
relay *outboxrelay.Relay,
consumers eventConsumers,
) *Application {
return &Application{
config: config,
@@ -53,6 +58,7 @@ func NewApplication(
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
}
}
@@ -149,11 +155,11 @@ func (application *Application) run(ctx context.Context) error {
slog.String("metrics_addr", application.config.MetricsAddr),
)
// The relay stops when the servers stop, including after a server
// The workers stop when the servers stop, including after a server
// failure that leaves ctx running.
runCtx, stopRun := context.WithCancel(ctx)
defer stopRun()
relayStopped := application.startRelay(runCtx)
workersStopped := application.startWorkers(runCtx)
apiServer := newHTTPServer(application.apiHandler)
metricsServer := newHTTPServer(application.metrics.Handler())
@@ -167,23 +173,30 @@ func (application *Application) run(ctx context.Context) error {
)
application.logger.Info("servers stopped")
stopRun()
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT, so
// the cleanup that closes its pool and producer runs after it.
<-relayStopped
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT and
// each consumer its record in progress within CONSUMER_SHUTDOWN_GRACE
// plus one offset commit, so the cleanup that closes their pools,
// producer, and group members runs after all of them stopped.
<-workersStopped
application.logger.Info("workers stopped")
return err
}
// startRelay runs the relay until ctx ends and returns a channel that closes
// when it has stopped.
func (application *Application) startRelay(ctx context.Context) <-chan struct{} {
stopped := make(chan struct{})
if application.relay == nil {
close(stopped)
return stopped
// startWorkers runs the relay and every consumer until ctx ends and returns
// a channel that closes when all of them have stopped. The workers stop
// together with the servers; none of them depends on another.
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
var workers sync.WaitGroup
if application.relay != nil {
workers.Go(func() { application.relay.Run(ctx) })
}
for _, consumer := range application.consumers {
workers.Go(func() { consumer.Run(ctx) })
}
stopped := make(chan struct{})
go func() {
defer close(stopped)
application.relay.Run(ctx)
workers.Wait()
}()
return stopped
}
+133
View File
@@ -0,0 +1,133 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"math"
"sync"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/kafka"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/worker/eventconsumer"
"lincodex/backend/internal/worker/retry"
)
// consumerGroupSeparator joins CONSUMER_GROUP_PREFIX and a consumer name.
const consumerGroupSeparator = "."
// eventConsumers are the consumers that run next to the HTTP servers.
type eventConsumers []*eventconsumer.Consumer
var _ eventconsumer.Metrics = (*prometheus.Metrics)(nil)
// eventHandlers lists the handlers that get a consumer. It is empty because
// no product module consumes domain events yet; a module adds its handler
// here, and its consumer then starts with the next deployment.
func eventHandlers() []inbound.EventHandler {
return nil
}
func newEventConsumers(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics *prometheus.Metrics,
) (eventConsumers, func(), error) {
return buildEventConsumers(ctx, settings, logger, metrics, eventHandlers())
}
// buildEventConsumers builds one consumer per handler and the resources they
// own: one PostgreSQL pool shared by all of them and one Kafka group member
// each. Nothing connects here, so an unavailable Kafka or database never
// blocks startup; the consumers retry in the background. It returns no
// consumer when CONSUMER_ENABLED is false, when no handler is registered, or
// when DATABASE_URL is unset.
func buildEventConsumers(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics eventconsumer.Metrics,
handlers []inbound.EventHandler,
) (eventConsumers, func(), error) {
switch {
case !settings.ConsumerEnabled:
logger.Info("event consumers are disabled")
return nil, func() {}, nil
case len(handlers) == 0:
logger.Info("no event consumer is registered")
return nil, func() {}, nil
case settings.DatabaseURL == "":
logger.Warn("event consumers skipped because DATABASE_URL is not set")
return nil, func() {}, nil
}
// A consumer processes one record at a time and writes a dead letter
// only after its transaction ended, so it needs one connection.
poolSize := len(handlers)
if poolSize > math.MaxInt32 {
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - %d handlers exceed the pool size limit", poolSize)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, int32(poolSize))
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - create pool: %w", err)
}
store := postgres.NewEventConsumerStore(pool, settings.ConsumerHandlerTimeout)
consumers := make(eventConsumers, 0, len(handlers))
closers := make([]func(), 0, len(handlers))
cleanup := func() {
// The application stops every consumer before this runs, so no
// record is in progress while the members leave their groups. They
// leave in parallel, so shutdown waits for the slowest leave rather
// than for the sum of them.
var leaving sync.WaitGroup
for _, closeSource := range closers {
leaving.Go(closeSource)
}
leaving.Wait()
pool.Close()
}
names := make(map[string]bool, len(handlers))
for _, handler := range handlers {
name := handler.ConsumerName()
if names[name] {
cleanup()
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - consumer %s is registered twice", name)
}
names[name] = true
group := settings.ConsumerGroupPrefix + consumerGroupSeparator + name
consumerLogger := logger.With(
slog.String("component", "event_consumer"),
slog.String("topic", settings.KafkaEventsTopic),
slog.String("group", group),
)
source, closeSource, err := kafka.NewEventSource(settings, group, consumerLogger)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - create Kafka group member for %s: %w", name, err)
}
closers = append(closers, closeSource)
consumer, err := eventconsumer.New(handler, source, store, metrics, consumerLogger, consumerSettings(settings))
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - create consumer: %w", err)
}
consumers = append(consumers, consumer)
}
return consumers, cleanup, nil
}
func consumerSettings(settings config.Config) eventconsumer.Settings {
return eventconsumer.Settings{
MaxAttempts: settings.ConsumerMaxAttempts,
Backoff: retry.Backoff{
Initial: settings.ConsumerBackoffInitial,
Max: settings.ConsumerBackoffMax,
},
HandlerTimeout: settings.ConsumerHandlerTimeout,
CommitTimeout: settings.ConsumerCommitTimeout,
ShutdownGrace: settings.ConsumerShutdownGrace,
}
}
@@ -0,0 +1,206 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/eventconsumer"
)
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 consumerTestConfig(t *testing.T) config.Config {
t.Helper()
settings, err := config.LoadFromEnv(func(key string) (string, bool) {
value, ok := map[string]string{
"SEAWEEDFS_ACCESS_KEY": "test-access",
"SEAWEEDFS_SECRET_KEY": "test-secret",
"EMAIL_PROVIDER": "disabled",
"EMAIL_FROM": "no-reply@example.com",
"APP_PUBLIC_URL": "http://localhost:8080",
"DATABASE_URL": "postgres://app@127.0.0.1:1/app",
}[key]
return value, ok
})
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
return settings
}
func TestBuildEventConsumersSkipsWithoutWork(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
disabled := consumerTestConfig(t)
disabled.ConsumerEnabled = false
noDatabase := consumerTestConfig(t)
noDatabase.DatabaseURL = ""
tests := []struct {
name string
settings config.Config
handlers []inbound.EventHandler
}{
{name: "disabled", settings: disabled, handlers: []inbound.EventHandler{namedHandler("audit")}},
{name: "no handler registered", settings: consumerTestConfig(t)},
{name: "database not configured", settings: noDatabase, handlers: []inbound.EventHandler{namedHandler("audit")}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
consumers, cleanup, err := buildEventConsumers(t.Context(), test.settings, logger, prometheus.New(), test.handlers)
if err != nil {
t.Fatalf("buildEventConsumers() error = %v", err)
}
cleanup()
if len(consumers) != 0 {
t.Fatalf("buildEventConsumers() built %d consumers without work to do", len(consumers))
}
})
}
}
func TestBootstrapRegistersNoEventHandlerYet(t *testing.T) {
if handlers := eventHandlers(); len(handlers) != 0 {
t.Fatalf("eventHandlers() = %d handlers; update the documentation when the first consumer is registered", len(handlers))
}
}
func TestBuildEventConsumersBuildsOneConsumerPerHandler(t *testing.T) {
settings := consumerTestConfig(t)
consumers, cleanup, err := buildEventConsumers(t.Context(), settings, slog.New(slog.DiscardHandler), prometheus.New(),
[]inbound.EventHandler{namedHandler("audit"), namedHandler("search_index")})
if err != nil {
t.Fatalf("buildEventConsumers() error = %v", err)
}
// Nothing connected, so closing the group members returns at once.
closed := make(chan struct{})
go func() {
defer close(closed)
cleanup()
}()
select {
case <-closed:
case <-time.After(relayLifecycleTimeout):
t.Fatal("cleanup did not return")
}
if len(consumers) != 2 || consumers[0].Name() != "audit" || consumers[1].Name() != "search_index" {
t.Fatalf("buildEventConsumers() = %v, want audit and search_index", consumers)
}
}
func TestBuildEventConsumersRejectsInvalidRegistrations(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
tests := map[string][]inbound.EventHandler{
"duplicate name": {namedHandler("audit"), namedHandler("audit")},
"invalid name": {namedHandler("Audit-Log")},
}
for name, handlers := range tests {
t.Run(name, func(t *testing.T) {
_, _, err := buildEventConsumers(t.Context(), consumerTestConfig(t), logger, prometheus.New(), handlers)
if err == nil {
t.Fatal("buildEventConsumers() accepted an invalid registration")
}
})
}
}
func TestEventConsumerLabelsMatchThePreparedMetrics(t *testing.T) {
metrics := prometheus.New()
metrics.PrepareEventConsumer("audit")
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
body := response.Body.String()
for _, outcome := range []string{eventconsumer.OutcomeApplied, eventconsumer.OutcomeDuplicate, eventconsumer.OutcomeIgnored, eventconsumer.OutcomeDeadLettered} {
if want := `lincodex_event_consumer_records_total{consumer="audit",outcome="` + outcome + `"} 0`; !strings.Contains(body, want) {
t.Fatalf("metrics output is missing %s", want)
}
}
for _, stage := range []string{eventconsumer.StageHandler, eventconsumer.StageStore, eventconsumer.StagePoll, eventconsumer.StageCommit} {
if want := `lincodex_event_consumer_failures_total{consumer="audit",stage="` + stage + `"} 0`; !strings.Contains(body, want) {
t.Fatalf("metrics output is missing %s", want)
}
}
}
// blockingSource returns nothing and counts polls until ctx ends.
type blockingSource struct {
polls atomic.Int64
running atomic.Bool
}
func (source *blockingSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) {
source.polls.Add(1)
source.running.Store(true)
<-ctx.Done()
source.running.Store(false)
return nil, ctx.Err()
}
func (*blockingSource) Commit(context.Context, []outbound.ConsumedRecord) error { return nil }
func (*blockingSource) Release() {}
type unusedStore struct{}
func (unusedStore) ApplyOnce(context.Context, string, uuid.UUID, outbound.ApplyEvent) (bool, error) {
return false, nil
}
func (unusedStore) RecordDeadLetter(context.Context, outbound.DeadLetter) error { return nil }
func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) {
metrics := prometheus.New()
logger := slog.New(slog.DiscardHandler)
source := &blockingSource{}
settings := consumerSettings(consumerTestConfig(t))
consumer, err := eventconsumer.New(namedHandler("audit"), source, unusedStore{}, metrics, logger, settings)
if err != nil {
t.Fatalf("eventconsumer.New() error = %v", err)
}
application := NewApplication(config.Config{
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer})
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
finished := make(chan error, 1)
go func() { finished <- application.run(ctx) }()
deadline := time.Now().Add(relayLifecycleTimeout)
for source.polls.Load() < 1 {
if time.Now().After(deadline) {
t.Fatal("the consumer did not poll while the servers ran")
}
time.Sleep(time.Millisecond)
}
cancel()
select {
case err := <-finished:
if err != nil {
t.Fatalf("run() error = %v", err)
}
case <-time.After(relayLifecycleTimeout):
t.Fatal("run() did not return after cancellation")
}
// run returns only after the consumer stopped polling, so the cleanup
// that closes its group member never races a poll.
if source.running.Load() {
t.Fatal("the consumer was still polling after run() returned")
}
}
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/worker/outboxrelay"
"lincodex/backend/internal/worker/retry"
)
const (
@@ -71,7 +72,7 @@ func relaySettings(settings config.Config) outboxrelay.Settings {
return outboxrelay.Settings{
BatchSize: settings.RelayBatchSize,
PollInterval: settings.RelayPollInterval,
Backoff: outboxrelay.Backoff{
Backoff: retry.Backoff{
Initial: settings.RelayBackoffInitial,
Max: settings.RelayBackoffMax,
},
+3 -2
View File
@@ -12,6 +12,7 @@ import (
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/outboxrelay"
"lincodex/backend/internal/worker/retry"
)
const relayLifecycleTimeout = 5 * time.Second
@@ -67,7 +68,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
relay := outboxrelay.New(store, readyPublisher{}, metrics, logger, outboxrelay.Settings{
BatchSize: 1,
PollInterval: time.Millisecond,
Backoff: outboxrelay.Backoff{Initial: time.Millisecond, Max: time.Millisecond},
Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond},
ShutdownTimeout: time.Second,
BacklogInterval: time.Second,
})
@@ -75,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, relay)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -48,6 +48,7 @@ func initialize(
v1.NewDenyAllSecurity,
httpadapter.NewRouter,
newOutboxRelay,
newEventConsumers,
NewApplication,
),
)
+10 -1
View File
@@ -62,8 +62,17 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay)
bootstrapEventConsumers, cleanup5, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers)
return application, func() {
cleanup5()
cleanup4()
cleanup3()
cleanup2()
+4 -2
View File
@@ -69,7 +69,7 @@ type DomainEventInput struct {
// NewDomainEvent validates input and assigns a time-ordered UUIDv7 event ID.
// The stored payload is the compact form of input.Payload.
func NewDomainEvent(input DomainEventInput) (DomainEvent, error) {
if err := input.validateIdentity(); err != nil {
if err := input.ValidateIdentity(); err != nil {
return DomainEvent{}, err
}
payload, err := compactPayload(input.Payload)
@@ -91,7 +91,9 @@ func NewDomainEvent(input DomainEventInput) (DomainEvent, error) {
}, nil
}
func (input DomainEventInput) validateIdentity() error {
// ValidateIdentity checks every field except the payload. Event consumers
// use it to apply the same rules to an event read from the event bus.
func (input DomainEventInput) ValidateIdentity() error {
if len(input.EventType) > maxDomainEventTypeLength || !domainEventTypePattern.MatchString(input.EventType) {
return invalidDomainEvent("event type must be a lowercase dotted name of at most 128 bytes")
}
@@ -0,0 +1,34 @@
package inbound
import (
"context"
"errors"
"lincodex/backend/internal/port/outbound"
)
// ErrEventRejected marks a handler failure that a retry cannot fix, for
// example an unsupported schema_version or a payload that breaks the
// contract of its event type. The consumer dead-letters the event at once
// instead of retrying it.
var ErrEventRejected = errors.New("event rejected by handler")
// EventHandler applies domain events from the event bus to this service's
// own state. The consumer runtime calls Handle inside the transaction that
// records the event as processed, so the effect and the dedup marker commit
// together and a repeated delivery is skipped.
type EventHandler interface {
// ConsumerName is a stable snake_case name of at most 64 characters. It
// scopes deduplication and names the consumer group, so renaming it
// makes the consumer process every retained event again.
ConsumerName() string
// Handles reports whether the handler applies events of eventType.
// Other events are acknowledged without a transaction.
Handles(eventType string) bool
// Handle applies event with unit and the context it receives only. An
// error rolls back the effect and the marker. An error matching
// ErrEventRejected is final; any other error is retried with backoff a
// bounded number of times. Errors must not quote the payload or personal
// data, because the reason is logged and stored with the dead letter.
Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error
}
@@ -0,0 +1,137 @@
package outbound
import (
"context"
"encoding/json"
"errors"
"time"
"github.com/google/uuid"
)
var (
// ErrInvalidEventRecord reports a record on the event bus that is not a
// valid event envelope. Retrying cannot fix it.
ErrInvalidEventRecord = errors.New("invalid event record")
// ErrEventEffectRejected reports that PostgreSQL refused to commit the
// effect of a handler that returned nil: the handler ignored a failed
// statement, so the transaction was aborted, or a deferred integrity
// constraint (SQLSTATE class 23) failed at commit. Nothing was committed.
// The consumer counts it as a failed handler attempt, because the same
// event usually fails the same way again.
ErrEventEffectRejected = errors.New("event effect rejected by the database")
)
// ConsumedEvent is a domain event decoded from the event bus. It carries the
// fields that the relay published from the outbox row.
type ConsumedEvent struct {
EventID uuid.UUID
EventType string
SchemaVersion int32
AggregateType string
AggregateID uuid.UUID
// AggregateVersion orders the events of one aggregate. Delivery is at
// least once, so a late duplicate of an earlier version can arrive after
// a later version; a handler that keeps aggregate state ignores versions
// it has already passed.
AggregateVersion int64
// OccurredAt is the informational insert time of the outbox row.
OccurredAt time.Time
// Payload is the JSON object stored in the outbox row.
Payload json.RawMessage
}
// ConsumedRecord is one record read from the event bus, in partition order.
type ConsumedRecord struct {
Topic string
Partition int32
Offset int64
// Event is the decoded envelope. It is valid only when Invalid is nil.
Event ConsumedEvent
// Invalid reports a value that is not a valid event envelope. It matches
// ErrInvalidEventRecord and never quotes the value.
Invalid error
// EventID is the event ID of a valid record, or for an invalid record the
// value of its event_id header; uuid.Nil when neither is a UUID.
EventID uuid.UUID
// Value is the raw record value. It may hold personal data later, so it
// must not reach logs, errors, or metrics.
Value []byte
}
// EventSource reads the event bus as one member of a consumer group.
type EventSource interface {
// Poll waits for the next records, in partition order, and holds group
// rebalancing until Release. It may return records together with an
// error that reports fetch problems of other partitions. After ctx ends
// it returns ctx.Err().
Poll(ctx context.Context) ([]ConsumedRecord, error)
// Commit stores, for each partition, the position after the last of the
// finished records, so the group resumes after them. finished must be in
// partition order and must not skip a record of the last poll. A failed
// commit leaves the records to be delivered again.
Commit(ctx context.Context, finished []ConsumedRecord) error
// Release lets the group rebalance after the polled records were
// finished or abandoned. Every Poll is followed by one Release.
Release()
}
// ApplyEvent applies one event inside the transaction of its dedup marker.
type ApplyEvent func(ctx context.Context, unit UnitOfWork) error
// DeadLetter describes a record that a consumer could not apply.
type DeadLetter struct {
Consumer string
Topic string
Partition int32
Offset int64
// EventID is uuid.Nil when the record had no event ID.
EventID uuid.UUID
// EventType is empty for an invalid record.
EventType string
ErrorClass DeadLetterClass
// Reason is a short sanitized cause without the record value.
Reason string
Attempts int
ValueSize int
ValueSHA256 [32]byte
}
// DeadLetterClass is a bounded cause of a dead letter.
type DeadLetterClass string
const (
// DeadLetterInvalidRecord is a value that is not a valid event envelope.
DeadLetterInvalidRecord DeadLetterClass = "invalid_record"
// DeadLetterHandlerRejected is an event the handler can never apply.
DeadLetterHandlerRejected DeadLetterClass = "handler_rejected"
// DeadLetterHandlerPanic is an event whose handler panicked.
DeadLetterHandlerPanic DeadLetterClass = "handler_panic"
// DeadLetterRetriesExhausted is an event whose handler kept failing.
DeadLetterRetriesExhausted DeadLetterClass = "retries_exhausted"
)
// EventConsumerStore keeps the dedup markers and dead letters of consumers.
type EventConsumerStore interface {
// ApplyOnce opens a transaction, records that consumer processes eventID,
// runs apply in the same transaction, and commits. When the marker
// already exists it rolls back without calling apply and reports
// applied=false. A concurrent call for the same consumer and eventID
// waits until the first transaction ends: after its commit it reports a
// duplicate, after its rollback it applies the event itself.
//
// An error from apply rolls the transaction back and is returned with its
// identity; its text keeps no PostgreSQL message, which could quote row
// values. A commit that PostgreSQL refuses returns an error matching
// ErrEventEffectRejected, and a serialization failure or deadlock
// (SQLSTATE class 40) one matching ErrTransactionConflict. A network
// failure during commit leaves the outcome unknown; a retry is then
// either applied or reported as a duplicate.
ApplyOnce(ctx context.Context, consumer string, eventID uuid.UUID, apply ApplyEvent) (applied bool, err error)
// RecordDeadLetter stores letter. A letter for the same consumer, record
// position, and value replaces the outcome of the existing row; a
// different value at the same position, after the topic was recreated,
// gets its own row.
RecordDeadLetter(ctx context.Context, letter DeadLetter) error
}
@@ -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")
}
}