// 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 // CatalogMetadata is the explicit public mapping reviewed for this exact // published bank opening. An opening without it is not exposed in the // public specialization catalog. CatalogMetadata *domain.AssessmentCategoryCatalogMetadata } // 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) } if input.CatalogMetadata != nil { if input.CatalogMetadata.IsZero() { return fmt.Errorf("bind public catalog metadata: %w", domain.ErrInvalidAssessmentFamily) } if err := repository.BindCategoryCatalog(ctx, opening, *input.CatalogMetadata); err != nil { return fmt.Errorf("bind public catalog metadata: %w", err) } } return nil }) if err != nil { return domain.AssessmentCategoryOpening{}, fmt.Errorf("Bank.OpenCategory - open category %s: %w", category, err) } return opening, nil } // SpecializationAvailability returns only catalog mappings whose opening, // current policy, live coverage, and published-family manifest still match. func (bank *Bank) SpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, error) { var availability []domain.SpecializationAvailability err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error availability, err = unit.AssessmentBank().ListCurrentSpecializationAvailability(ctx) if err != nil { return fmt.Errorf("read current bank availability: %w", err) } return nil }) if err != nil { return nil, fmt.Errorf("Bank.SpecializationAvailability - read catalog: %w", err) } return availability, 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 }