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

+26
View File
@@ -0,0 +1,26 @@
# Image of the demo seed operator command. Only the isolated demo stand
# overlay (deploy/docker/docker-compose.demo.yml) builds it; the backend and
# release images never contain the command.
ARG GO_IMAGE=golang:1.26.8-alpine
ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot
FROM ${GO_IMAGE} AS build
ENV GOTOOLCHAIN=local
WORKDIR /src/backend
COPY go.mod go.sum ./
RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/demo-seed ./cmd/demo-seed
FROM ${RUNTIME_IMAGE}
LABEL org.opencontainers.image.title="Lincodex demo seed" \
org.opencontainers.image.description="Operator command that seeds synthetic data on an isolated demo stand"
WORKDIR /
COPY --from=build /out/demo-seed /demo-seed
USER nonroot:nonroot
ENTRYPOINT ["/demo-seed"]
+8
View File
@@ -65,6 +65,14 @@ policy-publish-build: ## Build the local policy publication operator command
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/policy-publish ./cmd/policy-publish
.PHONY: demo-seed demo-seed-build
demo-seed: ## Seed, check, or count the isolated demo stand; needs DEMO_MODE=isolated (set ARGS)
$(GO) run ./cmd/demo-seed $(ARGS)
demo-seed-build: ## Build the local demo seed operator command
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/demo-seed ./cmd/demo-seed
.PHONY: deps install install-tools
deps: ## Download pinned Go module dependencies
$(GO) mod download
+29
View File
@@ -0,0 +1,29 @@
// Command demo-seed seeds the synthetic demonstration world of an isolated
// demo stand, checks whether a reset may discard the stand's database, and
// prints an inventory of counts. It requires DEMO_MODE=isolated.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"lincodex/backend/internal/adapter/primary/cli/demoseed"
)
func main() {
os.Exit(run())
}
func run() int {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := demoseed.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout, time.Now); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "demo-seed: %v\n", err)
return 2
}
return 0
}
+443
View File
@@ -0,0 +1,443 @@
//go:build integration
package integration_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/primary/cli/demoseed"
"lincodex/backend/internal/adapter/secondary/argon2id"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/anonymousprofile"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
seedusecase "lincodex/backend/internal/usecase/demoseed"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/policy"
)
const (
demoSeedTimeout = 4 * time.Minute
demoSeedActor = "operator:demo-seed-test"
demoSeedPassword = "synthetic demo stand password"
// demoSeedKeySecret keys the in-test attempt and view services only.
demoSeedKeySecret = "demo-seed-integration-key-secret-0123456789"
ordinaryEmail = "visitor@example.test"
)
// demoSeedStand is one isolated database with the startup policy seeded, as
// a freshly started backend leaves it.
type demoSeedStand struct {
ctx context.Context
pool *pgxpool.Pool
databaseURL string
}
func newDemoSeedStand(ctx context.Context, t *testing.T, env *testEnvironment) demoSeedStand {
t.Helper()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
return demoSeedStand{ctx: ctx, pool: pool, databaseURL: databaseURL}
}
// run executes the operator command with the given environment overrides on
// top of the stand's DATABASE_URL, the isolated mode, and the password.
func (stand demoSeedStand) run(t *testing.T, overrides map[string]string, args ...string) (string, error) {
t.Helper()
environment := map[string]string{
"DATABASE_URL": stand.databaseURL, demoseed.DemoModeName: demoseed.IsolatedDemoMode,
demoseed.PasswordName: demoSeedPassword,
}
for key, value := range overrides {
if value == "" {
delete(environment, key)
continue
}
environment[key] = value
}
lookup := func(key string) (string, bool) {
value, ok := environment[key]
return value, ok
}
var output bytes.Buffer
err := demoseed.Run(stand.ctx, args, lookup, &output, time.Now)
return output.String(), err
}
func (stand demoSeedStand) inventory(t *testing.T) string {
t.Helper()
output, err := stand.run(t, nil, "inventory")
if err != nil {
t.Fatalf("inventory error = %v (output %q)", err, output)
}
return output
}
func (stand demoSeedStand) count(t *testing.T, query string, args ...any) int {
t.Helper()
var value int
if err := stand.pool.QueryRow(stand.ctx, query, args...).Scan(&value); err != nil {
t.Fatalf("count %q: %v", query, err)
}
return value
}
func (stand demoSeedStand) userID(t *testing.T, email string) uuid.UUID {
t.Helper()
var id uuid.UUID
if err := stand.pool.QueryRow(stand.ctx, `SELECT id FROM users WHERE email_normalized = $1`, email).Scan(&id); err != nil {
t.Fatalf("read account %s: %v", email, err)
}
return id
}
// createOrdinaryAccount stores an unconfirmed registration outside the
// synthetic domain, the way a visitor's own sign-up leaves it.
func (stand demoSeedStand) createOrdinaryAccount(t *testing.T) uuid.UUID {
t.Helper()
hasher, err := argon2id.NewHasher(1)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
password, err := domain.NewPassword("ordinary visitor password")
if err != nil {
t.Fatalf("NewPassword() error = %v", err)
}
hash, err := hasher.Hash(stand.ctx, password)
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
address, err := domain.NewEmailAddress(ordinaryEmail)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
user, err := domain.NewUser(domain.Registration{
Email: address, PasswordHash: hash, Scenario: domain.ScenarioCandidate, RegisteredAt: time.Now().UTC().Truncate(time.Microsecond),
})
if err != nil {
t.Fatalf("NewUser() error = %v", err)
}
err = postgresadapter.NewTransactor(stand.pool).WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Users().Create(ctx, user)
})
if err != nil {
t.Fatalf("create ordinary account: %v", err)
}
return user.ID
}
func demoEmail(local string) string { return local + "@" + seedusecase.SyntheticDomain }
func TestDemoSeedCommand(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), demoSeedTimeout)
defer cancel()
t.Run("refuses without the isolated mode before it connects", func(t *testing.T) {
stand := newDemoSeedStand(ctx, t, env)
for _, args := range [][]string{{"seed", "--actor", demoSeedActor}, {"check-reset"}, {"inventory"}} {
for _, mode := range []string{"", "production", "Isolated"} {
overrides := map[string]string{demoseed.DemoModeName: mode}
if _, err := stand.run(t, overrides, args...); err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") {
t.Errorf("%v with DEMO_MODE=%q error = %v, want the isolated mode refusal", args, mode, err)
}
}
}
// An unreachable database proves that the guard runs before connecting.
if _, err := stand.run(t, map[string]string{demoseed.DemoModeName: "", "DATABASE_URL": "postgres://nobody@127.0.0.1:1/none"}, "check-reset"); err == nil ||
!strings.Contains(err.Error(), "DEMO_MODE=isolated") {
t.Errorf("check-reset against an unreachable database error = %v, want the mode refusal first", err)
}
if _, err := stand.run(t, map[string]string{demoseed.PasswordName: "short"}, "seed", "--actor", demoSeedActor); err == nil ||
!strings.Contains(err.Error(), demoseed.PasswordName) {
t.Errorf("seed with a short password error = %v, want a password refusal", err)
}
if accounts := stand.count(t, `SELECT count(*) FROM users`); accounts != 0 {
t.Fatalf("accounts after refusals = %d, want none", accounts)
}
if versions := stand.count(t, `SELECT count(*) FROM policy_versions`); versions != 1 {
t.Fatalf("policy versions after refusals = %d, want only the startup version", versions)
}
})
t.Run("refuses a stand with ordinary accounts that was never seeded", func(t *testing.T) {
stand := newDemoSeedStand(ctx, t, env)
visitor := stand.createOrdinaryAccount(t)
if output, err := stand.run(t, nil, "seed", "--actor", demoSeedActor); err == nil || !strings.Contains(err.Error(), "never seeded") {
t.Fatalf("seed over an ordinary account = %q, %v, want a refusal", output, err)
}
if output, err := stand.run(t, nil, "check-reset"); err == nil || !strings.Contains(err.Error(), "never deletes ordinary data") {
t.Fatalf("check-reset with an ordinary account = %q, %v, want a refusal", output, err)
}
if accounts := stand.count(t, `SELECT count(*) FROM users`); accounts != 1 || stand.userID(t, ordinaryEmail) != visitor {
t.Fatalf("accounts after the refused seed = %d, want only the visitor", accounts)
}
if versions := stand.count(t, `SELECT count(*) FROM policy_versions`); versions != 1 {
t.Fatalf("policy versions after the refused seed = %d, want the startup version only", versions)
}
})
t.Run("seeds once, repeats without change, and keeps ordinary data", func(t *testing.T) {
stand := newDemoSeedStand(ctx, t, env)
if output, err := stand.run(t, nil, "check-reset"); err != nil || !strings.Contains(output, "reset allowed (empty)") {
t.Fatalf("check-reset on an empty stand = %q, %v, want allowed", output, err)
}
first, err := stand.run(t, nil, "seed", "--actor", demoSeedActor)
if err != nil {
t.Fatalf("first seed error = %v (output %q)", err, first)
}
if strings.Contains(first, demoSeedPassword) || !strings.Contains(first, "login: candidate@"+seedusecase.SyntheticDomain) ||
!strings.Contains(first, "prepared full attempt: ") || strings.Contains(first, "created 0 records") {
t.Fatalf("first seed output = %q, want logins and prepared attempts without the password", first)
}
afterFirst := stand.inventory(t)
for _, want := range []string{
"synthetic_accounts=9\n", "verified_synthetic_accounts=9\n", "ordinary_accounts=0\n", "organizations=2\n",
"memberships=3\n", "candidate_profiles=7\n", "questionnaires=7\n", "attempts=6\n", "attempt_results=6\n",
"current_categories=6\n", "published_cards=6\n", "product_policy_versions=2\n", "published_families=28\n",
"category_openings=1\n", "category_attestations=1\n", "training_bindings=1\n",
} {
if !strings.Contains(afterFirst, want) {
t.Errorf("inventory after the first seed lacks %q:\n%s", want, afterFirst)
}
}
if facts := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`); facts < 6 {
t.Errorf("evidence facts after the prepared attempts = %d, want the projection of six results", facts)
}
second, err := stand.run(t, nil, "seed", "--actor", "operator:another-operator")
if err != nil || !strings.Contains(second, "created 0 records") {
t.Fatalf("second seed = %q, %v, want nothing created", second, err)
}
if afterSecond := stand.inventory(t); afterSecond != afterFirst {
t.Fatalf("inventory changed on the repeat:\nfirst:\n%s\nsecond:\n%s", afterFirst, afterSecond)
}
assertDemoSeedMarkers(t, stand)
assertDemoSeedPermissions(t, stand)
assertDemoSeedVisibleCohort(t, stand)
assertExpressAssignsNoCategory(t, stand)
if output, err := stand.run(t, nil, "check-reset"); err != nil || !strings.Contains(output, "reset allowed (synthetic)") {
t.Fatalf("check-reset on the seeded stand = %q, %v, want allowed", output, err)
}
visitor := stand.createOrdinaryAccount(t)
if output, err := stand.run(t, nil, "check-reset"); err == nil || !strings.Contains(err.Error(), "1 accounts outside") {
t.Fatalf("check-reset with a visitor = %q, %v, want a refusal that counts one ordinary account", output, err)
}
// A repeat after a visitor registered is still a no-op and leaves the
// visitor alone.
if output, err := stand.run(t, nil, "seed", "--actor", demoSeedActor); err != nil || !strings.Contains(output, "created 0 records") {
t.Fatalf("seed after a visitor = %q, %v, want nothing created", output, err)
}
if stand.userID(t, ordinaryEmail) != visitor {
t.Fatal("the visitor account changed")
}
})
}
// assertDemoSeedMarkers checks that every organization and profile of the seed
// names itself as synthetic and that the categories come from the synthetic
// demonstration source.
func assertDemoSeedMarkers(t *testing.T, stand demoSeedStand) {
t.Helper()
if unmarked := stand.count(t, `SELECT count(*) FROM organizations WHERE name NOT LIKE '%(синтетические данные)'`); unmarked != 0 {
t.Errorf("organizations without the synthetic marker = %d", unmarked)
}
if unmarked := stand.count(t, `SELECT count(*) FROM candidate_profiles AS profile WHERE NOT EXISTS (
SELECT 1 FROM candidate_profile_claims AS claim
WHERE claim.user_id = profile.user_id AND claim.kind = 'full_name' AND claim.value::text LIKE '%синтетический профиль%')`); unmarked != 0 {
t.Errorf("profiles without the synthetic marker in the name = %d", unmarked)
}
if prepared := stand.count(t, `SELECT count(DISTINCT user_id) FROM candidate_profile_claims
WHERE kind = 'experience' AND value::text LIKE '%подготовлена командой demo-seed%'`); prepared != 6 {
t.Errorf("profiles that label the prepared attempt = %d, want 6", prepared)
}
if other := stand.count(t, `SELECT count(*) FROM candidate_assessment_categories WHERE source <> 'synthetic_demo' OR calibration_status <> 'uncalibrated'`); other != 0 {
t.Errorf("categories outside the uncalibrated synthetic source = %d", other)
}
if outside := stand.count(t, `SELECT count(*) FROM users WHERE email_normalized NOT LIKE '%@' || $1`, seedusecase.SyntheticDomain); outside != 0 {
t.Errorf("seeded accounts outside the synthetic domain = %d", outside)
}
}
// assertDemoSeedPermissions checks the two organizations: each has its own
// owner, and the owner of Alpha is only a recruiter of Beta.
func assertDemoSeedPermissions(t *testing.T, stand demoSeedStand) {
t.Helper()
rows, err := stand.pool.Query(stand.ctx, `
SELECT split_part(users.email_normalized, '@', 1), organizations.name, memberships.role, memberships.state
FROM memberships
JOIN users ON users.id = memberships.user_id
JOIN organizations ON organizations.id = memberships.organization_id
ORDER BY 1, 2`)
if err != nil {
t.Fatalf("read memberships: %v", err)
}
defer rows.Close()
var got []string
for rows.Next() {
var account, organization, role, state string
if err := rows.Scan(&account, &organization, &role, &state); err != nil {
t.Fatalf("scan membership: %v", err)
}
got = append(got, fmt.Sprintf("%s|%s|%s|%s", account, strings.Fields(organization)[1], role, state))
}
want := []string{
"employer-alpha|«Альфа»|owner|active",
"employer-alpha|«Бета»|recruiter|active",
"employer-beta|«Бета»|owner|active",
}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("memberships = %v, want %v", got, want)
}
}
func demoSeedKeyring(t *testing.T) *identity.Keyring {
t.Helper()
keyring, err := identity.NewKeyring([]byte(demoSeedKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
return keyring
}
// assertDemoSeedVisibleCohort checks that the owner of Alpha sees the six
// prepared cards, which pass the minimum cohort of five, and no card of the
// self-service candidate, who did not publish.
func assertDemoSeedVisibleCohort(t *testing.T, stand demoSeedStand) {
t.Helper()
key, err := demoSeedKeyring(t).CandidateViewPseudonymKey()
if err != nil {
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
}
transactor := postgresadapter.NewTransactor(stand.pool)
quota := companyquota.NewService(time.Now)
views, err := candidateview.NewService(candidateview.Dependencies{
Transactor: transactor, Projector: anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(stand.pool), key, time.Now),
PseudonymKey: key, Clock: time.Now,
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
return quota.ReserveCardView(ctx, unit, organization, candidateID)
},
})
if err != nil {
t.Fatalf("candidateview.NewService() error = %v", err)
}
owner := stand.userID(t, demoEmail("employer-alpha"))
var organizationID uuid.UUID
if err := stand.pool.QueryRow(stand.ctx, `SELECT organization_id FROM memberships WHERE user_id = $1 AND role = 'owner'`, owner).Scan(&organizationID); err != nil {
t.Fatalf("read Alpha: %v", err)
}
var cards []domain.VisibleCandidateCard
err = transactor.WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
cards, err = views.ListVisibleCards(ctx, unit, owner, organizationID)
return err
})
if err != nil {
t.Fatalf("ListVisibleCards() error = %v", err)
}
selfService := stand.userID(t, demoEmail("candidate"))
if len(cards) != 6 {
t.Fatalf("visible cards of Alpha = %d, want the six prepared candidates", len(cards))
}
for _, card := range cards {
if card.CandidateID == selfService {
t.Fatal("the unpublished self-service candidate is visible")
}
}
}
// assertExpressAssignsNoCategory runs the express as the self-service
// candidate through the ordinary attempt operations, then checks that it
// created no category and no evidence, and that the full test still starts.
func assertExpressAssignsNoCategory(t *testing.T, stand demoSeedStand) {
t.Helper()
transactor := postgresadapter.NewTransactor(stand.pool)
attempts, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, demoSeedKeyring(t), time.Now,
assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true})
if err != nil {
t.Fatalf("NewAttemptServiceWithCategorySettings() error = %v", err)
}
candidateID := stand.userID(t, demoEmail("candidate"))
factsBefore := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`)
created, err := attempts.CreateAttempt(stand.ctx, assessment.CreateAttemptCommand{
ActorID: candidateID, IdempotencyKey: "express-" + uuid.NewString(), Kind: domain.AssessmentAttemptKindDemoExpress,
})
if err != nil || created.Outcome.StatusCode != http.StatusCreated {
t.Fatalf("create express = %+v, %v", created.Outcome, err)
}
var express domain.AssessmentAttempt
err = transactor.WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
express, err = unit.AssessmentAttempts().GetForCandidate(ctx, candidateID, created.Outcome.Response.ID)
return err
})
if err != nil {
t.Fatalf("read express attempt: %v", err)
}
snapshot := express.Snapshot()
if len(snapshot.Items) != 3 || snapshot.BankCategory != domain.AssessmentCategory(seedusecase.TrainingCategory) {
t.Fatalf("express has %d items from %q, want 3 from the training category", len(snapshot.Items), snapshot.BankCategory)
}
version := snapshot.Version
for _, item := range snapshot.Items {
reference, err := strconv.ParseInt(item.Variant.ReferenceAnswer, 10, 64)
if err != nil {
t.Fatalf("express reference answer %q: %v", item.Variant.ReferenceAnswer, err)
}
answer, err := json.Marshal(map[string]any{"format": "number", "number": reference})
if err != nil {
t.Fatalf("marshal express answer: %v", err)
}
result, err := attempts.SubmitAnswer(stand.ctx, assessment.SubmitAttemptAnswerCommand{
ActorID: candidateID, AttemptID: express.ID(), ItemID: item.ID, ExpectedVersion: version,
IdempotencyKey: "express-answer-" + uuid.NewString(), Answer: answer,
})
if err != nil || result.Outcome.StatusCode != http.StatusOK {
t.Fatalf("answer express item = %+v, %v", result.Outcome, err)
}
version = result.Outcome.Response.Version
}
finalized, err := attempts.FinalizeAttempt(stand.ctx, assessment.FinalizeAssessmentAttemptCommand{
ActorID: candidateID, AttemptID: express.ID(), ExpectedVersion: version, IdempotencyKey: "express-finalize-" + uuid.NewString(),
})
if err != nil || finalized.Outcome.StatusCode != http.StatusOK {
t.Fatalf("finalize express = %+v, %v", finalized.Outcome, err)
}
if categories := stand.count(t, `SELECT count(*) FROM candidate_assessment_categories WHERE candidate_id = $1`, candidateID); categories != 0 {
t.Fatalf("categories after a perfect express = %d, want none", categories)
}
if outcome := stand.count(t, `SELECT count(*) FROM assessment_attempts WHERE id = $1 AND outcome = 'demonstration'`, express.ID().UUID()); outcome != 1 {
t.Fatalf("express outcome rows = %d, want one demonstration outcome", outcome)
}
if facts := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`); facts != factsBefore {
t.Fatalf("evidence facts after the express = %d, want %d", facts, factsBefore)
}
specialization, grade, language := domain.SpecializationBackend, domain.GradeJunior, domain.TaskLanguageGo
full, err := attempts.CreateAttempt(stand.ctx, assessment.CreateAttemptCommand{
ActorID: candidateID, IdempotencyKey: "full-" + uuid.NewString(), Kind: domain.AssessmentAttemptKindRoot,
Specialization: &specialization, TargetGrade: &grade, TaskLanguage: &language,
})
if err != nil || full.Outcome.StatusCode != http.StatusCreated {
t.Fatalf("start the full test = %+v, %v, want a new attempt", full.Outcome, err)
}
}
@@ -0,0 +1,329 @@
// Package demoseed implements the local operator command of the isolated
// demonstration stand: it seeds the synthetic demo world, checks whether the
// stand's database may be discarded by a reset, and prints an inventory of
// counts. Every subcommand requires DEMO_MODE=isolated, and the command never
// deletes anything; the reset itself is a deploy target that discards the
// dedicated demo Compose project after this check.
package demoseed
import (
"context"
"crypto/rand"
"errors"
"flag"
"fmt"
"io"
"strings"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/argon2id"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/candidateprivacy"
"lincodex/backend/internal/usecase/consent"
seedusecase "lincodex/backend/internal/usecase/demoseed"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/profile"
"lincodex/backend/internal/usecase/questionnaire"
)
const (
usage = "usage: demo-seed seed --actor operator:<handle> | demo-seed check-reset | demo-seed inventory"
// DemoModeName and IsolatedDemoMode are the explicit guard of the command.
DemoModeName = "DEMO_MODE"
IsolatedDemoMode = "isolated"
// PasswordName holds the shared password of the synthetic accounts. It
// comes from the demo env file and is never printed.
PasswordName = "DEMO_ACCOUNT_PASSWORD" //nolint:gosec // The name of an environment variable, not a credential.
// poolSize covers the seed's sequential transactions and the nested
// reads of the services it drives.
poolSize = 4
// hashConcurrency is one Argon2id derivation at a time; the seed creates a
// handful of accounts once.
hashConcurrency = 1
// ephemeralKeyBytes is the size of the per-run idempotency secret. The
// seed is idempotent by the state it reads, so its idempotency records
// need no key shared with the backend.
ephemeralKeyBytes = 48
)
const syntheticWarning = "warning: synthetic demonstration data for an isolated demo stand only; never on a stand with real people\n"
// Subcommand names one action.
type Subcommand string
const (
SubcommandSeed Subcommand = "seed"
SubcommandCheckReset Subcommand = "check-reset"
SubcommandInventory Subcommand = "inventory"
)
// Command is a parsed, validated request.
type Command struct {
Subcommand Subcommand
Actor domain.AssessmentOperator
}
// Parse validates every argument before Run reads configuration or connects.
func Parse(args []string) (Command, error) {
if len(args) == 0 {
return Command{}, errors.New(usage)
}
switch Subcommand(args[0]) {
case SubcommandCheckReset, SubcommandInventory:
if len(args) != 1 {
return Command{}, errors.New(usage)
}
return Command{Subcommand: Subcommand(args[0])}, nil
case SubcommandSeed:
default:
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("demo-seed seed", flag.ContinueOnError)
flags.SetOutput(io.Discard)
actor := flags.String("actor", "", "operator handle")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
return Command{}, errors.New(usage)
}
operator, err := domain.ParseAssessmentOperator(strings.TrimSpace(*actor))
if err != nil {
return Command{}, errors.New("actor must be operator:<handle>")
}
return Command{Subcommand: SubcommandSeed, Actor: operator}, nil
}
// settings are the validated environment values of one run.
type settings struct {
databaseURL string
password domain.Password
}
// readSettings checks the demo mode guard, DATABASE_URL, and, for the seed,
// the account password, all before any connection. It loads no dotenv file.
func readSettings(command Command, lookup config.LookupEnv) (settings, error) {
mode, _ := lookup(DemoModeName)
if strings.TrimSpace(mode) != IsolatedDemoMode {
return settings{}, errors.New("DEMO_MODE=isolated is required; the demo seed runs only on an isolated demo stand")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return settings{}, errors.New("DATABASE_URL is not set")
}
result := settings{databaseURL: databaseURL}
if command.Subcommand != SubcommandSeed {
return result, nil
}
raw, _ := lookup(PasswordName)
password, err := domain.NewPassword(raw)
if err != nil {
return settings{}, fmt.Errorf("%s must be a password of at least %d characters", PasswordName, domain.MinNewPasswordCodePoints)
}
result.password = password
return result, nil
}
// Run parses the command, validates the environment, connects, and executes.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil || clock == nil {
return errors.New("demo seed command dependencies are required")
}
values, err := readSettings(command, lookup)
if err != nil {
return err
}
if _, err := io.WriteString(output, syntheticWarning); err != nil {
return errors.New("could not write the result")
}
pool, err := postgres.NewSizedPool(ctx, values.databaseURL, poolSize)
if err != nil {
return errors.New("database configuration is invalid")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("database is unavailable")
}
store := postgres.NewDemoSeedStore(pool)
inspector, err := seedusecase.NewInspector(store)
if err != nil {
return errors.New("demo seed is unavailable")
}
switch command.Subcommand {
case SubcommandCheckReset:
return ExecuteCheckReset(ctx, inspector, output)
case SubcommandInventory:
return ExecuteInventory(ctx, inspector, output)
case SubcommandSeed:
seeder, err := newSeeder(pool, store, clock)
if err != nil {
return errors.New("demo seed is unavailable")
}
return ExecuteSeed(ctx, seeder, seedusecase.Input{Actor: command.Actor, Password: values.password}, output)
}
return errors.New(usage)
}
// newSeeder wires the product services the seed drives. Synthetic category
// assignment is on because the command runs only with DEMO_MODE=isolated.
func newSeeder(pool *pgxpool.Pool, store outbound.DemoSeedStore, clock func() time.Time) (*seedusecase.Seeder, error) {
transactor := postgres.NewTransactor(pool)
hasher, err := argon2id.NewHasher(hashConcurrency)
if err != nil {
return nil, fmt.Errorf("demoseed.newSeeder - create hasher: %w", err)
}
secret := make([]byte, ephemeralKeyBytes)
if _, err := rand.Read(secret); err != nil {
return nil, fmt.Errorf("demoseed.newSeeder - draw idempotency secret: %w", err)
}
keyring, err := identity.NewKeyring(secret)
if err != nil {
return nil, fmt.Errorf("demoseed.newSeeder - create keyring: %w", err)
}
attempts, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, keyring, clock,
assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true})
if err != nil {
return nil, fmt.Errorf("demoseed.newSeeder - create attempt service: %w", err)
}
privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock})
if err != nil {
return nil, fmt.Errorf("demoseed.newSeeder - create privacy service: %w", err)
}
attestor, err := assessment.NewCategoryAttestor(transactor)
if err != nil {
return nil, fmt.Errorf("demoseed.newSeeder - create attestor: %w", err)
}
return seedusecase.NewSeeder(seedusecase.Dependencies{
Transactor: transactor, Store: store, Hasher: hasher,
Consents: consent.NewService(transactor, clock),
Profiles: profile.NewService(transactor, clock),
Questionnaires: questionnaire.NewService(transactor, clock),
Privacy: privacy, Attempts: attempts,
Bank: assessment.NewBank(transactor), Attestor: attestor, Clock: clock,
})
}
// Seeder runs the seed.
type Seeder interface {
Seed(ctx context.Context, input seedusecase.Input) (seedusecase.Report, error)
}
// ExecuteSeed seeds and prints what was created, the logins, and the
// prepared attempts. It prints synthetic addresses and identifiers only; the
// password stays in the demo env file.
func ExecuteSeed(ctx context.Context, seeder Seeder, input seedusecase.Input, output io.Writer) error {
if seeder == nil || output == nil {
return errors.New("demo seed command dependencies are required")
}
report, err := seeder.Seed(ctx, input)
if err != nil {
return safeSeedError(err)
}
var text strings.Builder
fmt.Fprintf(&text, "seeded: product policy version %d; created %d records, found %d already present\n",
report.PolicyVersion, len(report.Created), len(report.Present))
for _, item := range report.Created {
fmt.Fprintf(&text, "created: %s\n", item)
}
for _, login := range report.Logins {
fmt.Fprintf(&text, "login: %s (%s)\n", login.Email, login.Role)
}
text.WriteString("password: the " + PasswordName + " value of the demo env file; it is not printed\n")
for _, prepared := range report.PreparedAttempts {
fmt.Fprintf(&text, "prepared full attempt: %s of %s\n", prepared.AttemptID, prepared.Email)
}
text.WriteString("note: the prepared attempts were answered by the seed through the ordinary attempt operations; " +
"they are synthetic and no person took them. The express mode has its own policy section and bank and never assigns a category.\n")
if _, err := io.WriteString(output, text.String()); err != nil {
return errors.New("could not write the result")
}
return nil
}
func safeSeedError(err error) error {
switch {
case errors.Is(err, seedusecase.ErrStandNotFresh):
return errors.New("the stand holds ordinary accounts and was never seeded; seed only a fresh isolated demo stand")
case errors.Is(err, seedusecase.ErrForeignPolicy):
return errors.New("the product policy is neither the initial demo version nor the seeded one; seed only a fresh isolated demo stand")
case errors.Is(err, seedusecase.ErrAccountConflict):
return errors.New("a demo address belongs to an account the seed did not create; reset the isolated demo stand")
case errors.Is(err, seedusecase.ErrPreparedAttemptFailed):
return errors.New("a prepared attempt did not assign its demonstration category; reset the isolated demo stand")
case errors.Is(err, outbound.ErrPolicyVersionNotFound):
return errors.New("the product policy has no version yet; start the backend once so that it seeds the demo policy")
default:
return errors.New("demo seed failed")
}
}
// Inspector reads the census and the inventory.
type Inspector interface {
CheckReset(ctx context.Context) (seedusecase.ResetCheck, error)
Inventory(ctx context.Context) (outbound.DemoInventory, error)
}
// ExecuteCheckReset prints the verdict and fails when the database holds an
// account outside the synthetic domain, so the reset target stops before it
// discards anything.
func ExecuteCheckReset(ctx context.Context, inspector Inspector, output io.Writer) error {
if inspector == nil || output == nil {
return errors.New("demo seed command dependencies are required")
}
check, err := inspector.CheckReset(ctx)
if err != nil {
return errors.New("reset check failed")
}
if !check.Verdict.Allowed() {
return fmt.Errorf("reset refused: the stand holds %d accounts outside @%s; the reset never deletes ordinary data",
check.Census.Ordinary(), seedusecase.SyntheticDomain)
}
if _, err := fmt.Fprintf(output, "reset allowed (%s): %d accounts, all on @%s\n",
check.Verdict, check.Census.Total, seedusecase.SyntheticDomain); err != nil {
return errors.New("could not write the result")
}
return nil
}
// ExecuteInventory prints stable key=value counts, so two runs can be
// compared line by line.
func ExecuteInventory(ctx context.Context, inspector Inspector, output io.Writer) error {
if inspector == nil || output == nil {
return errors.New("demo seed command dependencies are required")
}
inventory, err := inspector.Inventory(ctx)
if err != nil {
return errors.New("inventory failed")
}
lines := []struct {
name string
value int64
}{
{"synthetic_accounts", inventory.SyntheticAccounts}, {"verified_synthetic_accounts", inventory.VerifiedSynthetic},
{"ordinary_accounts", inventory.OrdinaryAccounts}, {"organizations", inventory.Organizations},
{"memberships", inventory.Memberships}, {"consent_records", inventory.ConsentRecords},
{"candidate_profiles", inventory.CandidateProfiles}, {"questionnaires", inventory.Questionnaires},
{"attempts", inventory.Attempts}, {"attempt_results", inventory.AttemptResults},
{"current_categories", inventory.CurrentCategories}, {"evidence_facts", inventory.EvidenceFacts},
{"published_cards", inventory.PublishedCards}, {"product_policy_versions", inventory.ProductPolicyVersions},
{"published_families", inventory.PublishedFamilies}, {"category_openings", inventory.CategoryOpenings},
{"category_attestations", inventory.CategoryAttestations}, {"training_bindings", inventory.TrainingBindings},
}
var text strings.Builder
for _, line := range lines {
fmt.Fprintf(&text, "%s=%d\n", line.name, line.value)
}
if _, err := io.WriteString(output, text.String()); err != nil {
return errors.New("could not write the result")
}
return nil
}
@@ -0,0 +1,175 @@
package demoseed
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
seedusecase "lincodex/backend/internal/usecase/demoseed"
)
func TestParseAcceptsOnlyTheThreeSubcommands(t *testing.T) {
command, err := Parse([]string{"seed", "--actor", "operator:night"})
if err != nil || command.Subcommand != SubcommandSeed || command.Actor != "operator:night" {
t.Fatalf("Parse(seed) = %+v, %v", command, err)
}
for _, args := range [][]string{{"check-reset"}, {"inventory"}} {
if command, err := Parse(args); err != nil || string(command.Subcommand) != args[0] {
t.Errorf("Parse(%v) = %+v, %v", args, command, err)
}
}
for _, args := range [][]string{
nil, {"reset"}, {"seed"}, {"seed", "--actor", "alice"}, {"seed", "--actor", "system:demo-seed"},
{"seed", "--actor", "operator:night", "extra"}, {"check-reset", "--force"}, {"inventory", "all"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%v) accepted invalid arguments", args)
}
}
}
func lookupOf(values map[string]string) func(string) (string, bool) {
return func(key string) (string, bool) {
value, ok := values[key]
return value, ok
}
}
func TestRunRefusesWithoutTheIsolatedModeBeforeReadingAnythingElse(t *testing.T) {
for _, mode := range []string{"", "production", "ISOLATED", "isolated-ish"} {
values := map[string]string{"DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "a long synthetic password"}
if mode != "" {
values[DemoModeName] = mode
}
var output bytes.Buffer
err := Run(context.Background(), []string{"check-reset"}, lookupOf(values), &output, time.Now)
if err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") || output.Len() != 0 {
t.Errorf("Run with DEMO_MODE=%q = %v, output %q; want a refusal before any output", mode, err, output.String())
}
}
err := Run(context.Background(), []string{"seed", "--actor", "operator:night"},
lookupOf(map[string]string{DemoModeName: IsolatedDemoMode, "DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "short"}),
&bytes.Buffer{}, time.Now)
if err == nil || !strings.Contains(err.Error(), PasswordName) || strings.Contains(err.Error(), "short") {
t.Fatalf("Run(seed, short password) = %v, want a refusal that does not echo the value", err)
}
err = Run(context.Background(), []string{"inventory"}, lookupOf(map[string]string{DemoModeName: IsolatedDemoMode}), &bytes.Buffer{}, time.Now)
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
t.Fatalf("Run(inventory) without a database = %v", err)
}
}
type seederFake struct {
report seedusecase.Report
err error
}
func (fake seederFake) Seed(context.Context, seedusecase.Input) (seedusecase.Report, error) {
return fake.report, fake.err
}
func TestExecuteSeedPrintsLoginsAndAttemptsButNeverThePassword(t *testing.T) {
attemptID, err := domain.NewAssessmentAttemptID()
if err != nil {
t.Fatalf("NewAssessmentAttemptID() error = %v", err)
}
report := seedusecase.Report{
PolicyVersion: 2, Created: []string{"account candidate@demo.lincodex.test"},
Logins: []seedusecase.Login{{Email: "candidate@demo.lincodex.test", Role: "candidate"}},
PreparedAttempts: []seedusecase.PreparedAttempt{{Email: "prepared-1@demo.lincodex.test", AttemptID: attemptID}},
}
var output bytes.Buffer
password, err := domain.NewPassword("a long synthetic password")
if err != nil {
t.Fatalf("NewPassword() error = %v", err)
}
if err := ExecuteSeed(context.Background(), seederFake{report: report}, seedusecase.Input{Password: password}, &output); err != nil {
t.Fatalf("ExecuteSeed() error = %v", err)
}
text := output.String()
for _, want := range []string{
"created 1 records, found 0", "login: candidate@demo.lincodex.test", "prepared full attempt: " + attemptID.String(),
"no person took them", "never assigns a category",
} {
if !strings.Contains(text, want) {
t.Errorf("output lacks %q:\n%s", want, text)
}
}
if strings.Contains(text, "a long synthetic password") {
t.Fatal("the output contains the password")
}
for _, test := range []struct {
err error
want string
}{
{seedusecase.ErrStandNotFresh, "never seeded"},
{seedusecase.ErrForeignPolicy, "neither the initial demo version"},
{seedusecase.ErrAccountConflict, "did not create"},
{seedusecase.ErrPreparedAttemptFailed, "did not assign"},
{outbound.ErrPolicyVersionNotFound, "no version yet"},
{errors.New("pq: password authentication failed for user x"), "demo seed failed"},
} {
err := ExecuteSeed(context.Background(), seederFake{err: test.err}, seedusecase.Input{}, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "authentication") {
t.Errorf("ExecuteSeed(%v) = %v, want a safe message containing %q", test.err, err, test.want)
}
}
}
type inspectorFake struct {
census outbound.DemoAccountCensus
err error
}
func (fake inspectorFake) CheckReset(context.Context) (seedusecase.ResetCheck, error) {
return seedusecase.ResetCheck{Verdict: seedusecase.DecideReset(fake.census), Census: fake.census}, fake.err
}
func (fake inspectorFake) Inventory(context.Context) (outbound.DemoInventory, error) {
return outbound.DemoInventory{SyntheticAccounts: fake.census.Synthetic, OrdinaryAccounts: fake.census.Ordinary()}, fake.err
}
func TestExecuteCheckResetFailsOnOrdinaryAccounts(t *testing.T) {
for _, test := range []struct {
census outbound.DemoAccountCensus
want string
fails bool
}{
{outbound.DemoAccountCensus{}, "reset allowed (empty)", false},
{outbound.DemoAccountCensus{Total: 9, Synthetic: 9}, "reset allowed (synthetic): 9 accounts", false},
{outbound.DemoAccountCensus{Total: 10, Synthetic: 9}, "holds 1 accounts outside", true},
{outbound.DemoAccountCensus{Total: 1}, "holds 1 accounts outside", true},
} {
var output bytes.Buffer
err := ExecuteCheckReset(context.Background(), inspectorFake{census: test.census}, &output)
if test.fails != (err != nil) {
t.Fatalf("ExecuteCheckReset(%+v) = %v, want failure %v", test.census, err, test.fails)
}
text := output.String()
if err != nil {
text = err.Error()
}
if !strings.Contains(text, test.want) {
t.Errorf("ExecuteCheckReset(%+v) said %q, want %q", test.census, text, test.want)
}
}
if err := ExecuteCheckReset(context.Background(), inspectorFake{err: errors.New("connection reset")}, &bytes.Buffer{}); err == nil ||
err.Error() != "reset check failed" {
t.Fatalf("ExecuteCheckReset(store failure) = %v, want a refusal", err)
}
}
func TestExecuteInventoryPrintsStableCounts(t *testing.T) {
var output bytes.Buffer
if err := ExecuteInventory(context.Background(), inspectorFake{census: outbound.DemoAccountCensus{Total: 10, Synthetic: 9}}, &output); err != nil {
t.Fatalf("ExecuteInventory() error = %v", err)
}
if !strings.HasPrefix(output.String(), "synthetic_accounts=9\nverified_synthetic_accounts=0\nordinary_accounts=1\n") {
t.Fatalf("inventory = %q", output.String())
}
}
@@ -0,0 +1,252 @@
package postgres
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// DemoSeedStore implements outbound.DemoSeedStore on a pool. Its statements
// read counts and identifiers only.
type DemoSeedStore struct {
pool *pgxpool.Pool
}
var _ outbound.DemoSeedStore = (*DemoSeedStore)(nil)
// NewDemoSeedStore returns the store of the demo seed operator command.
func NewDemoSeedStore(pool *pgxpool.Pool) *DemoSeedStore {
return &DemoSeedStore{pool: pool}
}
// CountAccounts counts every account and those on the synthetic domain. The
// domain is compared on the normalized address, so letter case does not
// matter.
func (store *DemoSeedStore) CountAccounts(ctx context.Context, syntheticDomain string) (outbound.DemoAccountCensus, error) {
const location = "DemoSeedStore.CountAccounts"
var census outbound.DemoAccountCensus
if err := store.pool.QueryRow(ctx, `
SELECT count(*), count(*) FILTER (WHERE right(email_normalized, char_length($1::text) + 1) = '@' || $1::text)
FROM users`, syntheticDomain).Scan(&census.Total, &census.Synthetic); err != nil {
return outbound.DemoAccountCensus{}, fmt.Errorf("%s - count accounts: %w", location, sanitizeConnectError(err))
}
return census, nil
}
// CurrentCategoryAttempt returns the source attempt of the candidate's
// current category of the specialization.
func (store *DemoSeedStore) CurrentCategoryAttempt(
ctx context.Context,
candidateID uuid.UUID,
specialization domain.SpecializationCode,
) (domain.AssessmentAttemptID, bool, error) {
const location = "DemoSeedStore.CurrentCategoryAttempt"
var attemptID uuid.UUID
err := store.pool.QueryRow(ctx, `
SELECT source_attempt_id FROM candidate_assessment_categories
WHERE candidate_id = $1 AND specialization = $2`, candidateID, string(specialization)).Scan(&attemptID)
if errors.Is(err, pgx.ErrNoRows) {
return domain.AssessmentAttemptID{}, false, nil
}
if err != nil {
return domain.AssessmentAttemptID{}, false, fmt.Errorf("%s - read current category: %w", location, sanitizeConnectError(err))
}
return domain.AssessmentAttemptID(attemptID), true, nil
}
// TrainingBindingExists reports whether the category has a binding for the
// policy version.
func (store *DemoSeedStore) TrainingBindingExists(
ctx context.Context,
category string,
policyVersionID domain.PolicyVersionID,
) (bool, error) {
const location = "DemoSeedStore.TrainingBindingExists"
var exists bool
if err := store.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM assessment_training_bank_bindings
WHERE category = $1 AND product_policy_version_id = $2
)`, category, uuid.UUID(policyVersionID)).Scan(&exists); err != nil {
return false, fmt.Errorf("%s - read training binding: %w", location, sanitizeConnectError(err))
}
return exists, nil
}
type demoTrainingFamily struct {
id uuid.UUID
key string
version int32
hash []byte
}
type demoTrainingManifestEntry struct {
FamilyKey string `json:"family_key"`
Version int32 `json:"version"`
ContentSHA256 string `json:"content_sha256"`
}
// BindTrainingBank pins every published family of the training category in
// one transaction. The binding triggers check that the category has no real
// opening, that the item count matches the policy, and that the policy is
// the one in force.
func (store *DemoSeedStore) BindTrainingBank(ctx context.Context, binding outbound.DemoTrainingBinding) error {
const location = "DemoSeedStore.BindTrainingBank"
if binding.Category == "" || binding.ItemCount < 1 || binding.PolicyVersionID == (domain.PolicyVersionID{}) {
return fmt.Errorf("%s - binding is incomplete: %w", location, outbound.ErrDemoTrainingBindingMismatch)
}
if _, err := domain.ParseAssessmentOperator(string(binding.ReviewedBy)); err != nil {
return fmt.Errorf("%s - validate reviewer: %w", location, err)
}
tx, err := store.pool.BeginTx(ctx, transactionOptions)
if err != nil {
return fmt.Errorf("%s - begin transaction: %w", location, sanitizeConnectError(err))
}
finished := false
defer func() {
if !finished {
_ = rollback(ctx, tx)
}
}()
families, err := readPublishedTrainingFamilies(ctx, tx, binding.Category)
if err != nil {
return fmt.Errorf("%s - %w", location, err)
}
if len(families) != binding.ItemCount {
return fmt.Errorf("%s - %d published families for %d items: %w",
location, len(families), binding.ItemCount, outbound.ErrDemoTrainingBindingMismatch)
}
if err := insertTrainingBinding(ctx, tx, binding, families); err != nil {
return fmt.Errorf("%s - %w", location, err)
}
finished = true
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("%s - commit transaction: %w", location, markTransactionConflict(err))
}
return nil
}
func readPublishedTrainingFamilies(ctx context.Context, tx pgx.Tx, category string) ([]demoTrainingFamily, error) {
rows, err := tx.Query(ctx, `
SELECT id, family_key, version, content_sha256
FROM assessment_families
WHERE category = $1 AND lifecycle = 'published'
ORDER BY family_key, version`, category)
if err != nil {
return nil, fmt.Errorf("read published families: %w", sanitizeConnectError(err))
}
defer rows.Close()
var families []demoTrainingFamily
for rows.Next() {
var family demoTrainingFamily
if err := rows.Scan(&family.id, &family.key, &family.version, &family.hash); err != nil {
return nil, fmt.Errorf("scan published family: %w", err)
}
families = append(families, family)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate published families: %w", sanitizeConnectError(err))
}
return families, nil
}
// insertTrainingBinding stores the binding with the JSON manifest and the
// same canonical manifest hash that a category opening uses.
func insertTrainingBinding(ctx context.Context, tx pgx.Tx, binding outbound.DemoTrainingBinding, families []demoTrainingFamily) error {
entries := make([]demoTrainingManifestEntry, len(families))
canonical := make([]domain.AssessmentCategoryManifestEntry, len(families))
for index, family := range families {
entries[index] = demoTrainingManifestEntry{
FamilyKey: family.key, Version: family.version, ContentSHA256: hex.EncodeToString(family.hash),
}
canonical[index] = domain.AssessmentCategoryManifestEntry{
FamilyKey: domain.AssessmentFamilyKey(family.key), Version: family.version, ContentSHA256: family.hash,
}
}
manifest, err := json.Marshal(entries)
if err != nil {
return fmt.Errorf("encode manifest: %w", err)
}
manifestHash, err := assessmentCategoryManifestFingerprint(canonical)
if err != nil {
return fmt.Errorf("hash manifest: %w", err)
}
bindingID, err := uuid.NewV7()
if err != nil {
return fmt.Errorf("generate binding ID: %w", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO assessment_training_bank_bindings (
id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at
) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, clock_timestamp())`,
bindingID, binding.Category, uuid.UUID(binding.PolicyVersionID), binding.ItemCount,
manifestHash[:], manifest, string(binding.ReviewedBy)); err != nil {
return fmt.Errorf("insert binding: %w", sanitizeConnectError(err))
}
for index, family := range families {
if _, err := tx.Exec(ctx, `
INSERT INTO assessment_training_bank_binding_families (
binding_id, ordinal, family_id, family_key, family_version, content_sha256
) VALUES ($1, $2, $3, $4, $5, $6)`,
bindingID, index+1, family.id, family.key, family.version, family.hash); err != nil {
return fmt.Errorf("insert binding family: %w", sanitizeConnectError(err))
}
}
return nil
}
// Inventory counts the records of synthetic accounts and of the seed's bank
// categories in one read-only statement.
func (store *DemoSeedStore) Inventory(
ctx context.Context,
syntheticDomain string,
categories []string,
) (outbound.DemoInventory, error) {
const location = "DemoSeedStore.Inventory"
inventory := outbound.DemoInventory{SyntheticAccountDomain: syntheticDomain}
if err := store.pool.QueryRow(ctx, `
WITH synthetic AS (
SELECT id, email_verified_at FROM users
WHERE right(email_normalized, char_length($1::text) + 1) = '@' || $1::text
)
SELECT
(SELECT count(*) FROM synthetic),
(SELECT count(*) FROM synthetic WHERE email_verified_at IS NOT NULL),
(SELECT count(DISTINCT organization_id) FROM memberships WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM memberships WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM consent_records WHERE subject_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM candidate_profiles WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM candidate_questionnaires WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM assessment_attempts WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM assessment_attempt_results WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM candidate_assessment_categories WHERE candidate_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM skill_evidence_facts WHERE candidate_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM candidate_effective_publications WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM policy_versions WHERE policy_key = 'product'),
(SELECT count(*) FROM assessment_families WHERE category = ANY($2::text[]) AND lifecycle = 'published'),
(SELECT count(*) FROM assessment_category_openings WHERE category = ANY($2::text[])),
(SELECT count(*) FROM assessment_synthetic_category_reviews WHERE category = ANY($2::text[])),
(SELECT count(*) FROM assessment_training_bank_bindings WHERE category = ANY($2::text[])),
(SELECT count(*) FROM users)`,
syntheticDomain, categories,
).Scan(
&inventory.SyntheticAccounts, &inventory.VerifiedSynthetic, &inventory.Organizations, &inventory.Memberships,
&inventory.ConsentRecords, &inventory.CandidateProfiles, &inventory.Questionnaires, &inventory.Attempts,
&inventory.AttemptResults, &inventory.CurrentCategories, &inventory.EvidenceFacts, &inventory.PublishedCards,
&inventory.ProductPolicyVersions, &inventory.PublishedFamilies, &inventory.CategoryOpenings,
&inventory.CategoryAttestations, &inventory.TrainingBindings, &inventory.TotalAccounts,
); err != nil {
return outbound.DemoInventory{}, fmt.Errorf("%s - count records: %w", location, sanitizeConnectError(err))
}
inventory.OrdinaryAccounts = inventory.TotalAccounts - inventory.SyntheticAccounts
return inventory, nil
}
@@ -0,0 +1,94 @@
package outbound
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// ErrDemoTrainingBindingMismatch reports that the published families of the
// express training category do not match the binding the seed asked for.
var ErrDemoTrainingBindingMismatch = errors.New("demo training binding does not match the published families")
// DemoAccountCensus counts the accounts of a stand by whether their address
// belongs to the reserved synthetic demo domain. It holds counts only.
type DemoAccountCensus struct {
Total int64
Synthetic int64
}
// Ordinary is the number of accounts outside the synthetic demo domain.
func (census DemoAccountCensus) Ordinary() int64 { return census.Total - census.Synthetic }
// DemoTrainingBinding is the express training binding that the demo seed
// stores for the current product policy. The binding pins every published
// family of the training category, which must match ItemCount.
type DemoTrainingBinding struct {
Category string
PolicyVersionID domain.PolicyVersionID
ItemCount int
ReviewedBy domain.AssessmentOperator
}
// DemoInventory counts the records that the demo seed creates or relies on.
// Two seed runs on the same stand must report the same inventory. It holds
// counts only, never a personal value.
type DemoInventory struct {
SyntheticAccounts int64
VerifiedSynthetic int64
Organizations int64
Memberships int64
ConsentRecords int64
CandidateProfiles int64
Questionnaires int64
Attempts int64
AttemptResults int64
CurrentCategories int64
EvidenceFacts int64
PublishedCards int64
ProductPolicyVersions int64
PublishedFamilies int64
CategoryOpenings int64
CategoryAttestations int64
TrainingBindings int64
OrdinaryAccounts int64
TotalAccounts int64
SyntheticAccountDomain string
}
// DemoSeedStore holds the few storage operations of the demo seed that no
// product port covers: an account census, the current category of one
// candidate, the express training binding, and an inventory of counts. Every
// method runs in its own statement or transaction; none reads or returns a
// personal value.
type DemoSeedStore interface {
// CountAccounts counts all accounts and those whose address ends with
// "@" plus syntheticDomain.
CountAccounts(ctx context.Context, syntheticDomain string) (DemoAccountCensus, error)
// CurrentCategoryAttempt returns the attempt behind the candidate's
// current assessment category of the specialization, and false when the
// candidate holds no such category.
CurrentCategoryAttempt(
ctx context.Context,
candidateID uuid.UUID,
specialization domain.SpecializationCode,
) (domain.AssessmentAttemptID, bool, error)
// TrainingBindingExists reports whether the category already has a
// training binding for the policy version.
TrainingBindingExists(ctx context.Context, category string, policyVersionID domain.PolicyVersionID) (bool, error)
// BindTrainingBank stores the binding of every published family of the
// training category in one transaction. The database checks that the
// category is disjoint from real openings and that the policy is current.
// It returns ErrDemoTrainingBindingMismatch when the published family
// count differs from ItemCount.
BindTrainingBank(ctx context.Context, binding DemoTrainingBinding) error
// Inventory counts the seed's records on the stand.
Inventory(ctx context.Context, syntheticDomain string, categories []string) (DemoInventory, error)
}
@@ -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")
}
}