feat(deploy): add an isolated demo stand with synthetic seed and guarded reset

This commit is contained in:
shira committed 2026-10-09 14:46:18 +03:00
1 parent bd23c839fd
commit e1df4ff77c
26 files changed
+3292 -2

No files matched your search

@@ -0,0 +1,202 @@
package demoseed
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"slices"
"strconv"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
)
// preparedWrongAnswers is the number of frozen items the prepared attempt
// answers wrong, the last ones by ordinal. One mistake keeps the result above
// the demo pass mark of 80% for any item count the demo policy allows (at
// least eight scored items) and shows that the prepared answers are not a
// flawless script of the reference solution.
const preparedWrongAnswers = 1
// ensurePreparedAttempt returns the attempt behind the candidate's current
// Backend category. Without one it continues an active attempt or creates a
// new root attempt, answers every frozen item through the ordinary answer
// operation, and finalizes it, so the result, the category, and the evidence
// projection come from the same code and triggers as a candidate's attempt.
func (seeder *Seeder) ensurePreparedAttempt(ctx context.Context, userID uuid.UUID) (domain.AssessmentAttemptID, bool, error) {
attemptID, found, err := seeder.deps.Store.CurrentCategoryAttempt(ctx, userID, fullSpecialization)
if err != nil {
return domain.AssessmentAttemptID{}, false, fmt.Errorf("read current category: %w", err)
}
if found {
return attemptID, false, nil
}
attempt, resumed, err := seeder.activeOrNewAttempt(ctx, userID)
if err != nil {
return domain.AssessmentAttemptID{}, false, err
}
if resumed {
attempt, err = seeder.resumeSession(ctx, userID, attempt)
if err != nil {
return domain.AssessmentAttemptID{}, false, err
}
}
version, err := seeder.answerItems(ctx, userID, attempt)
if err != nil {
return domain.AssessmentAttemptID{}, false, err
}
finalized, err := seeder.deps.Attempts.FinalizeAttempt(ctx, assessment.FinalizeAssessmentAttemptCommand{
ActorID: userID, AttemptID: attempt.ID(), ExpectedVersion: version, IdempotencyKey: seedKey("finalize"),
})
if err != nil {
return domain.AssessmentAttemptID{}, false, fmt.Errorf("finalize attempt: %w", err)
}
if finalized.Outcome.StatusCode != http.StatusOK {
return domain.AssessmentAttemptID{}, false, fmt.Errorf("finalize answered %d %s: %w",
finalized.Outcome.StatusCode, finalized.Outcome.ProblemCode, ErrPreparedAttemptFailed)
}
sourceID, found, err := seeder.deps.Store.CurrentCategoryAttempt(ctx, userID, fullSpecialization)
if err != nil {
return domain.AssessmentAttemptID{}, false, fmt.Errorf("read assigned category: %w", err)
}
if !found || sourceID != attempt.ID() {
return domain.AssessmentAttemptID{}, false, ErrPreparedAttemptFailed
}
return attempt.ID(), true, nil
}
// activeOrNewAttempt returns the active Backend attempt left by an
// interrupted run, or creates the root attempt of the full category.
func (seeder *Seeder) activeOrNewAttempt(ctx context.Context, userID uuid.UUID) (domain.AssessmentAttempt, bool, error) {
var active domain.AssessmentAttempt
found := false
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
active, found, err = unit.AssessmentAttempts().GetActiveForSpecialization(ctx, userID, fullSpecialization)
return err
})
if err != nil {
return domain.AssessmentAttempt{}, false, fmt.Errorf("read active attempt: %w", err)
}
if found {
return active, true, nil
}
specialization, grade, language := fullSpecialization, fullGrade, fullTaskLanguage
created, err := seeder.deps.Attempts.CreateAttempt(ctx, assessment.CreateAttemptCommand{
ActorID: userID, IdempotencyKey: seedKey("create"), Kind: domain.AssessmentAttemptKindRoot,
Specialization: &specialization, TargetGrade: &grade, TaskLanguage: &language,
})
if err != nil {
return domain.AssessmentAttempt{}, false, fmt.Errorf("create attempt: %w", err)
}
if created.Outcome.StatusCode != http.StatusCreated {
return domain.AssessmentAttempt{}, false, fmt.Errorf("create answered %d %s: %w",
created.Outcome.StatusCode, created.Outcome.ProblemCode, ErrPreparedAttemptFailed)
}
attempt, err := seeder.readAttempt(ctx, userID, created.Outcome.Response.ID)
if err != nil {
return domain.AssessmentAttempt{}, false, err
}
return attempt, false, nil
}
// resumeSession opens a session on an attempt that an interrupted run left,
// because its earlier session may have ended by the idle timeout.
func (seeder *Seeder) resumeSession(ctx context.Context, userID uuid.UUID, attempt domain.AssessmentAttempt) (domain.AssessmentAttempt, error) {
if _, err := seeder.deps.Attempts.StartSession(ctx, assessment.StartAttemptSessionCommand{
ActorID: userID, AttemptID: attempt.ID(), ExpectedVersion: attempt.Version(), IdempotencyKey: seedKey("session"),
}); err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("resume attempt session: %w", err)
}
return seeder.readAttempt(ctx, userID, attempt.ID())
}
func (seeder *Seeder) readAttempt(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttempt, error) {
var attempt domain.AssessmentAttempt
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
attempt, err = unit.AssessmentAttempts().GetForCandidate(ctx, userID, attemptID)
return err
})
if err != nil {
return domain.AssessmentAttempt{}, fmt.Errorf("read attempt: %w", err)
}
return attempt, nil
}
// answerItems answers every unanswered frozen item in order and returns the
// attempt version after the last answer.
func (seeder *Seeder) answerItems(ctx context.Context, userID uuid.UUID, attempt domain.AssessmentAttempt) (int64, error) {
snapshot := attempt.Snapshot()
items := slices.Clone(snapshot.Items)
slices.SortFunc(items, func(left, right domain.AssessmentAttemptItemSnapshot) int {
return int(left.Ordinal - right.Ordinal)
})
version := snapshot.Version
for index, item := range items {
if !item.AnsweredAt.IsZero() {
continue
}
correct := index < len(items)-preparedWrongAnswers
answer, err := integerAnswer(item.Variant, correct)
if err != nil {
return 0, err
}
result, err := seeder.deps.Attempts.SubmitAnswer(ctx, assessment.SubmitAttemptAnswerCommand{
ActorID: userID, AttemptID: attempt.ID(), ItemID: item.ID, ExpectedVersion: version,
IdempotencyKey: seedKey("answer"), Answer: answer,
})
if err != nil {
return 0, fmt.Errorf("answer item %d: %w", item.Ordinal, err)
}
if result.Outcome.StatusCode != http.StatusOK {
return 0, fmt.Errorf("answer item %d answered %d %s: %w",
item.Ordinal, result.Outcome.StatusCode, result.Outcome.ProblemCode, ErrPreparedAttemptFailed)
}
version = result.Outcome.Response.Version
}
return version, nil
}
// integerAnswer builds the answer body of an integer item: the reference
// answer, or the next integer for a wrong answer. It checks the intended
// correctness against the variant, so a template change cannot silently turn
// the prepared answers into wrong ones.
func integerAnswer(variant domain.AssessmentVariant, correct bool) (json.RawMessage, error) {
if variant.AnswerFormat != domain.AnswerFormatInteger {
return nil, fmt.Errorf("demoseed.integerAnswer - unsupported answer format %q", variant.AnswerFormat)
}
reference, err := strconv.ParseInt(variant.ReferenceAnswer, 10, 64)
if err != nil {
return nil, errors.New("demoseed.integerAnswer - the reference answer is not an integer")
}
if !correct {
reference++
}
answer, err := json.Marshal(struct {
Format string `json:"format"`
Number int64 `json:"number"`
}{Format: "number", Number: reference})
if err != nil {
return nil, fmt.Errorf("demoseed.integerAnswer - encode answer: %w", err)
}
_, matches, err := domain.CanonicalAssessmentAnswerForVariant(answer, variant)
if err != nil {
return nil, fmt.Errorf("demoseed.integerAnswer - check answer: %w", err)
}
if matches != correct {
return nil, errors.New("demoseed.integerAnswer - the answer does not have the intended correctness")
}
return answer, nil
}
// seedKey returns a fresh idempotency key of one seed command. The seed is
// idempotent by the state it reads, not by replaying these keys.
func seedKey(operation string) string {
return "demo-seed:" + operation + ":" + uuid.NewString()
}
+144
View File
@@ -0,0 +1,144 @@
package demoseed
import (
"fmt"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/assessment"
)
const (
// FullCategory is the bank category of the prepared full attempt and of
// the full test the jury can start. It maps to Backend Junior with Go.
FullCategory = domain.AssessmentCategory("demo-backend-junior")
// TrainingCategory is the separate express training category. It never
// has a real opening, so an express run never feeds a category.
TrainingCategory = "demo-express"
fullBundleName = "demo-seed-backend-junior"
trainingBundleName = "demo-seed-express"
fullFamilyStem = "demo-seed-backend"
trainingFamilyStem = "demo-seed-express"
// bankAuthor marks the families as synthetic drafts. bankReviewer is the
// fixed audit label of the seed as their reviewer, not a subject review.
// Both are part of the family content, so they stay the same for every
// operator and a repeated import changes nothing.
bankAuthor = "ai:demo-seed-synthetic-bank"
bankReviewer = "operator:demo-seed-bank-reviewer"
// maxBankFamilies bounds what a policy may ask for; the bundle loader
// accepts at most 200 families per bundle.
maxBankFamilies = 200
)
// fullSpecialization and friends are the public catalog mapping of the full
// category.
var (
fullSpecialization = domain.SpecializationBackend
fullGrade = domain.GradeJunior
fullTaskLanguage = domain.TaskLanguageGo
)
// familyTemplate is one synthetic task family whose answer is an integer.
// The seed answers the integer formats only, so every template has one.
type familyTemplate struct {
specialization string
title string
generator domain.AssessmentSeedGenerator
solution string
principle string
criteria []domain.AssessmentRubricCriterion
}
const rubricPrinciple = "A submission is first compared with the reference answer of its variant and then judged against the criteria below. This rubric defines no points and no pass mark: how criteria turn into a grade is decided by the versioned grading policy."
// familyTemplates are the synthetic task families of the demonstration bank,
// the integer-answer families of the checked-in backend demo draft.
func familyTemplates() []familyTemplate {
return []familyTemplate{
{
specialization: "rate-limiting",
title: "Rejected requests of a sliding-window limiter",
generator: domain.AssessmentSeedGenerator{
Algorithm: "rate_limit_window.v1",
Parameters: map[string]domain.AssessmentParameterRange{
"requests": {Min: 12, Max: 30}, "window": {Min: 3, Max: 15},
"limit": {Min: 2, Max: 6}, "max_gap": {Min: 1, Max: 5},
},
StatementTemplate: "A gateway applies a sliding-window limiter. A request at second t is accepted only when fewer than {{.limit}} previously accepted requests arrived in (t - {{.window}}, t]. Rejected requests are not remembered. The gateway receives {{.requests}} requests at these non-decreasing arrival times: {{.timestamps}}. How many requests are rejected?",
},
solution: "Keep accepted arrival times in order. Before each request at t, remove accepted times at or before t - window. Accept and append t when fewer than limit times remain; otherwise count a rejection without appending it.",
principle: rubricPrinciple,
criteria: []domain.AssessmentRubricCriterion{
{ID: "correct_answer", Description: "The submitted number equals the reference answer of the variant."},
{ID: "window_boundary", Description: "A request exactly window seconds old is outside the half-open interval."},
{ID: "rejected_not_counted", Description: "Rejected requests do not occupy capacity in later windows."},
},
},
{
specialization: "messaging",
title: "Idempotent consumer with a duplicate window",
generator: domain.AssessmentSeedGenerator{
Algorithm: "dedup_window.v1",
Parameters: map[string]domain.AssessmentParameterRange{
"events": {Min: 10, Max: 40}, "keys": {Min: 2, Max: 6},
"ttl": {Min: 3, Max: 20}, "max_gap": {Min: 1, Max: 6},
},
StatementTemplate: "A consumer receives {{.events}} messages written as KEY@TIME, where TIME is the arrival second and times never decrease. It processes a message unless the same KEY was processed less than {{.ttl}} seconds earlier; such a message is dropped as a duplicate. A dropped message does not postpone the next processing of its KEY. The stream is: {{.stream}}. How many messages does the consumer process?",
},
solution: "Keep a map from key to the time of its last processed message. For each message, if the key is present and the time difference is smaller than ttl, drop it; otherwise record the time and count the message as processed.",
principle: rubricPrinciple,
criteria: []domain.AssessmentRubricCriterion{
{ID: "correct_answer", Description: "The submitted number equals the reference answer of the variant."},
{ID: "duplicate_boundary", Description: "A message exactly ttl seconds after the last processed one with the same key is processed, not dropped."},
{ID: "dropped_not_extending", Description: "A dropped duplicate does not move the time stored for its key."},
},
},
{
specialization: "caching",
title: "Hit count of a least-recently-used cache",
generator: domain.AssessmentSeedGenerator{
Algorithm: "lru_hits.v1",
Parameters: map[string]domain.AssessmentParameterRange{
"accesses": {Min: 15, Max: 50}, "keys": {Min: 3, Max: 10}, "capacity": {Min: 2, Max: 5},
},
StatementTemplate: "An in-memory cache holds at most {{.capacity}} entries and evicts the least recently used entry when it is full and a missing key must be stored. Reading a key that is present is a hit; reading a key that is absent is a miss, after which the key is stored. Both a hit and a miss make the key the most recently used one. The cache starts empty and serves these {{.accesses}} reads, drawn from {{.keys}} possible keys numbered from 1 to {{.keys}}: {{.sequence}}. How many reads are hits?",
},
solution: "Maintain the cached keys ordered from least to most recently used. On a hit move the key to the recent end; on a miss evict from the old end when the cache is full, then add the key at the recent end. Count the hits.",
principle: rubricPrinciple,
criteria: []domain.AssessmentRubricCriterion{
{ID: "correct_answer", Description: "The submitted number equals the reference answer of the variant."},
{ID: "recency_on_hit", Description: "A hit refreshes the recency of the key, so it is evicted later."},
{ID: "eviction_order", Description: "On a miss in a full cache the least recently used key is evicted before the new key is stored."},
},
},
}
}
// syntheticBundle builds count reviewed families of the category by cycling
// the templates under keys stem-01, stem-02, and so on.
func syntheticBundle(name string, category string, stem string, count int) (assessment.Bundle, error) {
if count < 1 || count > maxBankFamilies {
return assessment.Bundle{}, fmt.Errorf("demoseed.syntheticBundle - %d families are outside 1 to %d", count, maxBankFamilies)
}
templates := familyTemplates()
bundle := assessment.Bundle{
Name: name, Category: category, Author: bankAuthor,
Review: assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: bankReviewer},
Families: make([]assessment.BundleFamily, 0, count),
}
for index := range count {
template := templates[index%len(templates)]
bundle.Families = append(bundle.Families, assessment.BundleFamily{
Key: fmt.Sprintf("%s-%02d", stem, index+1), Version: 1,
Specialization: template.specialization,
Title: fmt.Sprintf("%s (synthetic demo %02d)", template.title, index+1),
SeedGenerator: template.generator,
AnswerKey: domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatInteger, ReferenceSolution: template.solution},
Rubric: domain.AssessmentRubric{Principle: template.principle, Criteria: template.criteria},
})
}
if _, err := bundle.Drafts(); err != nil {
return assessment.Bundle{}, fmt.Errorf("demoseed.syntheticBundle - validate bundle: %w", err)
}
return bundle, nil
}
@@ -0,0 +1,161 @@
package demoseed
import (
"fmt"
"lincodex/backend/internal/domain"
)
// SyntheticDomain is the reserved address domain of every demo account. The
// .test top-level domain never receives mail, so an account on it can only be
// verified by the seed, and the domain marks the account as synthetic in
// every listing and in the reset check.
const SyntheticDomain = "demo.lincodex.test"
// preparedCohortSize is the number of identical prepared candidates. The
// anonymous card shows a quasi-identifier combination only from five
// candidates on (domain.GeneralizeAnonymousCandidateCohort), so six keep the
// demo search non-empty after one candidate unpublishes or hides an
// organization during a session.
const preparedCohortSize = 6
// accountRole tells what the seed builds for an account.
type accountRole int
const (
roleEmployer accountRole = iota
// roleSelfService is the candidate the jury signs in with to run the
// express and to start the full test: profile and questionnaire, no
// attempt, no publication.
roleSelfService
// rolePrepared is a candidate with a prepared full attempt, its synthetic
// demonstration category, and a published card.
rolePrepared
)
// accountSpec is one synthetic account of the seed.
type accountSpec struct {
local string
role accountRole
ordinal int
fullName string
}
func (spec accountSpec) email() string { return spec.local + "@" + SyntheticDomain }
func (spec accountSpec) scenario() domain.Scenario {
if spec.role == roleEmployer {
return domain.ScenarioEmployer
}
return domain.ScenarioCandidate
}
const (
alphaOwnerLocal = "employer-alpha"
betaOwnerLocal = "employer-beta"
selfServiceName = "candidate"
preparedStem = "prepared-"
)
// accounts lists every synthetic account in creation order.
func accounts() []accountSpec {
specs := []accountSpec{
{local: alphaOwnerLocal, role: roleEmployer},
{local: betaOwnerLocal, role: roleEmployer},
{local: selfServiceName, role: roleSelfService, fullName: "Демо-кандидат для самостоятельного прохождения (синтетический профиль)"},
}
for ordinal := 1; ordinal <= preparedCohortSize; ordinal++ {
specs = append(specs, accountSpec{
local: fmt.Sprintf("%s%d", preparedStem, ordinal), role: rolePrepared, ordinal: ordinal,
fullName: fmt.Sprintf("Демо-кандидат %d с подготовленной попыткой (синтетический профиль)", ordinal),
})
}
return specs
}
// organizationSpec is one synthetic organization: its owner and, optionally,
// a second member with a role that the minimal release denies tenant actions.
type organizationSpec struct {
name string
description string
sphere string
ownerLocal string
memberLocal string
memberRole domain.OrganizationRole
}
// organizations lists the two synthetic organizations. The owner of Alpha is
// a recruiter of Beta, so one account shows two different permissions: full
// owner access in Alpha and the owner-only denial in Beta.
func organizations() []organizationSpec {
return []organizationSpec{
{
name: "Демо-компания «Альфа» (синтетические данные)",
description: "Синтетическая организация демонстрационного стенда. Реальной компании за ней нет.",
sphere: "Демонстрационные данные",
ownerLocal: alphaOwnerLocal,
},
{
name: "Демо-компания «Бета» (синтетические данные)",
description: "Вторая синтетическая организация демонстрационного стенда. Реальной компании за ней нет.",
sphere: "Демонстрационные данные",
ownerLocal: betaOwnerLocal,
memberLocal: alphaOwnerLocal,
memberRole: domain.OrganizationRoleRecruiter,
},
}
}
// preparedMarker is the profile text that labels the prepared attempt for
// the candidate and for anyone who reads the profile or its PDF.
const preparedMarker = "Синтетический профиль демонстрационного стенда. Полная попытка теста подготовлена командой demo-seed по обычным правилам теста; человек ее не проходил."
const selfServiceMarker = "Синтетический профиль демонстрационного стенда для самостоятельного прохождения экспресс-теста и полного теста."
// profileInput builds the manual profile of a candidate: a name, the
// synthetic address as contact, one stack tag, the declared role, and one
// synthetic work period. No FSP ID is linked; the profile has no place for
// one.
func profileInput(spec accountSpec) domain.CandidateProfileInput {
marker := selfServiceMarker
if spec.role == rolePrepared {
marker = preparedMarker
}
confirmed := domain.ProfileClaimConfirmed
return domain.CandidateProfileInput{
FullName: &domain.ProfileClaimInput[string]{Value: spec.fullName, Status: confirmed},
Email: &domain.ProfileClaimInput[string]{Value: spec.email(), Status: confirmed},
Stack: []domain.ProfileClaimInput[string]{{Value: "go", Status: confirmed}},
Roles: []domain.ProfileClaimInput[domain.ProfileRole]{{
Value: domain.ProfileRole{Specialization: fullSpecialization, SelfAssessedGrade: fullGrade}, Status: confirmed,
}},
Experience: []domain.ProfileClaimInput[domain.ProfileExperience]{{
Value: domain.ProfileExperience{
EmployerName: "Синтетическая компания (демо)", Specialization: fullSpecialization,
StartedOn: "2023-01", EndedOn: "2025-12", Summary: marker,
},
Status: confirmed,
}},
}
}
// questionnaireInput declares Backend Junior with Go and remote work, the
// selection of the full category.
func questionnaireInput() domain.CandidateQuestionnaireInput {
return domain.CandidateQuestionnaireInput{
Specializations: []domain.QuestionnaireSpecialization{{
Specialization: fullSpecialization, SelfAssessedGrade: fullGrade,
TaskLanguages: []domain.TaskLanguageCode{fullTaskLanguage}, Stack: []string{},
}},
WorkFormats: []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote},
}
}
// publishedFields are the card fields of every prepared candidate. They are
// identical across the cohort, so the cards form one cohort of six.
func publishedFields() []domain.CardField {
return []domain.CardField{
domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience,
domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats,
}
}
@@ -0,0 +1,82 @@
package demoseed
import (
"context"
"errors"
"fmt"
"lincodex/backend/internal/port/outbound"
)
// ResetVerdict says whether the operator tooling may discard the stand's
// database to rebuild the demo world.
type ResetVerdict string
const (
// ResetAllowedEmpty is a stand without any account: nothing to lose.
ResetAllowedEmpty ResetVerdict = "empty"
// ResetAllowedSynthetic is a seeded stand whose every account is a
// synthetic demo account.
ResetAllowedSynthetic ResetVerdict = "synthetic"
// ResetRefusedOrdinary is a stand that holds at least one account outside
// the synthetic domain. Such an account is ordinary data, and the reset
// never deletes it.
ResetRefusedOrdinary ResetVerdict = "ordinary_accounts"
)
// Allowed reports whether the verdict lets the reset proceed.
func (verdict ResetVerdict) Allowed() bool {
return verdict == ResetAllowedEmpty || verdict == ResetAllowedSynthetic
}
// ResetCheck is the read-only answer of CheckReset. It holds counts only.
type ResetCheck struct {
Verdict ResetVerdict
Census outbound.DemoAccountCensus
}
// DecideReset applies the reset rule to an account census: a database may be
// discarded only when it has no account at all or only synthetic demo
// accounts.
func DecideReset(census outbound.DemoAccountCensus) ResetVerdict {
switch {
case census.Total == 0:
return ResetAllowedEmpty
case census.Ordinary() == 0:
return ResetAllowedSynthetic
default:
return ResetRefusedOrdinary
}
}
// Inspector reads the account census and the inventory of a stand. It
// changes nothing.
type Inspector struct {
store outbound.DemoSeedStore
}
// NewInspector fails without a store.
func NewInspector(store outbound.DemoSeedStore) (*Inspector, error) {
if store == nil {
return nil, errors.New("demoseed.NewInspector - store must be set")
}
return &Inspector{store: store}, nil
}
// CheckReset counts the accounts and returns the verdict.
func (inspector *Inspector) CheckReset(ctx context.Context) (ResetCheck, error) {
census, err := inspector.store.CountAccounts(ctx, SyntheticDomain)
if err != nil {
return ResetCheck{}, fmt.Errorf("Inspector.CheckReset - count accounts: %w", err)
}
return ResetCheck{Verdict: DecideReset(census), Census: census}, nil
}
// Inventory returns the counts of the seed's records.
func (inspector *Inspector) Inventory(ctx context.Context) (outbound.DemoInventory, error) {
inventory, err := inspector.store.Inventory(ctx, SyntheticDomain, []string{string(FullCategory), TrainingCategory})
if err != nil {
return outbound.DemoInventory{}, fmt.Errorf("Inspector.Inventory - count records: %w", err)
}
return inventory, nil
}
+686
View File
@@ -0,0 +1,686 @@
// Package demoseed builds the small reproducible demonstration world of an
// isolated demo stand: synthetic accounts of both roles that are confirmed
// without mail, two organizations with different permissions, a candidate
// without an FSP ID, the express training bank apart from the full bank, and
// prepared full attempts that run through the ordinary attempt operations.
//
// The seed is idempotent: a second run finds every record and creates
// nothing. It never changes or removes a record it did not create, and it
// refuses a stand that holds accounts of other people but none of its own.
package demoseed
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/candidateprivacy"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/policy"
"lincodex/backend/internal/usecase/profile"
"lincodex/backend/internal/usecase/questionnaire"
)
var (
// ErrStandNotFresh reports a stand that holds ordinary accounts and no
// account of the seed. The seed never mixes demo records with them.
ErrStandNotFresh = errors.New("the stand holds ordinary accounts and was never seeded")
// ErrForeignPolicy reports a product policy that the seed did not expect:
// neither the initial demo version nor the demo version the seed publishes.
ErrForeignPolicy = errors.New("the product policy is not the initial or the seeded demo policy")
// ErrAccountConflict reports an address of the seed that belongs to an
// account in another state, for example an unconfirmed registration.
ErrAccountConflict = errors.New("a demo address belongs to an account the seed did not create")
// ErrPreparedAttemptFailed reports a prepared attempt that did not end
// with an assigned synthetic demonstration category.
ErrPreparedAttemptFailed = errors.New("the prepared attempt did not assign its demonstration category")
)
// seedPolicy is the demo product policy version the seed publishes: the
// explicit demo_basic attempt settings, the separate express training mode,
// the review band, and the matching section.
func seedPolicy() domain.ProductPolicy { return domain.DemoProductPolicyV4() }
// Dependencies are the product services and ports the seed drives.
type Dependencies struct {
Transactor outbound.Transactor
Store outbound.DemoSeedStore
Hasher outbound.PasswordHasher
Consents *consent.Service
Profiles *profile.Service
Questionnaires *questionnaire.Service
Privacy *candidateprivacy.Service
Attempts *assessment.AttemptService
Bank *assessment.Bank
Attestor *assessment.CategoryAttestor
Clock func() time.Time
}
// Seeder runs the demo seed.
type Seeder struct {
deps Dependencies
}
// NewSeeder fails when a dependency is missing.
func NewSeeder(deps Dependencies) (*Seeder, error) {
if deps.Transactor == nil || deps.Store == nil || deps.Hasher == nil || deps.Consents == nil ||
deps.Profiles == nil || deps.Questionnaires == nil || deps.Privacy == nil || deps.Attempts == nil ||
deps.Bank == nil || deps.Attestor == nil || deps.Clock == nil {
return nil, errors.New("demoseed.NewSeeder - every dependency must be set")
}
return &Seeder{deps: deps}, nil
}
// Input is a validated seed request. Password is the shared password of the
// synthetic accounts; it is set only when an account is created.
type Input struct {
Actor domain.AssessmentOperator
Password domain.Password
}
// Report lists what one run created and what it found. It holds addresses
// of synthetic accounts and identifiers only.
type Report struct {
PolicyVersion int32
Created []string
Present []string
Logins []Login
PreparedAttempts []PreparedAttempt
}
// Login is one synthetic account the operator hands out.
type Login struct {
Email string
Role string
}
// PreparedAttempt identifies one prepared full attempt.
type PreparedAttempt struct {
Email string
AttemptID domain.AssessmentAttemptID
}
func (report *Report) record(created bool, item string) {
if created {
report.Created = append(report.Created, item)
return
}
report.Present = append(report.Present, item)
}
// Seed builds the demo world or finds it complete.
func (seeder *Seeder) Seed(ctx context.Context, input Input) (Report, error) {
const location = "Seeder.Seed"
if _, err := domain.ParseAssessmentOperator(string(input.Actor)); err != nil {
return Report{}, fmt.Errorf("%s - validate actor: %w", location, err)
}
census, err := seeder.deps.Store.CountAccounts(ctx, SyntheticDomain)
if err != nil {
return Report{}, fmt.Errorf("%s - count accounts: %w", location, err)
}
if census.Synthetic == 0 && census.Ordinary() > 0 {
return Report{}, fmt.Errorf("%s - check the stand: %w", location, ErrStandNotFresh)
}
var report Report
productPolicy, err := seeder.ensurePolicy(ctx, input.Actor, &report)
if err != nil {
return Report{}, err
}
report.PolicyVersion = productPolicy.Version()
if err := seeder.ensureFullBank(ctx, input.Actor, productPolicy, &report); err != nil {
return Report{}, err
}
if err := seeder.ensureTrainingBank(ctx, input.Actor, productPolicy, &report); err != nil {
return Report{}, err
}
users, err := seeder.ensureAccounts(ctx, input.Password, &report)
if err != nil {
return Report{}, err
}
for _, spec := range organizations() {
if err := seeder.ensureOrganization(ctx, spec, users, &report); err != nil {
return Report{}, err
}
}
if err := seeder.ensureCandidates(ctx, users, &report); err != nil {
return Report{}, err
}
return report, nil
}
// ensureAccounts creates or finds every synthetic account, keyed by its
// local part.
func (seeder *Seeder) ensureAccounts(ctx context.Context, password domain.Password, report *Report) (map[string]domain.User, error) {
users := make(map[string]domain.User)
for _, spec := range accounts() {
user, err := seeder.ensureAccount(ctx, spec, password, report)
if err != nil {
return nil, err
}
users[spec.local] = user
report.Logins = append(report.Logins, Login{Email: spec.email(), Role: roleLabel(spec.role)})
}
return users, nil
}
// ensureCandidates completes every candidate account.
func (seeder *Seeder) ensureCandidates(ctx context.Context, users map[string]domain.User, report *Report) error {
for _, spec := range accounts() {
if spec.role == roleEmployer {
continue
}
attemptID, err := seeder.ensureCandidate(ctx, spec, users[spec.local], report)
if err != nil {
return err
}
if !attemptID.IsZero() {
report.PreparedAttempts = append(report.PreparedAttempts, PreparedAttempt{Email: spec.email(), AttemptID: attemptID})
}
}
return nil
}
func roleLabel(role accountRole) string {
switch role {
case roleEmployer:
return "employer"
case rolePrepared:
return "candidate with a prepared full attempt"
case roleSelfService:
return "candidate for the express and the full test"
}
return "account"
}
// ensurePolicy publishes the seed policy over the initial demo version or
// finds it already published. It refuses any other latest version, so an
// operator-owned policy is never replaced.
func (seeder *Seeder) ensurePolicy(ctx context.Context, actor domain.AssessmentOperator, report *Report) (domain.PolicyVersion, error) {
const location = "Seeder.ensurePolicy"
initial, err := demoDraft(domain.DemoProductPolicyV1(), domain.DemoPolicySeedAuthor)
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("%s - build initial draft: %w", location, err)
}
author, err := domain.ParsePolicyAuthor(string(actor))
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("%s - validate author: %w", location, err)
}
target, err := demoDraft(seedPolicy(), author)
if err != nil {
return domain.PolicyVersion{}, fmt.Errorf("%s - build seed draft: %w", location, err)
}
var version domain.PolicyVersion
created := false
err = seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
latest, err := unit.Policies().GetLatest(ctx, domain.ProductPolicyKey)
if err != nil {
return fmt.Errorf("read latest product policy: %w", err)
}
now, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("read database time: %w", err)
}
effective, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now)
if err != nil {
return fmt.Errorf("read effective product policy: %w", err)
}
if effective.ID() != latest.ID() || latest.Kind() != domain.PolicyKindDemo {
return ErrForeignPolicy
}
if latest.DocumentHash() == target.DocumentHash() {
version = latest
return nil
}
if latest.Version() != 1 || latest.DocumentHash() != initial.DocumentHash() {
return ErrForeignPolicy
}
version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return now }).Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: author, Policy: seedPolicy(),
})
if err != nil {
return fmt.Errorf("publish seed policy: %w", err)
}
created = true
return nil
})
if err != nil {
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
return domain.PolicyVersion{}, fmt.Errorf("%s - the stand has no product policy yet: %w", location, err)
}
return domain.PolicyVersion{}, fmt.Errorf("%s - transaction: %w", location, err)
}
report.record(created, fmt.Sprintf("product policy version %d", version.Version()))
return version, nil
}
func demoDraft(product domain.ProductPolicy, author domain.PolicyAuthor) (domain.PolicyVersionDraft, error) {
return domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: author, Policy: product,
})
}
// ensureFullBank imports and publishes the families of the full category,
// opens it under the seed policy with its catalog mapping, and attests the
// opening as a source of synthetic demonstration categories.
func (seeder *Seeder) ensureFullBank(
ctx context.Context,
actor domain.AssessmentOperator,
productPolicy domain.PolicyVersion,
report *Report,
) error {
const location = "Seeder.ensureFullBank"
required, err := domain.RequiredPublishedAssessmentFamilies(productPolicy.Policy())
if err != nil {
return fmt.Errorf("%s - read family requirement: %w", location, err)
}
bundle, err := syntheticBundle(fullBundleName, string(FullCategory), fullFamilyStem, int(required))
if err != nil {
return fmt.Errorf("%s - build bundle: %w", location, err)
}
if err := seeder.publishBundle(ctx, bundle, actor, report); err != nil {
return fmt.Errorf("%s - %w", location, err)
}
opening, err := seeder.deps.Bank.CategoryAvailability(ctx, FullCategory)
if err != nil || opening.PolicyVersionID != productPolicy.ID() {
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(
fullSpecialization, fullGrade, []domain.TaskLanguageCode{fullTaskLanguage},
)
if err != nil {
return fmt.Errorf("%s - build catalog mapping: %w", location, err)
}
if _, err := seeder.deps.Bank.OpenCategory(ctx, assessment.OpenCategoryInput{
Category: FullCategory, GradingPolicyID: productPolicy.ID(), OpenedBy: actor, CatalogMetadata: &metadata,
}); err != nil {
return fmt.Errorf("%s - open category: %w", location, err)
}
report.record(true, "opening of category "+string(FullCategory))
} else {
report.record(false, "opening of category "+string(FullCategory))
}
language := fullTaskLanguage
attestation, err := seeder.deps.Attestor.Attest(ctx, fullSpecialization, fullGrade, &language, string(actor))
if err != nil {
return fmt.Errorf("%s - attest category: %w", location, err)
}
report.record(attestation.Created, "synthetic demonstration attestation of "+string(FullCategory))
return nil
}
// ensureTrainingBank publishes the express families and binds them to the
// seed policy. The training category never gets a real opening.
func (seeder *Seeder) ensureTrainingBank(
ctx context.Context,
actor domain.AssessmentOperator,
productPolicy domain.PolicyVersion,
report *Report,
) error {
const location = "Seeder.ensureTrainingBank"
training := productPolicy.Policy().Assessment.Training
if training == nil {
return fmt.Errorf("%s - the seed policy has no express training mode", location)
}
bundle, err := syntheticBundle(trainingBundleName, TrainingCategory, trainingFamilyStem, int(training.DemoExpressItemCount))
if err != nil {
return fmt.Errorf("%s - build bundle: %w", location, err)
}
if err := seeder.publishBundle(ctx, bundle, actor, report); err != nil {
return fmt.Errorf("%s - %w", location, err)
}
exists, err := seeder.deps.Store.TrainingBindingExists(ctx, TrainingCategory, productPolicy.ID())
if err != nil {
return fmt.Errorf("%s - read binding: %w", location, err)
}
if !exists {
if err := seeder.deps.Store.BindTrainingBank(ctx, outbound.DemoTrainingBinding{
Category: TrainingCategory, PolicyVersionID: productPolicy.ID(),
ItemCount: int(training.DemoExpressItemCount), ReviewedBy: actor,
}); err != nil {
return fmt.Errorf("%s - bind training bank: %w", location, err)
}
}
report.record(!exists, "express training binding of "+TrainingCategory)
return nil
}
// publishBundle imports the bundle, which leaves stored versions unchanged,
// and publishes every family that has no published version yet.
func (seeder *Seeder) publishBundle(ctx context.Context, bundle assessment.Bundle, actor domain.AssessmentOperator, report *Report) error {
if _, err := seeder.deps.Bank.ImportBundle(ctx, bundle); err != nil {
return fmt.Errorf("import bundle %s: %w", bundle.Name, err)
}
published := 0
for _, family := range bundle.Families {
key := domain.AssessmentFamilyKey(family.Key)
if _, err := seeder.deps.Bank.ActiveFamily(ctx, key); err == nil {
continue
} else if !errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
return fmt.Errorf("read family %s: %w", family.Key, err)
}
if _, err := seeder.deps.Bank.PublishFamily(ctx, key, family.Version, actor); err != nil {
return fmt.Errorf("publish family %s: %w", family.Key, err)
}
published++
}
report.record(published > 0, fmt.Sprintf("%d published families of %s", len(bundle.Families), bundle.Category))
return nil
}
// ensureAccount creates a confirmed synthetic account with the C1 grant of a
// registration, or finds it. The address is on the reserved domain, so no
// mail is sent and ordinary registration keeps its email check.
func (seeder *Seeder) ensureAccount(ctx context.Context, spec accountSpec, password domain.Password, report *Report) (domain.User, error) {
const location = "Seeder.ensureAccount"
email, err := domain.NewEmailAddress(spec.email())
if err != nil {
return domain.User{}, fmt.Errorf("%s - build address: %w", location, err)
}
existing, found, err := seeder.readAccount(ctx, email)
if err != nil {
return domain.User{}, fmt.Errorf("%s - read account: %w", location, err)
}
if found {
if !existing.EmailVerified() || existing.Scenario != spec.scenario() {
return domain.User{}, fmt.Errorf("%s - %s: %w", location, spec.email(), ErrAccountConflict)
}
report.record(false, "account "+spec.email())
return existing, nil
}
if password.IsZero() {
return domain.User{}, fmt.Errorf("%s - a password is required to create %s", location, spec.email())
}
passwordHash, err := seeder.deps.Hasher.Hash(ctx, password)
if err != nil {
return domain.User{}, fmt.Errorf("%s - hash password: %w", location, err)
}
now := seeder.now()
user, err := domain.NewUser(domain.Registration{
Email: email, PasswordHash: passwordHash, Scenario: spec.scenario(), RegisteredAt: now,
})
if err != nil {
return domain.User{}, fmt.Errorf("%s - build account: %w", location, err)
}
var verified domain.User
err = seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.Users().Create(ctx, user); err != nil {
return fmt.Errorf("create account: %w", err)
}
text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposePersonalData, now)
if err != nil {
return fmt.Errorf("read C1 text: %w", err)
}
if _, err := seeder.deps.Consents.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, text.Version()); err != nil {
return fmt.Errorf("grant C1: %w", err)
}
verified, err = unit.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now)
if err != nil {
return fmt.Errorf("confirm address: %w", err)
}
return nil
})
if err != nil {
if errors.Is(err, outbound.ErrEmailTaken) {
return domain.User{}, fmt.Errorf("%s - %s: %w", location, spec.email(), ErrAccountConflict)
}
return domain.User{}, fmt.Errorf("%s - transaction: %w", location, err)
}
report.record(true, "account "+spec.email())
return verified, nil
}
func (seeder *Seeder) readAccount(ctx context.Context, email domain.EmailAddress) (domain.User, bool, error) {
var user domain.User
found := false
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
stored, err := unit.Users().GetByEmail(ctx, email)
if errors.Is(err, outbound.ErrUserNotFound) {
return nil
}
if err != nil {
return err
}
user, found = stored, true
return nil
})
return user, found, err
}
// ensureOrganization finds the organization by name among the organizations
// its owner owns, or creates it with the owner, and adds the second member.
func (seeder *Seeder) ensureOrganization(
ctx context.Context,
spec organizationSpec,
users map[string]domain.User,
report *Report,
) error {
const location = "Seeder.ensureOrganization"
owner := users[spec.ownerLocal]
organizationID, found, err := seeder.findOwnedOrganization(ctx, owner.ID, spec.name)
if err != nil {
return fmt.Errorf("%s - list organizations: %w", location, err)
}
if !found {
organizationID, err = seeder.createOrganization(ctx, spec, owner.ID)
if err != nil {
return fmt.Errorf("%s - %w", location, err)
}
}
report.record(!found, "organization "+spec.name)
if spec.memberLocal == "" {
return nil
}
member := users[spec.memberLocal]
created, err := seeder.ensureMembership(ctx, organizationID, member.ID, spec.memberRole)
if err != nil {
return fmt.Errorf("%s - %w", location, err)
}
report.record(created, fmt.Sprintf("%s membership of %s in %s", spec.memberRole, spec.memberLocal+"@"+SyntheticDomain, spec.name))
return nil
}
func (seeder *Seeder) findOwnedOrganization(ctx context.Context, ownerID uuid.UUID, name string) (uuid.UUID, bool, error) {
var organizationID uuid.UUID
found := false
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var after *outbound.OrganizationListPosition
for {
page, err := unit.Organizations().ListForUser(ctx, outbound.OrganizationListQuery{
UserID: ownerID, After: after, Limit: outbound.MaxOrganizationPageSize,
})
if err != nil {
return err
}
for _, item := range page.Items {
if item.Organization.Name() == name && item.Membership.Role() == domain.OrganizationRoleOwner {
organizationID, found = item.Organization.ID(), true
return nil
}
}
if !page.HasMore || len(page.Items) == 0 {
return nil
}
position := outbound.OrganizationPositionOf(page.Items[len(page.Items)-1])
after = &position
}
})
return organizationID, found, err
}
func (seeder *Seeder) createOrganization(ctx context.Context, spec organizationSpec, ownerID uuid.UUID) (uuid.UUID, error) {
profileValue, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{
Name: spec.name, Description: spec.description, Sphere: spec.sphere,
})
if err != nil {
return uuid.Nil, fmt.Errorf("build organization profile: %w", err)
}
now := seeder.now()
organization, err := domain.NewOrganization(profileValue, now)
if err != nil {
return uuid.Nil, fmt.Errorf("build organization: %w", err)
}
ownerMembership, err := domain.NewOwnerMembership(organization.ID(), ownerID, now)
if err != nil {
return uuid.Nil, fmt.Errorf("build owner membership: %w", err)
}
err = seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Organizations().CreateWithOwner(ctx, organization, ownerMembership)
})
if err != nil {
return uuid.Nil, fmt.Errorf("create organization: %w", err)
}
return organization.ID(), nil
}
func (seeder *Seeder) ensureMembership(ctx context.Context, organizationID, userID uuid.UUID, role domain.OrganizationRole) (bool, error) {
created := false
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
existing, err := unit.Memberships().Get(ctx, organizationID, userID)
if err == nil {
if existing.Role() != role {
return fmt.Errorf("membership has role %s, want %s: %w", existing.Role(), role, ErrAccountConflict)
}
return nil
}
if !errors.Is(err, outbound.ErrMembershipNotFound) {
return fmt.Errorf("read membership: %w", err)
}
membership, err := domain.NewMembership(domain.MembershipInput{
OrganizationID: organizationID, UserID: userID, Role: role, At: seeder.now(),
})
if err != nil {
return fmt.Errorf("build membership: %w", err)
}
if err := unit.Memberships().Insert(ctx, membership); err != nil {
return fmt.Errorf("insert membership: %w", err)
}
created = true
return nil
})
return created, err
}
// ensureCandidate gives a candidate its consents, manual profile, and
// questionnaire; a prepared candidate also gets the prepared full attempt and
// a published card. It returns the prepared attempt, or a zero ID.
func (seeder *Seeder) ensureCandidate(
ctx context.Context,
spec accountSpec,
user domain.User,
report *Report,
) (domain.AssessmentAttemptID, error) {
const location = "Seeder.ensureCandidate"
purposes := []domain.ConsentPurpose{domain.ConsentPurposeAutoCategorization}
if spec.role == rolePrepared {
purposes = append(purposes, domain.ConsentPurposePublication)
}
for _, purpose := range purposes {
if err := seeder.grantConsent(ctx, user.ID, purpose); err != nil {
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %s: %w", location, purpose, err)
}
}
created, err := seeder.ensureProfile(ctx, spec, user.ID)
if err != nil {
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err)
}
report.record(created, "profile of "+spec.email())
created, err = seeder.ensureQuestionnaire(ctx, user.ID)
if err != nil {
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err)
}
report.record(created, "questionnaire of "+spec.email())
if spec.role != rolePrepared {
return domain.AssessmentAttemptID{}, nil
}
attemptID, created, err := seeder.ensurePreparedAttempt(ctx, user.ID)
if err != nil {
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %s: %w", location, spec.email(), err)
}
report.record(created, "prepared full attempt of "+spec.email())
created, err = seeder.ensurePublication(ctx, user.ID)
if err != nil {
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err)
}
report.record(created, "published card of "+spec.email())
return attemptID, nil
}
// grantConsent grants the current text of the purpose; a repeat of the same
// version is idempotent in the ledger.
func (seeder *Seeder) grantConsent(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) error {
var version domain.ConsentTextVersion
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
text, err := unit.ConsentTexts().Current(ctx, purpose, seeder.now())
if err != nil {
return err
}
version = text.Version()
return nil
})
if err != nil {
return fmt.Errorf("read current text: %w", err)
}
if _, err := seeder.deps.Consents.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{
SubjectID: subjectID, Purpose: purpose, TextVersion: version,
}); err != nil {
return fmt.Errorf("grant: %w", err)
}
return nil
}
// ensureProfile saves the manual profile once. A profile that exists is left
// as it is, also when a visitor edited it; a reset restores it.
func (seeder *Seeder) ensureProfile(ctx context.Context, spec accountSpec, userID uuid.UUID) (bool, error) {
current, err := seeder.deps.Profiles.GetMyProfile(ctx, userID)
if err != nil {
return false, fmt.Errorf("read profile: %w", err)
}
if current.Version() > 0 {
return false, nil
}
if _, err := seeder.deps.Profiles.SaveMyProfile(ctx, userID, current.Version(), profileInput(spec)); err != nil {
return false, fmt.Errorf("save profile: %w", err)
}
return true, nil
}
// ensureQuestionnaire saves the questionnaire once, after the bank is open,
// because the questionnaire accepts only available task languages.
func (seeder *Seeder) ensureQuestionnaire(ctx context.Context, userID uuid.UUID) (bool, error) {
current, err := seeder.deps.Questionnaires.GetMyQuestionnaire(ctx, userID)
if err != nil {
return false, fmt.Errorf("read questionnaire: %w", err)
}
if current.Version() > 0 {
return false, nil
}
if _, err := seeder.deps.Questionnaires.SaveMyQuestionnaire(ctx, userID, current.Version(), questionnaireInput()); err != nil {
return false, fmt.Errorf("save questionnaire: %w", err)
}
return true, nil
}
// ensurePublication publishes the card once with the cohort fields.
func (seeder *Seeder) ensurePublication(ctx context.Context, userID uuid.UUID) (bool, error) {
settings, err := seeder.deps.Privacy.GetMyPrivacySettings(ctx, userID)
if err != nil {
return false, fmt.Errorf("read privacy settings: %w", err)
}
if settings.Publication.Version() > 0 {
return false, nil
}
if _, err := seeder.deps.Privacy.SetMyPublication(
ctx, userID, settings.Publication.Version(), domain.PublicationPublished, publishedFields(),
); err != nil {
return false, fmt.Errorf("publish card: %w", err)
}
return true, nil
}
func (seeder *Seeder) now() time.Time {
return seeder.deps.Clock().UTC().Truncate(time.Microsecond)
}
@@ -0,0 +1,107 @@
package demoseed
import (
"strings"
"testing"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestDecideResetAllowsOnlyEmptyOrSyntheticStands(t *testing.T) {
for _, test := range []struct {
census outbound.DemoAccountCensus
want ResetVerdict
}{
{outbound.DemoAccountCensus{}, ResetAllowedEmpty},
{outbound.DemoAccountCensus{Total: 9, Synthetic: 9}, ResetAllowedSynthetic},
{outbound.DemoAccountCensus{Total: 10, Synthetic: 9}, ResetRefusedOrdinary},
{outbound.DemoAccountCensus{Total: 1}, ResetRefusedOrdinary},
} {
if got := DecideReset(test.census); got != test.want || got.Allowed() == (test.want == ResetRefusedOrdinary) {
t.Errorf("DecideReset(%+v) = %s, want %s", test.census, got, test.want)
}
}
}
func TestSyntheticBundlesAreValidAndStable(t *testing.T) {
required, err := domain.RequiredPublishedAssessmentFamilies(seedPolicy())
if err != nil {
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
}
full, err := syntheticBundle(fullBundleName, string(FullCategory), fullFamilyStem, int(required))
if err != nil || len(full.Families) != int(required) {
t.Fatalf("full bundle = %d families, %v; want %d", len(full.Families), err, required)
}
again, err := syntheticBundle(fullBundleName, string(FullCategory), fullFamilyStem, int(required))
if err != nil || again.Families[len(again.Families)-1].Key != full.Families[len(full.Families)-1].Key ||
again.Review != full.Review {
t.Fatal("the bundle differs between two builds, so a repeated import would conflict")
}
for _, family := range full.Families {
if family.AnswerKey.AnswerFormat != domain.AnswerFormatInteger || !strings.Contains(family.Title, "synthetic demo") {
t.Errorf("family %s has format %q and title %q", family.Key, family.AnswerKey.AnswerFormat, family.Title)
}
}
training := seedPolicy().Assessment.Training
if training == nil || seedPolicy().Assessment.Attempt == nil || seedPolicy().Assessment.Attempt.RealMode != domain.AssessmentRealModeDemoBasic {
t.Fatal("the seed policy lacks the express mode or the demo_basic attempt settings")
}
if _, err := syntheticBundle(trainingBundleName, TrainingCategory, trainingFamilyStem, int(training.DemoExpressItemCount)); err != nil {
t.Fatalf("training bundle error = %v", err)
}
if _, err := syntheticBundle(fullBundleName, string(FullCategory), fullFamilyStem, 0); err == nil {
t.Fatal("an empty bundle was accepted")
}
}
func TestIntegerAnswerHasTheIntendedCorrectness(t *testing.T) {
variant := domain.AssessmentVariant{AnswerFormat: domain.AnswerFormatInteger, ReferenceAnswer: "7"}
for _, correct := range []bool{true, false} {
answer, err := integerAnswer(variant, correct)
if err != nil {
t.Fatalf("integerAnswer(%v) error = %v", correct, err)
}
_, matches, err := domain.CanonicalAssessmentAnswerForVariant(answer, variant)
if err != nil || matches != correct {
t.Errorf("integerAnswer(%v) = %s, matches %v, %v", correct, answer, matches, err)
}
}
for _, variant := range []domain.AssessmentVariant{
{AnswerFormat: domain.AnswerFormatIntegerSequence, ReferenceAnswer: "1 2"},
{AnswerFormat: domain.AnswerFormatInteger, ReferenceAnswer: "seven"},
} {
if _, err := integerAnswer(variant, true); err == nil {
t.Errorf("integerAnswer(%+v) answered an unsupported variant", variant)
}
}
}
func TestDatasetHasTwoRolesOnTheSyntheticDomainAndACohortOfAtLeastFive(t *testing.T) {
prepared, employers, selfService := 0, 0, 0
seen := map[string]bool{}
for _, spec := range accounts() {
if seen[spec.email()] || !strings.HasSuffix(spec.email(), "@"+SyntheticDomain) {
t.Fatalf("account %s is repeated or outside the synthetic domain", spec.email())
}
seen[spec.email()] = true
switch spec.role {
case roleEmployer:
employers++
case rolePrepared:
prepared++
case roleSelfService:
selfService++
}
if spec.role != roleEmployer && !strings.Contains(spec.fullName, "синтетический профиль") {
t.Errorf("candidate %s has no synthetic marker in the name", spec.email())
}
}
if employers != 2 || selfService != 1 || prepared < 5 {
t.Fatalf("dataset has %d employers, %d self-service and %d prepared candidates", employers, selfService, prepared)
}
specs := organizations()
if len(specs) != 2 || specs[0].ownerLocal == specs[1].ownerLocal || specs[1].memberRole.CanManageOrganization() {
t.Fatal("the organizations do not show two owners and a non-managing second role")
}
}