183 lines
6.6 KiB
Go
183 lines
6.6 KiB
Go
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", sanitizedDatabaseError(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", sanitizedDatabaseError(err))
|
|
}
|
|
rows, err := queries.LockPendingOutboxEvents(ctx, limit)
|
|
if err != nil {
|
|
return fmt.Errorf("postgres.claimPending - lock pending events: %w", sanitizedDatabaseError(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", sanitizedDatabaseError(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", sanitizedDatabaseError(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,
|
|
}
|
|
}
|
|
|
|
// 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})
|
|
}
|
|
return sanitizeConnectError(err)
|
|
}
|