diff --git a/backend/Makefile b/backend/Makefile index 21e55ff..9dd3e81 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -23,6 +23,16 @@ build: ## Build the application binary run: ## Run the application with the current environment $(GO) run ./cmd/app +.PHONY: migrate-status migrate-up migrate-down-one +migrate-status: ## Show embedded migration status for the database in DATABASE_URL + $(GO) run ./cmd/migrate status + +migrate-up: ## Apply pending embedded migrations to the database in DATABASE_URL + $(GO) run ./cmd/migrate up + +migrate-down-one: ## Roll back the latest applied migration in the database in DATABASE_URL + $(GO) run ./cmd/migrate down-one + .PHONY: deps install install-tools deps: ## Download pinned Go module dependencies $(GO) mod download @@ -63,7 +73,7 @@ gen-ml: ## Generate the internal ML service client $(GO_TOOL) ogen -config codegen/ogen-ml.yml --target internal/adapter/secondary/ml/api --package api --clean ../api/ml/openapi.bundle.yml .PHONY: gen-sqlc -gen-sqlc: ## Generate PostgreSQL health query code +gen-sqlc: ## Generate PostgreSQL query code from migrations and queries $(GO_TOOL) sqlc generate -f codegen/sqlc.yml .PHONY: gen-wire diff --git a/backend/cmd/migrate/main.go b/backend/cmd/migrate/main.go new file mode 100644 index 0000000..31a16f6 --- /dev/null +++ b/backend/cmd/migrate/main.go @@ -0,0 +1,116 @@ +// Command migrate applies, inspects, or rolls back the embedded schema +// migrations against DATABASE_URL with the same runner and advisory lock that +// the backend uses at startup. It is intended for local development. +package main + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/backend/config" + "lincodex/backend/db" + "lincodex/backend/internal/adapter/secondary/postgres" +) + +const usage = "usage: migrate status|up|down-one" + +func main() { + if err := run(os.Args[1:], os.Stdout); err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(args []string, output io.Writer) (runErr error) { + if len(args) != 1 { + return errors.New("main.run - " + usage) + } + command := args[0] + databaseURL := config.DatabaseURLFromEnv(os.LookupEnv) + if databaseURL == "" { + return errors.New("main.run - DATABASE_URL is not set") + } + migrations, err := db.Migrations() + if err != nil { + return fmt.Errorf("main.run - load migrations: %w", err) + } + migrator, err := postgres.NewMigrator(databaseURL, migrations) + if err != nil { + return fmt.Errorf("main.run - create migrator: %w", err) + } + defer func() { + if err := migrator.Close(); err != nil { + runErr = errors.Join(runErr, fmt.Errorf("main.run - close migrator: %w", err)) + } + }() + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + switch command { + case "status": + return printStatus(ctx, migrator, output) + case "up": + return applyUp(ctx, migrator, output) + case "down-one": + return rollBackOne(ctx, migrator, output) + default: + return errors.New("main.run - " + usage) + } +} + +func printStatus(ctx context.Context, migrator *postgres.Migrator, output io.Writer) error { + statuses, err := migrator.Status(ctx) + if err != nil { + return fmt.Errorf("main.printStatus - read status: %w", err) + } + for _, status := range statuses { + appliedAt := "pending" + if status.Applied { + appliedAt = status.AppliedAt.UTC().Format(time.RFC3339) + } + if _, err := fmt.Fprintf(output, "%-20s %s\n", appliedAt, status.Name); err != nil { + return fmt.Errorf("main.printStatus - write status: %w", err) + } + } + return nil +} + +func applyUp(ctx context.Context, migrator *postgres.Migrator, output io.Writer) error { + applied, err := migrator.Up(ctx) + if err != nil { + return fmt.Errorf("main.applyUp - apply migrations: %w", err) + } + for _, migration := range applied { + if _, err := fmt.Fprintf(output, "applied %s (%s)\n", migration.Name, migration.Duration); err != nil { + return fmt.Errorf("main.applyUp - write result: %w", err) + } + } + if _, err := fmt.Fprintf(output, "%d migration(s) applied\n", len(applied)); err != nil { + return fmt.Errorf("main.applyUp - write summary: %w", err) + } + return nil +} + +func rollBackOne(ctx context.Context, migrator *postgres.Migrator, output io.Writer) error { + migration, err := migrator.DownOne(ctx) + if errors.Is(err, postgres.ErrNoMigrationToRollBack) { + _, writeErr := fmt.Fprintln(output, "no applied migration to roll back") + if writeErr != nil { + return fmt.Errorf("main.rollBackOne - write result: %w", writeErr) + } + return nil + } + if err != nil { + return fmt.Errorf("main.rollBackOne - roll back migration: %w", err) + } + if _, err := fmt.Fprintf(output, "rolled back %s (%s)\n", migration.Name, migration.Duration); err != nil { + return fmt.Errorf("main.rollBackOne - write result: %w", err) + } + return nil +} diff --git a/backend/config/config.go b/backend/config/config.go index b6fa307..d27bd55 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -18,27 +18,32 @@ const ( defaultRedisTimeout = time.Second defaultReadinessTimeout = time.Second defaultShutdownTimeout = 10 * time.Second - maxPortNumber = 65535 + // Startup migrations are on by default so a deployed binary never serves + // with a schema older than the one it was built for. + defaultDatabaseMigrateOnStart = true + maxPortNumber = 65535 ) type Config struct { - HTTPAddr string - MetricsAddr string - DatabaseURL string - RedisAddr string - RedisPassword string - RedisDB int - RedisTimeout time.Duration - SeaweedFSEndpoint string - SeaweedFSAccessKey string - SeaweedFSSecretKey string - SeaweedFSBucket string - SeaweedFSRegion string - SeaweedFSTimeout time.Duration - KafkaBrokers []string - LogLevel string - ReadinessTimeout time.Duration - ShutdownTimeout time.Duration + HTTPAddr string + MetricsAddr string + DatabaseURL string + // DatabaseMigrateOnStart applies embedded migrations before serving. + DatabaseMigrateOnStart bool + RedisAddr string + RedisPassword string + RedisDB int + RedisTimeout time.Duration + SeaweedFSEndpoint string + SeaweedFSAccessKey string + SeaweedFSSecretKey string + SeaweedFSBucket string + SeaweedFSRegion string + SeaweedFSTimeout time.Duration + KafkaBrokers []string + LogLevel string + ReadinessTimeout time.Duration + ShutdownTimeout time.Duration } type LookupEnv func(string) (string, bool) @@ -51,7 +56,7 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { config := Config{ HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", defaultHTTPAddr), MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", defaultMetricsAddr), - DatabaseURL: strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")), + DatabaseURL: DatabaseURLFromEnv(lookup), RedisAddr: strings.TrimSpace(valueOrDefault(lookup, "REDIS_ADDR", defaultRedisAddr)), RedisPassword: valueOrDefault(lookup, "REDIS_PASSWORD", ""), RedisTimeout: defaultRedisTimeout, @@ -72,6 +77,11 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { } var err error + config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart) + if err != nil { + return Config{}, err + } + config.SeaweedFSTimeout, err = durationOrDefault(lookup, "SEAWEEDFS_TIMEOUT", config.SeaweedFSTimeout) if err != nil { return Config{}, err @@ -130,6 +140,30 @@ func valueOrDefault(lookup LookupEnv, key, fallback string) string { return fallback } +// DatabaseURLFromEnv reads DATABASE_URL for commands that need only the +// database, such as the migration command. +func DatabaseURLFromEnv(lookup LookupEnv) string { + return strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")) +} + +// boolOrDefault accepts only "true" or "false", ignoring case and surrounding +// spaces. strconv.ParseBool would also accept 1, t, and similar shorthands, +// which are easy to mistype in deployment files. +func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) { + value, ok := lookup(key) + if !ok { + return fallback, nil + } + switch strings.ToLower(strings.TrimSpace(value)) { + case "true": + return true, nil + case "false": + return false, nil + default: + return false, fmt.Errorf("config.boolOrDefault - %s must be true or false", key) + } +} + func durationOrDefault(lookup LookupEnv, key string, fallback time.Duration) (time.Duration, error) { value, ok := lookup(key) if !ok { diff --git a/backend/config/config_test.go b/backend/config/config_test.go index 077c28c..6542b62 100644 --- a/backend/config/config_test.go +++ b/backend/config/config_test.go @@ -21,6 +21,9 @@ func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) { if config.DatabaseURL != "" { t.Fatalf("DatabaseURL = %q, want empty", config.DatabaseURL) } + if !config.DatabaseMigrateOnStart { + t.Fatal("DatabaseMigrateOnStart = false, want startup migrations enabled by default") + } if config.RedisAddr != "localhost:6379" || config.RedisDB != 0 || config.RedisTimeout != time.Second || config.RedisPassword != "" { t.Fatalf("unexpected Redis defaults") } @@ -34,16 +37,17 @@ func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) { func TestLoadFromEnvReadsAddressesAndTimeouts(t *testing.T) { values := map[string]string{ - "HTTP_ADDR": "127.0.0.1:18080", - "REDIS_ADDR": "cache:6379", - "REDIS_PASSWORD": " local-secret ", - "REDIS_DB": "2", - "REDIS_TIMEOUT": "500ms", - "METRICS_ADDR": "127.0.0.1:19090", - "DATABASE_URL": " postgres://app:secret@db/app ", - "LOG_LEVEL": " DEBUG ", - "READINESS_TIMEOUT": "2s", - "SHUTDOWN_TIMEOUT": "15s", + "HTTP_ADDR": "127.0.0.1:18080", + "REDIS_ADDR": "cache:6379", + "REDIS_PASSWORD": " local-secret ", + "REDIS_DB": "2", + "REDIS_TIMEOUT": "500ms", + "METRICS_ADDR": "127.0.0.1:19090", + "DATABASE_URL": " postgres://app:secret@db/app ", + "DATABASE_MIGRATE_ON_START": " FALSE ", + "LOG_LEVEL": " DEBUG ", + "READINESS_TIMEOUT": "2s", + "SHUTDOWN_TIMEOUT": "15s", } config, err := LoadFromEnv(testEnvironment(values)) if err != nil { @@ -58,6 +62,9 @@ func TestLoadFromEnvReadsAddressesAndTimeouts(t *testing.T) { if config.DatabaseURL != "postgres://app:secret@db/app" { t.Fatalf("DatabaseURL was not trimmed: %q", config.DatabaseURL) } + if config.DatabaseMigrateOnStart { + t.Fatal("DatabaseMigrateOnStart = true, want the explicit false value") + } if config.LogLevel != "debug" { t.Fatalf("LogLevel was not normalized: %q", config.LogLevel) } @@ -84,6 +91,10 @@ func TestLoadFromEnvRejectsInvalidSettings(t *testing.T) { {name: "negative Redis database", values: map[string]string{"REDIS_DB": "-1"}, want: "Config.ValidateRedis - REDIS_DB"}, {name: "invalid Redis timeout", values: map[string]string{"REDIS_TIMEOUT": "soon"}, want: "config.durationOrDefault - parse REDIS_TIMEOUT"}, {name: "zero Redis timeout", values: map[string]string{"REDIS_TIMEOUT": "0s"}, want: "Config.ValidateRedis - REDIS_TIMEOUT"}, + {name: "invalid migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": "sometimes"}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, + {name: "numeric migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": "1"}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, + {name: "short migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": "t"}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, + {name: "empty migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": ""}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, {name: "invalid log level", values: map[string]string{"LOG_LEVEL": "trace"}, want: "Config.Validate - LOG_LEVEL"}, } for _, test := range tests { diff --git a/backend/db/migrations.go b/backend/db/migrations.go new file mode 100644 index 0000000..61811ed --- /dev/null +++ b/backend/db/migrations.go @@ -0,0 +1,25 @@ +// Package db embeds the versioned SQL migrations so the backend binary applies +// exactly the schema it was built with. The SQL files stay in db/migrations, +// where sqlc and sqlfluff also read them; go:embed cannot reach a parent +// directory, so the embedding package lives next to that directory. +package db + +import ( + "embed" + "fmt" + "io/fs" +) + +const migrationsDirectory = "migrations" + +//go:embed migrations/*.sql +var migrationFiles embed.FS + +// Migrations returns the goose SQL migrations with file names at the root. +func Migrations() (fs.FS, error) { + migrations, err := fs.Sub(migrationFiles, migrationsDirectory) + if err != nil { + return nil, fmt.Errorf("db.Migrations - open embedded migrations: %w", err) + } + return migrations, nil +} diff --git a/backend/db/migrations/.gitkeep b/backend/db/migrations/.gitkeep deleted file mode 100644 index 8b13789..0000000 --- a/backend/db/migrations/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/backend/db/migrations/00001_create_outbox_events.sql b/backend/db/migrations/00001_create_outbox_events.sql new file mode 100644 index 0000000..4e55b5d --- /dev/null +++ b/backend/db/migrations/00001_create_outbox_events.sql @@ -0,0 +1,54 @@ +-- +goose Up +-- Transactional outbox: a business transaction appends its domain events here +-- in the same PostgreSQL transaction as the business change. A relay publishes +-- unpublished rows to Kafka. Payloads carry identifiers and minimal facts only, +-- never contact data, tokens, passwords, or document contents. +CREATE TABLE outbox_events ( + -- Monotonic insertion key for the relay scan. It is assigned at insert + -- time, so a transaction that waited on a row lock gets a larger value + -- than the transaction it waited for. + position bigint GENERATED ALWAYS AS IDENTITY, + event_id uuid NOT NULL, + event_type text NOT NULL, + schema_version integer NOT NULL, + aggregate_type text NOT NULL, + aggregate_id uuid NOT NULL, + aggregate_version bigint NOT NULL, + payload jsonb NOT NULL, + -- Statement time rather than transaction start time. Informational only: + -- ordering uses position and aggregate_version. + occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(), + published_at timestamptz, + CONSTRAINT outbox_events_pkey PRIMARY KEY (event_id), + CONSTRAINT outbox_events_position_key UNIQUE (position), + CONSTRAINT outbox_events_aggregate_version_event_type_key UNIQUE ( + aggregate_type, aggregate_id, aggregate_version, event_type + ), + CONSTRAINT outbox_events_event_type_format CHECK ( + char_length(event_type) <= 128 + AND event_type ~ '^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$' + ), + CONSTRAINT outbox_events_schema_version_positive CHECK (schema_version > 0), + CONSTRAINT outbox_events_aggregate_type_format CHECK ( + char_length(aggregate_type) <= 64 + AND aggregate_type ~ '^[a-z][a-z0-9_]*$' + ), + CONSTRAINT outbox_events_aggregate_version_positive CHECK ( + aggregate_version > 0 + ), + -- The payload size limit is enforced in Go on compact JSON. The jsonb text + -- and binary forms differ in size from that input, so a database length + -- check could reject an event that the domain accepted. + CONSTRAINT outbox_events_payload_object CHECK ( + jsonb_typeof(payload) = 'object' + ) +); + +-- Supports the relay scan of unpublished events in insertion order. The index +-- shrinks as events are published. +CREATE INDEX outbox_events_unpublished_idx +ON outbox_events (position) +WHERE published_at IS NULL; + +-- +goose Down +DROP TABLE outbox_events; diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go new file mode 100644 index 0000000..3a37086 --- /dev/null +++ b/backend/db/migrations_test.go @@ -0,0 +1,44 @@ +package db + +import ( + "io/fs" + "regexp" + "strings" + "testing" +) + +var migrationNamePattern = regexp.MustCompile(`^[0-9]{5}_[a-z0-9_]+\.sql$`) + +// TestMigrationsHaveSequentialNamesAndBothDirections runs without a database so +// make -C backend check catches a malformed or one-way migration. +func TestMigrationsHaveSequentialNamesAndBothDirections(t *testing.T) { + migrations, err := Migrations() + if err != nil { + t.Fatalf("Migrations() error = %v", err) + } + names, err := fs.Glob(migrations, "*.sql") + if err != nil { + t.Fatalf("list migrations: %v", err) + } + if len(names) == 0 { + t.Fatal("no embedded migrations") + } + for _, name := range names { + if !migrationNamePattern.MatchString(name) { + t.Fatalf("migration %s does not match NNNNN_description.sql", name) + } + content, err := fs.ReadFile(migrations, name) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + text := string(content) + up := strings.Index(text, "-- +goose Up") + down := strings.Index(text, "-- +goose Down") + if up < 0 || down < up { + t.Fatalf("migration %s needs a -- +goose Up section followed by a -- +goose Down section", name) + } + if strings.TrimSpace(text[down+len("-- +goose Down"):]) == "" { + t.Fatalf("migration %s has an empty Down section", name) + } + } +} diff --git a/backend/db/queries/outbox.sql b/backend/db/queries/outbox.sql new file mode 100644 index 0000000..0d5cbad --- /dev/null +++ b/backend/db/queries/outbox.sql @@ -0,0 +1,18 @@ +-- name: InsertOutboxEvent :exec +INSERT INTO outbox_events ( + event_id, + event_type, + schema_version, + aggregate_type, + aggregate_id, + aggregate_version, + payload +) VALUES ( + sqlc.arg(event_id), + sqlc.arg(event_type), + sqlc.arg(schema_version), + sqlc.arg(aggregate_type), + sqlc.arg(aggregate_id), + sqlc.arg(aggregate_version), + sqlc.arg(payload) +); diff --git a/backend/go.mod b/backend/go.mod index f6067a8..f8da735 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -12,8 +12,10 @@ require ( github.com/go-faster/errors v0.8.0 github.com/go-faster/jx v1.2.0 github.com/goforj/wire v1.2.0 + github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.11.0 github.com/ogen-go/ogen v1.24.0 + github.com/pressly/goose/v3 v3.28.0 github.com/prometheus/client_golang v1.24.1 github.com/redis/go-redis/v9 v9.22.0 github.com/testcontainers/testcontainers-go v0.44.0 @@ -182,7 +184,6 @@ require ( github.com/google/cel-go v0.28.0 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/subcommands v1.2.0 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/gordonklaus/ineffassign v0.2.0 // indirect github.com/gostaticanalysis/analysisutil v0.7.1 // indirect github.com/gostaticanalysis/comment v1.5.0 // indirect @@ -283,7 +284,6 @@ require ( github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect - github.com/pressly/goose/v3 v3.28.0 // indirect github.com/prometheus/client_model v0.6.3 // indirect github.com/prometheus/common v0.72.0 // indirect github.com/prometheus/procfs v0.22.0 // indirect diff --git a/backend/integration_test/bootstrap_test.go b/backend/integration_test/bootstrap_test.go index d80e173..a3becac 100644 --- a/backend/integration_test/bootstrap_test.go +++ b/backend/integration_test/bootstrap_test.go @@ -152,6 +152,7 @@ func (env *testEnvironment) startPostgres(ctx context.Context, t *testing.T) { if err := env.Postgres.Check(ctx); err != nil { t.Fatalf("PostgreSQL readiness: %v", err) } + applyMigrations(ctx, t, env.Config.DatabaseURL) } func (env *testEnvironment) startRedis(ctx context.Context, t *testing.T) { diff --git a/backend/integration_test/outbox_test.go b/backend/integration_test/outbox_test.go new file mode 100644 index 0000000..aeb1d3c --- /dev/null +++ b/backend/integration_test/outbox_test.go @@ -0,0 +1,654 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + // The test aggregate lives in its own schema, outside production migrations. + testAggregateSchema = "outbox_test" + testAggregateTable = "accounts" + testAggregateType = "test_account" + testAccountEventType = "test.account_changed" + testEventSchema = 1 + parallelTransactions = 20 + contenderCount = 2 + outboxTestTimeout = 2 * time.Minute + lockWaitTimeout = 10 * time.Second + connectionsTimeout = 5 * time.Second + canceledFnTimeout = 300 * time.Millisecond + pollInterval = 10 * time.Millisecond + checkViolationCode = "23514" + accountStatusActive = "active" + accountStatusArchived = "archived" + contenderApplication = "outbox_contender_b" +) + +var ( + errForcedRollback = errors.New("forced rollback") + errStaleAccountVersion = errors.New("test account version is stale") + outboxEventsTable = pgx.Identifier{"outbox_events"} + testAccountsTable = pgx.Identifier{testAggregateSchema, testAggregateTable} + createTestAccountsTable = fmt.Sprintf(` + CREATE SCHEMA %[1]s; + CREATE TABLE %[2]s ( + id uuid PRIMARY KEY, + version bigint NOT NULL CHECK (version > 0), + status text NOT NULL + )`, pgx.Identifier{testAggregateSchema}.Sanitize(), testAccountsTable.Sanitize()) +) + +type testAccount struct { + id uuid.UUID + version int64 + status string +} + +type storedEvent struct { + position int64 + eventID uuid.UUID + eventType string + schemaVersion int32 + aggregateType string + aggregateID uuid.UUID + aggregateVersion int64 + payload []byte + publishedAt *time.Time +} + +type transactionFn = func(context.Context, outbound.UnitOfWork) error + +func TestOutboxTransactions(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), outboxTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + if _, err := pool.Exec(ctx, createTestAccountsTable); err != nil { + t.Fatalf("create test aggregate table: %v", err) + } + transactor := postgresadapter.NewTransactor(pool) + + // Subtests share tables and run sequentially; each starts from empty tables. + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, outboxEventsTable, testAccountsTable) + } + + t.Run("commits the aggregate change and its event together", func(t *testing.T) { + reset(t) + created := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + createdEvent := newAccountEvent(t, created) + if err := transactor.WithinTransaction(ctx, saveAccountWith(created, createdEvent)); err != nil { + t.Fatalf("WithinTransaction(create) error = %v", err) + } + archived := testAccount{id: created.id, version: 2, status: accountStatusArchived} + archivedEvent := newAccountEvent(t, archived) + if err := transactor.WithinTransaction(ctx, saveAccountWith(archived, archivedEvent)); err != nil { + t.Fatalf("WithinTransaction(update) error = %v", err) + } + + assertAccount(ctx, t, pool, archived) + events := readOutboxEvents(ctx, t, pool) + if len(events) != 2 { + t.Fatalf("outbox has %d events, want 2", len(events)) + } + assertStoredEvent(t, events[0], createdEvent) + assertStoredEvent(t, events[1], archivedEvent) + if events[0].position >= events[1].position { + t.Fatalf("positions %d and %d do not follow insertion order", events[0].position, events[1].position) + } + assertNoBusyConnections(t, pool) + }) + + t.Run("optimistic version check rejects a stale update before the event", func(t *testing.T) { + reset(t) + created := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + if err := transactor.WithinTransaction(ctx, saveAccountWith(created, newAccountEvent(t, created))); err != nil { + t.Fatalf("WithinTransaction(create) error = %v", err) + } + updated := testAccount{id: created.id, version: 2, status: accountStatusArchived} + if err := transactor.WithinTransaction(ctx, saveAccountWith(updated, newAccountEvent(t, updated))); err != nil { + t.Fatalf("WithinTransaction(update) error = %v", err) + } + // A writer that still expects version 1 must fail on the version check. + stale := testAccount{id: created.id, version: 2, status: "stale"} + err := transactor.WithinTransaction(ctx, saveAccountWith(stale, newAccountEvent(t, stale))) + if !errors.Is(err, errStaleAccountVersion) { + t.Fatalf("WithinTransaction(stale) error = %v, want errStaleAccountVersion", err) + } + assertAccount(ctx, t, pool, updated) + if events := readOutboxEvents(ctx, t, pool); len(events) != 2 { + t.Fatalf("outbox has %d events, want 2", len(events)) + } + assertNoBusyConnections(t, pool) + }) + + t.Run("rolls back both writes when the callback fails", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + return errForcedRollback + }) + if !errors.Is(err, errForcedRollback) { + t.Fatalf("WithinTransaction() error = %v, want the callback error", err) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("rolls back both writes and re-raises a panic", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + panicValue := fmt.Sprintf("forced panic %s", account.id) + recovered := func() (recovered any) { + defer func() { recovered = recover() }() + _ = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + panic(panicValue) + }) + return nil + }() + if recovered != panicValue { + t.Fatalf("recovered %v, want the original panic value", recovered) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("rolls back and releases the connection when the context is canceled mid-callback", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + callbackCtx, cancelCallback := context.WithTimeout(ctx, canceledFnTimeout) + defer cancelCallback() + err := transactor.WithinTransaction(callbackCtx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + // The deadline interrupts this statement after both writes. + _, err := integrationTx(t, unit).Exec(ctx, "SELECT pg_sleep(30)") + return err + }) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("WithinTransaction() error = %v, want context.DeadlineExceeded", err) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("rejects a nested transaction without touching the outer one", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + innerRan := false + var nestedErr error + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + nestedErr = transactor.WithinTransaction(ctx, func(context.Context, outbound.UnitOfWork) error { + innerRan = true + return nil + }) + return nil + }) + if err != nil { + t.Fatalf("outer WithinTransaction() error = %v", err) + } + if !errors.Is(nestedErr, outbound.ErrNestedTransaction) || innerRan { + t.Fatalf("nested WithinTransaction() error = %v, inner ran = %t, want ErrNestedTransaction without running", nestedErr, innerRan) + } + assertAccount(ctx, t, pool, account) + assertNoBusyConnections(t, pool) + }) + + t.Run("fails the commit when the callback ignores a statement error", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + event := newAccountEvent(t, account) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := saveAccountWith(account, event)(ctx, unit); err != nil { + return err + } + // The duplicate aborts the transaction even though the error is dropped. + if err := unit.Outbox().Append(ctx, event); !errors.Is(err, outbound.ErrOutboxEventConflict) { + return fmt.Errorf("duplicate append error = %w, want ErrOutboxEventConflict", err) + } + return nil + }) + if !errors.Is(err, pgx.ErrTxCommitRollback) { + t.Fatalf("WithinTransaction() error = %v, want pgx.ErrTxCommitRollback", err) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("stores every domain-valid edge payload", func(t *testing.T) { + reset(t) + prefix, suffix := `{"ids":[`, `0]}` + arrayAtLimit := prefix + strings.Repeat("0,", (domain.MaxDomainEventPayloadBytes-len(prefix)-len(suffix))/2) + suffix + payloads := []string{ + arrayAtLimit, + strings.Repeat(`{"a":`, 32) + "1" + strings.Repeat("}", 32), + `{"text":"\\u0000 is plain text here"}`, + `{"name":"Привет","emoji":"😀"}`, + `{"big":123456789012345678901234567890,"small":1e-300}`, + } + events := make([]domain.DomainEvent, 0, len(payloads)) + for _, payload := range payloads { + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: testAccountEventType, SchemaVersion: testEventSchema, AggregateType: testAggregateType, + AggregateID: uuid.New(), AggregateVersion: 1, Payload: []byte(payload), + }) + if err != nil { + t.Fatalf("NewDomainEvent(%.40s) error = %v", payload, err) + } + events = append(events, event) + } + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Outbox().Append(ctx, events...) + }) + if err != nil { + t.Fatalf("Append(edge payloads) error = %v", err) + } + stored := readOutboxEvents(ctx, t, pool) + byID := make(map[uuid.UUID]storedEvent, len(stored)) + for _, event := range stored { + byID[event.eventID] = event + } + for _, event := range events { + assertStoredEvent(t, byID[event.EventID()], event) + } + }) + + t.Run("parallel transactions commit independently and a lock waiter conflicts on the aggregate version", func(t *testing.T) { + reset(t) + // One connection per transaction plus a spare, so nothing queues in the pool. + concurrentPool := env.newPoolWithMaxConns(ctx, t, parallelTransactions+contenderCount+1) + concurrentTransactor := postgresadapter.NewTransactor(concurrentPool) + contested := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + if err := transactor.WithinTransaction(ctx, saveAccountWith(contested, newAccountEvent(t, contested))); err != nil { + t.Fatalf("create contested account: %v", err) + } + + // The contenders deliberately skip the optimistic version check to prove + // that the outbox unique key still blocks a second event for version 2. + // A holds its transaction open after writing; B then blocks on A's row + // lock and, once A commits, violates the outbox key. + contenderA := testAccount{id: contested.id, version: 2, status: "contender_a"} + contenderB := testAccount{id: contested.id, version: 2, status: "contender_b"} + writeA := blindSaveAccountWith(contenderA, newAccountEvent(t, contenderA)) + writeB := blindSaveAccountWith(contenderB, newAccountEvent(t, contenderB)) + aWrote, releaseA, aFinished := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(releaseA) }) } + defer release() + + independent := make([]transactionFn, 0, parallelTransactions) + for range parallelTransactions { + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + independent = append(independent, saveAccountWith(account, newAccountEvent(t, account))) + } + independentErrs := make([]error, len(independent)) + var errA, errB error + start := make(chan struct{}) + var group sync.WaitGroup + for index, write := range independent { + group.Go(func() { + <-start + independentErrs[index] = concurrentTransactor.WithinTransaction(ctx, write) + }) + } + group.Go(func() { + defer close(aFinished) + <-start + errA = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := writeA(ctx, unit); err != nil { + return err + } + close(aWrote) + select { + case <-releaseA: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }) + }) + group.Go(func() { + select { + case <-aWrote: + case <-aFinished: + errB = errors.New("contender A finished before writing") + return + } + errB = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + // Label the session so the test can observe its lock wait. + if _, err := integrationTx(t, unit).Exec(ctx, "SET LOCAL application_name = '"+contenderApplication+"'"); err != nil { + return fmt.Errorf("label contender B: %w", err) + } + return writeB(ctx, unit) + }) + }) + close(start) + + waitEvent, observed := waitForLockWait(ctx, pool, contenderApplication) + release() + group.Wait() + if !observed { + t.Fatalf("contender B was not observed waiting on a lock (last wait event %q)", waitEvent) + } + t.Logf("observed contender B waiting on a lock: wait_event=%s", waitEvent) + + for index, err := range independentErrs { + if err != nil { + t.Fatalf("independent transaction %d error = %v", index, err) + } + } + if errA != nil { + t.Fatalf("contender A error = %v", errA) + } + if !errors.Is(errB, outbound.ErrOutboxEventConflict) { + t.Fatalf("contender B error = %v, want ErrOutboxEventConflict", errB) + } + + assertAccount(ctx, t, pool, contenderA) + events := readOutboxEvents(ctx, t, pool) + if want := 1 + parallelTransactions + 1; len(events) != want { + t.Fatalf("outbox has %d events, want %d", len(events), want) + } + var orphans int + err := pool.QueryRow(ctx, fmt.Sprintf(` + SELECT count(*) FROM outbox_events AS e + WHERE NOT EXISTS ( + SELECT 1 FROM %s AS a + WHERE a.id = e.aggregate_id AND a.version >= e.aggregate_version + )`, testAccountsTable.Sanitize())).Scan(&orphans) + if err != nil { + t.Fatalf("count orphan events: %v", err) + } + if orphans != 0 { + t.Fatalf("found %d events without their aggregate change", orphans) + } + var winnerPayload []byte + err = pool.QueryRow(ctx, ` + SELECT payload FROM outbox_events + WHERE aggregate_id = $1 AND aggregate_version = 2`, contested.id).Scan(&winnerPayload) + if err != nil { + t.Fatalf("read contested event: %v", err) + } + assertJSONEqual(t, winnerPayload, accountPayload(contenderA)) + assertNoBusyConnections(t, concurrentPool) + assertNoBusyConnections(t, pool) + }) + + t.Run("domain validation and database constraints reject invalid versions", func(t *testing.T) { + reset(t) + for _, input := range []domain.DomainEventInput{ + {EventType: testAccountEventType, SchemaVersion: 0, AggregateType: testAggregateType, AggregateID: uuid.New(), AggregateVersion: 1, Payload: []byte(`{}`)}, + {EventType: testAccountEventType, SchemaVersion: 1, AggregateType: testAggregateType, AggregateID: uuid.New(), AggregateVersion: 0, Payload: []byte(`{}`)}, + } { + if _, err := domain.NewDomainEvent(input); !errors.Is(err, domain.ErrInvalidDomainEvent) { + t.Fatalf("NewDomainEvent(%+v) error = %v, want ErrInvalidDomainEvent", input, err) + } + } + + tests := []struct { + constraint string + schemaVersion int32 + aggregateVersion int64 + payload string + }{ + {constraint: "outbox_events_schema_version_positive", schemaVersion: 0, aggregateVersion: 1, payload: `{}`}, + {constraint: "outbox_events_aggregate_version_positive", schemaVersion: 1, aggregateVersion: 0, payload: `{}`}, + {constraint: "outbox_events_payload_object", schemaVersion: 1, aggregateVersion: 1, payload: `[]`}, + } + for _, test := range tests { + // Raw SQL bypasses domain validation to prove the database backstop. + _, err := pool.Exec(ctx, ` + 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::jsonb)`, + uuid.New(), testAccountEventType, test.schemaVersion, testAggregateType, + uuid.New(), test.aggregateVersion, test.payload) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != checkViolationCode || pgError.ConstraintName != test.constraint { + t.Fatalf("insert violating %s error = %v, want a check violation", test.constraint, err) + } + } + assertTablesEmpty(ctx, t, pool) + }) +} + +// integrationTx returns the transaction behind unit through the adapter's +// integration-only seam. +func integrationTx(t *testing.T, unit outbound.UnitOfWork) pgx.Tx { + t.Helper() + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + t.Errorf("unit of work has type %T, want the PostgreSQL adapter", unit) + } + return tx +} + +// saveAccountWith returns a transaction callback that writes the aggregate +// with an optimistic version check and then its event through the same unit +// of work. Version 1 inserts; later versions update from the previous version. +func saveAccountWith(account testAccount, event domain.DomainEvent) transactionFn { + insert := fmt.Sprintf(`INSERT INTO %s (id, version, status) VALUES ($1, $2, $3)`, testAccountsTable.Sanitize()) + update := fmt.Sprintf(`UPDATE %s SET version = $2, status = $3 WHERE id = $1 AND version = $2 - 1`, testAccountsTable.Sanitize()) + return func(ctx context.Context, unit outbound.UnitOfWork) error { + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return fmt.Errorf("unit of work has type %T, want the PostgreSQL adapter", unit) + } + statement := update + if account.version == 1 { + statement = insert + } + tag, err := tx.Exec(ctx, statement, account.id, account.version, account.status) + if err != nil { + return fmt.Errorf("save test account: %w", err) + } + if tag.RowsAffected() != 1 { + return errStaleAccountVersion + } + return unit.Outbox().Append(ctx, event) + } +} + +// blindSaveAccountWith overwrites the aggregate without a version check. Only +// the contention test uses it, to exercise the outbox uniqueness backstop. +func blindSaveAccountWith(account testAccount, event domain.DomainEvent) transactionFn { + update := fmt.Sprintf(`UPDATE %s SET version = $2, status = $3 WHERE id = $1`, testAccountsTable.Sanitize()) + return func(ctx context.Context, unit outbound.UnitOfWork) error { + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return fmt.Errorf("unit of work has type %T, want the PostgreSQL adapter", unit) + } + if _, err := tx.Exec(ctx, update, account.id, account.version, account.status); err != nil { + return fmt.Errorf("overwrite test account: %w", err) + } + return unit.Outbox().Append(ctx, event) + } +} + +// waitForLockWait polls pg_stat_activity until the session labeled +// applicationName waits on a heavyweight lock. +func waitForLockWait(ctx context.Context, pool *pgxpool.Pool, applicationName string) (string, bool) { + ctx, cancel := context.WithTimeout(ctx, lockWaitTimeout) + defer cancel() + ticker := time.NewTicker(pollInterval) + defer ticker.Stop() + lastWaitEvent := "" + for { + var waitEventType, waitEvent *string + err := pool.QueryRow(ctx, ` + SELECT wait_event_type, wait_event FROM pg_stat_activity + WHERE application_name = $1 AND state = 'active'`, applicationName).Scan(&waitEventType, &waitEvent) + if err == nil && waitEventType != nil && *waitEventType == "Lock" { + if waitEvent != nil { + return *waitEvent, true + } + return "", true + } + if err == nil && waitEvent != nil { + lastWaitEvent = *waitEvent + } + select { + case <-ctx.Done(): + return lastWaitEvent, false + case <-ticker.C: + } + } +} + +func accountPayload(account testAccount) []byte { + payload, err := json.Marshal(map[string]any{ + "account_id": account.id.String(), + "status": account.status, + }) + if err != nil { + panic(err) + } + return payload +} + +func newAccountEvent(t *testing.T, account testAccount) domain.DomainEvent { + t.Helper() + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: testAccountEventType, + SchemaVersion: testEventSchema, + AggregateType: testAggregateType, + AggregateID: account.id, + AggregateVersion: account.version, + Payload: accountPayload(account), + }) + if err != nil { + t.Fatalf("NewDomainEvent() error = %v", err) + } + return event +} + +func readOutboxEvents(ctx context.Context, t *testing.T, pool *pgxpool.Pool) []storedEvent { + t.Helper() + rows, err := pool.Query(ctx, ` + SELECT position, event_id, event_type, schema_version, aggregate_type, + aggregate_id, aggregate_version, payload, published_at + FROM outbox_events + ORDER BY position`) + if err != nil { + t.Fatalf("query outbox events: %v", err) + } + events, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (storedEvent, error) { + var event storedEvent + err := row.Scan(&event.position, &event.eventID, &event.eventType, &event.schemaVersion, &event.aggregateType, + &event.aggregateID, &event.aggregateVersion, &event.payload, &event.publishedAt) + return event, err + }) + if err != nil { + t.Fatalf("read outbox events: %v", err) + } + return events +} + +func assertStoredEvent(t *testing.T, stored storedEvent, want domain.DomainEvent) { + t.Helper() + if stored.eventID != want.EventID() || stored.eventType != want.EventType() || + stored.schemaVersion != want.SchemaVersion() || stored.aggregateType != want.AggregateType() || + stored.aggregateID != want.AggregateID() || stored.aggregateVersion != want.AggregateVersion() { + t.Fatalf("stored event %+v does not match written event %s v%d", stored, want.EventID(), want.AggregateVersion()) + } + if stored.publishedAt != nil { + t.Fatalf("new event %s is already marked as published", stored.eventID) + } + assertJSONEqual(t, stored.payload, want.Payload()) +} + +// assertJSONEqual compares JSON values because jsonb normalizes key order and +// whitespace. +func assertJSONEqual(t *testing.T, got, want []byte) { + t.Helper() + var gotValue, wantValue any + if err := json.Unmarshal(got, &gotValue); err != nil { + t.Fatalf("decode stored payload: %v", err) + } + if err := json.Unmarshal(want, &wantValue); err != nil { + t.Fatalf("decode expected payload: %v", err) + } + if !reflect.DeepEqual(gotValue, wantValue) { + t.Fatalf("payload = %.200s, want %.200s", got, want) + } +} + +func assertAccount(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want testAccount) { + t.Helper() + got := testAccount{id: want.id} + err := pool.QueryRow(ctx, fmt.Sprintf(`SELECT version, status FROM %s WHERE id = $1`, testAccountsTable.Sanitize()), + want.id).Scan(&got.version, &got.status) + if err != nil { + t.Fatalf("read test account: %v", err) + } + if got != want { + t.Fatalf("account = %+v, want %+v", got, want) + } +} + +func assertTablesEmpty(ctx context.Context, t *testing.T, pool *pgxpool.Pool) { + t.Helper() + for _, table := range []pgx.Identifier{testAccountsTable, outboxEventsTable} { + var count int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM "+table.Sanitize()).Scan(&count); err != nil { + t.Fatalf("count rows in %s: %v", table.Sanitize(), err) + } + if count != 0 { + t.Fatalf("%s has %d rows after rollback, want 0", table.Sanitize(), count) + } + } +} + +// assertNoBusyConnections proves that every transaction released its +// connection, including after a rollback, a panic, or a canceled query. pgx +// may destroy a connection broken by cancellation asynchronously, so the +// check polls briefly. +func assertNoBusyConnections(t *testing.T, pool *pgxpool.Pool) { + t.Helper() + deadline := time.Now().Add(connectionsTimeout) + for { + acquired := pool.Stat().AcquiredConns() + if acquired == 0 { + return + } + if time.Now().After(deadline) { + t.Fatalf("pool has %d acquired connections after the transactions finished", acquired) + } + time.Sleep(pollInterval) + } +} diff --git a/backend/integration_test/postgres_helpers_test.go b/backend/integration_test/postgres_helpers_test.go new file mode 100644 index 0000000..bfb9970 --- /dev/null +++ b/backend/integration_test/postgres_helpers_test.go @@ -0,0 +1,137 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/rand" + "io/fs" + "net/url" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/db" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" +) + +// applyMigrations brings the database at databaseURL to the latest embedded +// schema with the same runner the backend uses at startup. +func applyMigrations(ctx context.Context, t *testing.T, databaseURL string) { + t.Helper() + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("apply migrations: %v", err) + } +} + +func newMigrator(t *testing.T, databaseURL string) *postgresadapter.Migrator { + t.Helper() + migrations, err := db.Migrations() + if err != nil { + t.Fatalf("load embedded migrations: %v", err) + } + migrator, err := postgresadapter.NewMigrator(databaseURL, migrations) + if err != nil { + t.Fatalf("create migrator: %v", err) + } + t.Cleanup(func() { + if err := migrator.Close(); err != nil { + t.Errorf("close migrator: %v", err) + } + }) + return migrator +} + +// embeddedMigrationCount derives the expected count from the embedded files. +func embeddedMigrationCount(t *testing.T) int { + t.Helper() + migrations, err := db.Migrations() + if err != nil { + t.Fatalf("load embedded migrations: %v", err) + } + files, err := fs.Glob(migrations, "*.sql") + if err != nil { + t.Fatalf("list embedded migrations: %v", err) + } + if len(files) == 0 { + t.Fatal("no embedded migrations") + } + return len(files) +} + +// newPool opens a pool to the bootstrap database and closes it with t. +func (env *testEnvironment) newPool(ctx context.Context, t *testing.T) *pgxpool.Pool { + t.Helper() + return newPoolFor(ctx, t, env.Config.DatabaseURL) +} + +func newPoolFor(ctx context.Context, t *testing.T, databaseURL string) *pgxpool.Pool { + t.Helper() + pool, err := postgresadapter.NewPool(ctx, databaseURL) + if err != nil { + t.Fatalf("create PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// newPoolWithMaxConns opens a pool sized for a concurrency test, so goroutines +// run their transactions at the same time instead of queueing for connections. +func (env *testEnvironment) newPoolWithMaxConns(ctx context.Context, t *testing.T, maxConns int32) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + poolConfig.MaxConns = maxConns + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create sized PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// createIsolatedDatabase creates an empty database in the bootstrap container +// for tests that must change the whole schema, and drops it with t. +func (env *testEnvironment) createIsolatedDatabase(ctx context.Context, t *testing.T) string { + t.Helper() + if env.Config.DatabaseURL == "" { + t.Fatal("PostgreSQL was not selected in bootstrap") + } + admin := env.newPool(ctx, t) + name := "isolated_" + strings.ToLower(rand.Text()) + identifier := pgx.Identifier{name}.Sanitize() + if _, err := admin.Exec(ctx, "CREATE DATABASE "+identifier); err != nil { + t.Fatalf("create isolated database: %v", err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) + defer cancel() + if _, err := admin.Exec(ctx, "DROP DATABASE IF EXISTS "+identifier+" WITH (FORCE)"); err != nil { + t.Errorf("drop isolated database: %v", err) + } + }) + databaseURL, err := url.Parse(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + databaseURL.Path = "/" + name + return databaseURL.String() +} + +// truncateTables resets shared tables between sequential subtests. Callers +// must not run subtests that use these tables in parallel. +func truncateTables(ctx context.Context, t *testing.T, pool *pgxpool.Pool, tables ...pgx.Identifier) { + t.Helper() + names := make([]string, 0, len(tables)) + for _, table := range tables { + names = append(names, table.Sanitize()) + } + if _, err := pool.Exec(ctx, "TRUNCATE "+strings.Join(names, ", ")); err != nil { + t.Fatalf("truncate test tables: %v", err) + } +} diff --git a/backend/integration_test/postgres_migrations_test.go b/backend/integration_test/postgres_migrations_test.go new file mode 100644 index 0000000..137fef2 --- /dev/null +++ b/backend/integration_test/postgres_migrations_test.go @@ -0,0 +1,141 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" +) + +const ( + migrationTestTimeout = 3 * time.Minute + concurrentMigrators = 4 +) + +func TestPostgresMigrations(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + total := embeddedMigrationCount(t) + + t.Run("bootstrap database has every migration applied", func(t *testing.T) { + assertAllApplied(ctx, t, newMigrator(t, env.Config.DatabaseURL), total) + }) + + t.Run("up, down to zero, and up again on an isolated database", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + + applied, err := migrator.Up(ctx) + if err != nil { + t.Fatalf("first Up() error = %v", err) + } + if len(applied) != total { + t.Fatalf("first Up() applied %d migrations, want %d", len(applied), total) + } + assertOutboxTableExists(ctx, t, pool, true) + + for rolledBack := 0; ; rolledBack++ { + _, err := migrator.DownOne(ctx) + if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) { + if rolledBack != total { + t.Fatalf("rolled back %d migrations, want %d", rolledBack, total) + } + break + } + if err != nil { + t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err) + } + } + assertOutboxTableExists(ctx, t, pool, false) + var leftovers int + err = pool.QueryRow(ctx, ` + SELECT count(*) FROM pg_catalog.pg_class AS c + JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname NOT LIKE 'goose_db_version%'`).Scan(&leftovers) + if err != nil { + t.Fatalf("count leftover relations: %v", err) + } + if leftovers != 0 { + t.Fatalf("%d relations remain after rolling back every migration", leftovers) + } + + applied, err = migrator.Up(ctx) + if err != nil { + t.Fatalf("second Up() error = %v", err) + } + if len(applied) != total { + t.Fatalf("second Up() applied %d migrations, want %d", len(applied), total) + } + assertOutboxTableExists(ctx, t, pool, true) + assertAllApplied(ctx, t, migrator, total) + }) + + t.Run("concurrent runners apply each migration once", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrators := make([]*postgresadapter.Migrator, concurrentMigrators) + for index := range migrators { + migrators[index] = newMigrator(t, databaseURL) + } + applied := make([]int, len(migrators)) + errs := make([]error, len(migrators)) + start := make(chan struct{}) + var group sync.WaitGroup + for index, migrator := range migrators { + group.Go(func() { + <-start + results, err := migrator.Up(ctx) + applied[index], errs[index] = len(results), err + }) + } + close(start) + group.Wait() + + sum := 0 + for index, err := range errs { + if err != nil { + t.Fatalf("runner %d Up() error = %v", index, err) + } + sum += applied[index] + } + if sum != total { + t.Fatalf("runners applied %d migrations in total, want %d", sum, total) + } + assertAllApplied(ctx, t, migrators[0], total) + }) +} + +func assertAllApplied(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator, total int) { + t.Helper() + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() error = %v", err) + } + if len(statuses) != total { + t.Fatalf("Status() lists %d migrations, want %d", len(statuses), total) + } + for _, status := range statuses { + if !status.Applied { + t.Fatalf("migration %s is pending", status.Name) + } + } +} + +func assertOutboxTableExists(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool) { + t.Helper() + var exists bool + if err := pool.QueryRow(ctx, `SELECT to_regclass('public.outbox_events') IS NOT NULL`).Scan(&exists); err != nil { + t.Fatalf("check outbox table: %v", err) + } + if exists != want { + t.Fatalf("outbox_events exists = %t, want %t", exists, want) + } +} diff --git a/backend/internal/adapter/secondary/postgres/health.go b/backend/internal/adapter/secondary/postgres/health.go index d8f0377..9a01511 100644 --- a/backend/internal/adapter/secondary/postgres/health.go +++ b/backend/internal/adapter/secondary/postgres/health.go @@ -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 diff --git a/backend/internal/adapter/secondary/postgres/integration_seam.go b/backend/internal/adapter/secondary/postgres/integration_seam.go new file mode 100644 index 0000000..0454d25 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/integration_seam.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/migrator.go b/backend/internal/adapter/secondary/postgres/migrator.go new file mode 100644 index 0000000..a41a688 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/migrator.go @@ -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, + } +} diff --git a/backend/internal/adapter/secondary/postgres/migrator_test.go b/backend/internal/adapter/secondary/postgres/migrator_test.go new file mode 100644 index 0000000..d054c9e --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/migrator_test.go @@ -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) + } +} diff --git a/backend/internal/adapter/secondary/postgres/outbox.go b/backend/internal/adapter/secondary/postgres/outbox.go new file mode 100644 index 0000000..ae372af --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/outbox.go @@ -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 + } +} diff --git a/backend/internal/adapter/secondary/postgres/outbox_test.go b/backend/internal/adapter/secondary/postgres/outbox_test.go new file mode 100644 index 0000000..52cf89a --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/outbox_test.go @@ -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) + } +} diff --git a/backend/internal/adapter/secondary/postgres/pool.go b/backend/internal/adapter/secondary/postgres/pool.go new file mode 100644 index 0000000..07b0b97 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/pool.go @@ -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") +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 576325d..8c2fcaf 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go new file mode 100644 index 0000000..fb8dcc9 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index b9a2e69..c508693 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -9,6 +9,7 @@ import ( ) type Querier interface { + InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error Ping(ctx context.Context) (int32, error) } diff --git a/backend/internal/adapter/secondary/postgres/transactor.go b/backend/internal/adapter/secondary/postgres/transactor.go new file mode 100644 index 0000000..6d215ff --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/transactor.go @@ -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} +} diff --git a/backend/internal/bootstrap/app.go b/backend/internal/bootstrap/app.go index db6adc2..3356404 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -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) diff --git a/backend/internal/bootstrap/app_test.go b/backend/internal/bootstrap/app_test.go index 3c6c2ba..a62b49e 100644 --- a/backend/internal/bootstrap/app_test.go +++ b/backend/internal/bootstrap/app_test.go @@ -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) + } +} diff --git a/backend/internal/bootstrap/migrate.go b/backend/internal/bootstrap/migrate.go new file mode 100644 index 0000000..84eb989 --- /dev/null +++ b/backend/internal/bootstrap/migrate.go @@ -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 +} diff --git a/backend/internal/domain/.gitkeep b/backend/internal/domain/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/backend/internal/domain/domain_event.go b/backend/internal/domain/domain_event.go new file mode 100644 index 0000000..0f8188a --- /dev/null +++ b/backend/internal/domain/domain_event.go @@ -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) } diff --git a/backend/internal/domain/domain_event_test.go b/backend/internal/domain/domain_event_test.go new file mode 100644 index 0000000..813e866 --- /dev/null +++ b/backend/internal/domain/domain_event_test.go @@ -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)) +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go new file mode 100644 index 0000000..34f69b6 --- /dev/null +++ b/backend/internal/port/outbound/transaction.go @@ -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 +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 95000d7..e94302e 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -44,13 +44,38 @@ The planned backend boundaries are: Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0, httpkit 0.7.0, and cachekit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT or WebSocket dependencies for hypothetical features. -PostgreSQL with pgx, sqlc, and goose remains the planned database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment. +PostgreSQL with pgx, sqlc, and goose is the database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations: the SQL files are embedded in the binary, and the backend applies them at startup under a PostgreSQL advisory lock before it opens its listeners. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment. Redis is part of the core Compose project and connects through `backend/internal/adapter/secondary/redis/` to the outbound cache port. The adapter provides Get/Set/Del with TTL; bootstrap manages client construction and cleanup. The internal /readyz requires PostgreSQL, Redis, and the SeaweedFS bucket to be available. The cache is not a source of truth: future consumers must tolerate key eviction and Redis restarts. Profile, search, resume, and other product caching rules are not implemented yet. SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. Resume uploads, authorization, content limits, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup. -The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, while the Go client, outbox, and relay are not implemented yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. +The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node and the `outbox_events` table with its transactional writer exists, while the Go Kafka client and the relay are not implemented yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. + +### Transactional outbox + +Implemented: migration `backend/db/migrations/00001_create_outbox_events.sql` creates `outbox_events`. Columns: + +- `position`: a bigint identity, unique and monotonic in insertion order; the relay scans by it. +- `event_id`: uuid primary key, a UUIDv7 generated in Go. +- `event_type`: a lowercase dotted name of at most 128 bytes. +- `schema_version`: an integer above zero. +- `aggregate_type`: snake_case, at most 64 bytes. +- `aggregate_id`: a uuid. +- `aggregate_version`: a bigint above zero. +- `payload`: a jsonb object. +- `occurred_at`: `clock_timestamp()` at insert. It is informational only and does not define order. +- `published_at`: null until the relay publishes the row. + +A unique key on aggregate type, aggregate ID, aggregate version, and event type rejects a second event of the same type for the same aggregate version. A partial index on `position` where `published_at` is null serves the relay scan. CHECK constraints repeat the domain rules for versions, names, and the object payload as a backstop. The payload size limit lives only in Go, because the jsonb text and binary sizes differ from the compact input and a database length check could reject an event the domain accepted. + +A usecase writes through outbound ports. `Transactor.WithinTransaction(ctx, fn)` opens one READ COMMITTED transaction and passes a `UnitOfWork`; every repository it returns, including `Outbox().Append(ctx, events...)`, uses that transaction. The transaction commits when fn returns nil and rolls back when fn returns an error, panics, or its context is canceled. Calling `WithinTransaction` again with the callback context returns `outbound.ErrNestedTransaction` instead of opening a second connection. A conflict on the event ID or the unique key returns an error that wraps `outbound.ErrOutboxEventConflict` and names the constraint. A network error during commit leaves the outcome unknown, so callers that retry must be idempotent. + +The outbox uniqueness rule is a backstop, not concurrency control. Aggregate updates still check the expected version (`UPDATE ... WHERE version = $n`), so a stale writer fails before it records an event. + +`domain.NewDomainEvent` validates the event. The compact JSON payload is limited to 16 KiB and 32 nesting levels; numbers must fit a float64; NUL characters are rejected because jsonb cannot store them. jsonb normalizes the stored payload (key order, whitespace, duplicate keys), so consumers compare JSON values rather than bytes. Payloads carry identifiers and minimal facts only, never contact data, tokens, passwords, or resume and document contents. + +Planned relay contract (TASK-009): the relay selects unpublished rows (`published_at IS NULL`) ordered by `position` on every pass and never keeps an `occurred_at` or `position` watermark, because a row with a smaller position can become visible after a larger one commits. It publishes the events of one aggregate in `aggregate_version` order and then sets `published_at`. Also planned: retry bookkeeping (attempt count and last error, added by an additive migration), retention of published rows, topics, and idempotent consumers. Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool. ## Repository map and package purpose @@ -58,13 +83,14 @@ The MVP does not add a separate vector database, Kubernetes, or a search microse api/core/ public browser-to-Go contract and bundle api/ml/ internal Go-to-ML contract and bundle backend/cmd/app/main.go calls bootstrap.Run and reports errors +backend/cmd/migrate/ local migration status, up, and down-one backend/config/ shared runtime configuration backend/internal/domain/ product invariants, planned modules backend/internal/usecase/ application operations and orchestration backend/internal/port/ inbound and outbound interfaces backend/internal/adapter/ primary HTTP and secondary integrations backend/internal/bootstrap/ dependency wiring and process lifecycle -backend/db/ migrations and SQL queries +backend/db/ migrations, SQL queries, and the embedded migration set backend/codegen/ ogen server and ML-client configs, sqlc frontend/src/ app, pages, widgets, features, entities, shared frontend/codegen/ Orval configuration @@ -81,10 +107,10 @@ backend/ cmd/app/main.go calls bootstrap.Run and reports errors config/ shared runtime configuration internal/ - domain/ flat package; currently only .gitkeep + domain/ flat package; DomainEvent for the outbox usecase/health/ operational readiness usecase port/inbound/ readiness input boundary - port/outbound/ readiness, cache, and object storage boundaries + port/outbound/ readiness, cache, object storage, transaction, and outbox boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -93,21 +119,22 @@ backend/ router.go chi composition adapter/secondary/ ml/api/ generated client from backend/codegen/ogen-ml.yml + postgres/ pool, migrator, transactor, outbox writer, health check postgres/sqlc/ generated SQL adapter redis/ cache adapter and Redis check seaweedfs/ S3 adapter and bucket check prometheus/ bounded Go/process and request metrics bootstrap/ configuration, wiring, lifecycle, shutdown - db/ migrations and SQL queries; no product schema yet + db/ embedded migrations and SQL queries; outbox table, no product schema yet codegen/ ogen and sqlc configs pkg/ reserved for justified shared technical helpers ``` -Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. Until the types are defined, the directory contains only `.gitkeep`. +Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Product domain types and usecase modules, mail/FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap, a PostgreSQL health query, a Redis cache adapter, and a SeaweedFS S3 adapter. Accounts, resumes, assessments, invitations, worker jobs, file workflows, mail, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, a Redis cache adapter, and a SeaweedFS S3 adapter. Accounts, resumes, assessments, invitations, worker jobs, file workflows, mail, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. `backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. @@ -210,7 +237,7 @@ The target screen stack is React Router, TanStack Query, React Hook Form, and Zo ## Future extensions -Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node; the outbox, relay, topics, and consumers are planned and not implemented. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. +Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table and its transactional writer are implemented (see "Transactional outbox" above); the relay, topics, and consumers are planned and not implemented. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 3c78fc1..362a094 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -11,6 +11,8 @@ Install Docker Engine and the Docker Compose plugin. At the repository root, cop deploy/docker/docker-compose.yml starts PostgreSQL, Redis, SeaweedFS, Kafka, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Redis, SeaweedFS, Kafka, Go, and Nginx communicate on the Compose network. +Before it opens its listeners, the backend applies the database migrations embedded in its binary; a migration error stops the container. Compose does not pass `DATABASE_MIGRATE_ON_START`, so the deployed backend always migrates at startup, and the PostgreSQL role in `DATABASE_URL` needs DDL rights on the application schema. That flag is a local development option; a separate least-privilege migration role is future work. See [DEVELOPMENT.md](DEVELOPMENT.md#database-migrations). + The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context. The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index e99dabc..e2224c4 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -40,7 +40,7 @@ The repository contains a verifiable technical scaffold, not a product. Values b | wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` and `tool`) | | mockery | v3.8.0 | backend/go.mod (`tool`) | | golangci-lint | v2.14.0 | backend/go.mod (`tool`) | -| goose | v3.28.0 | backend/go.mod (`tool`) | +| goose | v3.28.0 | backend/go.mod (`require` and `tool`) | | chi | v5.3.2 | backend/go.mod | | pgx | v5.11.0 | backend/go.mod | | testcontainers-go | v0.44.0, including modules/postgres | backend/go.mod | @@ -48,14 +48,14 @@ The repository contains a verifiable technical scaffold, not a product. Values b What exists now: - Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, and a 404 for an unknown API route; it does not start ML. -- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. +- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, and a transactor with the transactional outbox writer; Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has a home page, a generated API client, and MSW handlers. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka. - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. -Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, mail delivery, the Go Kafka client, the transactional outbox and its relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ has no business schema, product usecase and adapter directories contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). +Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains only the outbox table and no business schema, product usecase and adapter directories contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). ## Install and work loop @@ -141,6 +141,24 @@ ML runs as a separate FastAPI process. It currently provides operational health/ Write all source comments and docstrings in English. Keep canonical agent instructions in one English version; maintain user documentation in Russian and English. +### Database migrations + +Migrations are goose SQL files in `backend/db/migrations/` named `NNNNN_description.sql` with sequential five-digit versions. Each file has a `-- +goose Up` section and a working `-- +goose Down` section. sqlc reads the same directory as its schema, and `make -C backend lint-sql` lints it. `backend/db/migrations.go` embeds the files, so the binary applies exactly the schema it was built with. `make -C backend check` loads the embedded set without a database and fails on a malformed name, a missing Down section, or a duplicate version. A deployed migration is immutable; change the schema with a new file. Two branches that add the same version must renumber before merging. To create a file with the next sequential number, run `go tool goose -dir db/migrations -s create sql` in `backend/`. + +goose runs each migration in its own transaction. A statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`, needs a file of its own with the `-- +goose NO TRANSACTION` annotation. Every migration connection sets `lock_timeout` to 10 seconds, so DDL fails instead of queueing behind long transactions and blocking later queries on the table, and `statement_timeout` to 4 minutes. + +At startup bootstrap applies pending migrations after configuration validation and before the HTTP and metrics listeners open. The runner in `backend/internal/adapter/secondary/postgres/migrator.go` uses the goose v3 Provider API with the pgx database/sql driver and a PostgreSQL session advisory lock, so instances that start together apply migrations one at a time. Lock waiting and migration work are limited to five minutes. A migration error stops startup; the error omits the connection string and the password. Without `DATABASE_URL` the step is skipped with a warning, and readiness stays `not_ready` as before. + +`DATABASE_MIGRATE_ON_START` accepts only `true` or `false` (case-insensitive, surrounding spaces ignored); the default is `true`. It is a local and development option, for example to start the service against a database that a developer migrates by hand. The Compose stack does not pass it, and the backend image contains no separate migration command, so a deployed backend always migrates at startup and its database role needs DDL rights on the application schema. A separate migration role and job with a least-privilege runtime role is future work. + +For a local database, export `DATABASE_URL` in your shell and use these targets: + +- `make -C backend migrate-status` lists each embedded migration as applied, with its time, or pending. +- `make -C backend migrate-up` applies pending migrations. +- `make -C backend migrate-down-one` rolls back the latest applied migration. + +The targets run `backend/cmd/migrate` with the same runner, lock, and timeouts as startup. The Makefile contains no connection strings; keep credentials out of committed files. Integration tests apply all migrations to the PostgreSQL container from the shared bootstrap; see [TESTING.md](TESTING.md). + ## Go readability - Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 5af0cca..43f1173 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -36,7 +36,7 @@ Security checks run separately: `make -C security check` scans source/dependenci ## Current scaffold coverage -Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or real model inference to validate as product behavior. +Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or real model inference to validate as product behavior. API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub. @@ -48,7 +48,7 @@ The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling Call bootstrap once in the parent test and share its environment with its subtests. Each call creates separate containers with dynamic ports and a separate SeaweedFS volume when needed. Cleanup is registered through `t.Cleanup`, including partial startup. Redis outage and SeaweedFS recreation scenarios manage resources through environment helpers without affecting other tests. Tests fail when Docker is unavailable. -Bootstrap starts infrastructure and clients. The application HTTP server, business-schema migrations, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness. +Bootstrap starts infrastructure and clients. When PostgreSQL is selected, it applies every embedded migration with the startup runner. `postgres_helpers_test.go` adds `env.newPool` for a pool to that database, `env.createIsolatedDatabase` for a separate database in the same container when a test changes the whole schema (for example up, down, and up again), `env.newPoolWithMaxConns` for concurrency tests that need one connection per transaction, and `truncateTables` for resetting shared tables between sequential subtests. Tests reach the transaction behind a unit of work only through `postgres.TransactionForIntegrationTest`, which is compiled only with the `integration` build tag. Test-only aggregates live in their own schema created by the test, not in production migrations. The application HTTP server, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness. ## Integration test sharding diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 064921b..6f2de92 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -44,13 +44,38 @@ Go владеет авторизацией, подтвержденными ка Общие настройки Go принадлежат backend/config/ вне internal. Сейчас logkit 0.6.0, httpkit 0.7.0 и cachekit 0.7.0 из wahrwelt-kit используются для технических функций. Метрики реализованы ограниченным собственным collector/middleware, а pgxpool state не должен блокировать startup. pgkit и httpkit/metrics пока не используются; технические библиотеки не владеют бизнес-логикой. Не добавлять невыбранные JWT или WebSocket зависимости ради предполагаемых будущих сценариев. -PostgreSQL с pgx, sqlc и goose остается основной базой. SQL написан вручную, sqlc генерирует типизированный адаптер. goose управляет версионными миграциями. wire в bootstrap - compile-time сборка зависимостей; во время выполнения DI-контейнера нет. Worker и API используют один пул БД в целевом однопроцессном варианте. +PostgreSQL с pgx, sqlc и goose остается основной базой. SQL написан вручную, sqlc генерирует типизированный адаптер. goose управляет версионными миграциями: SQL-файлы встроены в бинарник, и backend применяет их при старте под advisory lock PostgreSQL до открытия своих listeners. wire в bootstrap - compile-time сборка зависимостей; во время выполнения DI-контейнера нет. Worker и API используют один пул БД в целевом однопроцессном варианте. Redis входит в основной Compose и подключен через `backend/internal/adapter/secondary/redis/` к outbound-порту кеша. Адаптер предоставляет Get/Set/Del с TTL, а bootstrap управляет подключением и закрытием клиента. Внутренний /readyz требует доступности PostgreSQL, Redis и bucket SeaweedFS. Кеш не является источником истины: вытеснение ключей и перезапуск Redis должны быть допустимы для будущих потребителей. Кеширование профилей, поиска, резюме и другие продуктовые правила еще не реализованы. SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Загрузка резюме, проверка прав, ограничения содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование. -Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, а Go клиент, outbox и relay пока не реализованы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. +Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, таблица `outbox_events` и ее транзакционная запись уже есть, а Go клиент Kafka и relay пока не реализованы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. + +### Transactional outbox + +Реализовано: миграция `backend/db/migrations/00001_create_outbox_events.sql` создает `outbox_events`. Колонки: + +- `position`: bigint identity, уникальный и монотонный в порядке вставки; relay читает по нему. +- `event_id`: uuid primary key, UUIDv7 создается в Go. +- `event_type`: имя в нижнем регистре через точку, не длиннее 128 байт. +- `schema_version`: integer больше нуля. +- `aggregate_type`: snake_case, не длиннее 64 байт. +- `aggregate_id`: uuid. +- `aggregate_version`: bigint больше нуля. +- `payload`: jsonb-объект. +- `occurred_at`: `clock_timestamp()` в момент вставки. Только для информации, порядок он не задает. +- `published_at`: null, пока relay не опубликует строку. + +Уникальный ключ по типу агрегата, ID агрегата, версии агрегата и типу события отклоняет второе событие того же типа для той же версии агрегата. Частичный индекс по `position` при `published_at IS NULL` обслуживает выборку relay. CHECK-ограничения повторяют доменные правила для версий, имен и payload-объекта как последнюю защиту. Ограничение размера payload есть только в Go: текстовый и бинарный размер jsonb отличаются от компактного входа, и проверка длины в БД могла бы отклонить событие, принятое доменом. + +Usecase пишет через outbound-порты. `Transactor.WithinTransaction(ctx, fn)` открывает одну транзакцию READ COMMITTED и передает `UnitOfWork`; все репозитории из него, включая `Outbox().Append(ctx, events...)`, работают в этой транзакции. Транзакция фиксируется, если fn вернула nil, и откатывается, если fn вернула ошибку, вызвала panic или ее контекст отменен. Повторный вызов `WithinTransaction` с контекстом callback возвращает `outbound.ErrNestedTransaction` и не открывает второе соединение. Конфликт по ID события или уникальному ключу возвращает ошибку, которая оборачивает `outbound.ErrOutboxEventConflict` и называет ограничение. Сетевая ошибка во время commit оставляет результат неизвестным, поэтому вызывающий код с повторами должен быть идемпотентным. + +Правило уникальности outbox - последняя защита, а не управление конкурентностью. Обновления агрегата по-прежнему проверяют ожидаемую версию (`UPDATE ... WHERE version = $n`), чтобы устаревший writer упал до записи события. + +`domain.NewDomainEvent` проверяет событие. Компактный JSON payload ограничен 16 KiB и 32 уровнями вложенности; числа должны помещаться в float64; символы NUL отклоняются, потому что jsonb не может их хранить. jsonb нормализует сохраненный payload (порядок ключей, пробелы, дублирующиеся ключи), поэтому потребители сравнивают JSON-значения, а не байты. Payload содержит только идентификаторы и минимальные факты, но не контакты, токены, пароли, содержимое резюме и документов. + +Запланированный контракт relay (TASK-009): на каждом проходе relay выбирает неопубликованные строки (`published_at IS NULL`) в порядке `position` и никогда не хранит watermark по `occurred_at` или `position`, потому что строка с меньшей позицией может стать видимой после фиксации строки с большей. События одного агрегата он публикует в порядке `aggregate_version` и затем заполняет `published_at`. Также запланированы учет повторов (счетчик попыток и последняя ошибка, добавятся аддитивной миграцией), хранение опубликованных строк, топики и идемпотентные потребители. Bootstrap пока не подключает transactor, потому что его не использует ни один продуктовый usecase; первая бизнес-транзакция подключит его вместе с общим пулом. ## Структура репозитория и назначение пакетов @@ -58,13 +83,14 @@ SeaweedFS работает отдельным сервером в основно api/core/ публичный контракт браузер-Go и bundle api/ml/ внутренний контракт Go-ML и bundle backend/cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку +backend/cmd/migrate/ локальные status, up и down-one для миграций backend/config/ общая конфигурация runtime backend/internal/domain/ продуктовые правила, планируемые модули backend/internal/usecase/ операции приложения и orchestration backend/internal/port/ inbound и outbound интерфейсы backend/internal/adapter/ primary HTTP и secondary интеграции backend/internal/bootstrap/ wiring зависимостей и lifecycle процесса -backend/db/ миграции и SQL-запросы +backend/db/ миграции, SQL-запросы и встроенный набор миграций backend/codegen/ конфигурация ogen для сервера и ML-клиента, sqlc frontend/src/ app, pages, widgets, features, entities, shared frontend/codegen/ конфигурация Orval @@ -81,10 +107,10 @@ backend/ cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку config/ общая конфигурация runtime internal/ - domain/ плоский пакет; пока только .gitkeep + domain/ плоский пакет; DomainEvent для outbox usecase/health/ operational readiness usecase port/inbound/ inbound граница readiness - port/outbound/ границы readiness, кеша и объектного хранилища + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции и outbox adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -93,21 +119,22 @@ backend/ router.go сборка chi router adapter/secondary/ ml/api/ generated client из backend/codegen/ogen-ml.yml + postgres/ pool, migrator, transactor, запись outbox, health check postgres/sqlc/ generated SQL adapter redis/ адаптер кеша и проверка Redis seaweedfs/ S3-адаптер и проверка bucket prometheus/ ограниченные Go/process и request metrics bootstrap/ конфигурация, wiring, lifecycle, shutdown - db/ миграции и SQL-запросы; продуктовой схемы пока нет + db/ встроенные миграции и SQL-запросы; таблица outbox, продуктовой схемы пока нет codegen/ конфигурация ogen и sqlc pkg/ резерв для обоснованных общих технических helpers ``` -Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Пока типы не определены, каталог содержит только `.gitkeep`. +Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. `domain/`, продуктовые `usecase/`, адаптеры почты и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap, PostgreSQL health query, Redis cache adapter и S3-адаптер SeaweedFS. Аккаунты, резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, Redis cache adapter и S3-адаптер SeaweedFS. Аккаунты, резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. @@ -210,7 +237,7 @@ contact_grant относится к паре кандидат-компания ## Будущее расширение -Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka; outbox, relay, топики и потребители запланированы и не реализованы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера. +Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka. Таблица outbox и ее транзакционная запись реализованы (см. "Transactional outbox" выше); relay, топики и потребители запланированы и не реализованы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера. k3s не входит в критический путь. Его можно рассмотреть при готовом обслуживаемом кластере или измеренной потребности в нескольких узлах. Один узел k3s не дает HA. Переход требует probes/resources, секретов, storage backup, ingress и проверенных NetworkPolicy. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 0228654..a4b7709 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -13,6 +13,8 @@ Основной файл deploy/docker/docker-compose.yml запускает PostgreSQL, Redis, SeaweedFS, Kafka, Go backend и frontend контейнер. Frontend контейнер раздает статические файлы через Nginx и проксирует /api в backend. PostgreSQL, Redis, SeaweedFS, Kafka, backend и Nginx общаются по выделенной Compose сети. +До открытия listeners backend применяет встроенные в бинарник миграции базы данных; ошибка миграции останавливает контейнер. Compose не передает `DATABASE_MIGRATE_ON_START`, поэтому развернутый backend всегда мигрирует при старте, и роли PostgreSQL из `DATABASE_URL` нужны права DDL на схему приложения. Этот флаг - опция локальной разработки; отдельная роль миграций с минимальными правами - будущая работа. См. [DEVELOPMENT.md](DEVELOPMENT.md#миграции-базы-данных). + Контекст сборки backend - каталог `backend/`, поэтому Docker применяет `backend/.dockerignore`. Локальные инструменты, кеши, файлы окружения и результаты сборки не отправляются в этот build context. Для текущего `postgres:alpine` volume монтируется в `/var/lib/postgresql`; образ размещает данные в подкаталоге своей major-версии. При переходе тега на новую major-версию существующую базу нужно мигрировать через `pg_upgrade` или backup/restore. Обновление образа само по себе не преобразует данные. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 687abcf..f5dcccf 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -40,7 +40,7 @@ Frontend зависимости выбираются из актуальных s | wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` и `tool`) | | mockery | v3.8.0 | backend/go.mod (`tool`) | | golangci-lint | v2.14.0 | backend/go.mod (`tool`) | -| goose | v3.28.0 | backend/go.mod (`tool`) | +| goose | v3.28.0 | backend/go.mod (`require` и `tool`) | | chi | v5.3.2 | backend/go.mod | | pgx | v5.11.0 | backend/go.mod | | testcontainers-go | v0.44.0, включая modules/postgres | backend/go.mod | @@ -48,14 +48,14 @@ Frontend зависимости выбираются из актуальных s Что есть сейчас: - Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose и 404 для неизвестного API маршрута; ML он не запускает. -- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. +- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, и transactor с записью transactional outbox; Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть домашняя страница, generated API client и MSW handlers. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness. - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, transactional outbox и его relay, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть только таблица outbox и нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -141,6 +141,24 @@ ML - отдельный FastAPI процесс. Сейчас он предост Все комментарии и docstrings в коде пишутся на английском. Инструкции для агентов в корне и .agents также ведутся в единой английской версии; документация команды поддерживается на русском и английском. +### Миграции базы данных + +Миграции - SQL-файлы goose в `backend/db/migrations/` с именами `NNNNN_description.sql` и последовательными пятизначными версиями. В каждом файле есть секция `-- +goose Up` и работающая секция `-- +goose Down`. sqlc читает этот же каталог как схему, а `make -C backend lint-sql` проверяет его линтером. `backend/db/migrations.go` встраивает файлы в бинарник, поэтому он применяет ровно ту схему, с которой собран. `make -C backend check` загружает встроенный набор без базы данных и падает на неверном имени, отсутствующей секции Down или дублирующейся версии. Примененная на стенде миграция неизменна; схема меняется новым файлом. Две ветки с одинаковой версией должны перенумеровать файл перед слиянием. Чтобы создать файл со следующим номером, выполните `go tool goose -dir db/migrations -s create sql` в `backend/`. + +goose выполняет каждую миграцию в отдельной транзакции. Команде, которая не работает внутри транзакции, например `CREATE INDEX CONCURRENTLY`, нужен отдельный файл с аннотацией `-- +goose NO TRANSACTION`. Каждое соединение миграций устанавливает `lock_timeout` в 10 секунд, чтобы DDL падал, а не ждал за длинными транзакциями и не блокировал последующие запросы к таблице, и `statement_timeout` в 4 минуты. + +При старте bootstrap применяет ожидающие миграции после проверки конфигурации и до открытия HTTP и metrics listeners. Runner в `backend/internal/adapter/secondary/postgres/migrator.go` использует Provider API goose v3 с драйвером pgx для database/sql и сессионный advisory lock PostgreSQL, поэтому одновременно стартующие экземпляры применяют миграции по очереди. Ожидание блокировки и сами миграции ограничены пятью минутами. Ошибка миграции останавливает запуск; текст ошибки не содержит строку подключения и пароль. Без `DATABASE_URL` шаг пропускается с предупреждением, а readiness, как и раньше, остается `not_ready`. + +`DATABASE_MIGRATE_ON_START` принимает только `true` или `false` (без учета регистра, пробелы по краям игнорируются); по умолчанию `true`. Это опция для локальной разработки, например чтобы запустить сервис с базой, которую разработчик мигрирует вручную. Compose ее не передает, а в образе backend нет отдельной команды миграций, поэтому развернутый backend всегда мигрирует при старте, и его роли БД нужны права DDL на схему приложения. Отдельная роль и job миграций с минимальными правами runtime-роли - будущая работа. + +Для локальной базы экспортируйте `DATABASE_URL` в shell и используйте цели: + +- `make -C backend migrate-status` показывает каждую встроенную миграцию как примененную, со временем, или ожидающую. +- `make -C backend migrate-up` применяет ожидающие миграции. +- `make -C backend migrate-down-one` откатывает последнюю примененную миграцию. + +Цели запускают `backend/cmd/migrate` с тем же runner, блокировкой и таймаутами, что и старт сервиса. Makefile не содержит строк подключения; не храните учетные данные в коммитах. Интеграционные тесты применяют все миграции к контейнеру PostgreSQL из общего bootstrap; см. [TESTING.md](TESTING.md). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 6915475..23c0213 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -36,7 +36,7 @@ make -C ml check-generated использует datamodel-code-generator --check ## Что покрывает текущий каркас -Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат. +Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат. API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. @@ -48,7 +48,7 @@ Deployment smoke проверяет инфраструктурные маршр Вызывайте bootstrap один раз в родительском тесте и используйте окружение в его подтестах. Каждый вызов создает отдельные контейнеры с динамическими портами; для SeaweedFS также создается отдельный volume. Очистка зарегистрирована через `t.Cleanup`, включая частично запущенное окружение. Сценарии остановки Redis и пересоздания SeaweedFS управляют ресурсами через helpers этого окружения и не затрагивают другие тесты. При отсутствии Docker тесты завершаются ошибкой. -Bootstrap поднимает инфраструктуру и клиенты. HTTP-сервер приложения, миграции бизнес-схемы, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS. +Bootstrap поднимает инфраструктуру и клиенты. Если выбран PostgreSQL, он применяет все встроенные миграции тем же runner, что и старт сервиса. `postgres_helpers_test.go` добавляет `env.newPool` для пула к этой базе, `env.createIsolatedDatabase` для отдельной базы в том же контейнере, когда тест меняет всю схему (например up, down и повторный up), `env.newPoolWithMaxConns` для тестов конкурентности, которым нужно одно соединение на транзакцию, и `truncateTables` для сброса общих таблиц между последовательными подтестами. Тесты получают транзакцию из unit of work только через `postgres.TransactionForIntegrationTest`, который компилируется только с build tag `integration`. Тестовые агрегаты живут в собственной схеме, которую создает тест, а не в продуктовых миграциях. HTTP-сервер приложения, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS. ## Шардирование интеграционных тестов