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,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)
}
}