feat(backend): add transactional outbox and embedded goose migrations
This commit is contained in:
1 parent
653f3775f8
commit
15e2e50561
40 files changed
+2471
-67
No files matched your search
+11
-1
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+53
-19
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -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;
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
);
|
||||
+2
-2
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -21,13 +21,9 @@ func NewHealthChecker(ctx context.Context, config config.Config) (*HealthChecker
|
||||
return &HealthChecker{}, func() {}, nil
|
||||
}
|
||||
|
||||
poolConfig, err := pgxpool.ParseConfig(config.DatabaseURL)
|
||||
pool, err := NewPool(ctx, config.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("postgres.NewHealthChecker - parse DATABASE_URL: %w", err)
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("postgres.NewHealthChecker - create PostgreSQL pool: %w", err)
|
||||
return nil, nil, fmt.Errorf("postgres.NewHealthChecker - create pool: %w", err)
|
||||
}
|
||||
|
||||
return &HealthChecker{pool: pool, queries: sqlc.New(pool)}, pool.Close, nil
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// TransactionForIntegrationTest exposes the transaction behind a unit of work
|
||||
// to integration tests that write test-only tables. It is compiled only with
|
||||
// the integration build tag and is not part of the adapter API.
|
||||
func TransactionForIntegrationTest(unit outbound.UnitOfWork) (pgx.Tx, bool) {
|
||||
postgresUnit, ok := unit.(*UnitOfWork)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return postgresUnit.tx, true
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"path"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/pressly/goose/v3/lock"
|
||||
)
|
||||
|
||||
const (
|
||||
// The session advisory lock is retried once per second for up to five
|
||||
// minutes, so instances that start together apply migrations one at a time.
|
||||
migrationLockRetryPeriodSeconds = 1
|
||||
migrationLockRetryAttempts = 300
|
||||
|
||||
// migrationLockTimeout makes a DDL statement fail fast instead of queueing
|
||||
// behind long transactions while it blocks every later query on the table.
|
||||
migrationLockTimeout = 10 * time.Second
|
||||
// migrationStatementTimeout bounds one migration statement. It stays below
|
||||
// the five-minute startup limit so a slow statement reports its own error.
|
||||
migrationStatementTimeout = 4 * time.Minute
|
||||
)
|
||||
|
||||
// ErrNoMigrationToRollBack reports that no applied migration is left.
|
||||
var ErrNoMigrationToRollBack = errors.New("no applied migration to roll back")
|
||||
|
||||
// MigrationResult describes one applied or rolled back migration.
|
||||
type MigrationResult struct {
|
||||
Version int64
|
||||
Name string
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
// MigrationStatus describes one known migration.
|
||||
type MigrationStatus struct {
|
||||
Version int64
|
||||
Name string
|
||||
Applied bool
|
||||
AppliedAt time.Time
|
||||
}
|
||||
|
||||
// Migrator applies goose SQL migrations through database/sql with the pgx
|
||||
// driver. A PostgreSQL session advisory lock serializes concurrent runs.
|
||||
type Migrator struct {
|
||||
provider *goose.Provider
|
||||
}
|
||||
|
||||
// NewMigrator does not connect until a migration operation runs. The caller
|
||||
// must call Close.
|
||||
func NewMigrator(databaseURL string, migrations fs.FS) (*Migrator, error) {
|
||||
connConfig, err := migrationConnConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
locker, err := lock.NewPostgresSessionLocker(
|
||||
lock.WithLockTimeout(migrationLockRetryPeriodSeconds, migrationLockRetryAttempts),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("postgres.NewMigrator - create session locker: %w", err)
|
||||
}
|
||||
database := stdlib.OpenDB(*connConfig)
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, database, migrations,
|
||||
goose.WithSessionLocker(locker),
|
||||
goose.WithDisableGlobalRegistry(true),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("postgres.NewMigrator - load migrations: %w", err)
|
||||
if closeErr := database.Close(); closeErr != nil {
|
||||
err = errors.Join(err, fmt.Errorf("postgres.NewMigrator - close migration database: %w", closeErr))
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &Migrator{provider: provider}, nil
|
||||
}
|
||||
|
||||
// migrationConnConfig parses databaseURL and sets session timeouts for every
|
||||
// migration connection.
|
||||
func migrationConnConfig(databaseURL string) (*pgx.ConnConfig, error) {
|
||||
connConfig, err := pgx.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
// pgx redacts passwords only on a best-effort basis, so the parse error
|
||||
// is not wrapped to keep the connection string out of logs.
|
||||
return nil, errors.New("postgres.migrationConnConfig - DATABASE_URL is not a valid PostgreSQL connection string")
|
||||
}
|
||||
connConfig.RuntimeParams["lock_timeout"] = strconv.FormatInt(migrationLockTimeout.Milliseconds(), 10)
|
||||
connConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(migrationStatementTimeout.Milliseconds(), 10)
|
||||
return connConfig, nil
|
||||
}
|
||||
|
||||
// Up applies every pending migration and returns them in order.
|
||||
func (migrator *Migrator) Up(ctx context.Context) ([]MigrationResult, error) {
|
||||
results, err := migrator.provider.Up(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Migrator.Up - apply migrations: %w", sanitizeConnectError(err))
|
||||
}
|
||||
applied := make([]MigrationResult, 0, len(results))
|
||||
for _, result := range results {
|
||||
applied = append(applied, newMigrationResult(result))
|
||||
}
|
||||
return applied, nil
|
||||
}
|
||||
|
||||
// DownOne rolls back the most recently applied migration. It returns
|
||||
// ErrNoMigrationToRollBack when the schema is already at version zero.
|
||||
func (migrator *Migrator) DownOne(ctx context.Context) (MigrationResult, error) {
|
||||
result, err := migrator.provider.Down(ctx)
|
||||
if errors.Is(err, goose.ErrNoNextVersion) {
|
||||
return MigrationResult{}, fmt.Errorf("Migrator.DownOne - roll back migration: %w", ErrNoMigrationToRollBack)
|
||||
}
|
||||
if err != nil {
|
||||
return MigrationResult{}, fmt.Errorf("Migrator.DownOne - roll back migration: %w", sanitizeConnectError(err))
|
||||
}
|
||||
return newMigrationResult(result), nil
|
||||
}
|
||||
|
||||
// Status lists every embedded migration with its database state.
|
||||
func (migrator *Migrator) Status(ctx context.Context) ([]MigrationStatus, error) {
|
||||
statuses, err := migrator.provider.Status(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Migrator.Status - read migration status: %w", sanitizeConnectError(err))
|
||||
}
|
||||
result := make([]MigrationStatus, 0, len(statuses))
|
||||
for _, status := range statuses {
|
||||
result = append(result, MigrationStatus{
|
||||
Version: status.Source.Version,
|
||||
Name: path.Base(status.Source.Path),
|
||||
Applied: status.State == goose.StateApplied,
|
||||
AppliedAt: status.AppliedAt,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Close releases the migration connections.
|
||||
func (migrator *Migrator) Close() error {
|
||||
if err := migrator.provider.Close(); err != nil {
|
||||
return fmt.Errorf("Migrator.Close - close migration database: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newMigrationResult(result *goose.MigrationResult) MigrationResult {
|
||||
return MigrationResult{
|
||||
Version: result.Source.Version,
|
||||
Name: path.Base(result.Source.Path),
|
||||
Duration: result.Duration,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/db"
|
||||
)
|
||||
|
||||
// unreachableDatabaseURL points at a closed local port. The tests below never
|
||||
// need a server: constructors do not connect, and the connect test expects a
|
||||
// refusal.
|
||||
const unreachableDatabaseURL = "postgres://migrator:migration-secret@127.0.0.1:1/app?sslmode=disable&connect_timeout=2"
|
||||
|
||||
func TestNewMigratorLoadsEmbeddedMigrationsWithoutConnecting(t *testing.T) {
|
||||
migrations, err := db.Migrations()
|
||||
if err != nil {
|
||||
t.Fatalf("db.Migrations() error = %v", err)
|
||||
}
|
||||
migrator, err := NewMigrator(unreachableDatabaseURL, migrations)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMigrator() rejected the embedded migrations: %v", err)
|
||||
}
|
||||
if err := migrator.Close(); err != nil {
|
||||
t.Fatalf("Close() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMigratorRejectsDuplicateVersions(t *testing.T) {
|
||||
migrations := fstest.MapFS{
|
||||
"00001_first.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n-- +goose Down\nSELECT 1;\n")},
|
||||
"00001_second.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n-- +goose Down\nSELECT 1;\n")},
|
||||
}
|
||||
if migrator, err := NewMigrator(unreachableDatabaseURL, migrations); err == nil {
|
||||
_ = migrator.Close()
|
||||
t.Fatal("NewMigrator() accepted two migrations with the same version")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationConnConfigSetsSessionTimeouts(t *testing.T) {
|
||||
connConfig, err := migrationConnConfig(unreachableDatabaseURL)
|
||||
if err != nil {
|
||||
t.Fatalf("migrationConnConfig() error = %v", err)
|
||||
}
|
||||
for name, want := range map[string]time.Duration{
|
||||
"lock_timeout": migrationLockTimeout,
|
||||
"statement_timeout": migrationStatementTimeout,
|
||||
} {
|
||||
got, err := time.ParseDuration(connConfig.RuntimeParams[name] + "ms")
|
||||
if err != nil || got != want {
|
||||
t.Fatalf("%s = %q, want %s", name, connConfig.RuntimeParams[name], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationConnConfigHidesInvalidURL(t *testing.T) {
|
||||
const password = "parse-secret"
|
||||
_, err := migrationConnConfig("postgres://app:" + password + "@db:not-a-port/app")
|
||||
if err == nil {
|
||||
t.Fatal("migrationConnConfig() accepted an invalid URL")
|
||||
}
|
||||
if strings.Contains(err.Error(), password) {
|
||||
t.Fatalf("migrationConnConfig() error exposes the password: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeConnectErrorDropsConnectionIdentity(t *testing.T) {
|
||||
_, connectErr := pgconn.Connect(t.Context(), unreachableDatabaseURL)
|
||||
var original *pgconn.ConnectError
|
||||
if !errors.As(connectErr, &original) {
|
||||
t.Fatalf("pgconn.Connect() error = %v, want *pgconn.ConnectError", connectErr)
|
||||
}
|
||||
err := sanitizeConnectError(connectErr)
|
||||
for _, secret := range []string{"user=", "migrator", "migration-secret", "database=app"} {
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("sanitizeConnectError() = %v, still contains %q", err, secret)
|
||||
}
|
||||
}
|
||||
if !errors.Is(err, original.Unwrap()) {
|
||||
t.Fatalf("sanitizeConnectError() = %v, lost the network cause", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeConnectErrorKeepsOtherErrors(t *testing.T) {
|
||||
original := errors.New("relation does not exist")
|
||||
if err := sanitizeConnectError(original); err != original { //nolint:errorlint // Identity is the property under test.
|
||||
t.Fatalf("sanitizeConnectError() = %v, want the original error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
uniqueViolationCode = "23505"
|
||||
|
||||
outboxPrimaryKeyConstraint = "outbox_events_pkey"
|
||||
outboxAggregateVersionConstraint = "outbox_events_aggregate_version_event_type_key"
|
||||
)
|
||||
|
||||
type outboxWriter struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (writer outboxWriter) Append(ctx context.Context, events ...domain.DomainEvent) error {
|
||||
for _, event := range events {
|
||||
if event.EventID() == uuid.Nil {
|
||||
return fmt.Errorf("outboxWriter.Append - event was not built by domain.NewDomainEvent: %w", domain.ErrInvalidDomainEvent)
|
||||
}
|
||||
err := writer.queries.InsertOutboxEvent(ctx, sqlc.InsertOutboxEventParams{
|
||||
EventID: pgtype.UUID{Bytes: event.EventID(), Valid: true},
|
||||
EventType: event.EventType(),
|
||||
SchemaVersion: event.SchemaVersion(),
|
||||
AggregateType: event.AggregateType(),
|
||||
AggregateID: pgtype.UUID{Bytes: event.AggregateID(), Valid: true},
|
||||
AggregateVersion: event.AggregateVersion(),
|
||||
Payload: event.Payload(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("outboxWriter.Append - insert outbox event: %w", mapOutboxError(err))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mapOutboxError turns outbox uniqueness violations into a port sentinel that
|
||||
// keeps the constraint name. Other errors pass through; PostgreSQL error text
|
||||
// does not include key values.
|
||||
func mapOutboxError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) || pgError.Code != uniqueViolationCode {
|
||||
return err
|
||||
}
|
||||
switch pgError.ConstraintName {
|
||||
case outboxPrimaryKeyConstraint, outboxAggregateVersionConstraint:
|
||||
return fmt.Errorf("postgres.mapOutboxError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrOutboxEventConflict)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestMapOutboxErrorRecognizesOutboxConflicts(t *testing.T) {
|
||||
for _, constraint := range []string{outboxPrimaryKeyConstraint, outboxAggregateVersionConstraint} {
|
||||
err := mapOutboxError(&pgconn.PgError{Code: uniqueViolationCode, ConstraintName: constraint})
|
||||
if !errors.Is(err, outbound.ErrOutboxEventConflict) {
|
||||
t.Fatalf("mapOutboxError(%s) = %v, want ErrOutboxEventConflict", constraint, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), constraint) {
|
||||
t.Fatalf("mapOutboxError(%s) = %v, want the constraint name in the message", constraint, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapOutboxErrorKeepsOtherErrors(t *testing.T) {
|
||||
tests := []error{
|
||||
&pgconn.PgError{Code: uniqueViolationCode, ConstraintName: "other_table_key"},
|
||||
&pgconn.PgError{Code: "23514", ConstraintName: "outbox_events_schema_version_positive"},
|
||||
errors.New("connection reset"),
|
||||
}
|
||||
for _, original := range tests {
|
||||
if err := mapOutboxError(original); err != original { //nolint:errorlint // Identity is the property under test.
|
||||
t.Fatalf("mapOutboxError(%v) = %v, want the original error", original, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendRejectsZeroValueEventBeforeTheDatabase(t *testing.T) {
|
||||
// A nil query set proves that validation happens before any statement.
|
||||
err := outboxWriter{}.Append(t.Context(), domain.DomainEvent{})
|
||||
if !errors.Is(err, domain.ErrInvalidDomainEvent) {
|
||||
t.Fatalf("Append() error = %v, want ErrInvalidDomainEvent", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// NewPool creates a connection pool without opening a connection; the pool
|
||||
// connects lazily on first use, so constructing it never waits for the
|
||||
// database. Startup migrations, not the pool, decide whether the service
|
||||
// requires the database before serving. The caller owns the pool and must
|
||||
// close it.
|
||||
func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||
poolConfig, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
// pgx redacts passwords only on a best-effort basis, so the parse error
|
||||
// is not wrapped to keep the connection string out of logs.
|
||||
return nil, errors.New("postgres.NewPool - DATABASE_URL is not a valid PostgreSQL connection string")
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("postgres.NewPool - create PostgreSQL pool: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// sanitizeConnectError drops the pgx connection prefix, which names the
|
||||
// database user and database, while keeping the network or server cause.
|
||||
func sanitizeConnectError(err error) error {
|
||||
var connectError *pgconn.ConnectError
|
||||
if !errors.As(err, &connectError) {
|
||||
return err
|
||||
}
|
||||
if cause := connectError.Unwrap(); cause != nil {
|
||||
return fmt.Errorf("postgres.sanitizeConnectError - connect to PostgreSQL: %w", cause)
|
||||
}
|
||||
return errors.New("postgres.sanitizeConnectError - connect to PostgreSQL failed")
|
||||
}
|
||||
@@ -3,3 +3,20 @@
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type OutboxEvent struct {
|
||||
Position pgtype.Int8
|
||||
EventID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
AggregateType string
|
||||
AggregateID pgtype.UUID
|
||||
AggregateVersion int64
|
||||
Payload []byte
|
||||
OccurredAt pgtype.Timestamptz
|
||||
PublishedAt pgtype.Timestamptz
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: outbox.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const insertOutboxEvent = `-- name: InsertOutboxEvent :exec
|
||||
INSERT INTO outbox_events (
|
||||
event_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
aggregate_type,
|
||||
aggregate_id,
|
||||
aggregate_version,
|
||||
payload
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7
|
||||
)
|
||||
`
|
||||
|
||||
type InsertOutboxEventParams struct {
|
||||
EventID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
AggregateType string
|
||||
AggregateID pgtype.UUID
|
||||
AggregateVersion int64
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
func (q *Queries) InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error {
|
||||
_, err := q.db.Exec(ctx, insertOutboxEvent,
|
||||
arg.EventID,
|
||||
arg.EventType,
|
||||
arg.SchemaVersion,
|
||||
arg.AggregateType,
|
||||
arg.AggregateID,
|
||||
arg.AggregateVersion,
|
||||
arg.Payload,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
|
||||
Ping(ctx context.Context) (int32, error)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// rollbackTimeout bounds a rollback that runs after the caller's context may
|
||||
// already be canceled.
|
||||
const rollbackTimeout = 5 * time.Second
|
||||
|
||||
// transactionOptions selects READ COMMITTED explicitly. Outbox writes are
|
||||
// inserts guarded by unique constraints, and aggregate updates are expected to
|
||||
// use optimistic version checks in their WHERE clause, so stricter isolation
|
||||
// would only add serialization retries to every caller. A usecase that needs
|
||||
// SERIALIZABLE should get an explicit option rather than a silent default.
|
||||
var transactionOptions = pgx.TxOptions{
|
||||
IsoLevel: pgx.ReadCommitted,
|
||||
AccessMode: pgx.ReadWrite,
|
||||
}
|
||||
|
||||
// Transactor implements outbound.Transactor with a pgx pool owned by the caller.
|
||||
type Transactor struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewTransactor(pool *pgxpool.Pool) *Transactor {
|
||||
return &Transactor{pool: pool}
|
||||
}
|
||||
|
||||
var _ outbound.Transactor = (*Transactor)(nil)
|
||||
|
||||
// transactionContextKey marks a context passed to a transaction callback so a
|
||||
// nested WithinTransaction call fails instead of opening a second connection.
|
||||
type transactionContextKey struct{}
|
||||
|
||||
func (transactor *Transactor) WithinTransaction(
|
||||
ctx context.Context,
|
||||
fn func(ctx context.Context, unit outbound.UnitOfWork) error,
|
||||
) error {
|
||||
if ctx.Value(transactionContextKey{}) != nil {
|
||||
return fmt.Errorf("Transactor.WithinTransaction - begin transaction: %w", outbound.ErrNestedTransaction)
|
||||
}
|
||||
tx, err := transactor.pool.BeginTx(ctx, transactionOptions)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Transactor.WithinTransaction - begin transaction: %w", sanitizeConnectError(err))
|
||||
}
|
||||
finished := false
|
||||
defer func() {
|
||||
// Runs only when fn panics or calls runtime.Goexit. Not recovering
|
||||
// keeps the original panic and its stack; the rollback error cannot
|
||||
// change that outcome.
|
||||
if !finished {
|
||||
_ = rollback(ctx, tx)
|
||||
}
|
||||
}()
|
||||
|
||||
fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)})
|
||||
finished = true
|
||||
if fnErr != nil {
|
||||
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
|
||||
return errors.Join(fnErr, fmt.Errorf("Transactor.WithinTransaction - roll back transaction: %w", rollbackErr))
|
||||
}
|
||||
return fnErr
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
// pgx reports pgx.ErrTxCommitRollback when fn ignored a statement error
|
||||
// and PostgreSQL rolled the aborted transaction back instead. After a
|
||||
// network error the commit outcome is unknown; see outbound.Transactor.
|
||||
return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func rollback(ctx context.Context, tx pgx.Tx) error {
|
||||
rollbackContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), rollbackTimeout)
|
||||
defer cancel()
|
||||
if err := tx.Rollback(rollbackContext); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
|
||||
return fmt.Errorf("postgres.rollback - roll back: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnitOfWork binds repositories to one transaction. Repositories in this
|
||||
// adapter use tx directly; usecases depend on outbound.UnitOfWork and never
|
||||
// see pgx types.
|
||||
type UnitOfWork struct {
|
||||
tx pgx.Tx
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
var _ outbound.UnitOfWork = (*UnitOfWork)(nil)
|
||||
|
||||
func (unit *UnitOfWork) Outbox() outbound.OutboxWriter {
|
||||
return outboxWriter{queries: unit.queries}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,183 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
// MaxDomainEventPayloadBytes bounds the compact JSON payload. Events carry
|
||||
// identifiers and minimal facts; larger data stays in the source tables.
|
||||
MaxDomainEventPayloadBytes = 16 << 10
|
||||
maxDomainEventTypeLength = 128
|
||||
maxAggregateTypeLength = 64
|
||||
// maxDomainEventPayloadDepth bounds object and array nesting. Minimal facts
|
||||
// do not need deep structures, and the bound keeps decoding cheap.
|
||||
maxDomainEventPayloadDepth = 32
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidDomainEvent = errors.New("invalid domain event")
|
||||
|
||||
// Lowercase dotted names such as "identity.user_registered".
|
||||
domainEventTypePattern = regexp.MustCompile(`^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$`)
|
||||
// Lowercase snake_case names such as "user" or "company_member".
|
||||
aggregateTypePattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
|
||||
)
|
||||
|
||||
// DomainEvent is an immutable fact about one aggregate version, recorded in the
|
||||
// transactional outbox and later published to the event bus.
|
||||
//
|
||||
// The payload must carry identifiers and minimal facts only. It must never
|
||||
// contain contact data, tokens, passwords, document contents, or other personal
|
||||
// data that a consumer can read from the source of truth under its own access
|
||||
// rules.
|
||||
//
|
||||
// The outbox stores the payload as jsonb, which normalizes it: key order and
|
||||
// whitespace change and duplicate keys keep the last value. Consumers must
|
||||
// compare payloads as JSON values, not bytes.
|
||||
type DomainEvent struct {
|
||||
eventID uuid.UUID
|
||||
eventType string
|
||||
schemaVersion int32
|
||||
aggregateType string
|
||||
aggregateID uuid.UUID
|
||||
aggregateVersion int64
|
||||
payload []byte
|
||||
}
|
||||
|
||||
// DomainEventInput describes a new event. Payload must be a JSON object of at
|
||||
// most MaxDomainEventPayloadBytes in compact form, nested at most 32 levels,
|
||||
// with numbers in float64 range and no NUL characters, which jsonb cannot
|
||||
// store.
|
||||
type DomainEventInput struct {
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
AggregateType string
|
||||
AggregateID uuid.UUID
|
||||
AggregateVersion int64
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
// NewDomainEvent validates input and assigns a time-ordered UUIDv7 event ID.
|
||||
// The stored payload is the compact form of input.Payload.
|
||||
func NewDomainEvent(input DomainEventInput) (DomainEvent, error) {
|
||||
if err := input.validateIdentity(); err != nil {
|
||||
return DomainEvent{}, err
|
||||
}
|
||||
payload, err := compactPayload(input.Payload)
|
||||
if err != nil {
|
||||
return DomainEvent{}, err
|
||||
}
|
||||
eventID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return DomainEvent{}, fmt.Errorf("domain.NewDomainEvent - generate event ID: %w", err)
|
||||
}
|
||||
return DomainEvent{
|
||||
eventID: eventID,
|
||||
eventType: input.EventType,
|
||||
schemaVersion: input.SchemaVersion,
|
||||
aggregateType: input.AggregateType,
|
||||
aggregateID: input.AggregateID,
|
||||
aggregateVersion: input.AggregateVersion,
|
||||
payload: payload,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (input DomainEventInput) validateIdentity() error {
|
||||
if len(input.EventType) > maxDomainEventTypeLength || !domainEventTypePattern.MatchString(input.EventType) {
|
||||
return invalidDomainEvent("event type must be a lowercase dotted name of at most 128 bytes")
|
||||
}
|
||||
if input.SchemaVersion <= 0 {
|
||||
return invalidDomainEvent("schema version must be positive")
|
||||
}
|
||||
if len(input.AggregateType) > maxAggregateTypeLength || !aggregateTypePattern.MatchString(input.AggregateType) {
|
||||
return invalidDomainEvent("aggregate type must be a lowercase snake_case name of at most 64 bytes")
|
||||
}
|
||||
if input.AggregateID == uuid.Nil {
|
||||
return invalidDomainEvent("aggregate ID must not be nil")
|
||||
}
|
||||
if input.AggregateVersion <= 0 {
|
||||
return invalidDomainEvent("aggregate version must be positive")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func compactPayload(payload []byte) ([]byte, error) {
|
||||
// encoding/json accepts invalid UTF-8 inside strings; PostgreSQL does not.
|
||||
if !utf8.Valid(payload) {
|
||||
return nil, invalidDomainEvent("payload must be valid UTF-8")
|
||||
}
|
||||
var compact bytes.Buffer
|
||||
if err := json.Compact(&compact, payload); err != nil {
|
||||
return nil, invalidDomainEvent("payload must be valid JSON")
|
||||
}
|
||||
if compact.Len() == 0 || compact.Bytes()[0] != '{' {
|
||||
return nil, invalidDomainEvent("payload must be a JSON object")
|
||||
}
|
||||
if compact.Len() > MaxDomainEventPayloadBytes {
|
||||
return nil, invalidDomainEvent("payload exceeds 16 KiB")
|
||||
}
|
||||
var decoded any
|
||||
if err := json.Unmarshal(compact.Bytes(), &decoded); err != nil {
|
||||
// Compact already checked the syntax, so this is a number outside the
|
||||
// float64 range.
|
||||
return nil, invalidDomainEvent("payload numbers must fit a float64")
|
||||
}
|
||||
if err := checkPayloadValue(decoded, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return compact.Bytes(), nil
|
||||
}
|
||||
|
||||
// checkPayloadValue rejects values that PostgreSQL jsonb cannot store and
|
||||
// nesting deeper than maxDomainEventPayloadDepth.
|
||||
func checkPayloadValue(value any, depth int) error {
|
||||
switch typed := value.(type) {
|
||||
case map[string]any:
|
||||
if depth > maxDomainEventPayloadDepth {
|
||||
return invalidDomainEvent("payload nesting exceeds 32 levels")
|
||||
}
|
||||
for key, item := range typed {
|
||||
if strings.ContainsRune(key, 0) {
|
||||
return invalidDomainEvent("payload must not contain NUL characters")
|
||||
}
|
||||
if err := checkPayloadValue(item, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
if depth > maxDomainEventPayloadDepth {
|
||||
return invalidDomainEvent("payload nesting exceeds 32 levels")
|
||||
}
|
||||
for _, item := range typed {
|
||||
if err := checkPayloadValue(item, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case string:
|
||||
if strings.ContainsRune(typed, 0) {
|
||||
return invalidDomainEvent("payload must not contain NUL characters")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func invalidDomainEvent(reason string) error {
|
||||
return fmt.Errorf("domain.NewDomainEvent - %s: %w", reason, ErrInvalidDomainEvent)
|
||||
}
|
||||
|
||||
func (event DomainEvent) EventID() uuid.UUID { return event.eventID }
|
||||
func (event DomainEvent) EventType() string { return event.eventType }
|
||||
func (event DomainEvent) SchemaVersion() int32 { return event.schemaVersion }
|
||||
func (event DomainEvent) AggregateType() string { return event.aggregateType }
|
||||
func (event DomainEvent) AggregateID() uuid.UUID { return event.aggregateID }
|
||||
func (event DomainEvent) AggregateVersion() int64 { return event.aggregateVersion }
|
||||
func (event DomainEvent) Payload() json.RawMessage { return bytes.Clone(event.payload) }
|
||||
@@ -0,0 +1,138 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func validDomainEventInput() DomainEventInput {
|
||||
return DomainEventInput{
|
||||
EventType: "identity.user_registered",
|
||||
SchemaVersion: 1,
|
||||
AggregateType: "user",
|
||||
AggregateID: uuid.MustParse("0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d"),
|
||||
AggregateVersion: 1,
|
||||
Payload: []byte(` { "user_id" : "0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d" } `),
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDomainEventAcceptsValidInput(t *testing.T) {
|
||||
input := validDomainEventInput()
|
||||
event, err := NewDomainEvent(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDomainEvent() error = %v", err)
|
||||
}
|
||||
if event.EventID().Version() != 7 {
|
||||
t.Fatalf("EventID version = %d, want UUIDv7", event.EventID().Version())
|
||||
}
|
||||
if event.EventType() != input.EventType || event.SchemaVersion() != input.SchemaVersion ||
|
||||
event.AggregateType() != input.AggregateType || event.AggregateID() != input.AggregateID ||
|
||||
event.AggregateVersion() != input.AggregateVersion {
|
||||
t.Fatalf("NewDomainEvent() did not preserve identity fields: %+v", event)
|
||||
}
|
||||
if want := `{"user_id":"0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d"}`; string(event.Payload()) != want {
|
||||
t.Fatalf("Payload() = %s, want compact %s", event.Payload(), want)
|
||||
}
|
||||
event.Payload()[0] = '['
|
||||
if event.Payload()[0] != '{' {
|
||||
t.Fatal("Payload() exposed the event's internal buffer")
|
||||
}
|
||||
|
||||
other, err := NewDomainEvent(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDomainEvent() error = %v", err)
|
||||
}
|
||||
if other.EventID() == event.EventID() {
|
||||
t.Fatal("NewDomainEvent() reused an event ID")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDomainEventAcceptsPayloadAtSizeLimit(t *testing.T) {
|
||||
input := validDomainEventInput()
|
||||
prefix, suffix := `{"padding":"`, `"}`
|
||||
input.Payload = []byte(prefix + strings.Repeat("a", MaxDomainEventPayloadBytes-len(prefix)-len(suffix)) + suffix)
|
||||
if _, err := NewDomainEvent(input); err != nil {
|
||||
t.Fatalf("NewDomainEvent() rejected a payload at the limit: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDomainEventRejectsInvalidInput(t *testing.T) {
|
||||
prefix, suffix := `{"padding":"`, `"}`
|
||||
oversized := prefix + strings.Repeat("a", MaxDomainEventPayloadBytes-len(prefix)-len(suffix)+1) + suffix
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*DomainEventInput)
|
||||
}{
|
||||
{name: "empty event type", change: func(input *DomainEventInput) { input.EventType = "" }},
|
||||
{name: "event type without namespace", change: func(input *DomainEventInput) { input.EventType = "registered" }},
|
||||
{name: "uppercase event type", change: func(input *DomainEventInput) { input.EventType = "Identity.UserRegistered" }},
|
||||
{name: "long event type", change: func(input *DomainEventInput) { input.EventType = "a." + strings.Repeat("b", 127) }},
|
||||
{name: "zero schema version", change: func(input *DomainEventInput) { input.SchemaVersion = 0 }},
|
||||
{name: "negative schema version", change: func(input *DomainEventInput) { input.SchemaVersion = -1 }},
|
||||
{name: "empty aggregate type", change: func(input *DomainEventInput) { input.AggregateType = "" }},
|
||||
{name: "dotted aggregate type", change: func(input *DomainEventInput) { input.AggregateType = "identity.user" }},
|
||||
{name: "long aggregate type", change: func(input *DomainEventInput) { input.AggregateType = strings.Repeat("a", 65) }},
|
||||
{name: "nil aggregate ID", change: func(input *DomainEventInput) { input.AggregateID = uuid.Nil }},
|
||||
{name: "zero aggregate version", change: func(input *DomainEventInput) { input.AggregateVersion = 0 }},
|
||||
{name: "negative aggregate version", change: func(input *DomainEventInput) { input.AggregateVersion = -1 }},
|
||||
{name: "empty payload", change: func(input *DomainEventInput) { input.Payload = nil }},
|
||||
{name: "invalid JSON payload", change: func(input *DomainEventInput) { input.Payload = []byte(`{"user_id":`) }},
|
||||
{name: "array payload", change: func(input *DomainEventInput) { input.Payload = []byte(`[1]`) }},
|
||||
{name: "null payload", change: func(input *DomainEventInput) { input.Payload = []byte(`null`) }},
|
||||
{name: "invalid UTF-8 payload", change: func(input *DomainEventInput) { input.Payload = []byte("{\"a\":\"\xff\"}") }},
|
||||
{name: "escaped NUL in value", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":"x\u0000y"}`) }},
|
||||
{name: "escaped NUL in key", change: func(input *DomainEventInput) { input.Payload = []byte(`{"\u0000":1}`) }},
|
||||
{name: "escaped NUL in nested array", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":[{"b":"\u0000"}]}`) }},
|
||||
{name: "number outside float64 range", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":1e400}`) }},
|
||||
{name: "nesting too deep", change: func(input *DomainEventInput) { input.Payload = nestedPayload(maxDomainEventPayloadDepth + 1) }},
|
||||
{name: "oversized payload", change: func(input *DomainEventInput) { input.Payload = []byte(oversized) }},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
input := validDomainEventInput()
|
||||
test.change(&input)
|
||||
_, err := NewDomainEvent(input)
|
||||
if !errors.Is(err, ErrInvalidDomainEvent) {
|
||||
t.Fatalf("NewDomainEvent() error = %v, want ErrInvalidDomainEvent", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDomainEventDoesNotKeepCallerPayload(t *testing.T) {
|
||||
input := validDomainEventInput()
|
||||
input.Payload = []byte(`{"a":1}`)
|
||||
event, err := NewDomainEvent(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDomainEvent() error = %v", err)
|
||||
}
|
||||
copy(input.Payload, `{"b":2}`)
|
||||
if !bytes.Equal(event.Payload(), []byte(`{"a":1}`)) {
|
||||
t.Fatalf("Payload() = %s, changed with the caller's buffer", event.Payload())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDomainEventAcceptsEdgePayloads(t *testing.T) {
|
||||
for name, payload := range map[string][]byte{
|
||||
"escaped backslash before u0000 text": []byte(`{"a":"\\u0000"}`),
|
||||
"maximum nesting": nestedPayload(maxDomainEventPayloadDepth),
|
||||
"large integer": []byte(`{"a":123456789012345678901234567890}`),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
input := validDomainEventInput()
|
||||
input.Payload = payload
|
||||
if _, err := NewDomainEvent(input); err != nil {
|
||||
t.Fatalf("NewDomainEvent() error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// nestedPayload returns an object whose containers nest depth levels deep.
|
||||
func nestedPayload(depth int) []byte {
|
||||
return []byte(strings.Repeat(`{"a":`, depth) + "1" + strings.Repeat("}", depth))
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrOutboxEventConflict reports that the event ID, or the same event type
|
||||
// for the same aggregate version, is already recorded. The surrounding
|
||||
// transaction is aborted and rolled back.
|
||||
ErrOutboxEventConflict = errors.New("outbox event already recorded")
|
||||
|
||||
// ErrNestedTransaction reports a WithinTransaction call from inside another
|
||||
// transaction callback. Nested calls would silently use a second connection
|
||||
// and commit independently of the outer transaction.
|
||||
ErrNestedTransaction = errors.New("transaction already in progress")
|
||||
)
|
||||
|
||||
// Transactor runs a business operation in one database transaction.
|
||||
type Transactor interface {
|
||||
// WithinTransaction commits when fn returns nil and rolls back when fn
|
||||
// returns an error or panics. The error is returned unchanged in identity
|
||||
// and a panic is re-raised after the rollback. fn must use only the
|
||||
// UnitOfWork and context it receives and must not retain them after
|
||||
// returning. Calling WithinTransaction with that context returns
|
||||
// ErrNestedTransaction. After a database error inside fn the transaction is
|
||||
// aborted, so fn should return that error.
|
||||
//
|
||||
// A network failure during commit leaves the outcome unknown: the
|
||||
// transaction may or may not have committed. Callers that retry must make
|
||||
// the operation idempotent, for example through aggregate version checks
|
||||
// and the outbox uniqueness rules.
|
||||
WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit UnitOfWork) error) error
|
||||
}
|
||||
|
||||
// UnitOfWork exposes repositories bound to one transaction. Product
|
||||
// repositories are added here as their usecases appear.
|
||||
type UnitOfWork interface {
|
||||
Outbox() OutboxWriter
|
||||
}
|
||||
|
||||
// OutboxWriter appends domain events to the transactional outbox. Events become
|
||||
// visible to the relay only after the surrounding transaction commits.
|
||||
//
|
||||
// The outbox rejects a second event of the same type for the same aggregate
|
||||
// version. That rule is a backstop, not concurrency control: aggregate updates
|
||||
// must still check the expected version (UPDATE ... WHERE version = $n) so a
|
||||
// stale writer fails before it records an event.
|
||||
type OutboxWriter interface {
|
||||
// Append returns an error wrapping ErrOutboxEventConflict for a duplicate
|
||||
// and domain.ErrInvalidDomainEvent for an event not built by
|
||||
// domain.NewDomainEvent.
|
||||
Append(ctx context.Context, events ...domain.DomainEvent) error
|
||||
}
|
||||
Reference in new issue
Block a user