feat(assessment): add immutable family versions and the demo bank loader
This commit is contained in:
1 parent
94488e2b57
commit
204c6bae62
28 files changed
+6269
-9
No files matched your search
@@ -0,0 +1,476 @@
|
||||
// Package assessment loads the assessment bank: immutable family versions
|
||||
// from reviewed bundles, their publication, and the opening of a category.
|
||||
//
|
||||
// The package builds the storage and the loading rules. It does not author
|
||||
// or review content: a bundle that nobody reviewed is imported as a draft
|
||||
// and keeps its category closed.
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// Bank imports family versions and decides publication and category
|
||||
// availability. It holds no state; the same instance serves concurrent
|
||||
// callers. Each method runs in one transaction and does not retry a
|
||||
// transaction conflict: the caller may repeat the whole call, and every
|
||||
// method is safe to repeat.
|
||||
//
|
||||
// Publishing, retiring, and opening take an advisory lock of the category
|
||||
// first, so they run one after another per category and the coverage that
|
||||
// the database counts cannot miss a concurrent change.
|
||||
type Bank struct {
|
||||
transactor outbound.Transactor
|
||||
}
|
||||
|
||||
// NewBank panics on a nil transactor: a wiring mistake should fail at
|
||||
// construction, not at the first import. Which grading policy version is in
|
||||
// force is judged against the database clock, which stamps the effective time
|
||||
// of a policy version, and not against an application clock.
|
||||
func NewBank(transactor outbound.Transactor) *Bank {
|
||||
if transactor == nil {
|
||||
panic("assessment.NewBank - transactor must not be nil")
|
||||
}
|
||||
return &Bank{transactor: transactor}
|
||||
}
|
||||
|
||||
// ImportResult lists what ImportBundle did. A version that was already
|
||||
// stored with identical content is Unchanged.
|
||||
type ImportResult struct {
|
||||
Created []domain.AssessmentFamily
|
||||
Unchanged []domain.AssessmentFamily
|
||||
}
|
||||
|
||||
// ImportBundle stores every family version of the bundle as a draft, in one
|
||||
// transaction: either all versions are stored or none. A version must be the
|
||||
// next one of its family, keep the family's category, and, when the number
|
||||
// is already stored, have identical content; a stored version is never
|
||||
// edited. Importing the same bundle again, also at the same time from
|
||||
// another transaction, changes nothing and reports the versions as
|
||||
// unchanged.
|
||||
//
|
||||
// It does not publish: a version becomes visible to the bank's coverage only
|
||||
// through PublishFamily. The reviewer in a bundle is a declared value, not
|
||||
// an authenticated identity, until reviewer accounts exist. A pending draft
|
||||
// is never approved in place: its review is recorded by importing a new
|
||||
// version of the family that carries the review, and the pending version
|
||||
// stays an unpublished draft. Refusals are *domain.AssessmentRefusalError
|
||||
// with RefusalVersionConflict, RefusalVersionGap, or RefusalCategoryChanged;
|
||||
// an invalid bundle wraps domain.ErrInvalidAssessmentFamily.
|
||||
func (bank *Bank) ImportBundle(ctx context.Context, bundle Bundle) (ImportResult, error) {
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil {
|
||||
return ImportResult{}, fmt.Errorf("Bank.ImportBundle - validate bundle: %w", err)
|
||||
}
|
||||
var result ImportResult
|
||||
err = bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
result = ImportResult{}
|
||||
repository := unit.AssessmentBank()
|
||||
for _, draft := range drafts {
|
||||
family, created, err := importDraft(ctx, repository, draft)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if created {
|
||||
result.Created = append(result.Created, family)
|
||||
} else {
|
||||
result.Unchanged = append(result.Unchanged, family)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return ImportResult{}, fmt.Errorf("Bank.ImportBundle - import in transaction: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func importDraft(ctx context.Context, repository outbound.AssessmentBankRepository, draft domain.AssessmentFamilyDraft) (domain.AssessmentFamily, bool, error) {
|
||||
core := draft.Core()
|
||||
stored, found, err := readSameVersion(ctx, repository, draft)
|
||||
if err != nil || found {
|
||||
return stored, false, err
|
||||
}
|
||||
if err := checkNextVersion(ctx, repository, core); err != nil {
|
||||
return domain.AssessmentFamily{}, false, err
|
||||
}
|
||||
family, err := repository.CreateFamily(ctx, draft)
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyConflict) {
|
||||
// A concurrent import stored the version after the read above. The
|
||||
// insert did not abort the transaction, so read the winner and accept
|
||||
// it when its content is the same.
|
||||
stored, found, readErr := readSameVersion(ctx, repository, draft)
|
||||
if readErr != nil {
|
||||
return domain.AssessmentFamily{}, false, readErr
|
||||
}
|
||||
if found {
|
||||
return stored, false, nil
|
||||
}
|
||||
return domain.AssessmentFamily{}, false, fmt.Errorf("importDraft - store version: %w", err)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, false, fmt.Errorf("importDraft - store version: %w", err)
|
||||
}
|
||||
return family, true, nil
|
||||
}
|
||||
|
||||
// readSameVersion returns the stored version with the draft's key and number
|
||||
// when it exists and has the draft's content, and a refusal when its content
|
||||
// differs.
|
||||
func readSameVersion(ctx context.Context, repository outbound.AssessmentBankRepository, draft domain.AssessmentFamilyDraft) (domain.AssessmentFamily, bool, error) {
|
||||
core := draft.Core()
|
||||
stored, err := repository.GetFamilyVersion(ctx, core.Key, core.Version)
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
||||
return domain.AssessmentFamily{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, false, fmt.Errorf("readSameVersion - read stored version: %w", err)
|
||||
}
|
||||
if stored.ContentHash() != draft.ContentHash() {
|
||||
return domain.AssessmentFamily{}, false, domain.NewAssessmentRefusal(domain.RefusalVersionConflict,
|
||||
fmt.Sprintf("family %s version %d is stored with different content; import a new version instead", core.Key, core.Version))
|
||||
}
|
||||
return stored, true, nil
|
||||
}
|
||||
|
||||
// checkNextVersion requires version 1 for a new family and the successor of
|
||||
// the latest version, in the same category, for an existing one.
|
||||
func checkNextVersion(ctx context.Context, repository outbound.AssessmentBankRepository, core domain.AssessmentFamilyCore) error {
|
||||
latest, err := repository.GetLatestFamily(ctx, core.Key)
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
||||
if core.Version != 1 {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalVersionGap,
|
||||
fmt.Sprintf("family %s has no stored version, so version %d cannot be imported; start at version 1", core.Key, core.Version))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("checkNextVersion - read latest version: %w", err)
|
||||
}
|
||||
if core.Version != latest.Version()+1 {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalVersionGap,
|
||||
fmt.Sprintf("family %s is at version %d, so version %d cannot be imported; the next version is %d", core.Key, latest.Version(), core.Version, latest.Version()+1))
|
||||
}
|
||||
if core.Category != latest.Category() {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalCategoryChanged,
|
||||
fmt.Sprintf("family %s belongs to category %s and cannot move to %s", core.Key, latest.Category(), core.Category))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lockedFamily reads a version, takes the advisory lock of its category, and
|
||||
// reads the version again, so that its state is the one that no other
|
||||
// publication, retirement, or opening of the category can change until the
|
||||
// transaction ends.
|
||||
func lockedFamily(ctx context.Context, repository outbound.AssessmentBankRepository, key domain.AssessmentFamilyKey, version int32) (domain.AssessmentFamily, error) {
|
||||
family, err := repository.GetFamilyVersion(ctx, key, version)
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("read version: %w", err)
|
||||
}
|
||||
if err := repository.LockCategory(ctx, family.Category()); err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("lock category: %w", err)
|
||||
}
|
||||
family, err = repository.GetFamilyVersion(ctx, key, version)
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("reread version: %w", err)
|
||||
}
|
||||
return family, nil
|
||||
}
|
||||
|
||||
// PublishFamily publishes a draft version as the operator's decision. The
|
||||
// operator is a declared value of the caller, recorded with the publication.
|
||||
// A family has at most one published version: publishing version N retires
|
||||
// the published older version of the same key in the same transaction, and
|
||||
// any newer version of the key, in any state, refuses it.
|
||||
//
|
||||
// It refuses, with a *domain.AssessmentRefusalError that names the reason, a
|
||||
// version without a reviewer (RefusalReviewerMissing), with a review that is
|
||||
// not approved (RefusalReviewNotApproved), that is not a draft
|
||||
// (RefusalNotDraft), or whose family has a newer version (RefusalNewerVersionPublished). A pending draft is never approved in place:
|
||||
// import a new version that carries the review.
|
||||
func (bank *Bank) PublishFamily(ctx context.Context, key domain.AssessmentFamilyKey, version int32, by domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
if _, err := domain.ParseAssessmentOperator(string(by)); err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.PublishFamily - validate operator: %w", err)
|
||||
}
|
||||
var published domain.AssessmentFamily
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
repository := unit.AssessmentBank()
|
||||
family, err := lockedFamily(ctx, repository, key, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := family.CheckPublishable(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkNoNewerVersion(ctx, repository, family); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := retireOlderPublished(ctx, repository, family, by); err != nil {
|
||||
return err
|
||||
}
|
||||
published, err = repository.MarkPublished(ctx, family.ID(), by)
|
||||
if err != nil {
|
||||
return storageRefusal(fmt.Errorf("mark published: %w", err), domain.RefusalNotDraft)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.PublishFamily - publish %s version %d: %w", key, version, err)
|
||||
}
|
||||
return published, nil
|
||||
}
|
||||
|
||||
// checkNoNewerVersion refuses to publish a version while a newer version of
|
||||
// the family exists in any state, even a draft or a retired one: publishing
|
||||
// the older one would put superseded content back in the bank. To publish
|
||||
// earlier content again, import it as a new version.
|
||||
func checkNoNewerVersion(ctx context.Context, repository outbound.AssessmentBankRepository, family domain.AssessmentFamily) error {
|
||||
latest, err := repository.GetLatestFamily(ctx, family.Key())
|
||||
if err != nil {
|
||||
return fmt.Errorf("read latest version: %w", err)
|
||||
}
|
||||
if latest.Version() > family.Version() {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalNewerVersionPublished,
|
||||
fmt.Sprintf("version %d of family %s exists, so version %d cannot be published; import the content as a new version", latest.Version(), family.Key(), family.Version()))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// retireOlderPublished retires the published version of the family that
|
||||
// precedes the one being published. Having passed checkNoNewerVersion, the
|
||||
// published version, if any, is older.
|
||||
func retireOlderPublished(ctx context.Context, repository outbound.AssessmentBankRepository, family domain.AssessmentFamily, by domain.AssessmentOperator) error {
|
||||
active, err := repository.GetPublishedFamily(ctx, family.Key())
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("read published version: %w", err)
|
||||
}
|
||||
if _, err := repository.MarkRetired(ctx, active.ID(), by); err != nil {
|
||||
return storageRefusal(fmt.Errorf("retire older version: %w", err), domain.RefusalNotPublished)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RetireFamily withdraws a published version as the operator's decision. It
|
||||
// refuses a version that is not published with RefusalNotPublished.
|
||||
func (bank *Bank) RetireFamily(ctx context.Context, key domain.AssessmentFamilyKey, version int32, by domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
if _, err := domain.ParseAssessmentOperator(string(by)); err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.RetireFamily - validate operator: %w", err)
|
||||
}
|
||||
var retired domain.AssessmentFamily
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
repository := unit.AssessmentBank()
|
||||
family, err := lockedFamily(ctx, repository, key, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := family.CheckRetirable(); err != nil {
|
||||
return err
|
||||
}
|
||||
retired, err = repository.MarkRetired(ctx, family.ID(), by)
|
||||
if err != nil {
|
||||
return storageRefusal(fmt.Errorf("mark retired: %w", err), domain.RefusalNotPublished)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.RetireFamily - retire %s version %d: %w", key, version, err)
|
||||
}
|
||||
return retired, nil
|
||||
}
|
||||
|
||||
// ActiveFamily returns the one published version of the family, or an error
|
||||
// wrapping outbound.ErrAssessmentFamilyNotFound when none is published.
|
||||
func (bank *Bank) ActiveFamily(ctx context.Context, key domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
||||
var active domain.AssessmentFamily
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
active, err = unit.AssessmentBank().GetPublishedFamily(ctx, key)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, fmt.Errorf("Bank.ActiveFamily - read published version of %s: %w", key, err)
|
||||
}
|
||||
return active, nil
|
||||
}
|
||||
|
||||
// storageRefusal turns the sentinels of a race that the database decided
|
||||
// into the refusal a caller would have got without the race. lifecycle is
|
||||
// the reason for a lifecycle step that the state no longer allows. Other
|
||||
// errors pass through.
|
||||
func storageRefusal(err error, lifecycle domain.AssessmentRefusalReason) error {
|
||||
var refusal *domain.AssessmentRefusalError
|
||||
switch {
|
||||
case errors.As(err, &refusal):
|
||||
return err
|
||||
case errors.Is(err, outbound.ErrAssessmentFamilyLifecycle):
|
||||
refusal = domain.NewAssessmentRefusal(lifecycle, "the version changed state while the operation ran")
|
||||
case errors.Is(err, outbound.ErrAssessmentFamilyNotPublishable):
|
||||
refusal = domain.NewAssessmentRefusal(domain.RefusalReviewNotApproved, "the database found no approved review of the version")
|
||||
case errors.Is(err, outbound.ErrAssessmentCoverageInsufficient):
|
||||
refusal = domain.NewAssessmentRefusal(domain.RefusalCoverageInsufficient, "the database counted fewer published families than the policy requires")
|
||||
case errors.Is(err, outbound.ErrAssessmentGradingPolicyNotFound):
|
||||
refusal = domain.NewAssessmentRefusal(domain.RefusalGradingPolicyMissing, "the database found no usable grading policy version")
|
||||
default:
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w: %w", refusal, err)
|
||||
}
|
||||
|
||||
// OpenCategoryInput names the category to open, the agreed basic grading
|
||||
// policy by reference, and the operator who agreed to open it.
|
||||
type OpenCategoryInput struct {
|
||||
Category domain.AssessmentCategory
|
||||
// GradingPolicyID is the stored policy version whose assessment thresholds
|
||||
// apply. A zero ID, an ID that is not stored, and a stored version that
|
||||
// is not the one in force are refused.
|
||||
GradingPolicyID domain.PolicyVersionID
|
||||
OpenedBy domain.AssessmentOperator
|
||||
}
|
||||
|
||||
// OpenCategory makes a category available. It reads the referenced policy
|
||||
// version, which must be the version of the product policy in force now
|
||||
// (RefusalGradingPolicyNotCurrent otherwise), and counts the distinct
|
||||
// published families of the category; the number of families the category
|
||||
// needs is read from that policy, never defined here. It refuses, with a
|
||||
// *domain.AssessmentRefusalError, a missing or unknown policy reference
|
||||
// (RefusalGradingPolicyMissing) and a category with too few published
|
||||
// families (RefusalCoverageInsufficient). A refusal stores nothing.
|
||||
func (bank *Bank) OpenCategory(ctx context.Context, input OpenCategoryInput) (domain.AssessmentCategoryOpening, error) {
|
||||
category, err := domain.ParseAssessmentCategory(string(input.Category))
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("Bank.OpenCategory - validate category: %w", err)
|
||||
}
|
||||
var opening domain.AssessmentCategoryOpening
|
||||
err = bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
repository := unit.AssessmentBank()
|
||||
if err := repository.LockCategory(ctx, category); err != nil {
|
||||
return fmt.Errorf("lock category: %w", err)
|
||||
}
|
||||
policy, err := readGradingPolicy(ctx, unit, input.GradingPolicyID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
published, err := repository.CountPublishedFamilies(ctx, category)
|
||||
if err != nil {
|
||||
return fmt.Errorf("count published families: %w", err)
|
||||
}
|
||||
draft, err := domain.NewAssessmentCategoryOpeningDraft(category, policy, published, input.OpenedBy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opening, err = repository.CreateCategoryOpening(ctx, draft)
|
||||
if err != nil {
|
||||
return storageRefusal(fmt.Errorf("store opening: %w", err), domain.RefusalNotDraft)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("Bank.OpenCategory - open category %s: %w", category, err)
|
||||
}
|
||||
return opening, nil
|
||||
}
|
||||
|
||||
// readGradingPolicy reads the referenced policy version and requires it to
|
||||
// be the version of the product policy in force now.
|
||||
func readGradingPolicy(ctx context.Context, unit outbound.UnitOfWork, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
|
||||
if id.IsZero() {
|
||||
return domain.PolicyVersion{}, domain.NewAssessmentRefusal(domain.RefusalGradingPolicyMissing, "a category opens only under a referenced versioned grading policy")
|
||||
}
|
||||
policy, err := unit.Policies().GetByID(ctx, id)
|
||||
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
||||
return domain.PolicyVersion{}, domain.NewAssessmentRefusal(domain.RefusalGradingPolicyMissing, "the referenced grading policy version is not stored")
|
||||
}
|
||||
if err != nil {
|
||||
return domain.PolicyVersion{}, fmt.Errorf("read grading policy: %w", err)
|
||||
}
|
||||
if err := checkPolicyInForce(ctx, unit, policy); err != nil {
|
||||
return domain.PolicyVersion{}, err
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
// checkPolicyInForce refuses a policy version that is not the one in force
|
||||
// for its family now. "Now" is the database clock of the same transaction,
|
||||
// the clock that stamped the effective time of the versions.
|
||||
func checkPolicyInForce(ctx context.Context, unit outbound.UnitOfWork, policy domain.PolicyVersion) error {
|
||||
now, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read database time: %w", err)
|
||||
}
|
||||
current, err := unit.Policies().GetEffective(ctx, policy.Key(), now)
|
||||
if errors.Is(err, outbound.ErrPolicyVersionNotFound) || (err == nil && current.ID() != policy.ID()) {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalGradingPolicyNotCurrent,
|
||||
fmt.Sprintf("grading policy version %d is not the version in force", policy.Version()))
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("read policy in force: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CategoryAvailability returns the current opening of the category while the
|
||||
// category is available, which is live: the published families are counted
|
||||
// now and must still reach the coverage that the opening recorded. A
|
||||
// category without an opening returns an error wrapping
|
||||
// outbound.ErrAssessmentCategoryNotOpen, a category whose coverage fell below
|
||||
// the requirement, for example after a retirement, is refused with
|
||||
// RefusalCoverageInsufficient, and a category whose opening was made under a
|
||||
// policy version that is no longer the one in force is refused with
|
||||
// RefusalGradingPolicyNotCurrent: a policy change needs a new opening.
|
||||
func (bank *Bank) CategoryAvailability(ctx context.Context, category domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) {
|
||||
var opening domain.AssessmentCategoryOpening
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
repository := unit.AssessmentBank()
|
||||
var err error
|
||||
opening, err = repository.GetCurrentCategoryOpening(ctx, category)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
published, err := repository.CountPublishedFamilies(ctx, category)
|
||||
if err != nil {
|
||||
return fmt.Errorf("count published families: %w", err)
|
||||
}
|
||||
if published < opening.RequiredFamilies {
|
||||
return domain.NewAssessmentRefusal(domain.RefusalCoverageInsufficient,
|
||||
fmt.Sprintf("category has %d published families, its opening requires %d", published, opening.RequiredFamilies))
|
||||
}
|
||||
policy, err := unit.Policies().GetByID(ctx, opening.PolicyVersionID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read the opening's grading policy: %w", err)
|
||||
}
|
||||
return checkPolicyInForce(ctx, unit, policy)
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, fmt.Errorf("Bank.CategoryAvailability - check category %s: %w", category, err)
|
||||
}
|
||||
return opening, nil
|
||||
}
|
||||
|
||||
// GenerateVariant reads a stored version and generates the variant of a seed.
|
||||
// The same version and seed always return the same statement and reference
|
||||
// answer. A draft can be generated, so a reviewer can see what a version
|
||||
// produces before approving it.
|
||||
func (bank *Bank) GenerateVariant(ctx context.Context, key domain.AssessmentFamilyKey, version int32, seed domain.VariantSeed) (domain.AssessmentVariant, error) {
|
||||
var family domain.AssessmentFamily
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
family, err = unit.AssessmentBank().GetFamilyVersion(ctx, key, version)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentVariant{}, fmt.Errorf("Bank.GenerateVariant - read %s version %d: %w", key, version, err)
|
||||
}
|
||||
variant, err := family.NewVariant(seed)
|
||||
if err != nil {
|
||||
return domain.AssessmentVariant{}, fmt.Errorf("Bank.GenerateVariant - generate variant: %w", err)
|
||||
}
|
||||
return variant, nil
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
testOperator = domain.AssessmentOperator("operator:unit-publisher")
|
||||
testCategory = domain.AssessmentCategory("backend")
|
||||
)
|
||||
|
||||
// fakeBank is an in-memory outbound.AssessmentBankRepository. Methods that a
|
||||
// test does not need panic through the nil embedded interface.
|
||||
type fakeBank struct {
|
||||
outbound.AssessmentBankRepository
|
||||
|
||||
calls []string
|
||||
families map[string]domain.AssessmentFamily
|
||||
// onCreate runs inside CreateFamily, to store a version as a concurrent
|
||||
// import that wins the insert would.
|
||||
onCreate func()
|
||||
createErr error
|
||||
markPubErr error
|
||||
markRetErr error
|
||||
openErr error
|
||||
published int32
|
||||
publishedFam *domain.AssessmentFamily
|
||||
opening *domain.AssessmentCategoryOpening
|
||||
}
|
||||
|
||||
func versionKey(key domain.AssessmentFamilyKey, version int32) string {
|
||||
return fmt.Sprintf("%s/%d", key, version)
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetFamilyVersion(_ context.Context, key domain.AssessmentFamilyKey, version int32) (domain.AssessmentFamily, error) {
|
||||
bank.calls = append(bank.calls, "get")
|
||||
if family, ok := bank.families[versionKey(key, version)]; ok {
|
||||
return family, nil
|
||||
}
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentFamilyNotFound
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetLatestFamily(_ context.Context, key domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
||||
var latest domain.AssessmentFamily
|
||||
for _, family := range bank.families {
|
||||
if family.Key() == key && (latest.IsZero() || family.Version() > latest.Version()) {
|
||||
latest = family
|
||||
}
|
||||
}
|
||||
if latest.IsZero() {
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentFamilyNotFound
|
||||
}
|
||||
return latest, nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) DatabaseTime(context.Context) (time.Time, error) { return time.Now(), nil }
|
||||
|
||||
func (bank *fakeBank) CreateFamily(context.Context, domain.AssessmentFamilyDraft) (domain.AssessmentFamily, error) {
|
||||
bank.calls = append(bank.calls, "create")
|
||||
if bank.onCreate != nil {
|
||||
bank.onCreate()
|
||||
}
|
||||
return domain.AssessmentFamily{}, bank.createErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) LockCategory(context.Context, domain.AssessmentCategory) error {
|
||||
bank.calls = append(bank.calls, "lock")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetPublishedFamily(context.Context, domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
||||
if bank.publishedFam == nil {
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentFamilyNotFound
|
||||
}
|
||||
return *bank.publishedFam, nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) MarkPublished(_ context.Context, id domain.AssessmentFamilyID, _ domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
bank.calls = append(bank.calls, "publish:"+id.String())
|
||||
return domain.AssessmentFamily{}, bank.markPubErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) MarkRetired(_ context.Context, id domain.AssessmentFamilyID, _ domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
||||
bank.calls = append(bank.calls, "retire:"+id.String())
|
||||
return domain.AssessmentFamily{}, bank.markRetErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) CountPublishedFamilies(context.Context, domain.AssessmentCategory) (int32, error) {
|
||||
bank.calls = append(bank.calls, "count")
|
||||
return bank.published, nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) CreateCategoryOpening(context.Context, domain.AssessmentCategoryOpeningDraft) (domain.AssessmentCategoryOpening, error) {
|
||||
bank.calls = append(bank.calls, "open")
|
||||
return domain.AssessmentCategoryOpening{}, bank.openErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetCurrentCategoryOpening(context.Context, domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) {
|
||||
if bank.opening == nil {
|
||||
return domain.AssessmentCategoryOpening{}, outbound.ErrAssessmentCategoryNotOpen
|
||||
}
|
||||
return *bank.opening, nil
|
||||
}
|
||||
|
||||
type fakePolicies struct {
|
||||
outbound.PolicyRepository
|
||||
|
||||
stored map[domain.PolicyVersionID]domain.PolicyVersion
|
||||
effective domain.PolicyVersion
|
||||
}
|
||||
|
||||
func (policies fakePolicies) GetByID(_ context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
|
||||
if version, ok := policies.stored[id]; ok {
|
||||
return version, nil
|
||||
}
|
||||
return domain.PolicyVersion{}, outbound.ErrPolicyVersionNotFound
|
||||
}
|
||||
|
||||
func (policies fakePolicies) GetEffective(context.Context, domain.PolicyKey, time.Time) (domain.PolicyVersion, error) {
|
||||
if policies.effective.IsZero() {
|
||||
return domain.PolicyVersion{}, outbound.ErrPolicyVersionNotFound
|
||||
}
|
||||
return policies.effective, nil
|
||||
}
|
||||
|
||||
type fakeUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
bank *fakeBank
|
||||
policies fakePolicies
|
||||
}
|
||||
|
||||
func (unit *fakeUnit) AssessmentBank() outbound.AssessmentBankRepository { return unit.bank }
|
||||
|
||||
func (unit *fakeUnit) Policies() outbound.PolicyRepository { return unit.policies }
|
||||
|
||||
type fakeTransactor struct{ unit *fakeUnit }
|
||||
|
||||
func (transactor fakeTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
func newTestBank(t *testing.T) (*Bank, *fakeUnit) {
|
||||
t.Helper()
|
||||
unit := &fakeUnit{bank: &fakeBank{families: map[string]domain.AssessmentFamily{}}, policies: fakePolicies{stored: map[domain.PolicyVersionID]domain.PolicyVersion{}}}
|
||||
return NewBank(fakeTransactor{unit: unit}), unit
|
||||
}
|
||||
|
||||
// testPolicyVersion builds a stored policy version in force.
|
||||
func testPolicyVersion(t *testing.T, number int32) domain.PolicyVersion {
|
||||
t.Helper()
|
||||
values := domain.DemoProductPolicyV1()
|
||||
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: values,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
||||
}
|
||||
numbered, err := draft.WithVersion(number)
|
||||
if err != nil {
|
||||
t.Fatalf("WithVersion() error = %v", err)
|
||||
}
|
||||
hash, at := numbered.DocumentHash(), time.Now().Add(-time.Hour)
|
||||
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
|
||||
ID: numbered.ID(), Key: string(numbered.Key()), Version: number, Kind: string(numbered.Kind()), Author: string(numbered.Author()),
|
||||
EffectiveAt: at, CreatedAt: at, Document: numbered.Document(), DocumentHash: hash[:],
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestorePolicyVersion() error = %v", err)
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
// storedFamily builds a stored version of the first demo family with the
|
||||
// given number and lifecycle, approved by a reviewer unless pending.
|
||||
func storedFamily(t *testing.T, bundle Bundle, version int32, approved bool, lifecycle domain.AssessmentLifecycle) domain.AssessmentFamily {
|
||||
t.Helper()
|
||||
bundle.Families = bundle.Families[:1]
|
||||
bundle.Families[0].Version = version
|
||||
if approved {
|
||||
bundle.Author = "operator:unit-author"
|
||||
bundle.Review = BundleReview{Status: "approved", Reviewer: "operator:unit-reviewer"}
|
||||
}
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil {
|
||||
t.Fatalf("Drafts() error = %v", err)
|
||||
}
|
||||
draft := drafts[0]
|
||||
core, hash := draft.Core(), draft.ContentHash()
|
||||
generator, _ := draft.SeedGeneratorJSON()
|
||||
key, _ := draft.AnswerKeyJSON()
|
||||
rubric, _ := draft.RubricJSON()
|
||||
stored := domain.StoredAssessmentFamily{
|
||||
ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category),
|
||||
Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName), Author: string(core.Author),
|
||||
Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus), SeedGenerator: generator, AnswerKey: key, Rubric: rubric,
|
||||
ContentHash: hash[:], HashScheme: draft.HashScheme(), Lifecycle: string(lifecycle), CreatedAt: time.Now(),
|
||||
}
|
||||
if lifecycle != domain.AssessmentLifecycleDraft {
|
||||
stored.PublishedAt, stored.PublishedBy = time.Now(), string(testOperator)
|
||||
}
|
||||
if lifecycle == domain.AssessmentLifecycleRetired {
|
||||
stored.RetiredAt, stored.RetiredBy = time.Now(), string(testOperator)
|
||||
}
|
||||
family, err := domain.RestoreAssessmentFamily(stored)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentFamily() error = %v", err)
|
||||
}
|
||||
return family
|
||||
}
|
||||
|
||||
func assertRefusal(t *testing.T, operation string, err error, want domain.AssessmentRefusalReason) {
|
||||
t.Helper()
|
||||
var refusal *domain.AssessmentRefusalError
|
||||
if !errors.As(err, &refusal) || refusal.Reason != want || !errors.Is(err, domain.ErrAssessmentRefused) {
|
||||
t.Fatalf("%s error = %v, want a refusal with reason %s", operation, err, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportAcceptsAConcurrentIdenticalImport(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
bundle := loadDemoBundle(t)
|
||||
bundle.Families = bundle.Families[:1]
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil {
|
||||
t.Fatalf("Drafts() error = %v", err)
|
||||
}
|
||||
winner := storedFamily(t, bundle, 1, false, domain.AssessmentLifecycleDraft)
|
||||
unit.bank.createErr = outbound.ErrAssessmentFamilyConflict
|
||||
unit.bank.onCreate = func() { unit.bank.families[versionKey(drafts[0].Core().Key, 1)] = winner }
|
||||
|
||||
result, err := bank.ImportBundle(t.Context(), bundle)
|
||||
if err != nil || len(result.Created) != 0 || len(result.Unchanged) != 1 {
|
||||
t.Fatalf("ImportBundle(concurrent identical import) = %+v, %v, want one unchanged version", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportRefusesAConcurrentImportWithOtherContent(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
bundle := loadDemoBundle(t)
|
||||
bundle.Families = bundle.Families[:1]
|
||||
other := bundle
|
||||
other.Families = append([]BundleFamily(nil), bundle.Families...)
|
||||
other.Families[0].AnswerKey.ReferenceSolution = "A different approach."
|
||||
winner := storedFamily(t, other, 1, false, domain.AssessmentLifecycleDraft)
|
||||
unit.bank.createErr = outbound.ErrAssessmentFamilyConflict
|
||||
unit.bank.onCreate = func() { unit.bank.families[versionKey(winner.Key(), 1)] = winner }
|
||||
|
||||
_, err := bank.ImportBundle(t.Context(), bundle)
|
||||
assertRefusal(t, "ImportBundle(concurrent import with other content)", err, domain.RefusalVersionConflict)
|
||||
}
|
||||
|
||||
func TestDatabaseRacesBecomeRefusalsWithTheMatchingReason(t *testing.T) {
|
||||
bundle := loadDemoBundle(t)
|
||||
draft := storedFamily(t, bundle, 1, true, domain.AssessmentLifecycleDraft)
|
||||
published := storedFamily(t, bundle, 1, true, domain.AssessmentLifecyclePublished)
|
||||
|
||||
t.Run("publication lost to a state change", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(draft.Key(), 1)] = draft
|
||||
unit.bank.markPubErr = outbound.ErrAssessmentFamilyLifecycle
|
||||
_, err := bank.PublishFamily(t.Context(), draft.Key(), 1, testOperator)
|
||||
assertRefusal(t, "PublishFamily(lifecycle race)", err, domain.RefusalNotDraft)
|
||||
if !errors.Is(err, outbound.ErrAssessmentFamilyLifecycle) {
|
||||
t.Fatalf("PublishFamily() error = %v, want the storage sentinel kept", err)
|
||||
}
|
||||
})
|
||||
t.Run("publication refused by the review constraint", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(draft.Key(), 1)] = draft
|
||||
unit.bank.markPubErr = outbound.ErrAssessmentFamilyNotPublishable
|
||||
_, err := bank.PublishFamily(t.Context(), draft.Key(), 1, testOperator)
|
||||
assertRefusal(t, "PublishFamily(review constraint)", err, domain.RefusalReviewNotApproved)
|
||||
})
|
||||
t.Run("retirement lost to a state change", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(published.Key(), 1)] = published
|
||||
unit.bank.markRetErr = outbound.ErrAssessmentFamilyLifecycle
|
||||
_, err := bank.RetireFamily(t.Context(), published.Key(), 1, testOperator)
|
||||
assertRefusal(t, "RetireFamily(lifecycle race)", err, domain.RefusalNotPublished)
|
||||
})
|
||||
t.Run("opening refused by the coverage constraint", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
version := testPolicyVersion(t, 1)
|
||||
unit.policies.stored[version.ID()], unit.policies.effective = version, version
|
||||
required, err := domain.RequiredPublishedAssessmentFamilies(version.Policy())
|
||||
if err != nil {
|
||||
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
|
||||
}
|
||||
unit.bank.published = required
|
||||
unit.bank.openErr = outbound.ErrAssessmentCoverageInsufficient
|
||||
_, err = bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: version.ID(), OpenedBy: "operator:opener"})
|
||||
assertRefusal(t, "OpenCategory(coverage race)", err, domain.RefusalCoverageInsufficient)
|
||||
})
|
||||
t.Run("opening refused for an unusable policy", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
version := testPolicyVersion(t, 1)
|
||||
unit.policies.stored[version.ID()], unit.policies.effective = version, version
|
||||
required, _ := domain.RequiredPublishedAssessmentFamilies(version.Policy())
|
||||
unit.bank.published = required
|
||||
unit.bank.openErr = outbound.ErrAssessmentGradingPolicyNotFound
|
||||
_, err := bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: version.ID(), OpenedBy: "operator:opener"})
|
||||
assertRefusal(t, "OpenCategory(policy race)", err, domain.RefusalGradingPolicyMissing)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPublishRetiresTheOlderVersionAndRefusesWhenANewerOneIsPublished(t *testing.T) {
|
||||
bundle := loadDemoBundle(t)
|
||||
older := storedFamily(t, bundle, 1, true, domain.AssessmentLifecyclePublished)
|
||||
next := storedFamily(t, bundle, 2, true, domain.AssessmentLifecycleDraft)
|
||||
newer := storedFamily(t, bundle, 3, true, domain.AssessmentLifecyclePublished)
|
||||
|
||||
t.Run("older published version", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(next.Key(), 2)] = next
|
||||
unit.bank.publishedFam = &older
|
||||
if _, err := bank.PublishFamily(t.Context(), next.Key(), 2, testOperator); err != nil {
|
||||
t.Fatalf("PublishFamily() error = %v", err)
|
||||
}
|
||||
want := []string{"get", "lock", "get", "retire:" + older.ID().String(), "publish:" + next.ID().String()}
|
||||
if !slices.Equal(unit.bank.calls, want) {
|
||||
t.Fatalf("calls = %v, want %v: lock first, retire the older version, then publish", unit.bank.calls, want)
|
||||
}
|
||||
})
|
||||
t.Run("newer published version", func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(next.Key(), 2)] = next
|
||||
unit.bank.families[versionKey(newer.Key(), 3)] = newer
|
||||
unit.bank.publishedFam = &newer
|
||||
_, err := bank.PublishFamily(t.Context(), next.Key(), 2, testOperator)
|
||||
assertRefusal(t, "PublishFamily(newer is published)", err, domain.RefusalNewerVersionPublished)
|
||||
if slices.ContainsFunc(unit.bank.calls, func(call string) bool { return len(call) > 6 && call[:6] == "retire" }) {
|
||||
t.Fatalf("calls = %v, want nothing retired after a refusal", unit.bank.calls)
|
||||
}
|
||||
})
|
||||
t.Run("an operator that is not an operator", func(t *testing.T) {
|
||||
bank, _ := newTestBank(t)
|
||||
if _, err := bank.PublishFamily(t.Context(), next.Key(), 2, "ai:draft"); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("PublishFamily(ai operator) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestOpenCategoryRequiresThePolicyInForce(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
first, second := testPolicyVersion(t, 1), testPolicyVersion(t, 2)
|
||||
unit.policies.stored[first.ID()], unit.policies.stored[second.ID()] = first, second
|
||||
unit.policies.effective = second
|
||||
required, _ := domain.RequiredPublishedAssessmentFamilies(second.Policy())
|
||||
unit.bank.published = required
|
||||
|
||||
_, err := bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: first.ID(), OpenedBy: "operator:opener"})
|
||||
assertRefusal(t, "OpenCategory(superseded policy)", err, domain.RefusalGradingPolicyNotCurrent)
|
||||
if _, err := bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: second.ID(), OpenedBy: "operator:opener"}); err != nil {
|
||||
t.Fatalf("OpenCategory(policy in force) error = %v", err)
|
||||
}
|
||||
if unit.bank.calls[0] != "lock" {
|
||||
t.Fatalf("calls = %v, want the category lock first", unit.bank.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCategoryAvailabilityIsLive(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
if _, err := bank.CategoryAvailability(t.Context(), testCategory); !errors.Is(err, outbound.ErrAssessmentCategoryNotOpen) {
|
||||
t.Fatalf("CategoryAvailability(no opening) error = %v, want ErrAssessmentCategoryNotOpen", err)
|
||||
}
|
||||
inForce := testPolicyVersion(t, 1)
|
||||
unit.policies.stored[inForce.ID()], unit.policies.effective = inForce, inForce
|
||||
unit.bank.opening = &domain.AssessmentCategoryOpening{Category: testCategory, PolicyVersionID: inForce.ID(), RequiredFamilies: 5, PublishedFamilies: 5}
|
||||
unit.bank.published = 5
|
||||
if _, err := bank.CategoryAvailability(t.Context(), testCategory); err != nil {
|
||||
t.Fatalf("CategoryAvailability(enough coverage) error = %v", err)
|
||||
}
|
||||
unit.bank.published = 4
|
||||
_, err := bank.CategoryAvailability(t.Context(), testCategory)
|
||||
assertRefusal(t, "CategoryAvailability(coverage fell)", err, domain.RefusalCoverageInsufficient)
|
||||
}
|
||||
|
||||
func TestPublishRefusesAnOlderVersionWhileANewerOneExistsInAnyState(t *testing.T) {
|
||||
bundle := loadDemoBundle(t)
|
||||
older := storedFamily(t, bundle, 1, true, domain.AssessmentLifecycleDraft)
|
||||
for name, newer := range map[string]domain.AssessmentFamily{
|
||||
"draft": storedFamily(t, bundle, 2, true, domain.AssessmentLifecycleDraft),
|
||||
"published": storedFamily(t, bundle, 2, true, domain.AssessmentLifecyclePublished),
|
||||
"retired": storedFamily(t, bundle, 2, true, domain.AssessmentLifecycleRetired),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
unit.bank.families[versionKey(older.Key(), 1)] = older
|
||||
unit.bank.families[versionKey(newer.Key(), 2)] = newer
|
||||
_, err := bank.PublishFamily(t.Context(), older.Key(), 1, testOperator)
|
||||
assertRefusal(t, "PublishFamily(older than an existing version)", err, domain.RefusalNewerVersionPublished)
|
||||
if slices.ContainsFunc(unit.bank.calls, func(call string) bool { return strings.HasPrefix(call, "publish") || strings.HasPrefix(call, "retire") }) {
|
||||
t.Fatalf("calls = %v, want nothing published or retired after a refusal", unit.bank.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvailabilityRequiresTheOpeningPolicyToStayInForce(t *testing.T) {
|
||||
bank, unit := newTestBank(t)
|
||||
opened, replacement := testPolicyVersion(t, 1), testPolicyVersion(t, 2)
|
||||
unit.policies.stored[opened.ID()], unit.policies.stored[replacement.ID()] = opened, replacement
|
||||
unit.policies.effective = opened
|
||||
unit.bank.opening = &domain.AssessmentCategoryOpening{Category: testCategory, PolicyVersionID: opened.ID(), RequiredFamilies: 5, PublishedFamilies: 5}
|
||||
unit.bank.published = 5
|
||||
if _, err := bank.CategoryAvailability(t.Context(), testCategory); err != nil {
|
||||
t.Fatalf("CategoryAvailability(policy in force) error = %v", err)
|
||||
}
|
||||
// A new policy version takes force: the opening no longer applies.
|
||||
unit.policies.effective = replacement
|
||||
_, err := bank.CategoryAvailability(t.Context(), testCategory)
|
||||
assertRefusal(t, "CategoryAvailability(policy superseded)", err, domain.RefusalGradingPolicyNotCurrent)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxBundleBytes bounds the size of a bundle document that ParseBundle
|
||||
// reads.
|
||||
maxBundleBytes = 1 << 20
|
||||
// maxBundleFamilies bounds the family versions in one bundle, so one
|
||||
// import stays one reasonably sized transaction.
|
||||
maxBundleFamilies = 200
|
||||
)
|
||||
|
||||
// Bundle is a named set of family versions of one category: one author, one
|
||||
// independent review of the whole set, and the content of each version. It
|
||||
// is the input of the loader and carries no grading policy: the policy is
|
||||
// referenced when a category is opened.
|
||||
//
|
||||
// A bundle that someone prepared is not thereby reviewed. The review block
|
||||
// records what a reviewer decided; a pending review has no reviewer.
|
||||
type Bundle struct {
|
||||
Name string `json:"name"`
|
||||
Category string `json:"category"`
|
||||
Author string `json:"author"`
|
||||
Review BundleReview `json:"review"`
|
||||
Families []BundleFamily `json:"families"`
|
||||
}
|
||||
|
||||
// BundleReview is the independent review of a bundle. Reviewer is empty while
|
||||
// Status is "pending".
|
||||
type BundleReview struct {
|
||||
Status string `json:"status"`
|
||||
Reviewer string `json:"reviewer"`
|
||||
}
|
||||
|
||||
// BundleFamily is the content of one family version in a bundle.
|
||||
type BundleFamily struct {
|
||||
Key string `json:"key"`
|
||||
Version int32 `json:"version"`
|
||||
Specialization string `json:"specialization"`
|
||||
Title string `json:"title"`
|
||||
SeedGenerator domain.AssessmentSeedGenerator `json:"seed_generator"`
|
||||
AnswerKey domain.AssessmentAnswerKey `json:"answer_key"`
|
||||
Rubric domain.AssessmentRubric `json:"rubric"`
|
||||
}
|
||||
|
||||
// ParseBundle reads a bundle document strictly: an unknown field, trailing
|
||||
// data, or a document above the size bound is an error wrapping
|
||||
// domain.ErrInvalidAssessmentFamily. It does not validate the content; Drafts
|
||||
// does.
|
||||
func ParseBundle(reader io.Reader) (Bundle, error) {
|
||||
const location = "assessment.ParseBundle"
|
||||
content, err := io.ReadAll(io.LimitReader(reader, maxBundleBytes+1))
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("%s - read bundle: %w", location, err)
|
||||
}
|
||||
if len(content) > maxBundleBytes {
|
||||
return Bundle{}, fmt.Errorf("%s - bundle exceeds %d bytes: %w", location, maxBundleBytes, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(content))
|
||||
decoder.DisallowUnknownFields()
|
||||
var bundle Bundle
|
||||
if err := decoder.Decode(&bundle); err != nil {
|
||||
return Bundle{}, fmt.Errorf("%s - decode bundle: %w: %w", location, domain.ErrInvalidAssessmentFamily, err)
|
||||
}
|
||||
if decoder.More() {
|
||||
return Bundle{}, fmt.Errorf("%s - trailing data after the bundle: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
// Drafts builds the validated drafts of every family version, ordered by key
|
||||
// and version, so that two versions of one family are stored in order. It
|
||||
// returns an error wrapping domain.ErrInvalidAssessmentFamily for an invalid
|
||||
// bundle, a repeated key and version, or a family set that is empty or too
|
||||
// large. Every draft is imported as a draft whatever its review says;
|
||||
// publication is a separate decision.
|
||||
func (bundle Bundle) Drafts() ([]domain.AssessmentFamilyDraft, error) {
|
||||
const location = "Bundle.Drafts"
|
||||
name, err := domain.ParseAssessmentBundleName(bundle.Name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate name: %w", location, err)
|
||||
}
|
||||
category, err := domain.ParseAssessmentCategory(bundle.Category)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate category: %w", location, err)
|
||||
}
|
||||
author, err := domain.ParseAssessmentAuthor(bundle.Author)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate author: %w", location, err)
|
||||
}
|
||||
if len(bundle.Families) == 0 || len(bundle.Families) > maxBundleFamilies {
|
||||
return nil, fmt.Errorf("%s - bundle must have 1 to %d families: %w", location, maxBundleFamilies, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
families := slices.Clone(bundle.Families)
|
||||
slices.SortFunc(families, func(left, right BundleFamily) int {
|
||||
if byKey := strings.Compare(left.Key, right.Key); byKey != 0 {
|
||||
return byKey
|
||||
}
|
||||
return int(left.Version) - int(right.Version)
|
||||
})
|
||||
drafts := make([]domain.AssessmentFamilyDraft, 0, len(families))
|
||||
for index, family := range families {
|
||||
if index > 0 && family.Key == families[index-1].Key && family.Version == families[index-1].Version {
|
||||
return nil, fmt.Errorf("%s - family %s version %d appears twice: %w", location, family.Key, family.Version, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
draft, err := domain.NewAssessmentFamilyDraft(domain.NewAssessmentFamilyDraftInput{
|
||||
Key: domain.AssessmentFamilyKey(family.Key),
|
||||
Version: family.Version,
|
||||
Category: category,
|
||||
Specialization: domain.AssessmentSpecialization(family.Specialization),
|
||||
Title: family.Title,
|
||||
BundleName: name,
|
||||
Author: author,
|
||||
Reviewer: domain.AssessmentOperator(bundle.Review.Reviewer),
|
||||
ReviewStatus: domain.AssessmentReviewStatus(bundle.Review.Status),
|
||||
Generator: family.SeedGenerator,
|
||||
AnswerKey: family.AnswerKey,
|
||||
Rubric: family.Rubric,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - family %s version %d: %w", location, family.Key, family.Version, err)
|
||||
}
|
||||
drafts = append(drafts, draft)
|
||||
}
|
||||
return drafts, nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
const demoBundlePath = "../../../testdata/assessment/backend_demo_bundle.json"
|
||||
|
||||
func loadDemoBundle(t *testing.T) Bundle {
|
||||
t.Helper()
|
||||
file, err := os.Open(filepath.FromSlash(demoBundlePath))
|
||||
if err != nil {
|
||||
t.Fatalf("open demo bundle: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
bundle, err := ParseBundle(file)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseBundle() error = %v", err)
|
||||
}
|
||||
return bundle
|
||||
}
|
||||
|
||||
// The demo bundle is an AI draft without a human review. The test pins that
|
||||
// status, so filling the reviewer in is a visible decision.
|
||||
func TestDemoBundleIsAnUnreviewedAIDraft(t *testing.T) {
|
||||
bundle := loadDemoBundle(t)
|
||||
if bundle.Review.Status != "pending" || bundle.Review.Reviewer != "" {
|
||||
t.Fatalf("demo bundle review = %+v, want pending with an empty reviewer", bundle.Review)
|
||||
}
|
||||
if !strings.HasPrefix(bundle.Author, "ai:") {
|
||||
t.Fatalf("demo bundle author = %q, want an ai: identity", bundle.Author)
|
||||
}
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil {
|
||||
t.Fatalf("Drafts() error = %v", err)
|
||||
}
|
||||
if len(drafts) != len(bundle.Families) {
|
||||
t.Fatalf("Drafts() returned %d drafts for %d families", len(drafts), len(bundle.Families))
|
||||
}
|
||||
for _, draft := range drafts {
|
||||
core := draft.Core()
|
||||
if core.Reviewer != "" || core.ReviewStatus != domain.AssessmentReviewPending {
|
||||
t.Fatalf("draft %s has review %q/%s, want pending without reviewer", core.Key, core.Reviewer, core.ReviewStatus)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBundleRejectsInvalidDocuments(t *testing.T) {
|
||||
if _, err := ParseBundle(strings.NewReader(`{"name":"x","unknown":1}`)); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("ParseBundle(unknown field) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
if _, err := ParseBundle(strings.NewReader(`{} {}`)); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("ParseBundle(trailing data) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
|
||||
duplicate := loadDemoBundle(t)
|
||||
duplicate.Families = append(duplicate.Families, duplicate.Families[0])
|
||||
if _, err := duplicate.Drafts(); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("Drafts(repeated version) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
|
||||
selfReviewed := loadDemoBundle(t)
|
||||
selfReviewed.Author = "operator:same-person"
|
||||
selfReviewed.Review = BundleReview{Status: "approved", Reviewer: "operator:same-person"}
|
||||
if _, err := selfReviewed.Drafts(); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("Drafts(reviewer is the author) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
|
||||
empty := loadDemoBundle(t)
|
||||
empty.Families = nil
|
||||
if _, err := empty.Drafts(); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
||||
t.Fatalf("Drafts(no families) error = %v, want ErrInvalidAssessmentFamily", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user