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,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
}