feat(backend): add transactional outbox and embedded goose migrations
This commit is contained in:
1 parent
653f3775f8
commit
15e2e50561
40 files changed
+2471
-67
No files matched your search
@@ -21,13 +21,9 @@ func NewHealthChecker(ctx context.Context, config config.Config) (*HealthChecker
|
||||
return &HealthChecker{}, func() {}, nil
|
||||
}
|
||||
|
||||
poolConfig, err := pgxpool.ParseConfig(config.DatabaseURL)
|
||||
pool, err := NewPool(ctx, config.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("postgres.NewHealthChecker - parse DATABASE_URL: %w", err)
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("postgres.NewHealthChecker - create PostgreSQL pool: %w", err)
|
||||
return nil, nil, fmt.Errorf("postgres.NewHealthChecker - create pool: %w", err)
|
||||
}
|
||||
|
||||
return &HealthChecker{pool: pool, queries: sqlc.New(pool)}, pool.Close, nil
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// TransactionForIntegrationTest exposes the transaction behind a unit of work
|
||||
// to integration tests that write test-only tables. It is compiled only with
|
||||
// the integration build tag and is not part of the adapter API.
|
||||
func TransactionForIntegrationTest(unit outbound.UnitOfWork) (pgx.Tx, bool) {
|
||||
postgresUnit, ok := unit.(*UnitOfWork)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return postgresUnit.tx, true
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"path"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/pressly/goose/v3/lock"
|
||||
)
|
||||
|
||||
const (
|
||||
// The session advisory lock is retried once per second for up to five
|
||||
// minutes, so instances that start together apply migrations one at a time.
|
||||
migrationLockRetryPeriodSeconds = 1
|
||||
migrationLockRetryAttempts = 300
|
||||
|
||||
// migrationLockTimeout makes a DDL statement fail fast instead of queueing
|
||||
// behind long transactions while it blocks every later query on the table.
|
||||
migrationLockTimeout = 10 * time.Second
|
||||
// migrationStatementTimeout bounds one migration statement. It stays below
|
||||
// the five-minute startup limit so a slow statement reports its own error.
|
||||
migrationStatementTimeout = 4 * time.Minute
|
||||
)
|
||||
|
||||
// ErrNoMigrationToRollBack reports that no applied migration is left.
|
||||
var ErrNoMigrationToRollBack = errors.New("no applied migration to roll back")
|
||||
|
||||
// MigrationResult describes one applied or rolled back migration.
|
||||
type MigrationResult struct {
|
||||
Version int64
|
||||
Name string
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
// MigrationStatus describes one known migration.
|
||||
type MigrationStatus struct {
|
||||
Version int64
|
||||
Name string
|
||||
Applied bool
|
||||
AppliedAt time.Time
|
||||
}
|
||||
|
||||
// Migrator applies goose SQL migrations through database/sql with the pgx
|
||||
// driver. A PostgreSQL session advisory lock serializes concurrent runs.
|
||||
type Migrator struct {
|
||||
provider *goose.Provider
|
||||
}
|
||||
|
||||
// NewMigrator does not connect until a migration operation runs. The caller
|
||||
// must call Close.
|
||||
func NewMigrator(databaseURL string, migrations fs.FS) (*Migrator, error) {
|
||||
connConfig, err := migrationConnConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
locker, err := lock.NewPostgresSessionLocker(
|
||||
lock.WithLockTimeout(migrationLockRetryPeriodSeconds, migrationLockRetryAttempts),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("postgres.NewMigrator - create session locker: %w", err)
|
||||
}
|
||||
database := stdlib.OpenDB(*connConfig)
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, database, migrations,
|
||||
goose.WithSessionLocker(locker),
|
||||
goose.WithDisableGlobalRegistry(true),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("postgres.NewMigrator - load migrations: %w", err)
|
||||
if closeErr := database.Close(); closeErr != nil {
|
||||
err = errors.Join(err, fmt.Errorf("postgres.NewMigrator - close migration database: %w", closeErr))
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &Migrator{provider: provider}, nil
|
||||
}
|
||||
|
||||
// migrationConnConfig parses databaseURL and sets session timeouts for every
|
||||
// migration connection.
|
||||
func migrationConnConfig(databaseURL string) (*pgx.ConnConfig, error) {
|
||||
connConfig, err := pgx.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.migrationConnConfig - DATABASE_URL is not a valid PostgreSQL connection string")
|
||||
}
|
||||
connConfig.RuntimeParams["lock_timeout"] = strconv.FormatInt(migrationLockTimeout.Milliseconds(), 10)
|
||||
connConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(migrationStatementTimeout.Milliseconds(), 10)
|
||||
return connConfig, nil
|
||||
}
|
||||
|
||||
// Up applies every pending migration and returns them in order.
|
||||
func (migrator *Migrator) Up(ctx context.Context) ([]MigrationResult, error) {
|
||||
results, err := migrator.provider.Up(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Migrator.Up - apply migrations: %w", sanitizeConnectError(err))
|
||||
}
|
||||
applied := make([]MigrationResult, 0, len(results))
|
||||
for _, result := range results {
|
||||
applied = append(applied, newMigrationResult(result))
|
||||
}
|
||||
return applied, nil
|
||||
}
|
||||
|
||||
// DownOne rolls back the most recently applied migration. It returns
|
||||
// ErrNoMigrationToRollBack when the schema is already at version zero.
|
||||
func (migrator *Migrator) DownOne(ctx context.Context) (MigrationResult, error) {
|
||||
result, err := migrator.provider.Down(ctx)
|
||||
if errors.Is(err, goose.ErrNoNextVersion) {
|
||||
return MigrationResult{}, fmt.Errorf("Migrator.DownOne - roll back migration: %w", ErrNoMigrationToRollBack)
|
||||
}
|
||||
if err != nil {
|
||||
return MigrationResult{}, fmt.Errorf("Migrator.DownOne - roll back migration: %w", sanitizeConnectError(err))
|
||||
}
|
||||
return newMigrationResult(result), nil
|
||||
}
|
||||
|
||||
// Status lists every embedded migration with its database state.
|
||||
func (migrator *Migrator) Status(ctx context.Context) ([]MigrationStatus, error) {
|
||||
statuses, err := migrator.provider.Status(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Migrator.Status - read migration status: %w", sanitizeConnectError(err))
|
||||
}
|
||||
result := make([]MigrationStatus, 0, len(statuses))
|
||||
for _, status := range statuses {
|
||||
result = append(result, MigrationStatus{
|
||||
Version: status.Source.Version,
|
||||
Name: path.Base(status.Source.Path),
|
||||
Applied: status.State == goose.StateApplied,
|
||||
AppliedAt: status.AppliedAt,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Close releases the migration connections.
|
||||
func (migrator *Migrator) Close() error {
|
||||
if err := migrator.provider.Close(); err != nil {
|
||||
return fmt.Errorf("Migrator.Close - close migration database: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newMigrationResult(result *goose.MigrationResult) MigrationResult {
|
||||
return MigrationResult{
|
||||
Version: result.Source.Version,
|
||||
Name: path.Base(result.Source.Path),
|
||||
Duration: result.Duration,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/db"
|
||||
)
|
||||
|
||||
// unreachableDatabaseURL points at a closed local port. The tests below never
|
||||
// need a server: constructors do not connect, and the connect test expects a
|
||||
// refusal.
|
||||
const unreachableDatabaseURL = "postgres://migrator:migration-secret@127.0.0.1:1/app?sslmode=disable&connect_timeout=2"
|
||||
|
||||
func TestNewMigratorLoadsEmbeddedMigrationsWithoutConnecting(t *testing.T) {
|
||||
migrations, err := db.Migrations()
|
||||
if err != nil {
|
||||
t.Fatalf("db.Migrations() error = %v", err)
|
||||
}
|
||||
migrator, err := NewMigrator(unreachableDatabaseURL, migrations)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMigrator() rejected the embedded migrations: %v", err)
|
||||
}
|
||||
if err := migrator.Close(); err != nil {
|
||||
t.Fatalf("Close() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMigratorRejectsDuplicateVersions(t *testing.T) {
|
||||
migrations := fstest.MapFS{
|
||||
"00001_first.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n-- +goose Down\nSELECT 1;\n")},
|
||||
"00001_second.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n-- +goose Down\nSELECT 1;\n")},
|
||||
}
|
||||
if migrator, err := NewMigrator(unreachableDatabaseURL, migrations); err == nil {
|
||||
_ = migrator.Close()
|
||||
t.Fatal("NewMigrator() accepted two migrations with the same version")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationConnConfigSetsSessionTimeouts(t *testing.T) {
|
||||
connConfig, err := migrationConnConfig(unreachableDatabaseURL)
|
||||
if err != nil {
|
||||
t.Fatalf("migrationConnConfig() error = %v", err)
|
||||
}
|
||||
for name, want := range map[string]time.Duration{
|
||||
"lock_timeout": migrationLockTimeout,
|
||||
"statement_timeout": migrationStatementTimeout,
|
||||
} {
|
||||
got, err := time.ParseDuration(connConfig.RuntimeParams[name] + "ms")
|
||||
if err != nil || got != want {
|
||||
t.Fatalf("%s = %q, want %s", name, connConfig.RuntimeParams[name], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationConnConfigHidesInvalidURL(t *testing.T) {
|
||||
const password = "parse-secret"
|
||||
_, err := migrationConnConfig("postgres://app:" + password + "@db:not-a-port/app")
|
||||
if err == nil {
|
||||
t.Fatal("migrationConnConfig() accepted an invalid URL")
|
||||
}
|
||||
if strings.Contains(err.Error(), password) {
|
||||
t.Fatalf("migrationConnConfig() error exposes the password: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeConnectErrorDropsConnectionIdentity(t *testing.T) {
|
||||
_, connectErr := pgconn.Connect(t.Context(), unreachableDatabaseURL)
|
||||
var original *pgconn.ConnectError
|
||||
if !errors.As(connectErr, &original) {
|
||||
t.Fatalf("pgconn.Connect() error = %v, want *pgconn.ConnectError", connectErr)
|
||||
}
|
||||
err := sanitizeConnectError(connectErr)
|
||||
for _, secret := range []string{"user=", "migrator", "migration-secret", "database=app"} {
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("sanitizeConnectError() = %v, still contains %q", err, secret)
|
||||
}
|
||||
}
|
||||
if !errors.Is(err, original.Unwrap()) {
|
||||
t.Fatalf("sanitizeConnectError() = %v, lost the network cause", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeConnectErrorKeepsOtherErrors(t *testing.T) {
|
||||
original := errors.New("relation does not exist")
|
||||
if err := sanitizeConnectError(original); err != original { //nolint:errorlint // Identity is the property under test.
|
||||
t.Fatalf("sanitizeConnectError() = %v, want the original error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
uniqueViolationCode = "23505"
|
||||
|
||||
outboxPrimaryKeyConstraint = "outbox_events_pkey"
|
||||
outboxAggregateVersionConstraint = "outbox_events_aggregate_version_event_type_key"
|
||||
)
|
||||
|
||||
type outboxWriter struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (writer outboxWriter) Append(ctx context.Context, events ...domain.DomainEvent) error {
|
||||
for _, event := range events {
|
||||
if event.EventID() == uuid.Nil {
|
||||
return fmt.Errorf("outboxWriter.Append - event was not built by domain.NewDomainEvent: %w", domain.ErrInvalidDomainEvent)
|
||||
}
|
||||
err := writer.queries.InsertOutboxEvent(ctx, sqlc.InsertOutboxEventParams{
|
||||
EventID: pgtype.UUID{Bytes: event.EventID(), Valid: true},
|
||||
EventType: event.EventType(),
|
||||
SchemaVersion: event.SchemaVersion(),
|
||||
AggregateType: event.AggregateType(),
|
||||
AggregateID: pgtype.UUID{Bytes: event.AggregateID(), Valid: true},
|
||||
AggregateVersion: event.AggregateVersion(),
|
||||
Payload: event.Payload(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("outboxWriter.Append - insert outbox event: %w", mapOutboxError(err))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mapOutboxError turns outbox uniqueness violations into a port sentinel that
|
||||
// keeps the constraint name. Other errors pass through; PostgreSQL error text
|
||||
// does not include key values.
|
||||
func mapOutboxError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) || pgError.Code != uniqueViolationCode {
|
||||
return err
|
||||
}
|
||||
switch pgError.ConstraintName {
|
||||
case outboxPrimaryKeyConstraint, outboxAggregateVersionConstraint:
|
||||
return fmt.Errorf("postgres.mapOutboxError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrOutboxEventConflict)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestMapOutboxErrorRecognizesOutboxConflicts(t *testing.T) {
|
||||
for _, constraint := range []string{outboxPrimaryKeyConstraint, outboxAggregateVersionConstraint} {
|
||||
err := mapOutboxError(&pgconn.PgError{Code: uniqueViolationCode, ConstraintName: constraint})
|
||||
if !errors.Is(err, outbound.ErrOutboxEventConflict) {
|
||||
t.Fatalf("mapOutboxError(%s) = %v, want ErrOutboxEventConflict", constraint, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), constraint) {
|
||||
t.Fatalf("mapOutboxError(%s) = %v, want the constraint name in the message", constraint, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapOutboxErrorKeepsOtherErrors(t *testing.T) {
|
||||
tests := []error{
|
||||
&pgconn.PgError{Code: uniqueViolationCode, ConstraintName: "other_table_key"},
|
||||
&pgconn.PgError{Code: "23514", ConstraintName: "outbox_events_schema_version_positive"},
|
||||
errors.New("connection reset"),
|
||||
}
|
||||
for _, original := range tests {
|
||||
if err := mapOutboxError(original); err != original { //nolint:errorlint // Identity is the property under test.
|
||||
t.Fatalf("mapOutboxError(%v) = %v, want the original error", original, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendRejectsZeroValueEventBeforeTheDatabase(t *testing.T) {
|
||||
// A nil query set proves that validation happens before any statement.
|
||||
err := outboxWriter{}.Append(t.Context(), domain.DomainEvent{})
|
||||
if !errors.Is(err, domain.ErrInvalidDomainEvent) {
|
||||
t.Fatalf("Append() error = %v, want ErrInvalidDomainEvent", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// NewPool creates a connection pool without opening a connection; the pool
|
||||
// connects lazily on first use, so constructing it never waits for the
|
||||
// database. Startup migrations, not the pool, decide whether the service
|
||||
// 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)
|
||||
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")
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("postgres.NewPool - create PostgreSQL pool: %w", err)
|
||||
}
|
||||
return pool, 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 {
|
||||
var connectError *pgconn.ConnectError
|
||||
if !errors.As(err, &connectError) {
|
||||
return err
|
||||
}
|
||||
if cause := connectError.Unwrap(); cause != nil {
|
||||
return fmt.Errorf("postgres.sanitizeConnectError - connect to PostgreSQL: %w", cause)
|
||||
}
|
||||
return errors.New("postgres.sanitizeConnectError - connect to PostgreSQL failed")
|
||||
}
|
||||
@@ -3,3 +3,20 @@
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type OutboxEvent struct {
|
||||
Position pgtype.Int8
|
||||
EventID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
AggregateType string
|
||||
AggregateID pgtype.UUID
|
||||
AggregateVersion int64
|
||||
Payload []byte
|
||||
OccurredAt pgtype.Timestamptz
|
||||
PublishedAt pgtype.Timestamptz
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: outbox.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const insertOutboxEvent = `-- name: InsertOutboxEvent :exec
|
||||
INSERT INTO outbox_events (
|
||||
event_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
aggregate_type,
|
||||
aggregate_id,
|
||||
aggregate_version,
|
||||
payload
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7
|
||||
)
|
||||
`
|
||||
|
||||
type InsertOutboxEventParams struct {
|
||||
EventID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
AggregateType string
|
||||
AggregateID pgtype.UUID
|
||||
AggregateVersion int64
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
func (q *Queries) InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error {
|
||||
_, err := q.db.Exec(ctx, insertOutboxEvent,
|
||||
arg.EventID,
|
||||
arg.EventType,
|
||||
arg.SchemaVersion,
|
||||
arg.AggregateType,
|
||||
arg.AggregateID,
|
||||
arg.AggregateVersion,
|
||||
arg.Payload,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
|
||||
Ping(ctx context.Context) (int32, error)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// rollbackTimeout bounds a rollback that runs after the caller's context may
|
||||
// already be canceled.
|
||||
const rollbackTimeout = 5 * time.Second
|
||||
|
||||
// transactionOptions selects READ COMMITTED explicitly. Outbox writes are
|
||||
// inserts guarded by unique constraints, and aggregate updates are expected to
|
||||
// use optimistic version checks in their WHERE clause, so stricter isolation
|
||||
// would only add serialization retries to every caller. A usecase that needs
|
||||
// SERIALIZABLE should get an explicit option rather than a silent default.
|
||||
var transactionOptions = pgx.TxOptions{
|
||||
IsoLevel: pgx.ReadCommitted,
|
||||
AccessMode: pgx.ReadWrite,
|
||||
}
|
||||
|
||||
// Transactor implements outbound.Transactor with a pgx pool owned by the caller.
|
||||
type Transactor struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewTransactor(pool *pgxpool.Pool) *Transactor {
|
||||
return &Transactor{pool: pool}
|
||||
}
|
||||
|
||||
var _ outbound.Transactor = (*Transactor)(nil)
|
||||
|
||||
// transactionContextKey marks a context passed to a transaction callback so a
|
||||
// nested WithinTransaction call fails instead of opening a second connection.
|
||||
type transactionContextKey struct{}
|
||||
|
||||
func (transactor *Transactor) WithinTransaction(
|
||||
ctx context.Context,
|
||||
fn func(ctx context.Context, unit outbound.UnitOfWork) error,
|
||||
) error {
|
||||
if ctx.Value(transactionContextKey{}) != nil {
|
||||
return fmt.Errorf("Transactor.WithinTransaction - begin transaction: %w", outbound.ErrNestedTransaction)
|
||||
}
|
||||
tx, err := transactor.pool.BeginTx(ctx, transactionOptions)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Transactor.WithinTransaction - begin transaction: %w", sanitizeConnectError(err))
|
||||
}
|
||||
finished := false
|
||||
defer func() {
|
||||
// Runs only when fn panics or calls runtime.Goexit. Not recovering
|
||||
// keeps the original panic and its stack; the rollback error cannot
|
||||
// change that outcome.
|
||||
if !finished {
|
||||
_ = rollback(ctx, tx)
|
||||
}
|
||||
}()
|
||||
|
||||
fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)})
|
||||
finished = true
|
||||
if fnErr != nil {
|
||||
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
|
||||
return errors.Join(fnErr, fmt.Errorf("Transactor.WithinTransaction - roll back transaction: %w", rollbackErr))
|
||||
}
|
||||
return fnErr
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
// pgx reports pgx.ErrTxCommitRollback when fn ignored a statement error
|
||||
// and PostgreSQL rolled the aborted transaction back instead. After a
|
||||
// network error the commit outcome is unknown; see outbound.Transactor.
|
||||
return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func rollback(ctx context.Context, tx pgx.Tx) error {
|
||||
rollbackContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), rollbackTimeout)
|
||||
defer cancel()
|
||||
if err := tx.Rollback(rollbackContext); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
|
||||
return fmt.Errorf("postgres.rollback - roll back: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnitOfWork binds repositories to one transaction. Repositories in this
|
||||
// adapter use tx directly; usecases depend on outbound.UnitOfWork and never
|
||||
// see pgx types.
|
||||
type UnitOfWork struct {
|
||||
tx pgx.Tx
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
var _ outbound.UnitOfWork = (*UnitOfWork)(nil)
|
||||
|
||||
func (unit *UnitOfWork) Outbox() outbound.OutboxWriter {
|
||||
return outboxWriter{queries: unit.queries}
|
||||
}
|
||||
Reference in new issue
Block a user