Files
lincodex/backend/internal/usecase/policy/publisher.go
T

149 lines
5.8 KiB
Go

// 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
}