feat(backend): add transactional outbox and embedded goose migrations

This commit is contained in:
shira committed 2026-10-05 23:32:43 +03:00
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}
}
+3
View File
@@ -72,6 +72,9 @@ func run(ctx context.Context, config config.Config, logger *slog.Logger) error {
if err := config.Validate(); err != nil {
return fmt.Errorf("bootstrap.run - validate configuration: %w", err)
}
if err := migrateDatabase(ctx, config, logger); err != nil {
return fmt.Errorf("bootstrap.run - migrate database: %w", err)
}
application, cleanup, err := initialize(ctx, config, logger)
if err != nil {
return fmt.Errorf("bootstrap.run - initialize application: %w", err)
+35
View File
@@ -3,11 +3,14 @@ package bootstrap
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"strings"
"testing"
"time"
"lincodex/backend/config"
)
func TestServeServersGracefullyStopsOnCancellation(t *testing.T) {
@@ -67,3 +70,35 @@ func listenForTest(t *testing.T) net.Listener {
t.Cleanup(func() { _ = listener.Close() })
return listener
}
func TestMigrateDatabaseSkipsWithoutWork(t *testing.T) {
tests := []struct {
name string
settings config.Config
}{
{name: "disabled", settings: config.Config{DatabaseMigrateOnStart: false, DatabaseURL: "postgres://app@db/app"}},
{name: "database not configured", settings: config.Config{DatabaseMigrateOnStart: true}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if err := migrateDatabase(t.Context(), test.settings, slog.New(slog.DiscardHandler)); err != nil {
t.Fatalf("migrateDatabase() error = %v", err)
}
})
}
}
func TestMigrateDatabaseHidesConnectionStringOnFailure(t *testing.T) {
const password = "startup-secret-password"
settings := config.Config{
DatabaseMigrateOnStart: true,
DatabaseURL: "postgres://app:" + password + "@db:not-a-port/app",
}
err := migrateDatabase(t.Context(), settings, slog.New(slog.DiscardHandler))
if err == nil {
t.Fatal("migrateDatabase() accepted an invalid DATABASE_URL")
}
if strings.Contains(err.Error(), password) || strings.Contains(err.Error(), "db:not-a-port") {
t.Fatalf("migrateDatabase() error exposes the connection string: %v", err)
}
}
+57
View File
@@ -0,0 +1,57 @@
package bootstrap
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/db"
"lincodex/backend/internal/adapter/secondary/postgres"
)
// startupMigrationTimeout bounds lock waiting and migration work before the
// servers start. It matches the migration lock retry window.
const startupMigrationTimeout = 5 * time.Minute
// migrateDatabase applies embedded migrations before any listener opens, so the
// service never serves requests against an older schema. Without DATABASE_URL
// the service keeps its existing behavior: it starts and reports not ready.
func migrateDatabase(ctx context.Context, settings config.Config, logger *slog.Logger) error {
if !settings.DatabaseMigrateOnStart {
logger.Info("startup database migrations are disabled")
return nil
}
if settings.DatabaseURL == "" {
logger.Warn("startup database migrations skipped because DATABASE_URL is not set")
return nil
}
migrations, err := db.Migrations()
if err != nil {
return fmt.Errorf("bootstrap.migrateDatabase - load migrations: %w", err)
}
migrator, err := postgres.NewMigrator(settings.DatabaseURL, migrations)
if err != nil {
return fmt.Errorf("bootstrap.migrateDatabase - create migrator: %w", err)
}
ctx, cancel := context.WithTimeout(ctx, startupMigrationTimeout)
defer cancel()
applied, err := migrator.Up(ctx)
if closeErr := migrator.Close(); closeErr != nil {
err = errors.Join(err, fmt.Errorf("bootstrap.migrateDatabase - close migrator: %w", closeErr))
}
if err != nil {
return fmt.Errorf("bootstrap.migrateDatabase - apply migrations: %w", err)
}
for _, migration := range applied {
logger.Info("database migration applied",
slog.Int64("version", migration.Version),
slog.String("name", migration.Name),
slog.Duration("duration", migration.Duration),
)
}
logger.Info("database schema is up to date", slog.Int("applied_migrations", len(applied)))
return nil
}
View File
Whitespace-only changes.
+183
View File
@@ -0,0 +1,183 @@
package domain
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
const (
// MaxDomainEventPayloadBytes bounds the compact JSON payload. Events carry
// identifiers and minimal facts; larger data stays in the source tables.
MaxDomainEventPayloadBytes = 16 << 10
maxDomainEventTypeLength = 128
maxAggregateTypeLength = 64
// maxDomainEventPayloadDepth bounds object and array nesting. Minimal facts
// do not need deep structures, and the bound keeps decoding cheap.
maxDomainEventPayloadDepth = 32
)
var (
ErrInvalidDomainEvent = errors.New("invalid domain event")
// Lowercase dotted names such as "identity.user_registered".
domainEventTypePattern = regexp.MustCompile(`^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$`)
// Lowercase snake_case names such as "user" or "company_member".
aggregateTypePattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
)
// DomainEvent is an immutable fact about one aggregate version, recorded in the
// transactional outbox and later published to the event bus.
//
// The payload must carry identifiers and minimal facts only. It must never
// contain contact data, tokens, passwords, document contents, or other personal
// data that a consumer can read from the source of truth under its own access
// rules.
//
// The outbox stores the payload as jsonb, which normalizes it: key order and
// whitespace change and duplicate keys keep the last value. Consumers must
// compare payloads as JSON values, not bytes.
type DomainEvent struct {
eventID uuid.UUID
eventType string
schemaVersion int32
aggregateType string
aggregateID uuid.UUID
aggregateVersion int64
payload []byte
}
// DomainEventInput describes a new event. Payload must be a JSON object of at
// most MaxDomainEventPayloadBytes in compact form, nested at most 32 levels,
// with numbers in float64 range and no NUL characters, which jsonb cannot
// store.
type DomainEventInput struct {
EventType string
SchemaVersion int32
AggregateType string
AggregateID uuid.UUID
AggregateVersion int64
Payload []byte
}
// NewDomainEvent validates input and assigns a time-ordered UUIDv7 event ID.
// The stored payload is the compact form of input.Payload.
func NewDomainEvent(input DomainEventInput) (DomainEvent, error) {
if err := input.validateIdentity(); err != nil {
return DomainEvent{}, err
}
payload, err := compactPayload(input.Payload)
if err != nil {
return DomainEvent{}, err
}
eventID, err := uuid.NewV7()
if err != nil {
return DomainEvent{}, fmt.Errorf("domain.NewDomainEvent - generate event ID: %w", err)
}
return DomainEvent{
eventID: eventID,
eventType: input.EventType,
schemaVersion: input.SchemaVersion,
aggregateType: input.AggregateType,
aggregateID: input.AggregateID,
aggregateVersion: input.AggregateVersion,
payload: payload,
}, nil
}
func (input DomainEventInput) validateIdentity() error {
if len(input.EventType) > maxDomainEventTypeLength || !domainEventTypePattern.MatchString(input.EventType) {
return invalidDomainEvent("event type must be a lowercase dotted name of at most 128 bytes")
}
if input.SchemaVersion <= 0 {
return invalidDomainEvent("schema version must be positive")
}
if len(input.AggregateType) > maxAggregateTypeLength || !aggregateTypePattern.MatchString(input.AggregateType) {
return invalidDomainEvent("aggregate type must be a lowercase snake_case name of at most 64 bytes")
}
if input.AggregateID == uuid.Nil {
return invalidDomainEvent("aggregate ID must not be nil")
}
if input.AggregateVersion <= 0 {
return invalidDomainEvent("aggregate version must be positive")
}
return nil
}
func compactPayload(payload []byte) ([]byte, error) {
// encoding/json accepts invalid UTF-8 inside strings; PostgreSQL does not.
if !utf8.Valid(payload) {
return nil, invalidDomainEvent("payload must be valid UTF-8")
}
var compact bytes.Buffer
if err := json.Compact(&compact, payload); err != nil {
return nil, invalidDomainEvent("payload must be valid JSON")
}
if compact.Len() == 0 || compact.Bytes()[0] != '{' {
return nil, invalidDomainEvent("payload must be a JSON object")
}
if compact.Len() > MaxDomainEventPayloadBytes {
return nil, invalidDomainEvent("payload exceeds 16 KiB")
}
var decoded any
if err := json.Unmarshal(compact.Bytes(), &decoded); err != nil {
// Compact already checked the syntax, so this is a number outside the
// float64 range.
return nil, invalidDomainEvent("payload numbers must fit a float64")
}
if err := checkPayloadValue(decoded, 1); err != nil {
return nil, err
}
return compact.Bytes(), nil
}
// checkPayloadValue rejects values that PostgreSQL jsonb cannot store and
// nesting deeper than maxDomainEventPayloadDepth.
func checkPayloadValue(value any, depth int) error {
switch typed := value.(type) {
case map[string]any:
if depth > maxDomainEventPayloadDepth {
return invalidDomainEvent("payload nesting exceeds 32 levels")
}
for key, item := range typed {
if strings.ContainsRune(key, 0) {
return invalidDomainEvent("payload must not contain NUL characters")
}
if err := checkPayloadValue(item, depth+1); err != nil {
return err
}
}
case []any:
if depth > maxDomainEventPayloadDepth {
return invalidDomainEvent("payload nesting exceeds 32 levels")
}
for _, item := range typed {
if err := checkPayloadValue(item, depth+1); err != nil {
return err
}
}
case string:
if strings.ContainsRune(typed, 0) {
return invalidDomainEvent("payload must not contain NUL characters")
}
}
return nil
}
func invalidDomainEvent(reason string) error {
return fmt.Errorf("domain.NewDomainEvent - %s: %w", reason, ErrInvalidDomainEvent)
}
func (event DomainEvent) EventID() uuid.UUID { return event.eventID }
func (event DomainEvent) EventType() string { return event.eventType }
func (event DomainEvent) SchemaVersion() int32 { return event.schemaVersion }
func (event DomainEvent) AggregateType() string { return event.aggregateType }
func (event DomainEvent) AggregateID() uuid.UUID { return event.aggregateID }
func (event DomainEvent) AggregateVersion() int64 { return event.aggregateVersion }
func (event DomainEvent) Payload() json.RawMessage { return bytes.Clone(event.payload) }
@@ -0,0 +1,138 @@
package domain
import (
"bytes"
"errors"
"strings"
"testing"
"github.com/google/uuid"
)
func validDomainEventInput() DomainEventInput {
return DomainEventInput{
EventType: "identity.user_registered",
SchemaVersion: 1,
AggregateType: "user",
AggregateID: uuid.MustParse("0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d"),
AggregateVersion: 1,
Payload: []byte(` { "user_id" : "0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d" } `),
}
}
func TestNewDomainEventAcceptsValidInput(t *testing.T) {
input := validDomainEventInput()
event, err := NewDomainEvent(input)
if err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
if event.EventID().Version() != 7 {
t.Fatalf("EventID version = %d, want UUIDv7", event.EventID().Version())
}
if event.EventType() != input.EventType || event.SchemaVersion() != input.SchemaVersion ||
event.AggregateType() != input.AggregateType || event.AggregateID() != input.AggregateID ||
event.AggregateVersion() != input.AggregateVersion {
t.Fatalf("NewDomainEvent() did not preserve identity fields: %+v", event)
}
if want := `{"user_id":"0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d"}`; string(event.Payload()) != want {
t.Fatalf("Payload() = %s, want compact %s", event.Payload(), want)
}
event.Payload()[0] = '['
if event.Payload()[0] != '{' {
t.Fatal("Payload() exposed the event's internal buffer")
}
other, err := NewDomainEvent(input)
if err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
if other.EventID() == event.EventID() {
t.Fatal("NewDomainEvent() reused an event ID")
}
}
func TestNewDomainEventAcceptsPayloadAtSizeLimit(t *testing.T) {
input := validDomainEventInput()
prefix, suffix := `{"padding":"`, `"}`
input.Payload = []byte(prefix + strings.Repeat("a", MaxDomainEventPayloadBytes-len(prefix)-len(suffix)) + suffix)
if _, err := NewDomainEvent(input); err != nil {
t.Fatalf("NewDomainEvent() rejected a payload at the limit: %v", err)
}
}
func TestNewDomainEventRejectsInvalidInput(t *testing.T) {
prefix, suffix := `{"padding":"`, `"}`
oversized := prefix + strings.Repeat("a", MaxDomainEventPayloadBytes-len(prefix)-len(suffix)+1) + suffix
tests := []struct {
name string
change func(*DomainEventInput)
}{
{name: "empty event type", change: func(input *DomainEventInput) { input.EventType = "" }},
{name: "event type without namespace", change: func(input *DomainEventInput) { input.EventType = "registered" }},
{name: "uppercase event type", change: func(input *DomainEventInput) { input.EventType = "Identity.UserRegistered" }},
{name: "long event type", change: func(input *DomainEventInput) { input.EventType = "a." + strings.Repeat("b", 127) }},
{name: "zero schema version", change: func(input *DomainEventInput) { input.SchemaVersion = 0 }},
{name: "negative schema version", change: func(input *DomainEventInput) { input.SchemaVersion = -1 }},
{name: "empty aggregate type", change: func(input *DomainEventInput) { input.AggregateType = "" }},
{name: "dotted aggregate type", change: func(input *DomainEventInput) { input.AggregateType = "identity.user" }},
{name: "long aggregate type", change: func(input *DomainEventInput) { input.AggregateType = strings.Repeat("a", 65) }},
{name: "nil aggregate ID", change: func(input *DomainEventInput) { input.AggregateID = uuid.Nil }},
{name: "zero aggregate version", change: func(input *DomainEventInput) { input.AggregateVersion = 0 }},
{name: "negative aggregate version", change: func(input *DomainEventInput) { input.AggregateVersion = -1 }},
{name: "empty payload", change: func(input *DomainEventInput) { input.Payload = nil }},
{name: "invalid JSON payload", change: func(input *DomainEventInput) { input.Payload = []byte(`{"user_id":`) }},
{name: "array payload", change: func(input *DomainEventInput) { input.Payload = []byte(`[1]`) }},
{name: "null payload", change: func(input *DomainEventInput) { input.Payload = []byte(`null`) }},
{name: "invalid UTF-8 payload", change: func(input *DomainEventInput) { input.Payload = []byte("{\"a\":\"\xff\"}") }},
{name: "escaped NUL in value", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":"x\u0000y"}`) }},
{name: "escaped NUL in key", change: func(input *DomainEventInput) { input.Payload = []byte(`{"\u0000":1}`) }},
{name: "escaped NUL in nested array", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":[{"b":"\u0000"}]}`) }},
{name: "number outside float64 range", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":1e400}`) }},
{name: "nesting too deep", change: func(input *DomainEventInput) { input.Payload = nestedPayload(maxDomainEventPayloadDepth + 1) }},
{name: "oversized payload", change: func(input *DomainEventInput) { input.Payload = []byte(oversized) }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := validDomainEventInput()
test.change(&input)
_, err := NewDomainEvent(input)
if !errors.Is(err, ErrInvalidDomainEvent) {
t.Fatalf("NewDomainEvent() error = %v, want ErrInvalidDomainEvent", err)
}
})
}
}
func TestNewDomainEventDoesNotKeepCallerPayload(t *testing.T) {
input := validDomainEventInput()
input.Payload = []byte(`{"a":1}`)
event, err := NewDomainEvent(input)
if err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
copy(input.Payload, `{"b":2}`)
if !bytes.Equal(event.Payload(), []byte(`{"a":1}`)) {
t.Fatalf("Payload() = %s, changed with the caller's buffer", event.Payload())
}
}
func TestNewDomainEventAcceptsEdgePayloads(t *testing.T) {
for name, payload := range map[string][]byte{
"escaped backslash before u0000 text": []byte(`{"a":"\\u0000"}`),
"maximum nesting": nestedPayload(maxDomainEventPayloadDepth),
"large integer": []byte(`{"a":123456789012345678901234567890}`),
} {
t.Run(name, func(t *testing.T) {
input := validDomainEventInput()
input.Payload = payload
if _, err := NewDomainEvent(input); err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
})
}
}
// nestedPayload returns an object whose containers nest depth levels deep.
func nestedPayload(depth int) []byte {
return []byte(strings.Repeat(`{"a":`, depth) + "1" + strings.Repeat("}", depth))
}
@@ -0,0 +1,57 @@
package outbound
import (
"context"
"errors"
"lincodex/backend/internal/domain"
)
var (
// ErrOutboxEventConflict reports that the event ID, or the same event type
// for the same aggregate version, is already recorded. The surrounding
// transaction is aborted and rolled back.
ErrOutboxEventConflict = errors.New("outbox event already recorded")
// ErrNestedTransaction reports a WithinTransaction call from inside another
// transaction callback. Nested calls would silently use a second connection
// and commit independently of the outer transaction.
ErrNestedTransaction = errors.New("transaction already in progress")
)
// Transactor runs a business operation in one database transaction.
type Transactor interface {
// WithinTransaction commits when fn returns nil and rolls back when fn
// returns an error or panics. The error is returned unchanged in identity
// and a panic is re-raised after the rollback. fn must use only the
// UnitOfWork and context it receives and must not retain them after
// returning. Calling WithinTransaction with that context returns
// ErrNestedTransaction. After a database error inside fn the transaction is
// aborted, so fn should return that error.
//
// A network failure during commit leaves the outcome unknown: the
// transaction may or may not have committed. Callers that retry must make
// the operation idempotent, for example through aggregate version checks
// and the outbox uniqueness rules.
WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit UnitOfWork) error) error
}
// UnitOfWork exposes repositories bound to one transaction. Product
// repositories are added here as their usecases appear.
type UnitOfWork interface {
Outbox() OutboxWriter
}
// OutboxWriter appends domain events to the transactional outbox. Events become
// visible to the relay only after the surrounding transaction commits.
//
// The outbox rejects a second event of the same type for the same aggregate
// version. That rule is a backstop, not concurrency control: aggregate updates
// must still check the expected version (UPDATE ... WHERE version = $n) so a
// stale writer fails before it records an event.
type OutboxWriter interface {
// Append returns an error wrapping ErrOutboxEventConflict for a duplicate
// and domain.ErrInvalidDomainEvent for an event not built by
// domain.NewDomainEvent.
Append(ctx context.Context, events ...domain.DomainEvent) error
}