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 { return classifyCommitRefusal(err, outbound.ErrEventEffectRejected) } // classifyCommitRefusal is classifyCommitError with the sentinel that a // refused commit matches, so the scheduled job store applies the same rules // with its own port error. func classifyCommitRefusal(err, rejected error) error { if errors.Is(err, pgx.ErrTxCommitRollback) { return fmt.Errorf("postgres.classifyCommitRefusal - transaction was aborted by a failed statement: %w", rejected) } 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.classifyCommitRefusal - %w: %w", rejected, safe) case transactionRollbackClass: return fmt.Errorf("postgres.classifyCommitRefusal - %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 }