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