//go:build integration package integration_test import ( "context" "crypto/rand" "crypto/sha256" "errors" "fmt" "slices" "strings" "sync" "sync/atomic" "testing" "time" "github.com/google/uuid" "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" "lincodex/backend/internal/usecase/policy" ) const ( policyTestTimeout = 3 * time.Minute // concurrentPublishers stays below the publisher's attempt bound, so each // of them must succeed. concurrentPublishers = 8 concurrentSeeders = 4 // policyImmutableSQLState and policyImmutableConstraint identify the // refusal raised by the policy_versions trigger. policyImmutableSQLState = "23000" policyImmutableConstraint = "policy_versions_immutable" foreignKeyViolationState = "23503" policyTestAuthor = domain.PolicyAuthor("operator:integration-test") // databaseClockTolerance bounds the difference between the test clock and // the PostgreSQL container clock that stamps created_at. databaseClockTolerance = time.Minute ) // policyFixture works on its own database. "product" is the only policy // family and the table refuses TRUNCATE, so every subtest gets a fresh // database instead of a key of its own or a cleanup. type policyFixture struct { ctx context.Context databaseURL string pool *pgxpool.Pool store *postgresadapter.PolicyStore transactor *postgresadapter.Transactor } func TestPolicyVersions(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), policyTestTimeout) defer cancel() newFixture := func(t *testing.T) policyFixture { t.Helper() databaseURL := env.createIsolatedDatabase(ctx, t) applyMigrations(ctx, t, databaseURL) pool := newPoolFor(ctx, t, databaseURL) return policyFixture{ ctx: ctx, databaseURL: databaseURL, pool: pool, store: postgresadapter.NewPolicyStore(pool), transactor: postgresadapter.NewTransactor(pool), } } t.Run("saves two versions and reads both by ID", func(t *testing.T) { fixture := newFixture(t) before := time.Now() first := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(11)) scheduledAt := before.Add(time.Hour).Truncate(time.Microsecond) second := fixture.publish(t, fixture.store.Policies(), 2, scheduledAt, integrationPolicy(12)) for _, want := range []domain.PolicyVersion{first, second} { got, err := fixture.store.Policies().GetByID(ctx, want.ID()) if err != nil { t.Fatalf("GetByID(%s) error = %v", want.ID(), err) } assertSamePolicyVersion(t, got, want) } assertDatabaseTime(t, "created_at", first.CreatedAt(), before) if !first.EffectiveAt().Equal(first.CreatedAt()) || !second.EffectiveAt().Equal(scheduledAt) { t.Fatalf("effective times = %s and %s, want publication and %s", first.EffectiveAt(), second.EffectiveAt(), scheduledAt) } if got := fixture.readMaxPending(t, second.ID()); got != 12 { t.Fatalf("second version max_pending_per_need = %d, want 12", got) } var storedHash []byte if err := fixture.pool.QueryRow(ctx, `SELECT document_sha256 FROM policy_versions WHERE id = $1`, first.ID().UUID()).Scan(&storedHash); err != nil { t.Fatalf("read stored hash: %v", err) } if want := sha256.Sum256(first.Document()); string(storedHash) != string(want[:]) { t.Fatal("stored document_sha256 is not the SHA-256 of the canonical document") } if _, err := fixture.store.Policies().GetByID(ctx, domain.PolicyVersionID(uuid.New())); !errors.Is(err, outbound.ErrPolicyVersionNotFound) { t.Fatalf("GetByID(unknown) error = %v, want ErrPolicyVersionNotFound", err) } }) t.Run("the database sets the publication time", func(t *testing.T) { fixture := newFixture(t) before := time.Now() draft := fixture.draft(t, 1, time.Time{}, integrationPolicy(13)) hash := draft.DocumentHash() // A caller-supplied created_at and a missing effective_at are both // replaced by the stamp trigger. var createdAt, effectiveAt time.Time err := fixture.pool.QueryRow(ctx, ` INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256, created_at) VALUES ($1, $2, $3, $4, NULL, $5, $6, $7, '2000-01-01T00:00:00Z') RETURNING created_at, effective_at`, draft.ID().UUID(), string(draft.Key()), draft.Version(), string(draft.Kind()), string(draft.Author()), draft.Document(), hash[:]).Scan(&createdAt, &effectiveAt) if err != nil { t.Fatalf("insert with a caller-supplied created_at: %v", err) } assertDatabaseTime(t, "created_at", createdAt, before) if !effectiveAt.Equal(createdAt) { t.Fatalf("effective_at = %s, want created_at %s", effectiveAt, createdAt) } backdated := fixture.draft(t, 2, time.Now().Add(-time.Hour), integrationPolicy(14)) _, err = fixture.store.Policies().Create(ctx, backdated) if !errors.Is(err, outbound.ErrPolicyVersionBackdated) { t.Fatalf("Create(backdated) error = %v, want ErrPolicyVersionBackdated", err) } fixture.assertVersionCount(t, 1) }) t.Run("a conflict inside a unit of work leaves the transaction usable", func(t *testing.T) { fixture := newFixture(t) existing := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(15)) var stored []domain.PolicyVersion err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { duplicate := fixture.draft(t, 1, time.Time{}, integrationPolicy(16)) if _, err := unit.Policies().Create(ctx, duplicate); !errors.Is(err, outbound.ErrPolicyVersionConflict) { return fmt.Errorf("Create(duplicate number) error = %w, want ErrPolicyVersionConflict", err) } second, err := unit.Policies().Create(ctx, fixture.draft(t, 2, time.Time{}, integrationPolicy(17))) if err != nil { return fmt.Errorf("Create(v2) after the conflict: %w", err) } // The publisher works through the transaction too. third, err := policy.NewPublisher(unit.Policies(), time.Now).Publish(ctx, policy.PublishInput{ Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: integrationPolicy(18), }) if err != nil { return fmt.Errorf("Publish() in the transaction: %w", err) } got, err := unit.Policies().GetByID(ctx, second.ID()) if err != nil { return fmt.Errorf("GetByID() in the transaction: %w", err) } assertSamePolicyVersion(t, got, second) // The pool store must not bypass the transaction. if _, err := fixture.store.Policies().GetByID(ctx, second.ID()); !errors.Is(err, outbound.ErrNestedTransaction) { t.Errorf("standalone GetByID inside a transaction error = %v, want ErrNestedTransaction", err) } stored = []domain.PolicyVersion{existing, second, third} return nil }) if err != nil { t.Fatalf("WithinTransaction() error = %v", err) } for index, want := range stored { got, err := fixture.store.Policies().GetByID(ctx, want.ID()) if err != nil || got.Version() != int32(index+1) { t.Fatalf("GetByID(v%d) after commit = v%d, %v", index+1, got.Version(), err) } } fixture.assertVersionCount(t, len(stored)) }) t.Run("the newest effective publication wins, also over an earlier schedule", func(t *testing.T) { fixture := newFixture(t) policies := fixture.store.Policies() first := fixture.publish(t, policies, 1, time.Time{}, integrationPolicy(21)) if _, err := policies.GetEffective(ctx, domain.ProductPolicyKey, first.CreatedAt().Add(-time.Microsecond)); !errors.Is(err, outbound.ErrPolicyVersionNotFound) { t.Fatalf("GetEffective(before version 1) error = %v, want ErrPolicyVersionNotFound", err) } scheduledAt := first.CreatedAt().Add(time.Hour) scheduled := fixture.publish(t, policies, 2, scheduledAt, integrationPolicy(22)) fixture.assertEffective(t, first.CreatedAt(), first) fixture.assertEffective(t, scheduledAt.Add(-time.Minute), first) fixture.assertEffective(t, scheduledAt, scheduled) fixture.assertEffective(t, scheduledAt.Add(time.Hour), scheduled) // An urgent correction published after the schedule takes effect at // once and stays in effect when the scheduled time arrives. urgent := fixture.publish(t, policies, 3, time.Time{}, integrationPolicy(23)) fixture.assertEffective(t, first.CreatedAt(), first) fixture.assertEffective(t, urgent.CreatedAt(), urgent) fixture.assertEffective(t, scheduledAt, urgent) fixture.assertEffective(t, scheduledAt.Add(time.Hour), urgent) latest, err := policies.GetLatest(ctx, domain.ProductPolicyKey) if err != nil || latest.ID() != urgent.ID() { t.Fatalf("GetLatest() = v%d, %v; want v3", latest.Version(), err) } }) t.Run("a taken version number or ID is a conflict", func(t *testing.T) { fixture := newFixture(t) draft := fixture.draft(t, 1, time.Time{}, integrationPolicy(31)) if _, err := fixture.store.Policies().Create(ctx, draft); err != nil { t.Fatalf("Create() error = %v", err) } duplicateNumber := fixture.draft(t, 1, time.Time{}, integrationPolicy(32)) if _, err := fixture.store.Policies().Create(ctx, duplicateNumber); !errors.Is(err, outbound.ErrPolicyVersionConflict) { t.Fatalf("Create(duplicate number) error = %v, want ErrPolicyVersionConflict", err) } sameID, err := draft.WithVersion(2) if err != nil { t.Fatalf("WithVersion(2) error = %v", err) } if _, err := fixture.store.Policies().Create(ctx, sameID); !errors.Is(err, outbound.ErrPolicyVersionConflict) { t.Fatalf("Create(same ID) error = %v, want ErrPolicyVersionConflict", err) } fixture.assertVersionCount(t, 1) if got := fixture.readMaxPending(t, draft.ID()); got != 31 { t.Fatalf("stored version changed: max_pending_per_need = %d, want 31", got) } }) t.Run("the database refuses UPDATE, DELETE, and TRUNCATE of a version", func(t *testing.T) { fixture := newFixture(t) stored := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(41)) id := stored.ID().UUID() statements := []struct { name string sql string args []any }{ {name: "update of a value", sql: `UPDATE policy_versions SET author = 'operator:intruder' WHERE id = $1`, args: []any{id}}, {name: "update without a change", sql: `UPDATE policy_versions SET document = document WHERE id = $1`, args: []any{id}}, {name: "update of the document", sql: `UPDATE policy_versions SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '99') WHERE id = $1`, args: []any{id}}, {name: "delete", sql: `DELETE FROM policy_versions WHERE id = $1`, args: []any{id}}, {name: "delete of every row", sql: `DELETE FROM policy_versions`}, {name: "truncate", sql: `TRUNCATE policy_versions`}, } for _, statement := range statements { _, err := fixture.pool.Exec(ctx, statement.sql, statement.args...) assertPolicyImmutable(t, statement.name, err) } // The same refusal inside a unit of work aborts the transaction. err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { tx := integrationTx(t, unit) if _, err := tx.Exec(ctx, `UPDATE policy_versions SET effective_at = effective_at + interval '1 day' WHERE id = $1`, id); err != nil { return fmt.Errorf("move effective time: %w", postgresadapter.MapPolicyErrorForIntegrationTest(err)) } return nil }) if !errors.Is(err, outbound.ErrPolicyVersionImmutable) { t.Fatalf("UPDATE in a transaction error = %v, want ErrPolicyVersionImmutable", err) } got, err := fixture.store.Policies().GetByID(ctx, stored.ID()) if err != nil { t.Fatalf("GetByID() after refused changes error = %v", err) } assertSamePolicyVersion(t, got, stored) fixture.assertVersionCount(t, 1) }) t.Run("a document changed behind the trigger fails its hash check", func(t *testing.T) { fixture := newFixture(t) stored := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(45)) // The table owner can bypass the trigger. The change stays inside a // transaction that is always rolled back, which also restores the // trigger. errTampered := errors.New("roll back tampering") err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { tx := integrationTx(t, unit) if _, err := tx.Exec(ctx, `ALTER TABLE policy_versions DISABLE TRIGGER policy_versions_refuse_update_delete`); err != nil { return fmt.Errorf("disable trigger: %w", err) } if _, err := tx.Exec(ctx, `UPDATE policy_versions SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '46') WHERE id = $1`, stored.ID().UUID()); err != nil { return fmt.Errorf("change document: %w", err) } if _, err := unit.Policies().GetByID(ctx, stored.ID()); !errors.Is(err, domain.ErrPolicyDocumentIntegrity) { t.Errorf("GetByID(changed document) error = %v, want ErrPolicyDocumentIntegrity", err) } return errTampered }) if !errors.Is(err, errTampered) { t.Fatalf("WithinTransaction() error = %v, want the rollback marker", err) } got, err := fixture.store.Policies().GetByID(ctx, stored.ID()) if err != nil { t.Fatalf("GetByID() after rollback error = %v", err) } assertSamePolicyVersion(t, got, stored) _, err = fixture.pool.Exec(ctx, `DELETE FROM policy_versions WHERE id = $1`, stored.ID().UUID()) assertPolicyImmutable(t, "delete after the rolled-back bypass", err) }) t.Run("CHECK constraints refuse invalid rows from raw SQL", func(t *testing.T) { fixture := newFixture(t) demo := fixture.demoDraft(t) demoHash := demo.DocumentHash() calibratedDraft := fixture.draft(t, 1, time.Time{}, integrationPolicy(47)) calibratedHash := calibratedDraft.DocumentHash() valid := func() []any { // id, policy_key, version, kind, effective_at, author, document, document_sha256 return []any{uuid.New(), "product", int32(1), "demo", nil, "system:raw-sql", demo.Document(), demoHash[:]} } tests := []struct { constraint string mutate func(args []any) }{ {constraint: "policy_versions_effective_after_creation", mutate: func(args []any) { args[4] = time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC) }}, {constraint: "policy_versions_author_format", mutate: func(args []any) { args[5] = "operator:tester@example.com" }}, {constraint: "policy_versions_author_format", mutate: func(args []any) { args[5] = "tester" }}, {constraint: "policy_versions_kind_known", mutate: func(args []any) { args[3] = "draft" }}, {constraint: "policy_versions_policy_key_known", mutate: func(args []any) { args[1] = "other" }}, {constraint: "policy_versions_version_positive", mutate: func(args []any) { args[2] = int32(0) }}, {constraint: "policy_versions_document_object", mutate: func(args []any) { args[6] = []byte(`[]`) }}, {constraint: "policy_versions_document_sha256_size", mutate: func(args []any) { args[7] = demoHash[:31] }}, {constraint: "policy_versions_calibrated_kind_matches_document", mutate: func(args []any) { args[3] = "calibrated" }}, } for _, test := range tests { args := valid() test.mutate(args) _, err := fixture.pool.Exec(ctx, ` INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, args...) 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) } } fixture.assertVersionCount(t, 0) // The kind CHECK accepts a calibrated document under a calibrated kind. args := valid() args[3], args[6], args[7] = "calibrated", calibratedDraft.Document(), calibratedHash[:] if _, err := fixture.pool.Exec(ctx, ` INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, args...); err != nil { t.Fatalf("insert of a valid calibrated row: %v", err) } }) t.Run("a referencing record pins its version", func(t *testing.T) { fixture := newFixture(t) stored := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(51)) tx, err := fixture.pool.Begin(ctx) if err != nil { t.Fatalf("begin transaction: %v", err) } // The probe table exists only inside this transaction, which is // always rolled back. A temporary table cannot reference a permanent // one, so it is an ordinary table in a test-only schema. defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() // A future decision table carries policy_version_id the same way. if _, err := tx.Exec(ctx, ` CREATE SCHEMA policy_reference_test; CREATE TABLE policy_reference_test.decisions ( id uuid PRIMARY KEY, policy_version_id uuid NOT NULL REFERENCES policy_versions (id) )`); err != nil { t.Fatalf("create referencing table: %v", err) } if _, err := tx.Exec(ctx, `INSERT INTO policy_reference_test.decisions (id, policy_version_id) VALUES ($1, $2)`, uuid.New(), stored.ID().UUID()); err != nil { t.Fatalf("insert record that references the version: %v", err) } if _, err := tx.Exec(ctx, `SAVEPOINT unknown_reference`); err != nil { t.Fatalf("create savepoint: %v", err) } _, err = tx.Exec(ctx, `INSERT INTO policy_reference_test.decisions (id, policy_version_id) VALUES ($1, $2)`, uuid.New(), uuid.New()) var pgError *pgconn.PgError if !errors.As(err, &pgError) || pgError.Code != foreignKeyViolationState { t.Fatalf("insert record that references an unknown version error = %v, want a foreign key violation", err) } if _, err := tx.Exec(ctx, `ROLLBACK TO SAVEPOINT unknown_reference`); err != nil { t.Fatalf("roll back to savepoint: %v", err) } _, err = tx.Exec(ctx, `DELETE FROM policy_versions WHERE id = $1`, stored.ID().UUID()) assertPolicyImmutable(t, "delete of a referenced version", err) }) t.Run("concurrent publications get distinct version numbers", func(t *testing.T) { fixture := newFixture(t) // One connection per publisher, so they really race. counting := &conflictCountingPolicies{ PolicyRepository: postgresadapter.NewPolicyStore(newSizedPoolFor(ctx, t, fixture.databaseURL, concurrentPublishers)).Policies(), } publisher := policy.NewPublisher(counting, time.Now) versions := make([]domain.PolicyVersion, concurrentPublishers) errs := make([]error, concurrentPublishers) start := make(chan struct{}) var group sync.WaitGroup for index := range concurrentPublishers { group.Go(func() { <-start versions[index], errs[index] = publisher.Publish(ctx, policy.PublishInput{ Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: integrationPolicy(int32(60 + index)), }) }) } close(start) group.Wait() numbers := make([]int32, 0, concurrentPublishers) for index, err := range errs { if err != nil { t.Fatalf("publisher %d error = %v", index, err) } numbers = append(numbers, versions[index].Version()) } slices.Sort(numbers) for index, number := range numbers { if number != int32(index+1) { t.Fatalf("published version numbers = %v, want 1 to %d once each", numbers, concurrentPublishers) } } fixture.assertVersionCount(t, concurrentPublishers) // Whether publishers collide depends on scheduling, so the count is // reported rather than asserted. t.Logf("%d version number conflicts were retried", counting.conflicts.Load()) }) t.Run("the demo seed inserts once under concurrent starts", func(t *testing.T) { fixture := newFixture(t) publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(newSizedPoolFor(ctx, t, fixture.databaseURL, concurrentSeeders)).Policies(), time.Now) results := make([]policy.DemoSeedResult, concurrentSeeders) errs := make([]error, concurrentSeeders) start := make(chan struct{}) var group sync.WaitGroup for index := range concurrentSeeders { group.Go(func() { <-start results[index], errs[index] = publisher.EnsureDemoProductPolicy(ctx) }) } close(start) group.Wait() var created domain.PolicyVersion for index, err := range errs { if err != nil { t.Fatalf("seeder %d error = %v", index, err) } if results[index].Created { if !created.IsZero() { t.Fatal("two seeders reported an insert") } created = results[index].Version } } if created.IsZero() { t.Fatal("no seeder reported an insert") } again, err := publisher.EnsureDemoProductPolicy(ctx) if err != nil || again.Created { t.Fatalf("repeated seed = %+v, %v; want a skip", again, err) } fixture.assertVersionCount(t, 1) demo, err := fixture.store.Policies().GetEffective(ctx, domain.ProductPolicyKey, created.CreatedAt()) if err != nil { t.Fatalf("GetEffective(product) error = %v", err) } assertSamePolicyVersion(t, demo, created) if demo.Version() != 1 || demo.Kind() != domain.PolicyKindDemo || demo.Author() != domain.DemoPolicySeedAuthor || demo.DocumentHash() != fixture.demoDraft(t).DocumentHash() || !demo.EffectiveAt().Equal(demo.CreatedAt()) { t.Fatalf("seeded product policy = v%d %s by %s, want version 1 of the demo policy effective at publication", demo.Version(), demo.Kind(), demo.Author()) } }) t.Run("the demo seed skips existing versions without decoding them", func(t *testing.T) { fixture := newFixture(t) // A row of a future document layout that this build cannot decode. futureHash := make([]byte, sha256.Size) if _, err := rand.Read(futureHash); err != nil { t.Fatalf("generate hash bytes: %v", err) } if _, err := fixture.pool.Exec(ctx, ` INSERT INTO policy_versions (id, policy_key, version, kind, author, document, document_sha256) VALUES ($1, 'product', 1, 'demo', 'system:future-build', '{"schema_version": 2}', $2)`, uuid.New(), futureHash); err != nil { t.Fatalf("insert a row of an unknown schema version: %v", err) } if _, err := fixture.store.Policies().GetLatest(ctx, domain.ProductPolicyKey); !errors.Is(err, domain.ErrInvalidPolicy) { t.Fatalf("GetLatest(future layout) error = %v, want ErrInvalidPolicy", err) } result, err := policy.NewPublisher(fixture.store.Policies(), time.Now).EnsureDemoProductPolicy(ctx) if err != nil || result.Created { t.Fatalf("EnsureDemoProductPolicy() = %+v, %v; want a skip without error", result, err) } fixture.assertVersionCount(t, 1) }) t.Run("a new pool reads the same versions after a restart", func(t *testing.T) { fixture := newFixture(t) firstPool := newPoolFor(ctx, t, fixture.databaseURL) firstStore := postgresadapter.NewPolicyStore(firstPool) written := []domain.PolicyVersion{ fixture.publish(t, firstStore.Policies(), 1, time.Time{}, integrationPolicy(81)), fixture.publish(t, firstStore.Policies(), 2, time.Time{}, integrationPolicy(82)), } firstPool.Close() restarted := postgresadapter.NewPolicyStore(newPoolFor(ctx, t, fixture.databaseURL)) for _, want := range written { got, err := restarted.Policies().GetByID(ctx, want.ID()) if err != nil { t.Fatalf("GetByID(%s) after restart error = %v", want.ID(), err) } assertSamePolicyVersion(t, got, want) } latest, err := restarted.Policies().GetLatest(ctx, domain.ProductPolicyKey) if err != nil || latest.ID() != written[1].ID() { t.Fatalf("GetLatest() after restart = v%d, %v; want v2", latest.Version(), err) } if result, err := policy.NewPublisher(restarted.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil || result.Created { t.Fatalf("demo seed after restart = %+v, %v; want no insert", result, err) } }) } // integrationPolicy returns a valid calibrated policy for integration // fixtures. Its values differ from the demo policy, and maxPending tells // versions apart. func integrationPolicy(maxPending int32) domain.ProductPolicy { return domain.ProductPolicy{ Invitations: domain.InvitationPolicy{ ResponseDeadlineOptions: []domain.CalendarDays{1, 4, 9}, DefaultResponseDeadline: 4, MaxPendingPerNeed: maxPending, RepeatAfterDecline: 8, InterviewProposalDeadline: 2, NoDealPause: 6, }, OrganizationQuotas: domain.OrganizationQuotaPolicy{ InvitationWindow: 2, CardViewWindow: 6, TierE0: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 1, DistinctCardViewsPerWindow: 2}, TierE1: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 4}, TierE2: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 5, DistinctCardViewsPerWindow: 6}, }, Assessment: domain.AssessmentPolicy{ Calibration: domain.AssessmentCalibrationCalibrated, SameGradeRetryAfter: 4, MaxAttemptsPerWindow: 5, AttemptWindow: 40, PromotionMinInterval: 20, ConfirmationThreshold: 7000, HighStrengthThreshold: 8500, PracticeRequired: false, StopRule: domain.AssessmentStopRule{ MinScoredItems: 4, MaxScoredItems: 12, SeedItems: 1, UpperProbability: 9200, LowerProbability: 800, MaxStandardError: 3500, }, }, Identity: domain.IdentityPolicy{ VerificationTokenLifetime: 6, UnverifiedAccountLifetime: 2, SessionIdleTimeout: 3, SessionAbsoluteLifetime: 1, }, SearchStatus: domain.SearchStatusPolicy{SearchingConfirmationInterval: 10}, } } // draft builds a numbered calibrated test draft; a zero effectiveAt makes it // effective at publication. func (fixture policyFixture) draft(t *testing.T, number int32, effectiveAt time.Time, values domain.ProductPolicy) domain.PolicyVersionDraft { t.Helper() draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, EffectiveAt: effectiveAt, Policy: values, }) if err != nil { t.Fatalf("NewPolicyVersionDraft(v%d) error = %v", number, err) } numbered, err := draft.WithVersion(number) if err != nil { t.Fatalf("WithVersion(%d) error = %v", number, err) } return numbered } // demoDraft builds the draft the seed stores, for comparison only. func (fixture policyFixture) demoDraft(t *testing.T) domain.PolicyVersionDraft { t.Helper() draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(), }) if err != nil { t.Fatalf("NewPolicyVersionDraft(demo) error = %v", err) } return draft } func (fixture policyFixture) publish( t *testing.T, policies outbound.PolicyRepository, number int32, effectiveAt time.Time, values domain.ProductPolicy, ) domain.PolicyVersion { t.Helper() stored, err := policies.Create(fixture.ctx, fixture.draft(t, number, effectiveAt, values)) if err != nil { t.Fatalf("Create(v%d) error = %v", number, err) } return stored } func (fixture policyFixture) assertEffective(t *testing.T, at time.Time, want domain.PolicyVersion) { t.Helper() got, err := fixture.store.Policies().GetEffective(fixture.ctx, domain.ProductPolicyKey, at) if err != nil { t.Fatalf("GetEffective(%s) error = %v", at, err) } if got.ID() != want.ID() { t.Fatalf("GetEffective(%s) = v%d, want v%d", at, got.Version(), want.Version()) } } // readMaxPending reads one value from the stored jsonb document directly. func (fixture policyFixture) readMaxPending(t *testing.T, id domain.PolicyVersionID) int32 { t.Helper() var value int32 err := fixture.pool.QueryRow(fixture.ctx, `SELECT (document -> 'invitations' ->> 'max_pending_per_need')::integer FROM policy_versions WHERE id = $1`, id.UUID()).Scan(&value) if err != nil { t.Fatalf("read stored max_pending_per_need: %v", err) } return value } func (fixture policyFixture) assertVersionCount(t *testing.T, want int) { t.Helper() var count int if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM policy_versions`).Scan(&count); err != nil { t.Fatalf("count policy versions: %v", err) } if count != want { t.Fatalf("policy_versions has %d rows, want %d", count, want) } } // newSizedPoolFor opens a pool with maxConns connections to databaseURL, so // goroutines run at the same time instead of queueing for connections. func newSizedPoolFor(ctx context.Context, t *testing.T, databaseURL string, maxConns int32) *pgxpool.Pool { t.Helper() poolConfig, err := pgxpool.ParseConfig(databaseURL) if err != nil { t.Fatalf("parse 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 } // assertDatabaseTime checks that a time stamped by PostgreSQL is close to // the moment the test started the statement. func assertDatabaseTime(t *testing.T, name string, got, before time.Time) { t.Helper() if got.Before(before.Add(-databaseClockTolerance)) || got.After(time.Now().Add(databaseClockTolerance)) { t.Fatalf("%s = %s, want the database clock near %s", name, got, before) } } // assertPolicyImmutable checks the raw trigger error and its mapping. func assertPolicyImmutable(t *testing.T, statement string, err error) { t.Helper() var pgError *pgconn.PgError if !errors.As(err, &pgError) || pgError.Code != policyImmutableSQLState || pgError.ConstraintName != policyImmutableConstraint { t.Fatalf("%s error = %v, want SQLSTATE %s on %s", statement, err, policyImmutableSQLState, policyImmutableConstraint) } if mapped := postgresadapter.MapPolicyErrorForIntegrationTest(err); !errors.Is(mapped, outbound.ErrPolicyVersionImmutable) { t.Fatalf("%s mapped error = %v, want ErrPolicyVersionImmutable", statement, mapped) } if strings.Contains(err.Error(), "operator:") { t.Fatalf("%s error quotes row values: %v", statement, err) } } func assertSamePolicyVersion(t *testing.T, got, want domain.PolicyVersion) { t.Helper() if got.ID() != want.ID() || got.Key() != want.Key() || got.Version() != want.Version() || got.Kind() != want.Kind() || got.Author() != want.Author() || !got.EffectiveAt().Equal(want.EffectiveAt()) || !got.CreatedAt().Equal(want.CreatedAt()) || got.DocumentHash() != want.DocumentHash() || string(got.Document()) != string(want.Document()) { t.Fatalf("policy version = %s %s v%d, want %s %s v%d with the same metadata and document", got.ID(), got.Key(), got.Version(), want.ID(), want.Key(), want.Version()) } } // conflictCountingPolicies counts version number conflicts seen by Create. type conflictCountingPolicies struct { outbound.PolicyRepository conflicts atomic.Int64 } func (policies *conflictCountingPolicies) Create(ctx context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error) { stored, err := policies.PolicyRepository.Create(ctx, draft) if errors.Is(err, outbound.ErrPolicyVersionConflict) { policies.conflicts.Add(1) } return stored, err }