feat(policy): add immutable versioned product policy store

This commit is contained in:
shira committed 2026-10-06 01:52:39 +03:00
1 parent 0e2a3b02ab
commit 7a5105acc7
30 files changed
+3893 -37

No files matched your search

@@ -0,0 +1,116 @@
-- +goose Up
-- Versioned product policy: deadlines, quotas, thresholds, and coefficients
-- that product rules read. Every row is one immutable version of one policy
-- family. Records built under a policy, such as grade decisions, selection
-- snapshots, and invitations, will store the policy_versions.id they used, so
-- a newer version never changes how an earlier decision was made.
CREATE TABLE policy_versions (
-- UUIDv7 generated in Go.
id uuid NOT NULL,
-- Policy family. Each family has one document layout and one decoder in
-- Go; "product" is the only family. A new family changes this CHECK.
policy_key text NOT NULL,
-- Numbered from 1 within the family; the newest publication has the
-- highest number.
version integer NOT NULL,
-- Calibration state of the whole version, the flag consumers read. "demo"
-- values are an initial policy for verification and make no calibrated
-- quality claim.
kind text NOT NULL,
-- The version can apply to decisions made at or after this time. A NULL
-- in the INSERT means "at publication"; the stamp trigger fills it in.
effective_at timestamptz NOT NULL,
-- Operator identity such as "system:demo-seed" or "operator:<handle>".
-- Never an email address or other contact data.
author text NOT NULL,
-- The typed policy serialized by the domain in canonical form. jsonb
-- normalizes key order and whitespace; integrity is checked against
-- document_sha256 after the domain re-encodes the decoded document.
document jsonb NOT NULL,
-- SHA-256 of the canonical document bytes, 32 raw bytes.
document_sha256 bytea NOT NULL,
-- Publication time from the database clock, set by the stamp trigger on
-- every insert; a value from the caller is ignored.
created_at timestamptz NOT NULL,
CONSTRAINT policy_versions_pkey PRIMARY KEY (id),
CONSTRAINT policy_versions_policy_key_version_key UNIQUE (
policy_key, version
),
CONSTRAINT policy_versions_policy_key_known CHECK (
policy_key IN ('product')
),
CONSTRAINT policy_versions_version_positive CHECK (version > 0),
CONSTRAINT policy_versions_kind_known CHECK (
kind IN ('demo', 'calibrated')
),
CONSTRAINT policy_versions_author_format CHECK (
char_length(author) <= 128
AND author ~ '^(system|operator):[a-z0-9][a-z0-9._-]*$'
),
CONSTRAINT policy_versions_document_object CHECK (
jsonb_typeof(document) = 'object'
),
-- A calibrated version cannot carry an assessment section that its own
-- document marks as uncalibrated.
CONSTRAINT policy_versions_calibrated_kind_matches_document CHECK (
kind <> 'calibrated'
OR document #>> '{assessment,calibration}' = 'calibrated'
),
CONSTRAINT policy_versions_document_sha256_size CHECK (
octet_length(document_sha256) = 32
),
-- A version is never backdated: publishing it cannot change which version
-- applied at a moment that already passed.
CONSTRAINT policy_versions_effective_after_creation CHECK (
effective_at >= created_at
)
);
-- Sets created_at from the database clock and defaults effective_at to it.
-- NOT NULL and CHECK constraints run after BEFORE triggers, so they see the
-- stamped values.
-- +goose StatementBegin
CREATE FUNCTION policy_versions_stamp_creation() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.created_at := clock_timestamp();
NEW.effective_at := coalesce(NEW.effective_at, NEW.created_at);
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER policy_versions_stamp_creation
BEFORE INSERT ON policy_versions
FOR EACH ROW EXECUTE FUNCTION policy_versions_stamp_creation();
-- Refuses every UPDATE, DELETE, and TRUNCATE of policy versions. The error
-- uses SQLSTATE 23000 (integrity_constraint_violation) and the constraint name
-- policy_versions_immutable, which the adapter maps to a port sentinel without
-- reading the message. The message quotes no row values.
-- +goose StatementBegin
CREATE FUNCTION policy_versions_refuse_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'policy_versions_immutable',
TABLE = 'policy_versions',
MESSAGE = 'policy versions are immutable: publish a new version instead';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER policy_versions_refuse_update_delete
BEFORE UPDATE OR DELETE ON policy_versions
FOR EACH ROW EXECUTE FUNCTION policy_versions_refuse_change();
-- Row triggers do not fire for TRUNCATE, so a statement trigger covers it.
CREATE TRIGGER policy_versions_refuse_truncate
BEFORE TRUNCATE ON policy_versions
FOR EACH STATEMENT EXECUTE FUNCTION policy_versions_refuse_change();
-- +goose Down
DROP TABLE policy_versions;
DROP FUNCTION policy_versions_refuse_change();
DROP FUNCTION policy_versions_stamp_creation();
+96
View File
@@ -0,0 +1,96 @@
-- Stores a version and returns the stored row with the publication time and
-- effective time set by the stamp trigger. A taken ID or version number
-- returns no row instead of an error, so a conflict does not abort the
-- surrounding transaction. created_at is never taken from the caller, and a
-- NULL effective_at means "at publication".
-- name: InsertPolicyVersion :one
INSERT INTO policy_versions (
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256
) VALUES (
sqlc.arg(id),
sqlc.arg(policy_key),
sqlc.arg(version),
sqlc.arg(kind),
sqlc.narg(effective_at),
sqlc.arg(author),
sqlc.arg(document),
sqlc.arg(document_sha256)
)
ON CONFLICT DO NOTHING
RETURNING
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256,
created_at;
-- name: GetPolicyVersionByID :one
SELECT
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256,
created_at
FROM policy_versions
WHERE id = sqlc.arg(id);
-- Among the versions of a family already effective at a time, the newest
-- publication wins. A version scheduled for later therefore never undoes a
-- version published after it. The unique (policy_key, version) index serves
-- the backward scan.
-- name: GetEffectivePolicyVersion :one
SELECT
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256,
created_at
FROM policy_versions
WHERE
policy_key = sqlc.arg(policy_key)
AND effective_at <= sqlc.arg(at)
ORDER BY version DESC
LIMIT 1;
-- name: GetLatestPolicyVersion :one
SELECT
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256,
created_at
FROM policy_versions
WHERE policy_key = sqlc.arg(policy_key)
ORDER BY version DESC
LIMIT 1;
-- Reports whether a family has any version without reading a document, so a
-- caller that only needs presence never depends on decoding.
-- name: PolicyVersionExists :one
SELECT exists(
SELECT 1 FROM policy_versions
WHERE policy_key = sqlc.arg(policy_key)
) AS present;
+728
View File
@@ -0,0 +1,728 @@
//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
}
@@ -19,13 +19,20 @@ const (
concurrentMigrators = 4
)
// identityMigrationVersion creates identityTableNames.
const identityMigrationVersion = 2
const (
// identityMigrationVersion creates identityTableNames.
identityMigrationVersion = 2
// policyMigrationVersion creates policyTableNames and policyFunctionNames.
policyMigrationVersion = 3
)
var (
// Tables created by 00001 and by 00002.
// Tables created by 00001, 00002, and 00003.
outboxTables = []string{"outbox_events"}
identityTableNames = []string{"users", "email_tokens", "sessions"}
policyTableNames = []string{"policy_versions"}
// Trigger functions created by 00003.
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
)
func TestPostgresMigrations(t *testing.T) {
@@ -52,8 +59,10 @@ func TestPostgresMigrations(t *testing.T) {
}
assertTablesExist(ctx, t, pool, true, outboxTables...)
assertTablesExist(ctx, t, pool, true, identityTableNames...)
assertTablesExist(ctx, t, pool, true, policyTableNames...)
assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...)
identityRolledBack := false
identityRolledBack, policyRolledBack := false, false
for rolledBack := 0; ; rolledBack++ {
result, err := migrator.DownOne(ctx)
if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) {
@@ -65,6 +74,14 @@ func TestPostgresMigrations(t *testing.T) {
if err != nil {
t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err)
}
if result.Version == policyMigrationVersion {
// The policy migration rolls back its table, triggers, and
// function and leaves the identity tables.
assertTablesExist(ctx, t, pool, false, policyTableNames...)
assertFunctionsExist(ctx, t, pool, false, policyFunctionNames...)
assertTablesExist(ctx, t, pool, true, identityTableNames...)
policyRolledBack = true
}
if result.Version == identityMigrationVersion {
// The identity migration rolls back on its own and leaves the
// outbox migration before it.
@@ -73,11 +90,12 @@ func TestPostgresMigrations(t *testing.T) {
identityRolledBack = true
}
}
if !identityRolledBack {
t.Fatalf("migration %d was not rolled back", identityMigrationVersion)
if !identityRolledBack || !policyRolledBack {
t.Fatalf("migrations %d and %d were not both rolled back", identityMigrationVersion, policyMigrationVersion)
}
assertTablesExist(ctx, t, pool, false, outboxTables...)
assertTablesExist(ctx, t, pool, false, identityTableNames...)
assertTablesExist(ctx, t, pool, false, policyTableNames...)
var leftovers int
err = pool.QueryRow(ctx, `
SELECT count(*) FROM pg_catalog.pg_class AS c
@@ -89,6 +107,17 @@ func TestPostgresMigrations(t *testing.T) {
if leftovers != 0 {
t.Fatalf("%d relations remain after rolling back every migration", leftovers)
}
var leftoverFunctions int
err = pool.QueryRow(ctx, `
SELECT count(*) FROM pg_catalog.pg_proc AS p
JOIN pg_catalog.pg_namespace AS n ON n.oid = p.pronamespace
WHERE n.nspname = 'public'`).Scan(&leftoverFunctions)
if err != nil {
t.Fatalf("count leftover functions: %v", err)
}
if leftoverFunctions != 0 {
t.Fatalf("%d functions remain after rolling back every migration", leftoverFunctions)
}
applied, err = migrator.Up(ctx)
if err != nil {
@@ -99,6 +128,8 @@ func TestPostgresMigrations(t *testing.T) {
}
assertTablesExist(ctx, t, pool, true, outboxTables...)
assertTablesExist(ctx, t, pool, true, identityTableNames...)
assertTablesExist(ctx, t, pool, true, policyTableNames...)
assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...)
assertAllApplied(ctx, t, migrator, total)
})
@@ -164,3 +195,16 @@ func assertTablesExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, wa
}
}
}
func assertFunctionsExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool, signatures ...string) {
t.Helper()
for _, signature := range signatures {
var exists bool
if err := pool.QueryRow(ctx, `SELECT to_regprocedure($1) IS NOT NULL`, "public."+signature).Scan(&exists); err != nil {
t.Fatalf("check function %s: %v", signature, err)
}
if exists != want {
t.Fatalf("function %s exists = %t, want %t", signature, exists, want)
}
}
}
@@ -18,3 +18,11 @@ func TransactionForIntegrationTest(unit outbound.UnitOfWork) (pgx.Tx, bool) {
}
return postgresUnit.tx, true
}
// MapPolicyErrorForIntegrationTest applies the policy error mapping to an
// error from a raw statement, so integration tests can prove that the
// database refusal of a policy change becomes the port sentinel. It is
// compiled only with the integration build tag.
func MapPolicyErrorForIntegrationTest(err error) error {
return mapPolicyError(err)
}
@@ -0,0 +1,187 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
// integrityConstraintViolationCode is the SQLSTATE that the
// policy_versions_refuse_change trigger raises.
integrityConstraintViolationCode = "23000"
checkViolationCode = "23514"
// policyVersionsImmutableConstraint is the constraint name the trigger
// reports. It is not a table constraint; the trigger sets it so the error
// can be matched like one.
policyVersionsImmutableConstraint = "policy_versions_immutable"
)
// policyConstraintErrors maps policy errors whose cause is a caller-visible
// outcome to port sentinels by SQLSTATE and constraint name, never by text.
// Unique violations do not occur: the insert uses ON CONFLICT DO NOTHING.
var policyConstraintErrors = map[constraintViolation]error{
{integrityConstraintViolationCode, policyVersionsImmutableConstraint}: outbound.ErrPolicyVersionImmutable,
{checkViolationCode, "policy_versions_effective_after_creation"}: outbound.ErrPolicyVersionBackdated,
}
// mapPolicyError turns a known policy constraint or trigger error into its
// port sentinel and keeps the constraint name. Any other PostgreSQL error is
// replaced by its SQLSTATE and constraint name, as the identity repositories
// do, so authors and document values never reach error text. Deadlocks and
// serialization failures also match ErrTransactionConflict. A connection
// error loses the pgx prefix that names the database user and database;
// other errors that do not come from PostgreSQL pass through.
func mapPolicyError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := policyConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapPolicyError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
// PolicyStore provides the policy repository outside a transaction. Every
// call runs as its own statement on a pool connection. Called with a context
// that belongs to a Transactor callback, it fails with
// outbound.ErrNestedTransaction; use UnitOfWork.Policies there.
type PolicyStore struct {
queries *sqlc.Queries
}
func NewPolicyStore(pool *pgxpool.Pool) *PolicyStore {
return &PolicyStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
func (store *PolicyStore) Policies() outbound.PolicyRepository {
return policyRepository{queries: store.queries}
}
func (unit *UnitOfWork) Policies() outbound.PolicyRepository {
return policyRepository{queries: unit.queries}
}
type policyRepository struct {
queries *sqlc.Queries
}
var _ outbound.PolicyRepository = policyRepository{}
func (repository policyRepository) Create(ctx context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error) {
if draft.IsZero() || draft.Version() <= 0 {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.Create - draft was not built and numbered by domain.NewPolicyVersionDraft: %w", domain.ErrInvalidPolicyVersion)
}
effectiveAt := pgtype.Timestamptz{}
if scheduled, ok := draft.EffectiveAt(); ok {
effectiveAt = pgTime(scheduled)
}
hash := draft.DocumentHash()
row, err := repository.queries.InsertPolicyVersion(ctx, sqlc.InsertPolicyVersionParams{
ID: pgUUID(draft.ID().UUID()),
PolicyKey: string(draft.Key()),
Version: draft.Version(),
Kind: string(draft.Kind()),
EffectiveAt: effectiveAt,
Author: string(draft.Author()),
Document: draft.Document(),
DocumentSha256: hash[:],
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.Create - insert %s version %d: %w", draft.Key(), draft.Version(), outbound.ErrPolicyVersionConflict)
}
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.Create - insert policy version: %w", mapPolicyError(err))
}
return policyVersionFromRow(row)
}
func (repository policyRepository) GetByID(ctx context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
row, err := repository.queries.GetPolicyVersionByID(ctx, pgUUID(id.UUID()))
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.GetByID - select policy version: %w", mapPolicyNoRows(err))
}
return policyVersionFromRow(row)
}
func (repository policyRepository) GetEffective(ctx context.Context, key domain.PolicyKey, at time.Time) (domain.PolicyVersion, error) {
if err := requireTime("policyRepository.GetEffective", at, domain.ErrInvalidPolicyVersion); err != nil {
return domain.PolicyVersion{}, err
}
if err := requireKnownFamily("policyRepository.GetEffective", key); err != nil {
return domain.PolicyVersion{}, err
}
row, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{
PolicyKey: string(key),
At: pgTime(at),
})
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.GetEffective - select policy version: %w", mapPolicyNoRows(err))
}
return policyVersionFromRow(row)
}
func (repository policyRepository) GetLatest(ctx context.Context, key domain.PolicyKey) (domain.PolicyVersion, error) {
if err := requireKnownFamily("policyRepository.GetLatest", key); err != nil {
return domain.PolicyVersion{}, err
}
row, err := repository.queries.GetLatestPolicyVersion(ctx, string(key))
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("policyRepository.GetLatest - select policy version: %w", mapPolicyNoRows(err))
}
return policyVersionFromRow(row)
}
func (repository policyRepository) HasVersions(ctx context.Context, key domain.PolicyKey) (bool, error) {
if err := requireKnownFamily("policyRepository.HasVersions", key); err != nil {
return false, err
}
present, err := repository.queries.PolicyVersionExists(ctx, string(key))
if err != nil {
return false, fmt.Errorf("policyRepository.HasVersions - check policy versions: %w", mapPolicyError(err))
}
return present, nil
}
func requireKnownFamily(location string, key domain.PolicyKey) error {
if _, err := domain.ParsePolicyKey(string(key)); err != nil {
return fmt.Errorf("%s - validate family: %w", location, err)
}
return nil
}
func mapPolicyNoRows(err error) error {
if errors.Is(err, pgx.ErrNoRows) {
return outbound.ErrPolicyVersionNotFound
}
return mapPolicyError(err)
}
func policyVersionFromRow(row sqlc.PolicyVersion) (domain.PolicyVersion, error) {
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
ID: domain.PolicyVersionID(row.ID.Bytes),
Key: row.PolicyKey,
Version: row.Version,
Kind: row.Kind,
Author: row.Author,
EffectiveAt: row.EffectiveAt.Time,
CreatedAt: row.CreatedAt.Time,
Document: row.Document,
DocumentHash: row.DocumentSha256,
})
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("postgres.policyVersionFromRow - restore policy version: %w", err)
}
return version, nil
}
@@ -0,0 +1,89 @@
package postgres
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestMapPolicyErrorRecognizesPolicyConstraints(t *testing.T) {
tests := []struct {
code string
constraint string
want error
}{
{code: integrityConstraintViolationCode, constraint: policyVersionsImmutableConstraint, want: outbound.ErrPolicyVersionImmutable},
{code: checkViolationCode, constraint: "policy_versions_effective_after_creation", want: outbound.ErrPolicyVersionBackdated},
}
for _, test := range tests {
err := mapPolicyError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: "Key (author)=(operator:secret) already exists."})
if !errors.Is(err, test.want) {
t.Fatalf("mapPolicyError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
}
if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "secret") {
t.Fatalf("mapPolicyError(%s) = %v, want the constraint name and no detail", test.constraint, err)
}
}
}
func TestMapPolicyErrorMatchesCodeAndConstraintTogether(t *testing.T) {
// The immutability sentinel needs both the trigger's SQLSTATE and its
// constraint name; either one alone is another error.
for _, original := range []*pgconn.PgError{
{Code: "P0001", ConstraintName: policyVersionsImmutableConstraint, Message: "policy versions are immutable"},
{Code: integrityConstraintViolationCode, ConstraintName: "other_constraint", Message: "policy versions are immutable"},
} {
err := mapPolicyError(original)
if errors.Is(err, outbound.ErrPolicyVersionImmutable) {
t.Fatalf("mapPolicyError(%s %s) = %v, want no immutability sentinel", original.Code, original.ConstraintName, err)
}
var stateError sqlStateError
if !errors.As(err, &stateError) || stateError.SQLState() != original.Code || strings.Contains(err.Error(), "are immutable") {
t.Fatalf("mapPolicyError() = %v, want only SQLSTATE %s and the constraint", err, original.Code)
}
}
}
func TestMapPolicyErrorKeepsOtherErrors(t *testing.T) {
for _, original := range []error{context.Canceled, outbound.ErrNestedTransaction} {
if err := mapPolicyError(original); !errors.Is(err, original) {
t.Fatalf("mapPolicyError(%v) = %v, want the original error", original, err)
}
}
}
func TestPolicyRepositoryRejectsInvalidInputBeforeQuerying(t *testing.T) {
// A repository without queries proves that no statement runs.
repository := policyRepository{}
if _, err := repository.Create(t.Context(), domain.PolicyVersionDraft{}); !errors.Is(err, domain.ErrInvalidPolicyVersion) {
t.Fatalf("Create(zero draft) error = %v, want ErrInvalidPolicyVersion", err)
}
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(),
})
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
if _, err := repository.Create(t.Context(), draft); !errors.Is(err, domain.ErrInvalidPolicyVersion) {
t.Fatalf("Create(unnumbered draft) error = %v, want ErrInvalidPolicyVersion", err)
}
if _, err := repository.GetEffective(t.Context(), domain.ProductPolicyKey, time.Time{}); !errors.Is(err, domain.ErrInvalidPolicyVersion) {
t.Fatalf("GetEffective(zero time) error = %v, want ErrInvalidPolicyVersion", err)
}
if _, err := repository.GetEffective(t.Context(), "other", time.Now()); !errors.Is(err, domain.ErrInvalidPolicyVersion) {
t.Fatalf("GetEffective(unknown family) error = %v, want ErrInvalidPolicyVersion", err)
}
if _, err := repository.GetLatest(t.Context(), "other"); !errors.Is(err, domain.ErrInvalidPolicyVersion) {
t.Fatalf("GetLatest(unknown family) error = %v, want ErrInvalidPolicyVersion", err)
}
if _, err := repository.HasVersions(t.Context(), "other"); !errors.Is(err, domain.ErrInvalidPolicyVersion) {
t.Fatalf("HasVersions(unknown family) error = %v, want ErrInvalidPolicyVersion", err)
}
}
@@ -33,6 +33,18 @@ type OutboxEvent struct {
PublishedAt pgtype.Timestamptz
}
type PolicyVersion struct {
ID pgtype.UUID
PolicyKey string
Version int32
Kind string
EffectiveAt pgtype.Timestamptz
Author string
Document []byte
DocumentSha256 []byte
CreatedAt pgtype.Timestamptz
}
type Session struct {
ID pgtype.UUID
UserID pgtype.UUID
@@ -0,0 +1,214 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: policy.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getEffectivePolicyVersion = `-- name: GetEffectivePolicyVersion :one
SELECT
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256,
created_at
FROM policy_versions
WHERE
policy_key = $1
AND effective_at <= $2
ORDER BY version DESC
LIMIT 1
`
type GetEffectivePolicyVersionParams struct {
PolicyKey string
At pgtype.Timestamptz
}
// Among the versions of a family already effective at a time, the newest
// publication wins. A version scheduled for later therefore never undoes a
// version published after it. The unique (policy_key, version) index serves
// the backward scan.
func (q *Queries) GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error) {
row := q.db.QueryRow(ctx, getEffectivePolicyVersion, arg.PolicyKey, arg.At)
var i PolicyVersion
err := row.Scan(
&i.ID,
&i.PolicyKey,
&i.Version,
&i.Kind,
&i.EffectiveAt,
&i.Author,
&i.Document,
&i.DocumentSha256,
&i.CreatedAt,
)
return i, err
}
const getLatestPolicyVersion = `-- name: GetLatestPolicyVersion :one
SELECT
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256,
created_at
FROM policy_versions
WHERE policy_key = $1
ORDER BY version DESC
LIMIT 1
`
func (q *Queries) GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error) {
row := q.db.QueryRow(ctx, getLatestPolicyVersion, policyKey)
var i PolicyVersion
err := row.Scan(
&i.ID,
&i.PolicyKey,
&i.Version,
&i.Kind,
&i.EffectiveAt,
&i.Author,
&i.Document,
&i.DocumentSha256,
&i.CreatedAt,
)
return i, err
}
const getPolicyVersionByID = `-- name: GetPolicyVersionByID :one
SELECT
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256,
created_at
FROM policy_versions
WHERE id = $1
`
func (q *Queries) GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error) {
row := q.db.QueryRow(ctx, getPolicyVersionByID, id)
var i PolicyVersion
err := row.Scan(
&i.ID,
&i.PolicyKey,
&i.Version,
&i.Kind,
&i.EffectiveAt,
&i.Author,
&i.Document,
&i.DocumentSha256,
&i.CreatedAt,
)
return i, err
}
const insertPolicyVersion = `-- name: InsertPolicyVersion :one
INSERT INTO policy_versions (
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
ON CONFLICT DO NOTHING
RETURNING
id,
policy_key,
version,
kind,
effective_at,
author,
document,
document_sha256,
created_at
`
type InsertPolicyVersionParams struct {
ID pgtype.UUID
PolicyKey string
Version int32
Kind string
EffectiveAt pgtype.Timestamptz
Author string
Document []byte
DocumentSha256 []byte
}
// Stores a version and returns the stored row with the publication time and
// effective time set by the stamp trigger. A taken ID or version number
// returns no row instead of an error, so a conflict does not abort the
// surrounding transaction. created_at is never taken from the caller, and a
// NULL effective_at means "at publication".
func (q *Queries) InsertPolicyVersion(ctx context.Context, arg InsertPolicyVersionParams) (PolicyVersion, error) {
row := q.db.QueryRow(ctx, insertPolicyVersion,
arg.ID,
arg.PolicyKey,
arg.Version,
arg.Kind,
arg.EffectiveAt,
arg.Author,
arg.Document,
arg.DocumentSha256,
)
var i PolicyVersion
err := row.Scan(
&i.ID,
&i.PolicyKey,
&i.Version,
&i.Kind,
&i.EffectiveAt,
&i.Author,
&i.Document,
&i.DocumentSha256,
&i.CreatedAt,
)
return i, err
}
const policyVersionExists = `-- name: PolicyVersionExists :one
SELECT exists(
SELECT 1 FROM policy_versions
WHERE policy_key = $1
) AS present
`
// Reports whether a family has any version without reading a document, so a
// caller that only needs presence never depends on decoding.
func (q *Queries) PolicyVersionExists(ctx context.Context, policyKey string) (bool, error) {
row := q.db.QueryRow(ctx, policyVersionExists, policyKey)
var present bool
err := row.Scan(&present)
return present, err
}
@@ -33,12 +33,25 @@ type Querier interface {
// statement was locked above.
DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error)
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
// Among the versions of a family already effective at a time, the newest
// publication wins. A version scheduled for later therefore never undoes a
// version published after it. The unique (policy_key, version) index serves
// the backward scan.
GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error)
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
// Stores a version and returns the stored row with the publication time and
// effective time set by the stamp trigger. A taken ID or version number
// returns no row instead of an error, so a conflict does not abort the
// surrounding transaction. created_at is never taken from the caller, and a
// NULL effective_at means "at publication".
InsertPolicyVersion(ctx context.Context, arg InsertPolicyVersionParams) (PolicyVersion, error)
InsertSession(ctx context.Context, arg InsertSessionParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
@@ -46,6 +59,9 @@ type Querier interface {
// was issued for.
MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error)
Ping(ctx context.Context) (int32, error)
// Reports whether a family has any version without reading a document, so a
// caller that only needs presence never depends on decoding.
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
// Records activity on an active session and reports whether it is active.
+5 -1
View File
@@ -84,7 +84,8 @@ func run(ctx context.Context, config config.Config, logger *slog.Logger) error {
// start prepares the application without opening listeners. The mail
// transport is selected before migrations, so a configuration that cannot
// start never changes the database.
// start never changes the database. The demo policy seed runs after the
// migrations that create its table.
func start(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) {
if err := config.Validate(); err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - validate configuration: %w", err)
@@ -96,6 +97,9 @@ func start(ctx context.Context, config config.Config, logger *slog.Logger) (*App
if err := migrateDatabase(ctx, config, logger); err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - migrate database: %w", err)
}
if err := seedDemoPolicy(ctx, config, logger); err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - seed demo policy: %w", err)
}
application, cleanup, err := initialize(ctx, config, logger, mailSender)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err)
+57
View File
@@ -0,0 +1,57 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/policy"
)
// startupPolicySeedTimeout bounds the demo policy seed, which reads one row
// and inserts at most one.
const startupPolicySeedTimeout = 30 * time.Second
// seedDemoPolicy publishes the demo product policy as version 1 when the
// product family has no version yet, so a fresh database has an effective
// policy as soon as the service starts. It runs right after the startup
// migrations and under the same switch: it is skipped when
// DATABASE_MIGRATE_ON_START is false or DATABASE_URL is unset, and then a
// developer who migrates by hand also starts without a seeded policy. It
// checks presence only, so an existing version, even one this build cannot
// decode, is left alone and does not block startup. A database error stops
// startup, like a failed migration.
func seedDemoPolicy(ctx context.Context, settings config.Config, logger *slog.Logger) error {
if !settings.DatabaseMigrateOnStart || settings.DatabaseURL == "" {
return nil
}
pool, err := postgres.NewPool(ctx, settings.DatabaseURL)
if err != nil {
return fmt.Errorf("bootstrap.seedDemoPolicy - create pool: %w", err)
}
defer pool.Close()
ctx, cancel := context.WithTimeout(ctx, startupPolicySeedTimeout)
defer cancel()
publisher := policy.NewPublisher(postgres.NewPolicyStore(pool).Policies(), time.Now)
result, err := publisher.EnsureDemoProductPolicy(ctx)
if err != nil {
return fmt.Errorf("bootstrap.seedDemoPolicy - ensure demo product policy: %w", err)
}
if !result.Created {
logger.Info("product policy already present; demo seed skipped",
slog.String("policy_key", string(domain.ProductPolicyKey)),
)
return nil
}
logger.Info("demo product policy published",
slog.String("policy_key", string(result.Version.Key())),
slog.Int("policy_version", int(result.Version.Version())),
slog.String("policy_kind", string(result.Version.Kind())),
slog.String("policy_version_id", result.Version.ID().String()),
)
return nil
}
+42
View File
@@ -0,0 +1,42 @@
package bootstrap
import (
"log/slog"
"strings"
"testing"
"lincodex/backend/config"
)
func TestSeedDemoPolicySkipsWithoutStartupMigrations(t *testing.T) {
tests := []struct {
name string
settings config.Config
}{
// An unreachable address proves that no connection is attempted.
{name: "startup migrations disabled", settings: config.Config{DatabaseMigrateOnStart: false, DatabaseURL: "postgres://app@db:not-a-port/app"}},
{name: "database not configured", settings: config.Config{DatabaseMigrateOnStart: true}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if err := seedDemoPolicy(t.Context(), test.settings, slog.New(slog.DiscardHandler)); err != nil {
t.Fatalf("seedDemoPolicy() error = %v", err)
}
})
}
}
func TestSeedDemoPolicyHidesConnectionStringOnFailure(t *testing.T) {
const password = "seed-secret-password"
settings := config.Config{
DatabaseMigrateOnStart: true,
DatabaseURL: "postgres://app:" + password + "@db:not-a-port/app",
}
err := seedDemoPolicy(t.Context(), settings, slog.New(slog.DiscardHandler))
if err == nil {
t.Fatal("seedDemoPolicy() accepted an invalid DATABASE_URL")
}
if strings.Contains(err.Error(), password) || strings.Contains(err.Error(), "db:not-a-port") {
t.Fatalf("seedDemoPolicy() error exposes the connection string: %v", err)
}
}
+415
View File
@@ -0,0 +1,415 @@
package domain
import (
"errors"
"fmt"
"slices"
"time"
)
// ErrInvalidPolicy reports a policy value that is missing, out of range, or
// inconsistent with another value of the same policy.
var ErrInvalidPolicy = errors.New("invalid policy")
// Units of policy values. Every value carries its unit in its type and in its
// document field name, so a number never changes meaning between code and
// storage.
type (
// CalendarDays counts whole days of 24 hours. Duration does not follow
// daylight saving shifts; deadlines are computed in UTC.
CalendarDays int32
// BusinessDays counts working days. Converting it to a deadline needs a
// business calendar, which the consuming feature defines, so it has no
// Duration method.
BusinessDays int32
// Hours counts whole hours.
Hours int32
// BasisPoints is a non-negative decimal with four fractional digits,
// stored as an integer count of 0.0001 units: 0.80 is 8000. Thresholds
// compare exactly, without the drift of binary floating point, and the
// document keeps an integer that every JSON reader decodes the same way.
BasisPoints int32
)
// basisPointsPerUnit is the BasisPoints value of 1.0.
const basisPointsPerUnit BasisPoints = 10000
func (days CalendarDays) Duration() time.Duration { return time.Duration(days) * 24 * time.Hour }
func (hours Hours) Duration() time.Duration { return time.Duration(hours) * time.Hour }
// String formats the value as a decimal, for example "0.8000".
func (points BasisPoints) String() string {
return fmt.Sprintf("%d.%04d", points/basisPointsPerUnit, points%basisPointsPerUnit)
}
// Sanity bounds of policy values. They reject typing mistakes such as a
// value in the wrong unit; they are not product decisions, which the policy
// values themselves record.
const (
maxResponseDeadlineOptions = 5
maxResponseDeadline = CalendarDays(30)
maxPendingInvitationsPerNeed = 1000
maxRepeatAfterDecline = CalendarDays(365)
maxInterviewProposalDeadline = BusinessDays(30)
maxNoDealPause = CalendarDays(365)
maxInvitationQuotaWindow = CalendarDays(31)
maxCardViewQuotaWindow = Hours(7 * 24)
maxTierQuotaLimit = 100000
maxSameGradeRetryInterval = CalendarDays(365)
maxAssessmentAttemptsPerWindow = 20
maxAssessmentAttemptWindow = CalendarDays(730)
maxPromotionInterval = CalendarDays(730)
maxScoredItems = 200
maxSeedItems = 20
maxVerificationTokenLifetime = Hours(7 * 24)
maxUnverifiedAccountLifetime = CalendarDays(90)
maxSessionIdleTimeout = Hours(30 * 24)
maxSessionAbsoluteLifetime = CalendarDays(90)
maxSearchingConfirmationInterval = CalendarDays(365)
minExclusiveProbabilityBasisPoints = BasisPoints(1)
maxExclusiveProbabilityBasisPoints = basisPointsPerUnit - 1
minPositiveStandardErrorBasisPoints = BasisPoints(1)
)
// ProductPolicy holds the deadlines, quotas, thresholds, and coefficients
// that product rules read. A stored policy is immutable: a change is a new
// PolicyVersion, and records built under a policy keep the version they used.
type ProductPolicy struct {
Invitations InvitationPolicy
OrganizationQuotas OrganizationQuotaPolicy
Assessment AssessmentPolicy
Identity IdentityPolicy
SearchStatus SearchStatusPolicy
}
// Validate checks every section. A zero value is never valid, so a section
// that was left out fails instead of silently meaning zero.
func (policy ProductPolicy) Validate() error {
for _, validate := range []func() error{
policy.Invitations.Validate,
policy.OrganizationQuotas.Validate,
policy.Assessment.Validate,
policy.Identity.Validate,
policy.SearchStatus.Validate,
} {
if err := validate(); err != nil {
return err
}
}
return nil
}
// clone copies the slices, so a caller cannot change a stored version through
// a returned policy.
func (policy ProductPolicy) clone() ProductPolicy {
copied := policy
copied.Invitations.ResponseDeadlineOptions = slices.Clone(policy.Invitations.ResponseDeadlineOptions)
return copied
}
// InvitationPolicy governs salary offers sent to candidates.
type InvitationPolicy struct {
// ResponseDeadlineOptions are the response deadlines an employer may
// choose, in strictly increasing order.
ResponseDeadlineOptions []CalendarDays
// DefaultResponseDeadline is one of ResponseDeadlineOptions.
DefaultResponseDeadline CalendarDays
// MaxPendingPerNeed limits unanswered invitations for one employer need.
MaxPendingPerNeed int32
// RepeatAfterDecline is the pause before the same company may invite a
// candidate who declined.
RepeatAfterDecline CalendarDays
// InterviewProposalDeadline is the time the employer has to propose an
// interview after acceptance.
InterviewProposalDeadline BusinessDays
// NoDealPause is the pause after a contact that ended without a deal.
NoDealPause CalendarDays
}
func (policy InvitationPolicy) Validate() error {
const location = "InvitationPolicy.Validate"
options := policy.ResponseDeadlineOptions
if len(options) == 0 || len(options) > maxResponseDeadlineOptions {
return invalidPolicy(location, fmt.Sprintf("invitations.response_deadline_options_days must have 1 to %d values", maxResponseDeadlineOptions))
}
for index, option := range options {
if err := checkRange(location, "invitations.response_deadline_options_days", option, 1, maxResponseDeadline); err != nil {
return err
}
if index > 0 && option <= options[index-1] {
return invalidPolicy(location, "invitations.response_deadline_options_days must be strictly increasing")
}
}
if !slices.Contains(options, policy.DefaultResponseDeadline) {
return invalidPolicy(location, "invitations.default_response_deadline_days must be one of the response deadline options")
}
return firstError(
checkRange(location, "invitations.max_pending_per_need", policy.MaxPendingPerNeed, 1, maxPendingInvitationsPerNeed),
checkRange(location, "invitations.repeat_after_decline_days", policy.RepeatAfterDecline, 1, maxRepeatAfterDecline),
checkRange(location, "invitations.interview_proposal_deadline_business_days", policy.InterviewProposalDeadline, 1, maxInterviewProposalDeadline),
checkRange(location, "invitations.no_deal_pause_days", policy.NoDealPause, 1, maxNoDealPause),
)
}
// OrganizationTier is an employer trust level. Levels are ordered E0 < E1 <
// E2; the rules that move an organization between them belong to the quota
// feature, not to the policy. E0 is the level every organization starts at.
type OrganizationTier string
const (
OrganizationTierE0 OrganizationTier = "e0"
OrganizationTierE1 OrganizationTier = "e1"
OrganizationTierE2 OrganizationTier = "e2"
)
// ParseOrganizationTier accepts e0, e1, or e2.
func ParseOrganizationTier(value string) (OrganizationTier, error) {
tier := OrganizationTier(value)
switch tier {
case OrganizationTierE0, OrganizationTierE1, OrganizationTierE2:
return tier, nil
default:
return "", invalidPolicy("domain.ParseOrganizationTier", "tier must be e0, e1, or e2")
}
}
// OrganizationQuotaPolicy limits employer activity per trust level. Limits
// apply per rolling window.
type OrganizationQuotaPolicy struct {
InvitationWindow CalendarDays
CardViewWindow Hours
TierE0 OrganizationTierQuota
TierE1 OrganizationTierQuota
TierE2 OrganizationTierQuota
}
// OrganizationTierQuota is the quota of one level. An inactive level keeps
// its limits for the time it is enabled, but no organization can hold it
// before that. E0 is always active, and the active levels form a prefix: a
// level is active only when every lower level is.
type OrganizationTierQuota struct {
Active bool
InvitationsPerWindow int32
DistinctCardViewsPerWindow int32
}
// Tier returns the quota of a level. An unknown level returns
// ErrInvalidPolicy; callers check Active before assigning a level.
func (policy OrganizationQuotaPolicy) Tier(tier OrganizationTier) (OrganizationTierQuota, error) {
switch tier {
case OrganizationTierE0:
return policy.TierE0, nil
case OrganizationTierE1:
return policy.TierE1, nil
case OrganizationTierE2:
return policy.TierE2, nil
default:
return OrganizationTierQuota{}, invalidPolicy("OrganizationQuotaPolicy.Tier", "tier must be e0, e1, or e2")
}
}
func (policy OrganizationQuotaPolicy) Validate() error {
const location = "OrganizationQuotaPolicy.Validate"
if err := firstError(
checkRange(location, "organization_quotas.invitation_window_days", policy.InvitationWindow, 1, maxInvitationQuotaWindow),
checkRange(location, "organization_quotas.card_view_window_hours", policy.CardViewWindow, 1, maxCardViewQuotaWindow),
); err != nil {
return err
}
if !policy.TierE0.Active {
return invalidPolicy(location, "organization_quotas.tiers.e0 must be active, because every organization starts there")
}
tiers := []struct {
name OrganizationTier
quota OrganizationTierQuota
}{
{name: OrganizationTierE0, quota: policy.TierE0},
{name: OrganizationTierE1, quota: policy.TierE1},
{name: OrganizationTierE2, quota: policy.TierE2},
}
// The zero quota is below every valid limit and counts as active, so the
// lowest level passes the ordering checks.
lower := OrganizationTierQuota{Active: true}
for _, tier := range tiers {
prefix := "organization_quotas.tiers." + string(tier.name)
if err := firstError(
checkRange(location, prefix+".invitations_per_window", tier.quota.InvitationsPerWindow, 1, maxTierQuotaLimit),
checkRange(location, prefix+".distinct_card_views_per_window", tier.quota.DistinctCardViewsPerWindow, 1, maxTierQuotaLimit),
); err != nil {
return err
}
if tier.quota.Active && !lower.Active {
return invalidPolicy(location, prefix+" cannot be active while a lower tier is inactive")
}
// A higher level is granted after more trust, so it never has a
// smaller limit than the level below it.
if tier.quota.InvitationsPerWindow < lower.InvitationsPerWindow ||
tier.quota.DistinctCardViewsPerWindow < lower.DistinctCardViewsPerWindow {
return invalidPolicy(location, prefix+" limits must not be lower than the tier below")
}
lower = tier.quota
}
return nil
}
// AssessmentCalibration records whether assessment thresholds come from a
// calibration study.
type AssessmentCalibration string
const (
// AssessmentCalibrationUncalibratedInitial marks initial values chosen for
// verification of the product flow. They make no psychometric claim.
AssessmentCalibrationUncalibratedInitial AssessmentCalibration = "uncalibrated_initial"
// AssessmentCalibrationCalibrated marks values backed by a pilot and a
// documented calibration.
AssessmentCalibrationCalibrated AssessmentCalibration = "calibrated"
)
// AssessmentPolicy governs grade assessment attempts and decisions. P_G is
// the estimated probability that the candidate meets the claimed grade.
type AssessmentPolicy struct {
Calibration AssessmentCalibration
// SameGradeRetryAfter is the pause before another attempt at the same
// grade.
SameGradeRetryAfter CalendarDays
// MaxAttemptsPerWindow limits attempts in any AttemptWindow. Whether the
// limit counts per grade, per specialty, or across all assessments of a
// candidate is an open question for the attempt tasks (TASK-157 and
// TASK-158); the policy stores only the number.
MaxAttemptsPerWindow int32
AttemptWindow CalendarDays
// PromotionMinInterval is the minimum time between grade promotions.
PromotionMinInterval CalendarDays
// ConfirmationThreshold is the lowest P_G that confirms the grade.
ConfirmationThreshold BasisPoints
// HighStrengthThreshold is the lowest P_G reported as a strong result.
HighStrengthThreshold BasisPoints
// PracticeRequired makes the unscored practice block mandatory before a
// scored attempt.
PracticeRequired bool
StopRule AssessmentStopRule
}
// AssessmentStopRule ends an adaptive attempt. After MinScoredItems the
// attempt stops when P_G reaches UpperProbability or falls to
// LowerProbability, or when the standard error is at most MaxStandardError;
// it always stops after MaxScoredItems. SeedItems are unscored items for
// collecting statistics on new tasks and come on top of the scored ones.
type AssessmentStopRule struct {
MinScoredItems int32
MaxScoredItems int32
SeedItems int32
UpperProbability BasisPoints
LowerProbability BasisPoints
MaxStandardError BasisPoints
}
func (policy AssessmentPolicy) Validate() error {
const location = "AssessmentPolicy.Validate"
switch policy.Calibration {
case AssessmentCalibrationUncalibratedInitial, AssessmentCalibrationCalibrated:
default:
return invalidPolicy(location, "assessment.calibration must be uncalibrated_initial or calibrated")
}
if err := firstError(
checkRange(location, "assessment.same_grade_retry_after_days", policy.SameGradeRetryAfter, 1, maxSameGradeRetryInterval),
checkRange(location, "assessment.max_attempts_per_window", policy.MaxAttemptsPerWindow, 1, maxAssessmentAttemptsPerWindow),
checkRange(location, "assessment.attempt_window_days", policy.AttemptWindow, 1, maxAssessmentAttemptWindow),
checkRange(location, "assessment.promotion_min_interval_days", policy.PromotionMinInterval, 1, maxPromotionInterval),
checkProbability(location, "assessment.confirmation_threshold_bp", policy.ConfirmationThreshold),
checkProbability(location, "assessment.high_strength_threshold_bp", policy.HighStrengthThreshold),
); err != nil {
return err
}
if policy.HighStrengthThreshold < policy.ConfirmationThreshold {
return invalidPolicy(location, "assessment.high_strength_threshold_bp must not be below the confirmation threshold")
}
return policy.StopRule.validate(location, policy.ConfirmationThreshold)
}
func (rule AssessmentStopRule) validate(location string, confirmation BasisPoints) error {
if err := firstError(
checkRange(location, "assessment.stop_rule.min_scored_items", rule.MinScoredItems, 1, maxScoredItems),
checkRange(location, "assessment.stop_rule.max_scored_items", rule.MaxScoredItems, rule.MinScoredItems, maxScoredItems),
checkRange(location, "assessment.stop_rule.seed_items", rule.SeedItems, 0, maxSeedItems),
checkProbability(location, "assessment.stop_rule.upper_probability_bp", rule.UpperProbability),
checkProbability(location, "assessment.stop_rule.lower_probability_bp", rule.LowerProbability),
checkRange(location, "assessment.stop_rule.max_standard_error_bp", rule.MaxStandardError, minPositiveStandardErrorBasisPoints, basisPointsPerUnit),
); err != nil {
return err
}
// An attempt must be able to stop above the confirmation threshold and
// below it; otherwise an early stop could never confirm or never reject.
if rule.LowerProbability >= confirmation || rule.UpperProbability < confirmation {
return invalidPolicy(location, "assessment.stop_rule probabilities must satisfy lower < confirmation threshold <= upper")
}
return nil
}
// IdentityPolicy holds the account and session lifetimes of the identity
// contract.
type IdentityPolicy struct {
VerificationTokenLifetime Hours
// UnverifiedAccountLifetime counts from the latest registration.
UnverifiedAccountLifetime CalendarDays
SessionIdleTimeout Hours
SessionAbsoluteLifetime CalendarDays
}
func (policy IdentityPolicy) Validate() error {
const location = "IdentityPolicy.Validate"
if err := firstError(
checkRange(location, "identity.verification_token_lifetime_hours", policy.VerificationTokenLifetime, 1, maxVerificationTokenLifetime),
checkRange(location, "identity.unverified_account_lifetime_days", policy.UnverifiedAccountLifetime, 1, maxUnverifiedAccountLifetime),
checkRange(location, "identity.session_idle_timeout_hours", policy.SessionIdleTimeout, 1, maxSessionIdleTimeout),
checkRange(location, "identity.session_absolute_lifetime_days", policy.SessionAbsoluteLifetime, 1, maxSessionAbsoluteLifetime),
); err != nil {
return err
}
if policy.SessionIdleTimeout.Duration() > policy.SessionAbsoluteLifetime.Duration() {
return invalidPolicy(location, "identity.session_idle_timeout_hours must not exceed the absolute session lifetime")
}
return nil
}
// SearchStatusPolicy governs the candidate "searching" status.
type SearchStatusPolicy struct {
// SearchingConfirmationInterval is how often a candidate confirms that
// the "searching" status is still current.
SearchingConfirmationInterval CalendarDays
}
func (policy SearchStatusPolicy) Validate() error {
return checkRange("SearchStatusPolicy.Validate", "search_status.searching_confirmation_interval_days",
policy.SearchingConfirmationInterval, 1, maxSearchingConfirmationInterval)
}
func checkRange[T ~int32](location, field string, value, minimum, maximum T) error {
if value < minimum || value > maximum {
return invalidPolicy(location, fmt.Sprintf("%s must be between %d and %d", field, minimum, maximum))
}
return nil
}
// checkProbability accepts a probability strictly between 0 and 1: a
// threshold of 0 or 1 would make a rule always or never apply.
func checkProbability(location, field string, value BasisPoints) error {
return checkRange(location, field, value, minExclusiveProbabilityBasisPoints, maxExclusiveProbabilityBasisPoints)
}
func invalidPolicy(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidPolicy)
}
func firstError(errs ...error) error {
for _, err := range errs {
if err != nil {
return err
}
}
return nil
}
+62
View File
@@ -0,0 +1,62 @@
package domain
// DemoProductPolicyV1 returns the initial product policy that is published as
// version 1 of ProductPolicyKey with PolicyKindDemo. Its values are the agreed
// starting rules for verifying the product flow, not results of a study: the
// assessment section is marked AssessmentCalibrationUncalibratedInitial, and
// its thresholds and stop rule make no psychometric or quality claim until a
// pilot calibrates them and a calibrated version is published.
//
// The policy holds rules only. Assessment content, such as the task bank,
// blueprints, and variants, is separate work and is not part of it.
//
// Tests must not use this policy as a fixture for other values; they build
// their own policies under their own keys.
func DemoProductPolicyV1() ProductPolicy {
return ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: []CalendarDays{3, 7, 14},
DefaultResponseDeadline: 7,
MaxPendingPerNeed: 20,
RepeatAfterDecline: 30,
InterviewProposalDeadline: 5,
NoDealPause: 30,
},
OrganizationQuotas: OrganizationQuotaPolicy{
InvitationWindow: 7,
CardViewWindow: 24,
TierE0: OrganizationTierQuota{Active: true, InvitationsPerWindow: 10, DistinctCardViewsPerWindow: 50},
TierE1: OrganizationTierQuota{Active: true, InvitationsPerWindow: 40, DistinctCardViewsPerWindow: 150},
// E2 stays inactive until the organization verification that
// grants it exists.
TierE2: OrganizationTierQuota{Active: false, InvitationsPerWindow: 100, DistinctCardViewsPerWindow: 400},
},
Assessment: AssessmentPolicy{
Calibration: AssessmentCalibrationUncalibratedInitial,
SameGradeRetryAfter: 30,
MaxAttemptsPerWindow: 3,
AttemptWindow: 180,
PromotionMinInterval: 90,
ConfirmationThreshold: 8000,
HighStrengthThreshold: 9000,
PracticeRequired: true,
StopRule: AssessmentStopRule{
MinScoredItems: 8,
MaxScoredItems: 23,
SeedItems: 2,
UpperProbability: 9000,
LowerProbability: 1000,
MaxStandardError: 2500,
},
},
Identity: IdentityPolicy{
VerificationTokenLifetime: 24,
UnverifiedAccountLifetime: 7,
SessionIdleTimeout: 24,
SessionAbsoluteLifetime: 7,
},
SearchStatus: SearchStatusPolicy{
SearchingConfirmationInterval: 30,
},
}
}
+275
View File
@@ -0,0 +1,275 @@
package domain
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
)
const (
// productPolicySchemaVersion is the layout of the stored document. A new
// layout adds a decoder for its version; stored versions are never
// rewritten.
productPolicySchemaVersion = 1
// maxPolicyDocumentBytes bounds a document before decoding. The current
// layout encodes to well under 2 KiB.
maxPolicyDocumentBytes = 64 << 10
)
// PolicyDocumentHash is the SHA-256 of the canonical policy document.
type PolicyDocumentHash [sha256.Size]byte
// The document types mirror ProductPolicy field by field. Every field is a
// pointer, so the decoder can tell a missing field from a zero value: a
// missing field is an error, never a default. Field names carry their unit.
type productPolicyDocument struct {
SchemaVersion *int32 `json:"schema_version"`
Invitations *invitationPolicyDocument `json:"invitations"`
OrganizationQuotas *organizationQuotaDocument `json:"organization_quotas"`
Assessment *assessmentPolicyDocument `json:"assessment"`
Identity *identityPolicyDocument `json:"identity"`
SearchStatus *searchStatusDocument `json:"search_status"`
}
type invitationPolicyDocument struct {
ResponseDeadlineOptionsDays *[]CalendarDays `json:"response_deadline_options_days"`
DefaultResponseDeadlineDays *CalendarDays `json:"default_response_deadline_days"`
MaxPendingPerNeed *int32 `json:"max_pending_per_need"`
RepeatAfterDeclineDays *CalendarDays `json:"repeat_after_decline_days"`
InterviewProposalDeadlineBusinessDays *BusinessDays `json:"interview_proposal_deadline_business_days"`
NoDealPauseDays *CalendarDays `json:"no_deal_pause_days"`
}
type organizationQuotaDocument struct {
InvitationWindowDays *CalendarDays `json:"invitation_window_days"`
CardViewWindowHours *Hours `json:"card_view_window_hours"`
Tiers *organizationTiersDocument `json:"tiers"`
}
type organizationTiersDocument struct {
E0 *organizationTierQuotaDocument `json:"e0"`
E1 *organizationTierQuotaDocument `json:"e1"`
E2 *organizationTierQuotaDocument `json:"e2"`
}
type organizationTierQuotaDocument struct {
Active *bool `json:"active"`
InvitationsPerWindow *int32 `json:"invitations_per_window"`
DistinctCardViewsPerWindow *int32 `json:"distinct_card_views_per_window"`
}
type assessmentPolicyDocument struct {
Calibration *AssessmentCalibration `json:"calibration"`
SameGradeRetryAfterDays *CalendarDays `json:"same_grade_retry_after_days"`
MaxAttemptsPerWindow *int32 `json:"max_attempts_per_window"`
AttemptWindowDays *CalendarDays `json:"attempt_window_days"`
PromotionMinIntervalDays *CalendarDays `json:"promotion_min_interval_days"`
ConfirmationThresholdBP *BasisPoints `json:"confirmation_threshold_bp"`
HighStrengthThresholdBP *BasisPoints `json:"high_strength_threshold_bp"`
PracticeRequired *bool `json:"practice_required"`
StopRule *assessmentStopDocument `json:"stop_rule"`
}
type assessmentStopDocument struct {
MinScoredItems *int32 `json:"min_scored_items"`
MaxScoredItems *int32 `json:"max_scored_items"`
SeedItems *int32 `json:"seed_items"`
UpperProbabilityBP *BasisPoints `json:"upper_probability_bp"`
LowerProbabilityBP *BasisPoints `json:"lower_probability_bp"`
MaxStandardErrorBP *BasisPoints `json:"max_standard_error_bp"`
}
type identityPolicyDocument struct {
VerificationTokenLifetimeHours *Hours `json:"verification_token_lifetime_hours"`
UnverifiedAccountLifetimeDays *CalendarDays `json:"unverified_account_lifetime_days"`
SessionIdleTimeoutHours *Hours `json:"session_idle_timeout_hours"`
SessionAbsoluteLifetimeDays *CalendarDays `json:"session_absolute_lifetime_days"`
}
type searchStatusDocument struct {
SearchingConfirmationIntervalDays *CalendarDays `json:"searching_confirmation_interval_days"`
}
// encodeProductPolicy returns the canonical document: compact JSON with the
// fields in declaration order. The same policy always encodes to the same
// bytes, which makes the document hash deterministic.
func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, error) {
invitations := policy.Invitations
quotas := policy.OrganizationQuotas
assessment := policy.Assessment
identity := policy.Identity
document := productPolicyDocument{
SchemaVersion: pointer(int32(productPolicySchemaVersion)),
Invitations: &invitationPolicyDocument{
ResponseDeadlineOptionsDays: pointer(invitations.ResponseDeadlineOptions),
DefaultResponseDeadlineDays: pointer(invitations.DefaultResponseDeadline),
MaxPendingPerNeed: pointer(invitations.MaxPendingPerNeed),
RepeatAfterDeclineDays: pointer(invitations.RepeatAfterDecline),
InterviewProposalDeadlineBusinessDays: pointer(invitations.InterviewProposalDeadline),
NoDealPauseDays: pointer(invitations.NoDealPause),
},
OrganizationQuotas: &organizationQuotaDocument{
InvitationWindowDays: pointer(quotas.InvitationWindow),
CardViewWindowHours: pointer(quotas.CardViewWindow),
Tiers: &organizationTiersDocument{
E0: encodeTierQuota(quotas.TierE0),
E1: encodeTierQuota(quotas.TierE1),
E2: encodeTierQuota(quotas.TierE2),
},
},
Assessment: &assessmentPolicyDocument{
Calibration: pointer(assessment.Calibration),
SameGradeRetryAfterDays: pointer(assessment.SameGradeRetryAfter),
MaxAttemptsPerWindow: pointer(assessment.MaxAttemptsPerWindow),
AttemptWindowDays: pointer(assessment.AttemptWindow),
PromotionMinIntervalDays: pointer(assessment.PromotionMinInterval),
ConfirmationThresholdBP: pointer(assessment.ConfirmationThreshold),
HighStrengthThresholdBP: pointer(assessment.HighStrengthThreshold),
PracticeRequired: pointer(assessment.PracticeRequired),
StopRule: &assessmentStopDocument{
MinScoredItems: pointer(assessment.StopRule.MinScoredItems),
MaxScoredItems: pointer(assessment.StopRule.MaxScoredItems),
SeedItems: pointer(assessment.StopRule.SeedItems),
UpperProbabilityBP: pointer(assessment.StopRule.UpperProbability),
LowerProbabilityBP: pointer(assessment.StopRule.LowerProbability),
MaxStandardErrorBP: pointer(assessment.StopRule.MaxStandardError),
},
},
Identity: &identityPolicyDocument{
VerificationTokenLifetimeHours: pointer(identity.VerificationTokenLifetime),
UnverifiedAccountLifetimeDays: pointer(identity.UnverifiedAccountLifetime),
SessionIdleTimeoutHours: pointer(identity.SessionIdleTimeout),
SessionAbsoluteLifetimeDays: pointer(identity.SessionAbsoluteLifetime),
},
SearchStatus: &searchStatusDocument{
SearchingConfirmationIntervalDays: pointer(policy.SearchStatus.SearchingConfirmationInterval),
},
}
encoded, err := json.Marshal(document)
if err != nil {
return nil, PolicyDocumentHash{}, fmt.Errorf("domain.encodeProductPolicy - marshal document: %w", err)
}
return encoded, sha256.Sum256(encoded), nil
}
func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument {
return &organizationTierQuotaDocument{
Active: pointer(quota.Active),
InvitationsPerWindow: pointer(quota.InvitationsPerWindow),
DistinctCardViewsPerWindow: pointer(quota.DistinctCardViewsPerWindow),
}
}
// decodeProductPolicy reads a document strictly: it rejects unknown fields,
// missing fields, null values, values of the wrong type or out of the int32
// range, an unknown schema version, and trailing data. It checks structure
// only; ProductPolicy.Validate checks the values. encoding/json matches field
// names without regard to letter case and keeps the last of duplicate keys;
// the document hash, computed over the canonical re-encoding, is what pins
// the content.
func decodeProductPolicy(document []byte) (ProductPolicy, error) {
const location = "domain.decodeProductPolicy"
if len(document) > maxPolicyDocumentBytes {
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("document must have at most %d bytes", maxPolicyDocumentBytes))
}
decoder := json.NewDecoder(bytes.NewReader(document))
decoder.DisallowUnknownFields()
var parsed productPolicyDocument
if err := decoder.Decode(&parsed); err != nil {
return ProductPolicy{}, fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return ProductPolicy{}, invalidPolicy(location, "document must contain one JSON object")
}
reader := documentReader{}
if version := require(&reader, "schema_version", parsed.SchemaVersion); reader.missing == "" && version != productPolicySchemaVersion {
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d", productPolicySchemaVersion))
}
invitations := require(&reader, "invitations", parsed.Invitations)
quotas := require(&reader, "organization_quotas", parsed.OrganizationQuotas)
tiers := require(&reader, "organization_quotas.tiers", quotas.Tiers)
assessment := require(&reader, "assessment", parsed.Assessment)
stopRule := require(&reader, "assessment.stop_rule", assessment.StopRule)
identity := require(&reader, "identity", parsed.Identity)
searchStatus := require(&reader, "search_status", parsed.SearchStatus)
policy := ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: require(&reader, "invitations.response_deadline_options_days", invitations.ResponseDeadlineOptionsDays),
DefaultResponseDeadline: require(&reader, "invitations.default_response_deadline_days", invitations.DefaultResponseDeadlineDays),
MaxPendingPerNeed: require(&reader, "invitations.max_pending_per_need", invitations.MaxPendingPerNeed),
RepeatAfterDecline: require(&reader, "invitations.repeat_after_decline_days", invitations.RepeatAfterDeclineDays),
InterviewProposalDeadline: require(&reader, "invitations.interview_proposal_deadline_business_days", invitations.InterviewProposalDeadlineBusinessDays),
NoDealPause: require(&reader, "invitations.no_deal_pause_days", invitations.NoDealPauseDays),
},
OrganizationQuotas: OrganizationQuotaPolicy{
InvitationWindow: require(&reader, "organization_quotas.invitation_window_days", quotas.InvitationWindowDays),
CardViewWindow: require(&reader, "organization_quotas.card_view_window_hours", quotas.CardViewWindowHours),
TierE0: decodeTierQuota(&reader, "organization_quotas.tiers.e0", tiers.E0),
TierE1: decodeTierQuota(&reader, "organization_quotas.tiers.e1", tiers.E1),
TierE2: decodeTierQuota(&reader, "organization_quotas.tiers.e2", tiers.E2),
},
Assessment: AssessmentPolicy{
Calibration: require(&reader, "assessment.calibration", assessment.Calibration),
SameGradeRetryAfter: require(&reader, "assessment.same_grade_retry_after_days", assessment.SameGradeRetryAfterDays),
MaxAttemptsPerWindow: require(&reader, "assessment.max_attempts_per_window", assessment.MaxAttemptsPerWindow),
AttemptWindow: require(&reader, "assessment.attempt_window_days", assessment.AttemptWindowDays),
PromotionMinInterval: require(&reader, "assessment.promotion_min_interval_days", assessment.PromotionMinIntervalDays),
ConfirmationThreshold: require(&reader, "assessment.confirmation_threshold_bp", assessment.ConfirmationThresholdBP),
HighStrengthThreshold: require(&reader, "assessment.high_strength_threshold_bp", assessment.HighStrengthThresholdBP),
PracticeRequired: require(&reader, "assessment.practice_required", assessment.PracticeRequired),
StopRule: AssessmentStopRule{
MinScoredItems: require(&reader, "assessment.stop_rule.min_scored_items", stopRule.MinScoredItems),
MaxScoredItems: require(&reader, "assessment.stop_rule.max_scored_items", stopRule.MaxScoredItems),
SeedItems: require(&reader, "assessment.stop_rule.seed_items", stopRule.SeedItems),
UpperProbability: require(&reader, "assessment.stop_rule.upper_probability_bp", stopRule.UpperProbabilityBP),
LowerProbability: require(&reader, "assessment.stop_rule.lower_probability_bp", stopRule.LowerProbabilityBP),
MaxStandardError: require(&reader, "assessment.stop_rule.max_standard_error_bp", stopRule.MaxStandardErrorBP),
},
},
Identity: IdentityPolicy{
VerificationTokenLifetime: require(&reader, "identity.verification_token_lifetime_hours", identity.VerificationTokenLifetimeHours),
UnverifiedAccountLifetime: require(&reader, "identity.unverified_account_lifetime_days", identity.UnverifiedAccountLifetimeDays),
SessionIdleTimeout: require(&reader, "identity.session_idle_timeout_hours", identity.SessionIdleTimeoutHours),
SessionAbsoluteLifetime: require(&reader, "identity.session_absolute_lifetime_days", identity.SessionAbsoluteLifetimeDays),
},
SearchStatus: SearchStatusPolicy{
SearchingConfirmationInterval: require(&reader, "search_status.searching_confirmation_interval_days", searchStatus.SearchingConfirmationIntervalDays),
},
}
if reader.missing != "" {
return ProductPolicy{}, invalidPolicy(location, reader.missing+" is required")
}
return policy, nil
}
func decodeTierQuota(reader *documentReader, field string, document *organizationTierQuotaDocument) OrganizationTierQuota {
tier := require(reader, field, document)
return OrganizationTierQuota{
Active: require(reader, field+".active", tier.Active),
InvitationsPerWindow: require(reader, field+".invitations_per_window", tier.InvitationsPerWindow),
DistinctCardViewsPerWindow: require(reader, field+".distinct_card_views_per_window", tier.DistinctCardViewsPerWindow),
}
}
// documentReader remembers the first missing field while a document is read.
type documentReader struct {
missing string
}
// require returns the value behind a document pointer, or the zero value
// after recording field as missing.
func require[T any](reader *documentReader, field string, value *T) T {
if value == nil {
if reader.missing == "" {
reader.missing = field
}
var zero T
return zero
}
return *value
}
func pointer[T any](value T) *T { return &value }
+480
View File
@@ -0,0 +1,480 @@
package domain
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"strings"
"testing"
"time"
)
// demoProductPolicyV1Document is the canonical document of the demo policy.
// Stored versions are verified by hashing the canonical re-encoding of their
// document, so any change to field order, names, or encoding would make
// every stored version fail its integrity check. A new layout needs a new
// schema version and decoder, not an edit here.
const demoProductPolicyV1Document = `{"schema_version":1,` +
`"invitations":{"response_deadline_options_days":[3,7,14],"default_response_deadline_days":7,` +
`"max_pending_per_need":20,"repeat_after_decline_days":30,"interview_proposal_deadline_business_days":5,` +
`"no_deal_pause_days":30},` +
`"organization_quotas":{"invitation_window_days":7,"card_view_window_hours":24,"tiers":{` +
`"e0":{"active":true,"invitations_per_window":10,"distinct_card_views_per_window":50},` +
`"e1":{"active":true,"invitations_per_window":40,"distinct_card_views_per_window":150},` +
`"e2":{"active":false,"invitations_per_window":100,"distinct_card_views_per_window":400}}},` +
`"assessment":{"calibration":"uncalibrated_initial","same_grade_retry_after_days":30,` +
`"max_attempts_per_window":3,"attempt_window_days":180,"promotion_min_interval_days":90,` +
`"confirmation_threshold_bp":8000,"high_strength_threshold_bp":9000,"practice_required":true,` +
`"stop_rule":{"min_scored_items":8,"max_scored_items":23,"seed_items":2,"upper_probability_bp":9000,` +
`"lower_probability_bp":1000,"max_standard_error_bp":2500}},` +
`"identity":{"verification_token_lifetime_hours":24,"unverified_account_lifetime_days":7,` +
`"session_idle_timeout_hours":24,"session_absolute_lifetime_days":7},` +
`"search_status":{"searching_confirmation_interval_days":30}}`
var (
testPolicyCreatedAt = time.Date(2026, time.October, 6, 9, 0, 0, 0, time.UTC)
testPolicyEffectiveAt = testPolicyCreatedAt.Add(time.Hour)
)
// testPolicy returns a valid policy whose values differ from the demo policy,
// so a test never relies on demo values by accident.
func testPolicy() ProductPolicy {
return ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: []CalendarDays{2, 5},
DefaultResponseDeadline: 5,
MaxPendingPerNeed: 4,
RepeatAfterDecline: 11,
InterviewProposalDeadline: 3,
NoDealPause: 12,
},
OrganizationQuotas: OrganizationQuotaPolicy{
InvitationWindow: 3,
CardViewWindow: 12,
TierE0: OrganizationTierQuota{Active: true, InvitationsPerWindow: 2, DistinctCardViewsPerWindow: 5},
TierE1: OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 6},
TierE2: OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 7},
},
Assessment: AssessmentPolicy{
Calibration: AssessmentCalibrationCalibrated,
SameGradeRetryAfter: 10,
MaxAttemptsPerWindow: 2,
AttemptWindow: 60,
PromotionMinInterval: 45,
ConfirmationThreshold: 7500,
HighStrengthThreshold: 8800,
PracticeRequired: false,
StopRule: AssessmentStopRule{
MinScoredItems: 5,
MaxScoredItems: 15,
SeedItems: 0,
UpperProbability: 9500,
LowerProbability: 500,
MaxStandardError: 3000,
},
},
Identity: IdentityPolicy{
VerificationTokenLifetime: 12,
UnverifiedAccountLifetime: 3,
SessionIdleTimeout: 6,
SessionAbsoluteLifetime: 2,
},
SearchStatus: SearchStatusPolicy{SearchingConfirmationInterval: 14},
}
}
func testDraftInput() NewPolicyVersionDraftInput {
return NewPolicyVersionDraftInput{
Key: ProductPolicyKey,
Kind: PolicyKindCalibrated,
Author: "operator:policy-tester",
EffectiveAt: testPolicyEffectiveAt,
Policy: testPolicy(),
}
}
func mustDraft(t *testing.T, input NewPolicyVersionDraftInput, number int32) PolicyVersionDraft {
t.Helper()
draft, err := NewPolicyVersionDraft(input)
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
numbered, err := draft.WithVersion(number)
if err != nil {
t.Fatalf("WithVersion(%d) error = %v", number, err)
}
return numbered
}
// storedFrom returns the row storage would hold for the draft.
func storedFrom(draft PolicyVersionDraft) StoredPolicyVersion {
hash := draft.DocumentHash()
effectiveAt, scheduled := draft.EffectiveAt()
if !scheduled {
effectiveAt = testPolicyCreatedAt
}
return StoredPolicyVersion{
ID: draft.ID(),
Key: string(draft.Key()),
Version: draft.Version(),
Kind: string(draft.Kind()),
Author: string(draft.Author()),
EffectiveAt: effectiveAt,
CreatedAt: testPolicyCreatedAt,
Document: draft.Document(),
DocumentHash: hash[:],
}
}
func mustRestore(t *testing.T, stored StoredPolicyVersion) PolicyVersion {
t.Helper()
version, err := RestorePolicyVersion(stored)
if err != nil {
t.Fatalf("RestorePolicyVersion() error = %v", err)
}
return version
}
func TestDemoProductPolicyV1IsValidDemoAndUncalibrated(t *testing.T) {
demo := DemoProductPolicyV1()
if err := demo.Validate(); err != nil {
t.Fatalf("DemoProductPolicyV1().Validate() error = %v", err)
}
if demo.Assessment.Calibration != AssessmentCalibrationUncalibratedInitial {
t.Fatalf("demo assessment calibration = %q, want uncalibrated_initial", demo.Assessment.Calibration)
}
if demo.OrganizationQuotas.TierE2.Active {
t.Fatal("demo tier E2 is active before organization verification exists")
}
draft := mustDraft(t, NewPolicyVersionDraftInput{
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: demo,
}, 1)
if got := string(draft.Document()); got != demoProductPolicyV1Document {
t.Fatalf("demo canonical document =\n%s\nwant\n%s", got, demoProductPolicyV1Document)
}
if draft.DocumentHash() != sha256.Sum256([]byte(demoProductPolicyV1Document)) {
t.Fatal("demo document hash is not the SHA-256 of the canonical document")
}
if _, scheduled := draft.EffectiveAt(); scheduled {
t.Fatal("a draft without an effective time reports a schedule")
}
calibrated := NewPolicyVersionDraftInput{Key: ProductPolicyKey, Kind: PolicyKindCalibrated, Author: DemoPolicySeedAuthor, Policy: demo}
if _, err := NewPolicyVersionDraft(calibrated); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("NewPolicyVersionDraft(demo values as calibrated) error = %v, want ErrInvalidPolicyVersion", err)
}
}
func TestProductPolicyValidateRejectsEachSection(t *testing.T) {
tests := map[string]func(*ProductPolicy){
"zero policy": func(policy *ProductPolicy) { *policy = ProductPolicy{} },
"no deadline options": func(policy *ProductPolicy) { policy.Invitations.ResponseDeadlineOptions = nil },
"too many deadline options": func(policy *ProductPolicy) {
policy.Invitations.ResponseDeadlineOptions = []CalendarDays{1, 2, 3, 4, 5, 6}
},
"deadline option out of range": func(policy *ProductPolicy) { policy.Invitations.ResponseDeadlineOptions = []CalendarDays{2, 31} },
"deadline options not increasing": func(policy *ProductPolicy) { policy.Invitations.ResponseDeadlineOptions = []CalendarDays{5, 5} },
"default deadline not an option": func(policy *ProductPolicy) { policy.Invitations.DefaultResponseDeadline = 3 },
"zero pending limit": func(policy *ProductPolicy) { policy.Invitations.MaxPendingPerNeed = 0 },
"negative repeat after decline": func(policy *ProductPolicy) { policy.Invitations.RepeatAfterDecline = -1 },
"zero interview deadline": func(policy *ProductPolicy) { policy.Invitations.InterviewProposalDeadline = 0 },
"no-deal pause over a year": func(policy *ProductPolicy) { policy.Invitations.NoDealPause = 366 },
"zero invitation window": func(policy *ProductPolicy) { policy.OrganizationQuotas.InvitationWindow = 0 },
"card view window over a week": func(policy *ProductPolicy) { policy.OrganizationQuotas.CardViewWindow = 169 },
"zero tier limit": func(policy *ProductPolicy) { policy.OrganizationQuotas.TierE0.InvitationsPerWindow = 0 },
"inactive E0": func(policy *ProductPolicy) { policy.OrganizationQuotas.TierE0.Active = false },
"active E2 above inactive E1": func(policy *ProductPolicy) { policy.OrganizationQuotas.TierE1.Active = false },
"higher tier below lower tier": func(policy *ProductPolicy) {
policy.OrganizationQuotas.TierE2.DistinctCardViewsPerWindow = policy.OrganizationQuotas.TierE1.DistinctCardViewsPerWindow - 1
},
"unknown calibration": func(policy *ProductPolicy) { policy.Assessment.Calibration = "pilot" },
"zero retry interval": func(policy *ProductPolicy) { policy.Assessment.SameGradeRetryAfter = 0 },
"zero attempts per window": func(policy *ProductPolicy) { policy.Assessment.MaxAttemptsPerWindow = 0 },
"zero attempt window": func(policy *ProductPolicy) { policy.Assessment.AttemptWindow = 0 },
"zero promotion interval": func(policy *ProductPolicy) { policy.Assessment.PromotionMinInterval = 0 },
"confirmation threshold of one": func(policy *ProductPolicy) { policy.Assessment.ConfirmationThreshold = 10000 },
"confirmation threshold of zero": func(policy *ProductPolicy) { policy.Assessment.ConfirmationThreshold = 0 },
"high strength below confirmation": func(policy *ProductPolicy) { policy.Assessment.HighStrengthThreshold = 7000 },
"zero minimum scored items": func(policy *ProductPolicy) { policy.Assessment.StopRule.MinScoredItems = 0 },
"maximum below minimum scored items": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxScoredItems = 4 },
"negative seed items": func(policy *ProductPolicy) { policy.Assessment.StopRule.SeedItems = -1 },
"lower stop at confirmation": func(policy *ProductPolicy) { policy.Assessment.StopRule.LowerProbability = 7500 },
"upper stop below confirmation": func(policy *ProductPolicy) { policy.Assessment.StopRule.UpperProbability = 7000 },
"zero standard error": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 0 },
"standard error above one": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 10001 },
"zero token lifetime": func(policy *ProductPolicy) { policy.Identity.VerificationTokenLifetime = 0 },
"zero unverified account lifetime": func(policy *ProductPolicy) { policy.Identity.UnverifiedAccountLifetime = 0 },
"zero idle timeout": func(policy *ProductPolicy) { policy.Identity.SessionIdleTimeout = 0 },
"absolute lifetime over limit": func(policy *ProductPolicy) { policy.Identity.SessionAbsoluteLifetime = 91 },
"idle timeout above absolute": func(policy *ProductPolicy) { policy.Identity.SessionIdleTimeout = 49 },
"zero searching confirmation": func(policy *ProductPolicy) { policy.SearchStatus.SearchingConfirmationInterval = 0 },
"searching confirmation over a year": func(policy *ProductPolicy) { policy.SearchStatus.SearchingConfirmationInterval = 366 },
"negative searching confirmation": func(policy *ProductPolicy) { policy.SearchStatus.SearchingConfirmationInterval = -30 },
"tier invitations above sanity bound": func(policy *ProductPolicy) {
policy.OrganizationQuotas.TierE2.InvitationsPerWindow = maxTierQuotaLimit + 1
},
}
if err := testPolicy().Validate(); err != nil {
t.Fatalf("testPolicy().Validate() error = %v", err)
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
policy := testPolicy()
mutate(&policy)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err)
}
input := testDraftInput()
input.Policy = policy
if _, err := NewPolicyVersionDraft(input); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("NewPolicyVersionDraft() error = %v, want ErrInvalidPolicy", err)
}
})
}
}
func TestNewPolicyVersionDraftRejectsInvalidMetadata(t *testing.T) {
tests := map[string]func(*NewPolicyVersionDraftInput){
"empty family": func(input *NewPolicyVersionDraftInput) { input.Key = "" },
"unknown family": func(input *NewPolicyVersionDraftInput) { input.Key = "test_policy" },
"unknown kind": func(input *NewPolicyVersionDraftInput) { input.Kind = "draft" },
"author without prefix": func(input *NewPolicyVersionDraftInput) { input.Author = "policy-tester" },
"author with an email": func(input *NewPolicyVersionDraftInput) { input.Author = "operator:tester@example.com" },
"author over 128 bytes": func(input *NewPolicyVersionDraftInput) {
input.Author = PolicyAuthor("operator:" + strings.Repeat("a", 120))
},
"calibrated without calibration": func(input *NewPolicyVersionDraftInput) {
input.Policy.Assessment.Calibration = AssessmentCalibrationUncalibratedInitial
},
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
input := testDraftInput()
mutate(&input)
if _, err := NewPolicyVersionDraft(input); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("NewPolicyVersionDraft() error = %v, want ErrInvalidPolicyVersion", err)
}
})
}
draft, err := NewPolicyVersionDraft(testDraftInput())
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
if draft.Version() != 0 {
t.Fatalf("new draft version = %d, want unnumbered", draft.Version())
}
if _, err := draft.WithVersion(0); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("WithVersion(0) error = %v, want ErrInvalidPolicyVersion", err)
}
if _, err := (PolicyVersionDraft{}).WithVersion(1); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("zero draft WithVersion(1) error = %v, want ErrInvalidPolicyVersion", err)
}
}
func TestPolicyVersionRoundTripAndHashDeterminism(t *testing.T) {
input := testDraftInput()
first := mustDraft(t, input, 3)
second := mustDraft(t, input, 3)
if first.ID() == second.ID() || first.ID().UUID().Version() != 7 {
t.Fatalf("IDs = %s and %s, want distinct UUIDv7 values", first.ID(), second.ID())
}
if string(first.Document()) != string(second.Document()) || first.DocumentHash() != second.DocumentHash() {
t.Fatal("the same policy encoded to different documents or hashes")
}
if first.DocumentHash() != sha256.Sum256(first.Document()) {
t.Fatal("document hash is not the SHA-256 of the canonical document")
}
changed := input
changed.Policy = testPolicy()
changed.Policy.Invitations.MaxPendingPerNeed++
if mustDraft(t, changed, 3).DocumentHash() == first.DocumentHash() {
t.Fatal("a different policy produced the same hash")
}
restored := mustRestore(t, storedFrom(first))
assertRestoredFromDraft(t, restored, first)
// jsonb returns the document with other key order and whitespace; the
// hash is checked against the canonical re-encoding, not the bytes.
var generic map[string]any
if err := json.Unmarshal(first.Document(), &generic); err != nil {
t.Fatalf("unmarshal document: %v", err)
}
reordered, err := json.MarshalIndent(generic, "", " ")
if err != nil {
t.Fatalf("marshal reordered document: %v", err)
}
stored := storedFrom(first)
stored.Document = reordered
assertRestoredFromDraft(t, mustRestore(t, stored), first)
}
func TestPolicyVersionAccessorsReturnCopies(t *testing.T) {
draft := mustDraft(t, testDraftInput(), 1)
version := mustRestore(t, storedFrom(draft))
for _, values := range []struct {
policy ProductPolicy
document []byte
}{
{policy: draft.Policy(), document: draft.Document()},
{policy: version.Policy(), document: version.Document()},
} {
values.policy.Invitations.ResponseDeadlineOptions[0] = 99
values.document[0] = '['
}
if draft.Policy().Invitations.ResponseDeadlineOptions[0] == 99 || draft.Document()[0] != '{' ||
version.Policy().Invitations.ResponseDeadlineOptions[0] == 99 || version.Document()[0] != '{' {
t.Fatal("changing a returned value changed the draft or the stored version")
}
}
func TestOrganizationTierLookup(t *testing.T) {
quotas := DemoProductPolicyV1().OrganizationQuotas
for value, want := range map[string]OrganizationTierQuota{"e0": quotas.TierE0, "e1": quotas.TierE1, "e2": quotas.TierE2} {
tier, err := ParseOrganizationTier(value)
if err != nil {
t.Fatalf("ParseOrganizationTier(%q) error = %v", value, err)
}
if got, err := quotas.Tier(tier); err != nil || got != want {
t.Fatalf("Tier(%s) = %+v, %v; want %+v", tier, got, err, want)
}
}
if _, err := ParseOrganizationTier("E0"); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("ParseOrganizationTier(E0) error = %v, want ErrInvalidPolicy", err)
}
if _, err := quotas.Tier("e3"); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("Tier(e3) error = %v, want ErrInvalidPolicy", err)
}
}
func TestRestorePolicyVersionRejectsInvalidDocuments(t *testing.T) {
version := mustDraft(t, testDraftInput(), 1)
editDocument := func(edit func(map[string]any)) []byte {
var generic map[string]any
if err := json.Unmarshal(version.Document(), &generic); err != nil {
t.Fatalf("unmarshal document: %v", err)
}
edit(generic)
encoded, err := json.Marshal(generic)
if err != nil {
t.Fatalf("marshal document: %v", err)
}
return encoded
}
section := func(document map[string]any, name string) map[string]any {
value, ok := document[name].(map[string]any)
if !ok {
t.Fatalf("document has no %s object", name)
}
return value
}
tests := []struct {
name string
document []byte
want error
}{
{name: "unknown top-level field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { document["notes"] = "x" })},
{name: "unknown nested field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "identity")["password_reset_hours"] = 1
})},
{name: "missing section", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { delete(document, "search_status") })},
{name: "missing nested field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
delete(section(document, "assessment"), "practice_required")
})},
{name: "null field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = nil
})},
{name: "fractional number", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = 4.5
})},
{name: "number as string", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = "4"
})},
{name: "number above int32", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = 1 << 40
})},
{name: "unknown schema version", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { document["schema_version"] = 2 })},
{name: "missing schema version", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { delete(document, "schema_version") })},
{name: "out-of-range value", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "search_status")["searching_confirmation_interval_days"] = 0
})},
{name: "trailing data", want: ErrInvalidPolicy, document: append(version.Document(), []byte(` {}`)...)},
{name: "array instead of object", want: ErrInvalidPolicy, document: []byte(`[]`)},
{name: "oversized document", want: ErrInvalidPolicy, document: padDocument(version.Document(), maxPolicyDocumentBytes+1)},
{name: "valid change without a new hash", want: ErrPolicyDocumentIntegrity, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = 5
})},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
stored := storedFrom(version)
stored.Document = test.document
if _, err := RestorePolicyVersion(stored); !errors.Is(err, test.want) {
t.Fatalf("RestorePolicyVersion() error = %v, want %v", err, test.want)
}
})
}
t.Run("whitespace up to the size limit is accepted", func(t *testing.T) {
// The oversized case above fails on size alone: the same padding
// that ends at the limit restores.
stored := storedFrom(version)
stored.Document = padDocument(version.Document(), maxPolicyDocumentBytes)
assertRestoredFromDraft(t, mustRestore(t, stored), version)
})
t.Run("hash of the wrong size", func(t *testing.T) {
stored := storedFrom(version)
stored.DocumentHash = stored.DocumentHash[:16]
if _, err := RestorePolicyVersion(stored); !errors.Is(err, ErrPolicyDocumentIntegrity) {
t.Fatalf("RestorePolicyVersion() error = %v, want ErrPolicyDocumentIntegrity", err)
}
})
t.Run("invalid metadata", func(t *testing.T) {
for name, mutate := range map[string]func(*StoredPolicyVersion){
"nil ID": func(stored *StoredPolicyVersion) { stored.ID = PolicyVersionID{} },
"unknown kind": func(stored *StoredPolicyVersion) { stored.Kind = "draft" },
"invalid author": func(stored *StoredPolicyVersion) { stored.Author = "someone" },
"unknown family": func(stored *StoredPolicyVersion) { stored.Key = "other" },
"zero version": func(stored *StoredPolicyVersion) { stored.Version = 0 },
"zero creation": func(stored *StoredPolicyVersion) { stored.CreatedAt = time.Time{} },
"backdated": func(stored *StoredPolicyVersion) { stored.EffectiveAt = stored.CreatedAt.Add(-time.Second) },
} {
stored := storedFrom(version)
mutate(&stored)
if _, err := RestorePolicyVersion(stored); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("%s: RestorePolicyVersion() error = %v, want ErrInvalidPolicyVersion", name, err)
}
}
})
}
func TestPolicyUnits(t *testing.T) {
if got := CalendarDays(7).Duration(); got != 7*24*time.Hour {
t.Fatalf("CalendarDays(7).Duration() = %s", got)
}
if got := Hours(24).Duration(); got != 24*time.Hour {
t.Fatalf("Hours(24).Duration() = %s", got)
}
for points, want := range map[BasisPoints]string{8000: "0.8000", 2500: "0.2500", 1: "0.0001", 10000: "1.0000"} {
if got := points.String(); got != want {
t.Fatalf("BasisPoints(%d).String() = %q, want %q", int32(points), got, want)
}
}
}
// padDocument appends JSON whitespace until the document has size bytes, so
// it stays a valid document of the same content.
func padDocument(document []byte, size int) []byte {
padded := append([]byte(nil), document...)
return append(padded, bytes.Repeat([]byte(" "), size-len(document))...)
}
func assertRestoredFromDraft(t *testing.T, got PolicyVersion, draft PolicyVersionDraft) {
t.Helper()
want := storedFrom(draft)
if got.ID() != draft.ID() || got.Key() != draft.Key() || got.Version() != draft.Version() || got.Kind() != draft.Kind() ||
got.Author() != draft.Author() || !got.EffectiveAt().Equal(want.EffectiveAt) || !got.CreatedAt().Equal(want.CreatedAt) ||
got.DocumentHash() != draft.DocumentHash() || string(got.Document()) != string(draft.Document()) {
t.Fatalf("restored version = %+v, want the draft %+v", got, draft)
}
}
+352
View File
@@ -0,0 +1,352 @@
package domain
import (
"crypto/subtle"
"errors"
"fmt"
"regexp"
"time"
"github.com/google/uuid"
)
const maxPolicyAuthorLength = 128
var (
// ErrInvalidPolicyVersion reports version metadata that is missing or
// malformed: the family, number, kind, author, or times.
ErrInvalidPolicyVersion = errors.New("invalid policy version")
// ErrPolicyDocumentIntegrity reports a stored document whose canonical
// form no longer matches the stored SHA-256. The row was changed outside
// the application.
ErrPolicyDocumentIntegrity = errors.New("policy document does not match its hash")
// "system:<name>" or "operator:<handle>", as in the
// policy_versions_author_format CHECK. The character set excludes "@", so
// an email address cannot be stored as an author.
policyAuthorPattern = regexp.MustCompile(`^(system|operator):[a-z0-9][a-z0-9._-]*$`)
)
// PolicyVersionID identifies one stored policy version. Records built under
// a policy, such as grade decisions, selection snapshots, and invitations,
// store it in a policy_version_id column that references policy_versions.id.
type PolicyVersionID uuid.UUID
// NewPolicyVersionID returns a time-ordered UUIDv7.
func NewPolicyVersionID() (PolicyVersionID, error) {
id, err := uuid.NewV7()
if err != nil {
return PolicyVersionID{}, fmt.Errorf("domain.NewPolicyVersionID - generate ID: %w", err)
}
return PolicyVersionID(id), nil
}
func (id PolicyVersionID) UUID() uuid.UUID { return uuid.UUID(id) }
func (id PolicyVersionID) String() string { return uuid.UUID(id).String() }
func (id PolicyVersionID) IsZero() bool { return uuid.UUID(id) == uuid.Nil }
// PolicyKey names a policy family. Each family has exactly one document
// layout and decoder; ProductPolicyKey, decoded as ProductPolicy, is the only
// family. A new family adds its type and decoder here and to the
// policy_versions_policy_key_known CHECK.
type PolicyKey string
// ProductPolicyKey is the family of the product policy that product rules
// read.
const ProductPolicyKey PolicyKey = "product"
// ParsePolicyKey accepts a known family.
func ParsePolicyKey(value string) (PolicyKey, error) {
if PolicyKey(value) != ProductPolicyKey {
return "", invalidPolicyVersion("domain.ParsePolicyKey", "unknown policy family")
}
return ProductPolicyKey, nil
}
// PolicyKind is the calibration state of a whole version.
type PolicyKind string
const (
// PolicyKindDemo marks an initial policy for verification of the product
// flow. Its values make no calibrated quality claim.
PolicyKindDemo PolicyKind = "demo"
// PolicyKindCalibrated marks a policy whose assessment section is backed
// by a calibration. A calibrated version cannot carry an uncalibrated
// assessment section.
PolicyKindCalibrated PolicyKind = "calibrated"
)
func ParsePolicyKind(value string) (PolicyKind, error) {
kind := PolicyKind(value)
switch kind {
case PolicyKindDemo, PolicyKindCalibrated:
return kind, nil
default:
return "", invalidPolicyVersion("domain.ParsePolicyKind", "kind must be demo or calibrated")
}
}
// PolicyAuthor identifies who published a version: "system:<name>" for an
// automated publisher or "operator:<handle>" for a person. It is an operator
// identity, never contact data. It is not a reference to users, because a
// version must outlive the account and the seed has no account.
type PolicyAuthor string
// DemoPolicySeedAuthor publishes the demo product policy.
const DemoPolicySeedAuthor PolicyAuthor = "system:demo-seed"
func ParsePolicyAuthor(value string) (PolicyAuthor, error) {
if len(value) > maxPolicyAuthorLength || !policyAuthorPattern.MatchString(value) {
return "", invalidPolicyVersion("domain.ParsePolicyAuthor",
"author must be system:<name> or operator:<handle> of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'")
}
return PolicyAuthor(value), nil
}
// PolicyVersionDraft is a version that is not stored yet. It has an ID, a
// validated policy, and its canonical document, but no publication time:
// the database sets that when it stores the draft. Its number is assigned
// with WithVersion before it is stored.
type PolicyVersionDraft struct {
id PolicyVersionID
key PolicyKey
version int32
kind PolicyKind
author PolicyAuthor
effectiveAt time.Time
policy ProductPolicy
document []byte
documentHash PolicyDocumentHash
}
// NewPolicyVersionDraftInput describes a version to publish. A zero
// EffectiveAt makes the version effective at publication; a set one schedules
// it and must not be earlier than the publication time, which storage
// enforces.
type NewPolicyVersionDraftInput struct {
Key PolicyKey
Kind PolicyKind
Author PolicyAuthor
EffectiveAt time.Time
Policy ProductPolicy
}
// NewPolicyVersionDraft validates input, encodes the canonical document with
// its hash, and assigns a UUIDv7. The draft has no number yet.
func NewPolicyVersionDraft(input NewPolicyVersionDraftInput) (PolicyVersionDraft, error) {
const location = "domain.NewPolicyVersionDraft"
if err := validateVersionIdentity(location, input.Key, input.Kind, input.Author); err != nil {
return PolicyVersionDraft{}, err
}
if err := input.Policy.Validate(); err != nil {
return PolicyVersionDraft{}, fmt.Errorf("%s - validate policy: %w", location, err)
}
if err := checkKindMatchesCalibration(location, input.Kind, input.Policy); err != nil {
return PolicyVersionDraft{}, err
}
document, hash, err := encodeProductPolicy(input.Policy)
if err != nil {
return PolicyVersionDraft{}, err
}
id, err := NewPolicyVersionID()
if err != nil {
return PolicyVersionDraft{}, fmt.Errorf("%s - assign ID: %w", location, err)
}
return PolicyVersionDraft{
id: id,
key: input.Key,
kind: input.Kind,
author: input.Author,
effectiveAt: input.EffectiveAt,
policy: input.Policy.clone(),
document: document,
documentHash: hash,
}, nil
}
// WithVersion returns a copy of the draft with its number in the family.
func (draft PolicyVersionDraft) WithVersion(number int32) (PolicyVersionDraft, error) {
if draft.IsZero() {
return PolicyVersionDraft{}, invalidPolicyVersion("PolicyVersionDraft.WithVersion", "draft was not built by NewPolicyVersionDraft")
}
if number <= 0 {
return PolicyVersionDraft{}, invalidPolicyVersion("PolicyVersionDraft.WithVersion", "version must be positive")
}
numbered := draft
numbered.version = number
return numbered, nil
}
func (draft PolicyVersionDraft) ID() PolicyVersionID { return draft.id }
func (draft PolicyVersionDraft) Key() PolicyKey { return draft.key }
// Version is zero until WithVersion assigns the number.
func (draft PolicyVersionDraft) Version() int32 { return draft.version }
func (draft PolicyVersionDraft) Kind() PolicyKind { return draft.kind }
func (draft PolicyVersionDraft) Author() PolicyAuthor { return draft.author }
// EffectiveAt returns the scheduled effective time, or false when the
// version becomes effective at publication.
func (draft PolicyVersionDraft) EffectiveAt() (time.Time, bool) {
return draft.effectiveAt, !draft.effectiveAt.IsZero()
}
// Policy returns a copy of the typed policy.
func (draft PolicyVersionDraft) Policy() ProductPolicy { return draft.policy.clone() }
// Document returns a copy of the canonical document.
func (draft PolicyVersionDraft) Document() []byte { return append([]byte(nil), draft.document...) }
func (draft PolicyVersionDraft) DocumentHash() PolicyDocumentHash { return draft.documentHash }
// IsZero reports a draft not built by NewPolicyVersionDraft.
func (draft PolicyVersionDraft) IsZero() bool { return draft.id.IsZero() }
// PolicyVersion is one stored, immutable version of a policy family. Only
// RestorePolicyVersion builds it; accessors return copies.
type PolicyVersion struct {
id PolicyVersionID
key PolicyKey
version int32
kind PolicyKind
author PolicyAuthor
effectiveAt time.Time
createdAt time.Time
policy ProductPolicy
document []byte
documentHash PolicyDocumentHash
}
// StoredPolicyVersion is a policy_versions row as storage reads it.
type StoredPolicyVersion struct {
ID PolicyVersionID
Key string
Version int32
Kind string
Author string
EffectiveAt time.Time
CreatedAt time.Time
Document []byte
DocumentHash []byte
}
// RestorePolicyVersion rebuilds a stored version. It decodes the document
// strictly, validates it like NewPolicyVersionDraft, and requires the SHA-256
// of its canonical re-encoding to equal the stored hash; otherwise it returns
// ErrPolicyDocumentIntegrity. jsonb normalizes the stored text, so the hash
// is never compared with the stored bytes directly.
func RestorePolicyVersion(stored StoredPolicyVersion) (PolicyVersion, error) {
const location = "domain.RestorePolicyVersion"
if stored.ID.IsZero() {
return PolicyVersion{}, invalidPolicyVersion(location, "ID must not be nil")
}
key, err := ParsePolicyKey(stored.Key)
if err != nil {
return PolicyVersion{}, fmt.Errorf("%s - parse key: %w", location, err)
}
kind, err := ParsePolicyKind(stored.Kind)
if err != nil {
return PolicyVersion{}, fmt.Errorf("%s - parse kind: %w", location, err)
}
author, err := ParsePolicyAuthor(stored.Author)
if err != nil {
return PolicyVersion{}, fmt.Errorf("%s - parse author: %w", location, err)
}
switch {
case stored.Version <= 0:
return PolicyVersion{}, invalidPolicyVersion(location, "version must be positive")
case stored.CreatedAt.IsZero() || stored.EffectiveAt.IsZero():
return PolicyVersion{}, invalidPolicyVersion(location, "creation and effective times must be set")
case stored.EffectiveAt.Before(stored.CreatedAt):
return PolicyVersion{}, invalidPolicyVersion(location, "effective time must not be earlier than the creation time")
}
policy, err := decodeProductPolicy(stored.Document)
if err != nil {
return PolicyVersion{}, fmt.Errorf("%s - decode document: %w", location, err)
}
if err := policy.Validate(); err != nil {
return PolicyVersion{}, fmt.Errorf("%s - validate policy: %w", location, err)
}
if err := checkKindMatchesCalibration(location, kind, policy); err != nil {
return PolicyVersion{}, err
}
document, hash, err := encodeProductPolicy(policy)
if err != nil {
return PolicyVersion{}, err
}
if len(stored.DocumentHash) != len(hash) || subtle.ConstantTimeCompare(stored.DocumentHash, hash[:]) != 1 {
return PolicyVersion{}, fmt.Errorf("%s - verify document hash: %w", location, ErrPolicyDocumentIntegrity)
}
return PolicyVersion{
id: stored.ID,
key: key,
version: stored.Version,
kind: kind,
author: author,
effectiveAt: stored.EffectiveAt,
createdAt: stored.CreatedAt,
policy: policy,
document: document,
documentHash: hash,
}, nil
}
func validateVersionIdentity(location string, key PolicyKey, kind PolicyKind, author PolicyAuthor) error {
if _, err := ParsePolicyKey(string(key)); err != nil {
return fmt.Errorf("%s - validate key: %w", location, err)
}
if _, err := ParsePolicyKind(string(kind)); err != nil {
return fmt.Errorf("%s - validate kind: %w", location, err)
}
if _, err := ParsePolicyAuthor(string(author)); err != nil {
return fmt.Errorf("%s - validate author: %w", location, err)
}
return nil
}
func checkKindMatchesCalibration(location string, kind PolicyKind, policy ProductPolicy) error {
if kind == PolicyKindCalibrated && policy.Assessment.Calibration != AssessmentCalibrationCalibrated {
return invalidPolicyVersion(location, "a calibrated version requires a calibrated assessment section")
}
return nil
}
func invalidPolicyVersion(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidPolicyVersion)
}
func (version PolicyVersion) ID() PolicyVersionID { return version.id }
func (version PolicyVersion) Key() PolicyKey { return version.key }
// Version is the number of the version within its family, starting at 1.
func (version PolicyVersion) Version() int32 { return version.version }
// Kind is the calibration state of the whole version. Consumers that make or
// report a quality claim read this flag; the assessment section's own marker
// always agrees with it for calibrated versions.
func (version PolicyVersion) Kind() PolicyKind { return version.kind }
func (version PolicyVersion) Author() PolicyAuthor { return version.author }
func (version PolicyVersion) EffectiveAt() time.Time { return version.effectiveAt }
// CreatedAt is the publication time from the database clock.
func (version PolicyVersion) CreatedAt() time.Time { return version.createdAt }
// Policy returns a copy of the typed policy.
func (version PolicyVersion) Policy() ProductPolicy { return version.policy.clone() }
// Document returns a copy of the canonical document.
func (version PolicyVersion) Document() []byte { return append([]byte(nil), version.document...) }
func (version PolicyVersion) DocumentHash() PolicyDocumentHash { return version.documentHash }
// IsZero reports a PolicyVersion not built by RestorePolicyVersion.
func (version PolicyVersion) IsZero() bool { return version.id.IsZero() }
+74
View File
@@ -0,0 +1,74 @@
package outbound
import (
"context"
"errors"
"time"
"lincodex/backend/internal/domain"
)
var (
// ErrPolicyVersionNotFound reports that no version matches: an unknown
// ID, a family without versions, or no version effective at the time.
ErrPolicyVersionNotFound = errors.New("policy version not found")
// ErrPolicyVersionConflict reports that the family already has a version
// with the same number, or the ID is taken. Nothing was stored and the
// surrounding transaction stays usable; a publisher computes the next
// number again and retries.
ErrPolicyVersionConflict = errors.New("policy version already exists")
// ErrPolicyVersionBackdated reports a scheduled effective time earlier
// than the publication time that the database assigned.
ErrPolicyVersionBackdated = errors.New("policy version effective time precedes its publication")
// ErrPolicyVersionImmutable reports an attempt to change or remove a
// stored version. The database refuses every UPDATE, DELETE, and
// TRUNCATE of policy versions; publish a new version instead.
ErrPolicyVersionImmutable = errors.New("policy version is immutable")
)
// PolicyRepository stores immutable policy versions. It has no update or
// delete method. UnitOfWork binds it to a transaction; an adapter may also
// provide it outside a transaction, where every call is its own statement.
// Every method that takes a time rejects the zero time, and every method
// that takes a family rejects an unknown one with
// domain.ErrInvalidPolicyVersion before it reads storage. A returned version
// passed domain.RestorePolicyVersion, including its document hash check, so
// a row changed outside the application fails with
// domain.ErrPolicyDocumentIntegrity and a row of an unknown document layout
// fails with domain.ErrInvalidPolicy.
//
// A record built under a policy stores the ID of the version it used and
// reads that version with GetByID later. It never recomputes the version
// with GetEffective, whose answer for a past time changes when a version
// scheduled for that time is superseded by a later publication.
type PolicyRepository interface {
// Create stores a numbered draft and returns the stored version with the
// publication time from the database clock. A draft without an effective
// time becomes effective at publication. It returns an error wrapping
// ErrPolicyVersionConflict when the family already has that number or the
// ID exists, without aborting a surrounding transaction, and
// ErrPolicyVersionBackdated when the scheduled effective time precedes
// the publication time.
Create(ctx context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error)
// GetByID returns ErrPolicyVersionNotFound when no version has the ID.
GetByID(ctx context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error)
// GetEffective returns the newest publication among the versions of the
// family whose effective time is not after at: the highest number, not
// the latest effective time. A version scheduled for later therefore
// never undoes a version published after it. It returns
// ErrPolicyVersionNotFound when no version is effective yet.
GetEffective(ctx context.Context, key domain.PolicyKey, at time.Time) (domain.PolicyVersion, error)
// GetLatest returns the version with the highest number in the family,
// whether or not it is effective yet, or ErrPolicyVersionNotFound.
GetLatest(ctx context.Context, key domain.PolicyKey) (domain.PolicyVersion, error)
// HasVersions reports whether the family has any version. It reads no
// document, so it works even when a stored document cannot be decoded.
HasVersions(ctx context.Context, key domain.PolicyKey) (bool, error)
}
@@ -49,6 +49,7 @@ type Transactor interface {
// repositories are added here as their usecases appear.
type UnitOfWork interface {
IdentityRepositories
Policies() PolicyRepository
Outbox() OutboxWriter
}
@@ -0,0 +1,148 @@
// Package policy publishes immutable versions of product policies.
package policy
import (
"context"
"errors"
"fmt"
"math"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// maxPublishAttempts bounds retries after a concurrent publication took the
// computed version number. Each round lets at least one contender commit, so
// a publisher racing with fewer than this many others always succeeds.
const maxPublishAttempts = 10
// ErrPublishContended reports that every attempt lost the version number to
// a concurrent publication of the same family. Nothing was stored.
var ErrPublishContended = errors.New("policy publication contended")
// Publisher stores new policy versions with the next free number of their
// family. The repository may be standalone or bound to a transaction: a
// number conflict does not abort the transaction, and under READ COMMITTED
// every retry reads the numbers committed in the meantime.
type Publisher struct {
policies outbound.PolicyRepository
clock func() time.Time
}
// NewPublisher takes the application clock, which it uses only to refuse a
// scheduled effective time that has already passed before storage is
// touched. The publication time itself comes from the database.
func NewPublisher(policies outbound.PolicyRepository, clock func() time.Time) *Publisher {
return &Publisher{policies: policies, clock: clock}
}
// PublishInput describes a version to publish. A zero EffectiveAt makes the
// version effective at publication.
type PublishInput struct {
Key domain.PolicyKey
Kind domain.PolicyKind
Author domain.PolicyAuthor
EffectiveAt time.Time
Policy domain.ProductPolicy
}
// Publish validates the input, then stores the policy as the next version of
// its family. The number is the highest stored number plus one; when a
// concurrent publication takes it first, Publish reads the highest number
// again, up to maxPublishAttempts times.
func (publisher *Publisher) Publish(ctx context.Context, input PublishInput) (domain.PolicyVersion, error) {
if !input.EffectiveAt.IsZero() && input.EffectiveAt.Before(publisher.clock()) {
return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - scheduled effective time has passed: %w", domain.ErrInvalidPolicyVersion)
}
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: input.Key,
Kind: input.Kind,
Author: input.Author,
EffectiveAt: input.EffectiveAt,
Policy: input.Policy,
})
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - build draft: %w", err)
}
for range maxPublishAttempts {
if err := ctx.Err(); err != nil {
return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - wait for next attempt: %w", err)
}
number, err := publisher.nextVersionNumber(ctx, input.Key)
if err != nil {
return domain.PolicyVersion{}, err
}
numbered, err := draft.WithVersion(number)
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - number draft: %w", err)
}
stored, err := publisher.policies.Create(ctx, numbered)
if errors.Is(err, outbound.ErrPolicyVersionConflict) {
continue
}
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - store version: %w", err)
}
return stored, nil
}
return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - store version after %d attempts: %w", maxPublishAttempts, ErrPublishContended)
}
func (publisher *Publisher) nextVersionNumber(ctx context.Context, key domain.PolicyKey) (int32, error) {
latest, err := publisher.policies.GetLatest(ctx, key)
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
return 1, nil
}
if err != nil {
return 0, fmt.Errorf("Publisher.nextVersionNumber - read latest version: %w", err)
}
if latest.Version() == math.MaxInt32 {
return 0, fmt.Errorf("Publisher.nextVersionNumber - version numbers are exhausted: %w", domain.ErrInvalidPolicyVersion)
}
return latest.Version() + 1, nil
}
// DemoSeedResult reports what EnsureDemoProductPolicy did. Version is set only
// when this call stored the demo version.
type DemoSeedResult struct {
Created bool
Version domain.PolicyVersion
}
// EnsureDemoProductPolicy publishes domain.DemoProductPolicyV1 as version 1
// of domain.ProductPolicyKey, effective at publication, when the family has
// no version yet. It checks presence only and never decodes a stored
// version, so a row of a newer or unknown document layout cannot block it.
// It is idempotent, also when several instances run it at once: the loser of
// the race for version 1 reports that nothing was created.
func (publisher *Publisher) EnsureDemoProductPolicy(ctx context.Context) (DemoSeedResult, error) {
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey,
Kind: domain.PolicyKindDemo,
Author: domain.DemoPolicySeedAuthor,
Policy: domain.DemoProductPolicyV1(),
})
if err != nil {
return DemoSeedResult{}, fmt.Errorf("Publisher.EnsureDemoProductPolicy - build demo draft: %w", err)
}
numbered, err := draft.WithVersion(1)
if err != nil {
return DemoSeedResult{}, fmt.Errorf("Publisher.EnsureDemoProductPolicy - number demo draft: %w", err)
}
present, err := publisher.policies.HasVersions(ctx, domain.ProductPolicyKey)
if err != nil {
return DemoSeedResult{}, fmt.Errorf("Publisher.EnsureDemoProductPolicy - check existing versions: %w", err)
}
if present {
return DemoSeedResult{}, nil
}
stored, err := publisher.policies.Create(ctx, numbered)
if errors.Is(err, outbound.ErrPolicyVersionConflict) {
return DemoSeedResult{}, nil
}
if err != nil {
return DemoSeedResult{}, fmt.Errorf("Publisher.EnsureDemoProductPolicy - store demo version: %w", err)
}
return DemoSeedResult{Created: true, Version: stored}, nil
}
@@ -0,0 +1,316 @@
package policy
import (
"context"
"errors"
"sync"
"testing"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var testNow = time.Date(2026, time.October, 6, 12, 0, 0, 0, time.UTC)
func testClock() time.Time { return testNow }
// memoryPolicies is an in-memory PolicyRepository that stamps publication
// times like the database. beforeCreate runs before each Create and lets a
// test simulate a concurrent publication.
type memoryPolicies struct {
mu sync.Mutex
versions []domain.PolicyVersion
beforeCreate func(draft domain.PolicyVersionDraft)
createCalls int
readCalls int
getLatestErr error
hasVersionErr error
}
var _ outbound.PolicyRepository = (*memoryPolicies)(nil)
func (store *memoryPolicies) Create(_ context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error) {
store.mu.Lock()
store.createCalls++
hook := store.beforeCreate
store.mu.Unlock()
if hook != nil {
hook(draft)
}
store.mu.Lock()
defer store.mu.Unlock()
for _, stored := range store.versions {
if stored.Key() == draft.Key() && stored.Version() == draft.Version() {
return domain.PolicyVersion{}, outbound.ErrPolicyVersionConflict
}
}
stored, err := restoreDraft(draft, testNow)
if err != nil {
return domain.PolicyVersion{}, err
}
store.versions = append(store.versions, stored)
return stored, nil
}
func restoreDraft(draft domain.PolicyVersionDraft, createdAt time.Time) (domain.PolicyVersion, error) {
effectiveAt, scheduled := draft.EffectiveAt()
if !scheduled {
effectiveAt = createdAt
}
hash := draft.DocumentHash()
return domain.RestorePolicyVersion(domain.StoredPolicyVersion{
ID: draft.ID(), Key: string(draft.Key()), Version: draft.Version(), Kind: string(draft.Kind()),
Author: string(draft.Author()), EffectiveAt: effectiveAt, CreatedAt: createdAt,
Document: draft.Document(), DocumentHash: hash[:],
})
}
func (store *memoryPolicies) GetByID(context.Context, domain.PolicyVersionID) (domain.PolicyVersion, error) {
return domain.PolicyVersion{}, errors.New("memoryPolicies.GetByID - not used by the publisher")
}
func (store *memoryPolicies) GetEffective(context.Context, domain.PolicyKey, time.Time) (domain.PolicyVersion, error) {
return domain.PolicyVersion{}, errors.New("memoryPolicies.GetEffective - not used by the publisher")
}
func (store *memoryPolicies) GetLatest(_ context.Context, key domain.PolicyKey) (domain.PolicyVersion, error) {
store.mu.Lock()
defer store.mu.Unlock()
store.readCalls++
if store.getLatestErr != nil {
return domain.PolicyVersion{}, store.getLatestErr
}
var latest domain.PolicyVersion
for _, stored := range store.versions {
if stored.Key() == key && stored.Version() > latest.Version() {
latest = stored
}
}
if latest.IsZero() {
return domain.PolicyVersion{}, outbound.ErrPolicyVersionNotFound
}
return latest, nil
}
func (store *memoryPolicies) HasVersions(_ context.Context, key domain.PolicyKey) (bool, error) {
store.mu.Lock()
defer store.mu.Unlock()
store.readCalls++
if store.hasVersionErr != nil {
return false, store.hasVersionErr
}
for _, stored := range store.versions {
if stored.Key() == key {
return true, nil
}
}
return false, nil
}
// insertDirect stores a version as a concurrent publisher would.
func (store *memoryPolicies) insertDirect(t *testing.T, number int32) {
t.Helper()
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: "operator:concurrent", Policy: publisherTestPolicy(),
})
if err == nil {
draft, err = draft.WithVersion(number)
}
var stored domain.PolicyVersion
if err == nil {
stored, err = restoreDraft(draft, testNow)
}
if err != nil {
t.Errorf("build concurrent version: %v", err)
return
}
store.mu.Lock()
defer store.mu.Unlock()
store.versions = append(store.versions, stored)
}
// publisherTestPolicy is a valid policy built independently of the demo
// policy, so these tests never stand in for the agreed demo values.
func publisherTestPolicy() domain.ProductPolicy {
return domain.ProductPolicy{
Invitations: domain.InvitationPolicy{
ResponseDeadlineOptions: []domain.CalendarDays{2, 6}, DefaultResponseDeadline: 2,
MaxPendingPerNeed: 9, RepeatAfterDecline: 9, InterviewProposalDeadline: 4, NoDealPause: 9,
},
OrganizationQuotas: domain.OrganizationQuotaPolicy{
InvitationWindow: 5, CardViewWindow: 10,
TierE0: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 9},
TierE1: domain.OrganizationTierQuota{Active: false, InvitationsPerWindow: 4, DistinctCardViewsPerWindow: 9},
TierE2: domain.OrganizationTierQuota{Active: false, InvitationsPerWindow: 5, DistinctCardViewsPerWindow: 9},
},
Assessment: domain.AssessmentPolicy{
Calibration: domain.AssessmentCalibrationCalibrated, SameGradeRetryAfter: 9, MaxAttemptsPerWindow: 4,
AttemptWindow: 90, PromotionMinInterval: 60, ConfirmationThreshold: 7700, HighStrengthThreshold: 9100,
PracticeRequired: true,
StopRule: domain.AssessmentStopRule{
MinScoredItems: 6, MaxScoredItems: 18, SeedItems: 3,
UpperProbability: 9300, LowerProbability: 1200, MaxStandardError: 2700,
},
},
Identity: domain.IdentityPolicy{
VerificationTokenLifetime: 9, UnverifiedAccountLifetime: 4, SessionIdleTimeout: 9, SessionAbsoluteLifetime: 4,
},
SearchStatus: domain.SearchStatusPolicy{SearchingConfirmationInterval: 9},
}
}
func publishInput() PublishInput {
return PublishInput{
Key: domain.ProductPolicyKey,
Kind: domain.PolicyKindCalibrated,
Author: "operator:publisher-test",
Policy: publisherTestPolicy(),
}
}
func TestPublishNumbersVersionsAndAppliesSchedule(t *testing.T) {
store := &memoryPolicies{}
publisher := NewPublisher(store, testClock)
for want := int32(1); want <= 3; want++ {
version, err := publisher.Publish(t.Context(), publishInput())
if err != nil {
t.Fatalf("Publish() error = %v", err)
}
if version.Version() != want || !version.EffectiveAt().Equal(version.CreatedAt()) {
t.Fatalf("Publish() = v%d effective %s, want v%d effective at publication", version.Version(), version.EffectiveAt(), want)
}
}
scheduled := publishInput()
scheduled.EffectiveAt = testNow.Add(time.Hour)
version, err := publisher.Publish(t.Context(), scheduled)
if err != nil || !version.EffectiveAt().Equal(scheduled.EffectiveAt) {
t.Fatalf("Publish(scheduled) = effective %s, %v; want %s", version.EffectiveAt(), err, scheduled.EffectiveAt)
}
}
func TestPublishRetriesAfterAConcurrentPublication(t *testing.T) {
store := &memoryPolicies{}
raced := false
store.beforeCreate = func(draft domain.PolicyVersionDraft) {
if !raced {
raced = true
store.insertDirect(t, draft.Version())
}
}
version, err := NewPublisher(store, testClock).Publish(t.Context(), publishInput())
if err != nil {
t.Fatalf("Publish() error = %v", err)
}
if version.Version() != 2 || store.createCalls != 2 {
t.Fatalf("Publish() = v%d after %d attempts, want v2 after 2", version.Version(), store.createCalls)
}
}
func TestPublishGivesUpAfterBoundedAttempts(t *testing.T) {
store := &memoryPolicies{}
store.beforeCreate = func(draft domain.PolicyVersionDraft) { store.insertDirect(t, draft.Version()) }
_, err := NewPublisher(store, testClock).Publish(t.Context(), publishInput())
if !errors.Is(err, ErrPublishContended) {
t.Fatalf("Publish() error = %v, want ErrPublishContended", err)
}
if store.createCalls != maxPublishAttempts {
t.Fatalf("Publish() made %d attempts, want %d", store.createCalls, maxPublishAttempts)
}
}
func TestPublishValidatesBeforeReadingStorage(t *testing.T) {
tests := map[string]struct {
mutate func(*PublishInput)
want error
}{
"effective time in the past": {
mutate: func(input *PublishInput) { input.EffectiveAt = testNow.Add(-time.Second) },
want: domain.ErrInvalidPolicyVersion,
},
"unknown family": {mutate: func(input *PublishInput) { input.Key = "other" }, want: domain.ErrInvalidPolicyVersion},
"invalid author": {mutate: func(input *PublishInput) { input.Author = "tester@example.com" }, want: domain.ErrInvalidPolicyVersion},
"invalid policy": {mutate: func(input *PublishInput) { input.Policy.Assessment.StopRule.MinScoredItems = 0 }, want: domain.ErrInvalidPolicy},
"calibration flag": {mutate: func(input *PublishInput) {
input.Policy.Assessment.Calibration = domain.AssessmentCalibrationUncalibratedInitial
}, want: domain.ErrInvalidPolicyVersion},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
store := &memoryPolicies{}
input := publishInput()
test.mutate(&input)
if _, err := NewPublisher(store, testClock).Publish(t.Context(), input); !errors.Is(err, test.want) {
t.Fatalf("Publish() error = %v, want %v", err, test.want)
}
if store.readCalls != 0 || store.createCalls != 0 {
t.Fatalf("Publish() touched storage %d reads and %d creates for refused input", store.readCalls, store.createCalls)
}
})
}
}
func TestPublishReturnsStorageErrorsWithoutRetry(t *testing.T) {
unavailable := errors.New("database unavailable")
store := &memoryPolicies{getLatestErr: unavailable}
if _, err := NewPublisher(store, testClock).Publish(t.Context(), publishInput()); !errors.Is(err, unavailable) {
t.Fatalf("Publish() error = %v, want the storage error", err)
}
if store.readCalls != 1 || store.createCalls != 0 {
t.Fatalf("Publish() made %d reads and %d creates, want one read", store.readCalls, store.createCalls)
}
}
func TestEnsureDemoProductPolicyInsertsOnce(t *testing.T) {
store := &memoryPolicies{}
publisher := NewPublisher(store, testClock)
first, err := publisher.EnsureDemoProductPolicy(t.Context())
if err != nil || !first.Created {
t.Fatalf("EnsureDemoProductPolicy() = %+v, %v; want a created version", first, err)
}
version := first.Version
if version.Key() != domain.ProductPolicyKey || version.Version() != 1 || version.Kind() != domain.PolicyKindDemo ||
version.Author() != domain.DemoPolicySeedAuthor || !version.EffectiveAt().Equal(version.CreatedAt()) {
t.Fatalf("demo version = %s v%d %s by %s effective %s", version.Key(), version.Version(), version.Kind(), version.Author(), version.EffectiveAt())
}
if version.Policy().Assessment.Calibration != domain.AssessmentCalibrationUncalibratedInitial {
t.Fatal("demo version carries a calibrated assessment section")
}
second, err := publisher.EnsureDemoProductPolicy(t.Context())
if err != nil || second.Created || !second.Version.IsZero() {
t.Fatalf("second EnsureDemoProductPolicy() = %+v, %v; want a skip", second, err)
}
if len(store.versions) != 1 || store.createCalls != 1 {
t.Fatalf("store holds %d versions after %d creates, want one", len(store.versions), store.createCalls)
}
}
func TestEnsureDemoProductPolicySkipsAnyExistingVersion(t *testing.T) {
store := &memoryPolicies{}
store.insertDirect(t, 4)
// A presence check only: the stored version is never read.
store.getLatestErr = errors.New("memoryPolicies.GetLatest - must not be called by the seed")
result, err := NewPublisher(store, testClock).EnsureDemoProductPolicy(t.Context())
if err != nil || result.Created || store.createCalls != 0 {
t.Fatalf("EnsureDemoProductPolicy() = %+v, %v after %d creates; want a skip", result, err, store.createCalls)
}
}
func TestEnsureDemoProductPolicyTreatsAConcurrentSeedAsPresent(t *testing.T) {
store := &memoryPolicies{}
store.beforeCreate = func(draft domain.PolicyVersionDraft) { store.insertDirect(t, draft.Version()) }
result, err := NewPublisher(store, testClock).EnsureDemoProductPolicy(t.Context())
if err != nil || result.Created || len(store.versions) != 1 {
t.Fatalf("EnsureDemoProductPolicy() = %+v, %v with %d stored versions; want a skip", result, err, len(store.versions))
}
}
func TestEnsureDemoProductPolicyReturnsPresenceErrors(t *testing.T) {
unavailable := errors.New("database unavailable")
store := &memoryPolicies{hasVersionErr: unavailable}
if _, err := NewPublisher(store, testClock).EnsureDemoProductPolicy(t.Context()); !errors.Is(err, unavailable) {
t.Fatalf("EnsureDemoProductPolicy() error = %v, want the storage error", err)
}
}