//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 := newAccountEventE(account) if err != nil { t.Fatalf("NewDomainEvent() error = %v", err) } return event } // newAccountEventE is newAccountEvent for goroutines, which must not call // t.Fatal. func newAccountEventE(account testAccount) (domain.DomainEvent, error) { return domain.NewDomainEvent(domain.DomainEventInput{ EventType: testAccountEventType, SchemaVersion: testEventSchema, AggregateType: testAggregateType, AggregateID: account.id, AggregateVersion: account.version, Payload: accountPayload(account), }) } 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) } }