feat(outbox): relay committed outbox events to Kafka

This commit is contained in:
shira committed 2026-10-06 03:01:53 +03:00
1 parent 78f1651f6b
commit 6c3b34f73e
42 files changed
+3731 -45

No files matched your search

@@ -0,0 +1,181 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"strconv"
"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"
)
// OutboxRelayStore implements outbound.OutboxRelayStore with a pgx pool owned
// by the caller. Each claim holds one connection and one transaction for the
// duration of the publish callback.
type OutboxRelayStore struct {
pool *pgxpool.Pool
timeouts OutboxRelayTimeouts
}
// OutboxRelayTimeouts bound the claim transaction on the PostgreSQL server.
//
// The relay context already cancels a pass whose client is alive. These
// limits are set with SET LOCAL at the start of the transaction because they
// also hold when the client cannot act: a frozen process, or a network path
// that drops without closing the connection, would otherwise keep the row
// locks and an open transaction until TCP keepalive notices, which delays
// other relays and vacuum.
type OutboxRelayTimeouts struct {
// Statement bounds every statement of the claim (statement_timeout).
Statement time.Duration
// IdleInTransaction bounds the gap between statements, which is the
// publish call (idle_in_transaction_session_timeout). It must exceed the
// publish deadline, or a slow but successful publish loses its mark.
IdleInTransaction time.Duration
}
func NewOutboxRelayStore(pool *pgxpool.Pool, timeouts OutboxRelayTimeouts) *OutboxRelayStore {
return &OutboxRelayStore{pool: pool, timeouts: timeouts}
}
var _ outbound.OutboxRelayStore = (*OutboxRelayStore)(nil)
func (store *OutboxRelayStore) ClaimPending(ctx context.Context, limit int, publish outbound.PublishOutboxBatch) error {
if limit <= 0 || limit > math.MaxInt32 {
return fmt.Errorf("OutboxRelayStore.ClaimPending - limit must be between 1 and %d", math.MaxInt32)
}
// PostgreSQL reads 0 as no limit, so a value below one millisecond would
// silently remove the bound.
if store.timeouts.Statement < time.Millisecond || store.timeouts.IdleInTransaction < time.Millisecond {
return errors.New("OutboxRelayStore.ClaimPending - statement and idle timeouts must be at least 1ms")
}
tx, err := store.pool.BeginTx(ctx, transactionOptions)
if err != nil {
return fmt.Errorf("OutboxRelayStore.ClaimPending - begin transaction: %w", sanitizeConnectError(err))
}
finished := false
defer func() {
// Runs only when publish panics; the panic keeps its stack and the
// rollback error cannot change that outcome.
if !finished {
_ = rollback(ctx, tx)
}
}()
claimErr := claimPending(ctx, tx, int32(limit), store.timeouts, publish)
finished = true
if claimErr != nil {
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
return errors.Join(claimErr, fmt.Errorf("OutboxRelayStore.ClaimPending - roll back transaction: %w", rollbackErr))
}
return claimErr
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("OutboxRelayStore.ClaimPending - commit transaction: %w", relayDatabaseError(err))
}
return nil
}
func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRelayTimeouts, publish outbound.PublishOutboxBatch) error {
queries := sqlc.New(tx)
err := queries.SetRelayTransactionTimeouts(ctx, sqlc.SetRelayTransactionTimeoutsParams{
StatementTimeoutMs: milliseconds(timeouts.Statement),
IdleTimeoutMs: milliseconds(timeouts.IdleInTransaction),
})
if err != nil {
return fmt.Errorf("postgres.claimPending - set transaction timeouts: %w", relayDatabaseError(err))
}
rows, err := queries.LockPendingOutboxEvents(ctx, limit)
if err != nil {
return fmt.Errorf("postgres.claimPending - lock pending events: %w", relayDatabaseError(err))
}
if len(rows) == 0 {
return nil
}
events := make([]outbound.OutboxEvent, 0, len(rows))
claimed := make(map[uuid.UUID]bool, len(rows))
for _, row := range rows {
event := outboxEventFromRow(row)
events = append(events, event)
claimed[event.EventID] = true
}
acknowledged := publish(ctx, events)
marked := make([]pgtype.UUID, 0, len(acknowledged))
seen := make(map[uuid.UUID]bool, len(acknowledged))
for _, eventID := range acknowledged {
// An ID outside the batch could be locked by another relay, and the
// update would wait for it, so it is a caller error.
if !claimed[eventID] {
return errors.New("postgres.claimPending - acknowledged event is not in the claimed batch")
}
if seen[eventID] {
continue
}
seen[eventID] = true
marked = append(marked, pgtype.UUID{Bytes: eventID, Valid: true})
}
if len(marked) == 0 {
return nil
}
count, err := queries.MarkOutboxEventsPublished(ctx, marked)
if err != nil {
return fmt.Errorf("postgres.claimPending - mark published events: %w", relayDatabaseError(err))
}
if count != int64(len(marked)) {
return fmt.Errorf("postgres.claimPending - marked %d events, want %d", count, len(marked))
}
return nil
}
// Backlog reads the pending count and the age of the earliest pending event.
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{
Pending: row.PendingEvents,
OldestAge: time.Duration(row.OldestPendingAgeSeconds * float64(time.Second)),
}, nil
}
// milliseconds formats a duration as a PostgreSQL time setting in
// milliseconds, the unit set_config assumes for these parameters.
func milliseconds(duration time.Duration) string {
return strconv.FormatInt(duration.Milliseconds(), 10)
}
func outboxEventFromRow(row sqlc.LockPendingOutboxEventsRow) outbound.OutboxEvent {
return outbound.OutboxEvent{
EventID: row.EventID.Bytes,
EventType: row.EventType,
SchemaVersion: row.SchemaVersion,
AggregateType: row.AggregateType,
AggregateID: row.AggregateID.Bytes,
AggregateVersion: row.AggregateVersion,
Payload: json.RawMessage(row.Payload),
OccurredAt: row.OccurredAt.Time,
}
}
// 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 {
var pgError *pgconn.PgError
if errors.As(err, &pgError) {
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
return sanitizeConnectError(err)
}
@@ -0,0 +1,57 @@
package postgres
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/port/outbound"
)
func TestClaimPendingRejectsAnInvalidLimitBeforeTheDatabase(t *testing.T) {
// A nil pool proves that validation happens before any connection.
valid := OutboxRelayTimeouts{Statement: time.Second, IdleInTransaction: time.Second}
publish := func(context.Context, []outbound.OutboxEvent) []uuid.UUID {
t.Fatal("publish called for an invalid claim")
return nil
}
store := NewOutboxRelayStore(nil, valid)
for _, limit := range []int{0, -1, 1 << 31} {
if err := store.ClaimPending(t.Context(), limit, publish); err == nil {
t.Fatalf("ClaimPending(limit %d) accepted the limit", limit)
}
}
// A timeout that rounds to 0 ms would disable the server-side bound.
for _, timeouts := range []OutboxRelayTimeouts{
{Statement: time.Microsecond, IdleInTransaction: time.Second},
{Statement: time.Second},
} {
if err := NewOutboxRelayStore(nil, timeouts).ClaimPending(t.Context(), 1, publish); err == nil {
t.Fatalf("ClaimPending() accepted timeouts %+v", timeouts)
}
}
}
func TestRelayDatabaseErrorKeepsOnlyTheSQLState(t *testing.T) {
original := &pgconn.PgError{
Code: "22P02",
Message: `invalid input syntax for type json: "secret-payload"`,
Detail: `Token "secret-payload" is invalid.`,
}
err := relayDatabaseError(original)
if strings.Contains(err.Error(), "secret-payload") {
t.Fatalf("relayDatabaseError() kept the message: %v", err)
}
var stateError sqlStateError
if !errors.As(err, &stateError) || stateError.SQLState() != "22P02" {
t.Fatalf("relayDatabaseError() = %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)
}
}
@@ -15,11 +15,9 @@ import (
// requires the database before serving. The caller owns the pool and must
// close it.
func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
poolConfig, err := pgxpool.ParseConfig(databaseURL)
poolConfig, err := parsePoolConfig(databaseURL)
if err != nil {
// pgx redacts passwords only on a best-effort basis, so the parse error
// is not wrapped to keep the connection string out of logs.
return nil, errors.New("postgres.NewPool - DATABASE_URL is not a valid PostgreSQL connection string")
return nil, err
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
@@ -28,6 +26,35 @@ func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
return pool, nil
}
// NewSizedPool is NewPool with at most maxConns connections, for a component
// whose concurrency is known, so it cannot take connections that request
// handling needs.
func NewSizedPool(ctx context.Context, databaseURL string, maxConns int32) (*pgxpool.Pool, error) {
if maxConns < 1 {
return nil, errors.New("postgres.NewSizedPool - maxConns must be positive")
}
poolConfig, err := parsePoolConfig(databaseURL)
if err != nil {
return nil, err
}
poolConfig.MaxConns = maxConns
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("postgres.NewSizedPool - create PostgreSQL pool: %w", err)
}
return pool, nil
}
func parsePoolConfig(databaseURL string) (*pgxpool.Config, error) {
poolConfig, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
// pgx redacts passwords only on a best-effort basis, so the parse error
// is not wrapped to keep the connection string out of logs.
return nil, errors.New("postgres.parsePoolConfig - DATABASE_URL is not a valid PostgreSQL connection string")
}
return poolConfig, nil
}
// sanitizeConnectError drops the pgx connection prefix, which names the
// database user and database, while keeping the network or server cause.
func sanitizeConnectError(err error) error {
@@ -11,6 +11,38 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const getOutboxBacklog = `-- name: GetOutboxBacklog :one
SELECT
(
SELECT count(*)
FROM outbox_events AS pending
WHERE pending.published_at IS NULL
)::bigint AS pending_events,
coalesce((
SELECT extract(EPOCH FROM clock_timestamp() - oldest.occurred_at)
FROM outbox_events AS oldest
WHERE oldest.published_at IS NULL
ORDER BY oldest.position
LIMIT 1
), 0)::float8 AS oldest_pending_age_seconds
`
type GetOutboxBacklogRow struct {
PendingEvents int64
OldestPendingAgeSeconds float64
}
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
// clock that set occurred_at.
func (q *Queries) GetOutboxBacklog(ctx context.Context) (GetOutboxBacklogRow, error) {
row := q.db.QueryRow(ctx, getOutboxBacklog)
var i GetOutboxBacklogRow
err := row.Scan(&i.PendingEvents, &i.OldestPendingAgeSeconds)
return i, err
}
const insertOutboxEvent = `-- name: InsertOutboxEvent :exec
INSERT INTO outbox_events (
event_id,
@@ -53,3 +85,124 @@ func (q *Queries) InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventPa
)
return err
}
const lockPendingOutboxEvents = `-- name: LockPendingOutboxEvents :many
SELECT
pending.event_id,
pending.event_type,
pending.schema_version,
pending.aggregate_type,
pending.aggregate_id,
pending.aggregate_version,
pending.payload,
pending.occurred_at
FROM outbox_events AS pending
WHERE
pending.published_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM outbox_events AS earlier
WHERE
earlier.aggregate_type = pending.aggregate_type
AND earlier.aggregate_id = pending.aggregate_id
AND earlier.published_at IS NULL
AND (earlier.aggregate_version, earlier.position)
< (pending.aggregate_version, pending.position)
)
ORDER BY pending.position
LIMIT $1
FOR UPDATE OF pending SKIP LOCKED
`
type LockPendingOutboxEventsRow struct {
EventID pgtype.UUID
EventType string
SchemaVersion int32
AggregateType string
AggregateID pgtype.UUID
AggregateVersion int64
Payload []byte
OccurredAt pgtype.Timestamptz
}
// Locks the next relay batch. For each aggregate only its earliest unpublished
// event (lowest aggregate_version, then position) qualifies, so a relay never
// holds a later version while an earlier one is still pending, whether that
// earlier row is locked by another relay or was just rolled back. Rows locked
// by another relay are skipped without waiting. The statement snapshot can
// only see a later version after the earlier version's transaction committed,
// because aggregate writers check the expected version, so scanning without a
// position watermark cannot overtake an earlier version.
func (q *Queries) LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error) {
rows, err := q.db.Query(ctx, lockPendingOutboxEvents, batchLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []LockPendingOutboxEventsRow
for rows.Next() {
var i LockPendingOutboxEventsRow
if err := rows.Scan(
&i.EventID,
&i.EventType,
&i.SchemaVersion,
&i.AggregateType,
&i.AggregateID,
&i.AggregateVersion,
&i.Payload,
&i.OccurredAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const markOutboxEventsPublished = `-- name: MarkOutboxEventsPublished :execrows
UPDATE outbox_events
SET published_at = clock_timestamp()
WHERE
event_id = ANY($1::uuid [])
AND published_at IS NULL
`
// Marks the events that the broker acknowledged. The relay passes only IDs
// whose rows its own transaction locked, so the statement never waits and the
// count equals the number of distinct IDs.
func (q *Queries) MarkOutboxEventsPublished(ctx context.Context, eventIds []pgtype.UUID) (int64, error) {
result, err := q.db.Exec(ctx, markOutboxEventsPublished, eventIds)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const setRelayTransactionTimeouts = `-- name: SetRelayTransactionTimeouts :exec
SELECT
set_config('statement_timeout', $1::text, true),
set_config(
'idle_in_transaction_session_timeout',
$2::text,
true
)
`
type SetRelayTransactionTimeoutsParams struct {
StatementTimeoutMs string
IdleTimeoutMs string
}
// 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
// stays silent longer than a publish may take, for example after the process
// froze or lost the network without closing the connection. Both settings
// are local to the transaction.
func (q *Queries) SetRelayTransactionTimeouts(ctx context.Context, arg SetRelayTransactionTimeoutsParams) error {
_, err := q.db.Exec(ctx, setRelayTransactionTimeouts, arg.StatementTimeoutMs, arg.IdleTimeoutMs)
return err
}
@@ -41,6 +41,11 @@ type Querier interface {
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
// clock that set occurred_at.
GetOutboxBacklog(ctx context.Context) (GetOutboxBacklogRow, error)
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)
@@ -55,6 +60,19 @@ type Querier interface {
InsertSession(ctx context.Context, arg InsertSessionParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
// Locks the next relay batch. For each aggregate only its earliest unpublished
// event (lowest aggregate_version, then position) qualifies, so a relay never
// holds a later version while an earlier one is still pending, whether that
// earlier row is locked by another relay or was just rolled back. Rows locked
// by another relay are skipped without waiting. The statement snapshot can
// only see a later version after the earlier version's transaction committed,
// because aggregate writers check the expected version, so scanning without a
// position watermark cannot overtake an earlier version.
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
// Marks the events that the broker acknowledged. The relay passes only IDs
// whose rows its own transaction locked, so the statement never waits and the
// count equals the number of distinct IDs.
MarkOutboxEventsPublished(ctx context.Context, eventIds []pgtype.UUID) (int64, error)
// Verifies the email only for the registration version the consumed token
// was issued for.
MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error)
@@ -64,6 +82,13 @@ 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 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
// stays silent longer than a publish may take, for example after the process
// froze or lost the network without closing the connection. Both settings
// are local to the transaction.
SetRelayTransactionTimeouts(ctx context.Context, arg SetRelayTransactionTimeoutsParams) error
// Records activity on an active session and reports whether it is active.
// The row is written only when last_seen_at is older than touch_cutoff, so
// frequent requests do not rewrite it. last_seen_at never moves back, and a