diff --git a/api/README.en.md b/api/README.en.md index 920b6f4..c6b5624 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -14,7 +14,7 @@ From the repository root, `make -C api check` checks contracts and `make generat ## Contract conventions -`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation requires Idempotency-Key, but no operation stores keys yet. +`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation and the assessment commands require Idempotency-Key, but no operation stores keys yet. ### Errors @@ -163,6 +163,80 @@ Questionnaire: - PUT replaces the whole questionnaire and needs no Idempotency-Key. A body equal to the stored state changes nothing, keeps the version, and answers 200 even with an older `expected_version`, so a retry after a lost response does not fail with 412. - Order of checks for a save: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), domain rules (400), version (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. +### Assessment + +The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). + +| Method and path | operationId | Security | Success | Specific errors | +| --- | --- | --- | --- | --- | +| `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | session | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | +| `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | +| `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | session | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | +| `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | +| `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422 | +| `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | session | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` | + +Every operation also declares the `default` problem response. + +Access: + +- The candidate comes only from the session; no operation takes a candidate identifier. An employer account answers 403 `forbidden`. An attempt of another candidate answers 404 `not_found`, the same as an unknown identifier, so attempt identifiers cannot be probed. +- No operation offers an employer the answers, the attempt history, or anti-cheat signals. Employers will see only the current category through a separate projection. + +Modes and versions: + +- `mode` is `demo_basic` or `adaptive`. The server picks it from the published bank of the category; the client never sends it. `demo_basic` scores a fixed form of reviewed demo items by their keys against the pass mark of the versioned basic grading policy, computes no ability estimate, and decides in one step: it never offers an additional practice. `adaptive` is the adaptive test of FR04. +- Creation fixes `versions`: `policy_version` (the number of the `product` policy version), `bank_version`, and `algorithm_version`. The attempt and its result keep them, so a result is reproduced from the stored answers and these versions, and a later version never rewrites it. +- The attempt `version` advances by exactly one with each committed change, including server-side transitions such as a verdict, a session start, expiry, or automatic finalization; a transition applied when the attempt is read is committed first and also advances it. + +Attempt lifecycle, with the commands each state accepts: + +| State | Meaning | Accepts | +| --- | --- | --- | +| `in_progress` | Items are being answered; `current_item` is the item to answer | an answer to `current_item` | +| `practice_pending` | The item part is done; the main practice has no finished verdict (not submitted, `pending`, or `failed`) | a practice solution while it is `not_started` or `failed` | +| `additional_practice_pending` | Adaptive only: finalize found the probability in the band below confirmation and offered one additional practice in the same attempt | the additional practice solution while it is `not_started` or `failed`; finalize in the same statuses declines the offer | +| `ready_to_finalize` | Every required part is done | finalize | +| `completed` | A decision was made; the result is available | only the repeat of finalize | +| `expired` | The time or session limit passed before the candidate finished; the result confirms no grade | none | +| `insufficient_bank` | The bank could not cover the blueprint within the limit; the result confirms no grade | none | + +- Additional practice (PRD FR04): with 0.50 <= P_G < 0.80 in the demo policy, the first finalize of an adaptive attempt completes nothing. It appends a practice of kind `additional` to `practices`, moves the attempt to `additional_practice_pending`, and returns the attempt. The practice continues the same attempt, keeps its time and session limits, and spends no new attempt. The next finalize after its verdict decides; P_G still below 0.80 gives `not_confirmed`. Finalizing without submitting it declines the offer with the same outcome. `practices` is a list with a `kind` rather than one more nullable field, so later practice kinds stay additive. +- Finalize therefore always answers with `AssessmentAttempt`, never with a result or a `oneOf` of both. When the state is `completed`, the client reads `GetMyAssessmentResult`. One response type keeps generated clients unambiguous and leaves room for non-terminal decisions without a breaking change. +- Limits: `expires_at` and `sessions` (`used`, `max`, `idle_timeout_seconds`, null when the policy defines no session limit) come from the policy version; PRD FR04 allows two sessions within 72 hours. Creation starts session 1. A read or command on the active attempt after `idle_timeout_seconds` without one starts the next session; one beyond `max` starts none, and the attempt becomes `expired`. Reading a terminal attempt or a result never starts a session. +- At the limits: a practice already `pending` is graded first. Then `ready_to_finalize` is finalized by the server and becomes `completed`, an unsubmitted additional practice is declined (`completed`, `not_confirmed`), and `in_progress` and `practice_pending` become `expired`. A finalize after that answers 200 with the `completed` attempt; any other command answers 409 `state_conflict`. +- Insufficient bank is a distinct state in two places. Before the start, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or without enough families that this candidate has not seen, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating anything. During an attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families. +- No new problem code is added, so TASK-157 gets 409 `state_conflict` plus the availability status instead of a `bank_unavailable` code. The `ProblemCode` enum is copied byte-for-byte into the ML contract (`test_contract_copies.py`), so a new code would also change the ML contract and its generated models. The availability read also tells the client why an attempt cannot start and, for `cooldown`, from when, which a fixed problem detail cannot carry. +- Availability shows the limits of each grade before the start: `time_limit_seconds`, `max_sessions`, `max_items`, and `practice_required`, null when unknown. +- Counting against the retry rules (3 attempts per 180 days, the 30-day same-grade interval): an attempt that ends `not_determined` with the reason `expired` or `practice_incomplete` is the candidate's attempt and counts. `insufficient_bank` and `sandbox_unavailable` are platform faults: they never count and start no interval. After a failure, including the first test, a lower grade can be tested at once. + +Items and answers: + +- An item has an `id` (the instance), `sequence`, a plain-text `prompt`, and `content` (`ItemContent`) in one of the formats `choice`, `number`, `string`, `order`, `find_error`, `configuration`, and `practice`. It never contains an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check, and seed items look like scored ones. `multiple`, `max_selections`, and `max_length` are properties of the format or the task family and never derived from the key. The variant is fixed when first served, so a reload, a retry, or a resumed session returns the same instance. +- An answer (`AssessmentAnswer`) has the same seven formats and carries only the answer. Unknown fields such as `score`, `duration`, or `seed` answer 400. The server records the times and scores the answer with the key of the item instance; time never enters the grade decision. Responses never say whether an answer was correct. +- The practice solution runs asynchronously in the sandbox against three hidden check groups; the client polls the attempt while it is `pending`. The verdict shows only the score 0-3 and the pass state of each group. Every outcome caused by the solution (a compilation or runtime error, a time or memory limit) is `finished` with groups not passed. `failed` (`sandbox_busy` or `sandbox_error`) means only that the infrastructure could not run it; it consumes nothing. This keeps `failed` from acting as an oracle for hidden checks and from allowing endless retries. After `finished` no other solution is accepted. +- If the latest submission is still `failed` when the limit passes, the result is `not_determined` with the reason `sandbox_unavailable`. A practice never submitted gives `practice_incomplete`. +- An attempt has no practice only in `demo_basic` while code practice is disabled until the sandbox isolation is verified; the result then lists the `practice_not_included` limitation. + +Commands, retries, and versions: + +- Create, answer, and finalize require Idempotency-Key with the 24-hour replay described above, so a repeated command returns the same outcome. Answers and finalize also carry `expected_version`, the attempt `version` the client read. Creation has no version to compare and relies on the key; the single active attempt per specialization is enforced by the state. +- Each item accepts one answer. Sending the stored answer again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Equality is defined per format: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. A different answer for an answered item answers 409 `state_conflict` with the current version; with a stale version the version check comes first and answers 412. +- Exception: a practice whose latest verdict is `failed` is outside the repeat rule. A submission with the same or a different solution and the current version queues it again and advances the version. +- Finalizing a `completed` attempt answers 200 with that attempt, so the result is computed once. A retry of the finalize that offered an additional practice, sent with a new key, carries the old version and answers 412, so it never declines the offer by accident. +- A stale `expected_version` answers 412 `version_conflict`, not 409. This deviates from the wording of the TASK-155 test step and of TASK-152, which say 409. It keeps the repository rule above and the questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is the same, to read the resource again. 409 `state_conflict` is kept for a command that the attempt state does not allow at the current version: the item is not current or has another answer, the attempt is terminal or past its limits, a practice verdict is pending, or the attempt is not ready to finalize. The two codes therefore lead to different client actions. +- A premature finalize answers 409 `state_conflict` without listing the unfinished items, because `Problem` allows no extension fields. The client reads them from the attempt: `state`, `progress`, `current_item`, and `practices`. +- Order of checks for a command: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), the attempt (404, after any due transition), the repeat of a stored answer or of finalize on a completed attempt (200), the version (412), the state (409 `state_conflict`), then domain rules (400 with pointers such as `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 `state_conflict` are stored under the key and replayed, while 400, including domain rules, 412, 429, and 5xx are not. Create and answers are rate-limited (429 with `Retry-After`), which also limits sandbox load. `TestAssessmentSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. + +Result: + +- `GetMyAssessmentResult` answers for a terminal attempt and 409 `state_conflict` for an active one, including `additional_practice_pending`. `outcome` is `confirmed`, `not_confirmed`, or `not_determined` with `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). A result never lowers a confirmed grade: `previous_confirmed_grade` stays in force when the attempt confirmed nothing. +- `calibration_status` and `limitations` describe the method. Fields that the method does not compute are null, never zero: `demo_basic` has null `uncertainty` and `strength`, and `adaptive` has null `basic_score`. `uncertainty` holds `theta`, `standard_error`, `interval_95`, and `p_grade`. `practices` lists the verdicts by kind. `durations` is a separate label and never enters the decision. +- `next_steps` come from the server: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (the command is planned), and `take_higher_grade`. A first confirmation is not a promotion, so `take_higher_grade` after it has a null `available_at`; after a promotion the next one waits for the 90-day promotion interval. +- The result never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. + +Planned, additive: a short approach description of up to 1500 characters next to the practice, which never decides the grade (PRD FR05); the debug run operation of the practice; the notice and storage of the anti-cheat signals (time, focus changes, pastes, parallel sessions), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05). + ### Generator checks `testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core. @@ -190,4 +264,11 @@ Known generator limitations: - Orval Zod schemas ignore `uniqueItems` and do not reject unknown fields of `additionalProperties: false` objects; the server stays authoritative for both. - Orval clears `src/shared/api/endpoints/` and `src/shared/api/schemas/` before generation (`clean: true`), because a schema used by several tags moves from a tag directory to the schema root. +#### Format unions + +- Format unions such as `ItemContent` and `AssessmentAnswer` are `oneOf` without a `discriminator` object. Redocly resolves `discriminator.mapping` values as references, and `scripts/merge-schemas.py` rewrites only `$ref`, so a mapping in a split schema file cannot resolve in the merged `components/schemas.yml`. Every variant fixes `format` with a one-value enum; ogen discriminates by that value and by the fields unique to a variant and rejects a body that matches several variants, and Orval generates a Zod union. +- Orval names the constants of an inline property ``, so a property name that repeats another schema name collides in `index.ts` (TS2308). The union of item formats is therefore `ItemContent`, not `AssessmentItemContent`, next to the `AssessmentItem.content` property. + +Generated Zod is not strict. A body that mixes the fields of two formats or carries an extra `score` or `seed` is accepted after unknown keys are silently stripped, and `uniqueItems` is not checked; only the server rejects such bodies. `frontend/src/shared/api/assessment-contract.test.ts` pins the accepted formats and that no answer or item DTO has a score, key, seed, or correctness field. + See the [development guide](../docs/en/DEVELOPMENT.md). diff --git a/api/README.md b/api/README.md index 73b5b36..a243634 100644 --- a/api/README.md +++ b/api/README.md @@ -14,7 +14,7 @@ ## Соглашения контракта -`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount` требует Idempotency-Key, но ни одна операция пока не хранит ключи. +`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount` и команды оценки требуют Idempotency-Key, но ни одна операция пока не хранит ключи. ### Ошибки @@ -163,6 +163,80 @@ ML-сервис отвечает на ошибки той же схемой `Pro - PUT заменяет анкету целиком, и Idempotency-Key ему не нужен. Тело, равное сохраненному состоянию, ничего не меняет, сохраняет версию и дает 200 даже со старым `expected_version`, поэтому повтор после потерянного ответа не падает с 412. - Порядок проверок при сохранении: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), доменные правила (400), версия (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер. +### Оценка + +Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`). + +| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | +| --- | --- | --- | --- | --- | +| `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | сессия | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | +| `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict` или `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | +| `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | сессия | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | +| `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | +| `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422 | +| `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | сессия | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` | + +Каждая операция также объявляет problem-ответ `default`. + +Доступ: + +- Кандидат берется только из сессии; ни одна операция не принимает идентификатор кандидата. Аккаунт работодателя получает 403 `forbidden`. Попытка другого кандидата дает 404 `not_found`, как и неизвестный идентификатор, поэтому идентификаторы попыток нельзя перебирать. +- Ни одна операция не дает работодателю ответы, историю попыток или античит-сигналы. Работодатель будет видеть только текущую категорию через отдельную проекцию. + +Режимы и версии: + +- `mode` - это `demo_basic` или `adaptive`. Сервер выбирает его по опубликованному банку категории; клиент режим не передает. `demo_basic` оценивает фиксированную форму проверенных демо-заданий по их ключам относительно проходного балла версионированной базовой политики, не вычисляет оценку способности и решает за один шаг: дополнительную практику он не предлагает. `adaptive` - адаптивный тест из FR04. +- Создание фиксирует `versions`: `policy_version` (номер версии политики `product`), `bank_version` и `algorithm_version`. Попытка и ее результат хранят их, поэтому результат воспроизводится по сохраненным ответам и этим версиям, а более поздняя версия его не переписывает. +- `version` попытки растет ровно на единицу с каждым зафиксированным изменением, включая серверные переходы: вердикт, начало сессии, истечение, автоматическое завершение. Переход, примененный при чтении попытки, фиксируется до ответа и тоже увеличивает версию. + +Жизненный цикл попытки и команды, которые принимает каждое состояние: + +| Состояние | Значение | Принимает | +| --- | --- | --- | +| `in_progress` | Идут ответы на задания; `current_item` - задание, на которое нужно ответить | ответ на `current_item` | +| `practice_pending` | Задания пройдены; у основной практики нет готового вердикта (не отправлена, `pending` или `failed`) | решение практики, пока она `not_started` или `failed` | +| `additional_practice_pending` | Только adaptive: завершение нашло вероятность в полосе ниже подтверждения и предложило одну дополнительную практику в той же попытке | решение дополнительной практики, пока она `not_started` или `failed`; завершение в тех же статусах отклоняет предложение | +| `ready_to_finalize` | Все обязательные части выполнены | завершение | +| `completed` | Решение принято; результат доступен | только повтор завершения | +| `expired` | Лимит времени или сессий истек раньше, чем кандидат закончил; результат не подтверждает грейд | ничего | +| `insufficient_bank` | Банк не смог обеспечить покрытие в пределах лимита; результат не подтверждает грейд | ничего | + +- Дополнительная практика (FR04 в PRD): при 0.50 <= P_G < 0.80 в демо-политике первое завершение adaptive-попытки ничего не решает. Оно добавляет в `practices` практику вида `additional`, переводит попытку в `additional_practice_pending` и возвращает попытку. Практика продолжает ту же попытку, сохраняет ее лимиты времени и сессий и не расходует новую попытку. Следующее завершение после ее вердикта принимает решение; если P_G остается ниже 0.80, итог `not_confirmed`. Завершение без отправки практики отклоняет предложение с тем же итогом. `practices` - список с полем `kind`, а не еще одно nullable-поле, поэтому новые виды практики добавляются без ломающих изменений. +- Поэтому завершение всегда отвечает `AssessmentAttempt`, а не результатом и не `oneOf` из двух схем. Когда состояние `completed`, клиент читает `GetMyAssessmentResult`. Один тип ответа делает сгенерированные клиенты однозначными и оставляет место для незавершающих решений без ломающих изменений. +- Лимиты: `expires_at` и `sessions` (`used`, `max`, `idle_timeout_seconds`; null, если политика не задает лимит сессий) берутся из версии политики; FR04 в PRD допускает две сессии в пределах 72 часов. Создание начинает сессию 1. Чтение или команда по активной попытке после `idle_timeout_seconds` без них начинает следующую сессию; сессия сверх `max` не начинается, и попытка становится `expired`. Чтение терминальной попытки или результата сессию не начинает. +- При достижении лимитов практика в статусе `pending` сначала оценивается. Затем сервер сам завершает `ready_to_finalize` и переводит в `completed`, неотправленная дополнительная практика считается отклоненной (`completed`, `not_confirmed`), а `in_progress` и `practice_pending` становятся `expired`. Завершение после этого дает 200 с попыткой в `completed`; любая другая команда дает 409 `state_conflict`. +- Недостаточный банк - отдельное состояние в двух местах. До старта `GetMyAssessmentAvailability` показывает `insufficient_bank` для грейда без опубликованного банка или без достаточного числа семейств, которых кандидат еще не видел, а `CreateMyAssessmentAttempt` отвечает 409 `state_conflict` и ничего не создает. Во время попытки терминальное состояние `insufficient_bank` завершает ее без подтвержденного грейда вместо повтора семейств. +- Новый код проблемы не добавлен, поэтому TASK-157 получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может. +- Доступность показывает лимиты каждого грейда до старта: `time_limit_seconds`, `max_sessions`, `max_items` и `practice_required`; null, если значение неизвестно. +- Учет в правилах повтора (3 попытки за 180 дней, 30 дней до повтора того же грейда): попытка с итогом `not_determined` по причине `expired` или `practice_incomplete` - попытка кандидата и учитывается. `insufficient_bank` и `sandbox_unavailable` - сбои платформы: они не учитываются и не запускают интервал. После неудачи, включая первый тест, меньший грейд можно проверить сразу. + +Задания и ответы: + +- У задания есть `id` (экземпляр), `sequence`, `prompt` простым текстом и `content` (`ItemContent`) в одном из форматов `choice`, `number`, `string`, `order`, `find_error`, `configuration` и `practice`. Оно никогда не содержит ключ ответа, правильный вариант, балл, идентификатор семейства или варианта, seed или скрытую проверку, а посевные задания выглядят так же, как оцениваемые. `multiple`, `max_selections` и `max_length` - свойства формата или семейства заданий и никогда не выводятся из ключа. Вариант фиксируется при первой выдаче, поэтому перезагрузка, повтор запроса и возобновление сессии возвращают тот же экземпляр. +- Ответ (`AssessmentAnswer`) имеет те же семь форматов и несет только ответ. Неизвестные поля вроде `score`, `duration` или `seed` дают 400. Сервер сам записывает время и оценивает ответ по ключу экземпляра задания; время не входит в решение о грейде. Ответы API никогда не сообщают, был ли ответ правильным. +- Решение практики исполняется в песочнице асинхронно на трех группах скрытых проверок; клиент опрашивает попытку, пока оно `pending`. Вердикт показывает только балл 0-3 и прохождение каждой группы. Любой исход, вызванный самим решением (ошибка компиляции или выполнения, лимит времени или памяти), - это `finished` с непройденными группами. `failed` (`sandbox_busy` или `sandbox_error`) означает только, что инфраструктура не смогла исполнить решение; он ничего не расходует. Так `failed` не становится оракулом для скрытых проверок и не дает бесконечных повторов. После `finished` другое решение не принимается. +- Если к истечению лимита последняя отправка все еще `failed`, результат - `not_determined` с причиной `sandbox_unavailable`. Неотправленная практика дает `practice_incomplete`. +- Попытка бывает без практики только в `demo_basic`, пока кодовая практика выключена до проверки изоляции песочницы; результат тогда содержит ограничение `practice_not_included`. + +Команды, повторы и версии: + +- Создание, ответ и завершение требуют Idempotency-Key с 24-часовым повтором, описанным выше, поэтому повтор команды возвращает тот же исход. Ответ и завершение также передают `expected_version` - прочитанную клиентом `version` попытки. У создания нет версии для сравнения, оно опирается на ключ; единственную активную попытку по специализации обеспечивает состояние. +- Каждое задание принимает один ответ. Повторная отправка сохраненного ответа, даже с новым ключом или старым `expected_version`, ничего не сохраняет, не меняет версию и дает 200 с текущей попыткой. Равенство определено для каждого формата: множества для `option_ids` и `line_numbers`, точная последовательность для `element_ids`, числовое равенство для `number`, совпадение текста без нормализации для `text` и `config`, тот же язык и совпадающий исходный код для практики. Другой ответ на уже отвеченное задание дает 409 `state_conflict` при текущей версии; при устаревшей версии ее проверка идет раньше и дает 412. +- Исключение: практика, последний вердикт которой `failed`, не подпадает под правило повтора. Отправка того же или другого решения с текущей версией снова ставит его в очередь и увеличивает версию. +- Завершение попытки в `completed` дает 200 с этой попыткой, поэтому результат вычисляется один раз. Повтор завершения, которое предложило дополнительную практику, с новым ключом несет старую версию и получает 412, поэтому он не может случайно отклонить предложение. +- Устаревший `expected_version` дает 412 `version_conflict`, а не 409. Это отступление от формулировки шага проверки TASK-155 и TASK-152, где указан 409. Так сохраняется правило репозитория выше и прецедент анкеты: `version_conflict` - это 412 и для If-Match, и для `expected_version` в теле, потому что действие клиента одно - прочитать ресурс снова. 409 `state_conflict` оставлен для команды, которую состояние попытки не допускает при текущей версии: задание не текущее или уже имеет другой ответ, попытка терминальная или вышла за лимиты, вердикт практики еще не готов или попытка не готова к завершению. Поэтому два кода ведут к разным действиям клиента. +- Преждевременное завершение дает 409 `state_conflict` без перечня незавершенных заданий, потому что `Problem` не допускает дополнительных полей. Клиент берет их из попытки: `state`, `progress`, `current_item` и `practices`. +- Порядок проверок команды: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), попытка (404, после всех назревших переходов), повтор сохраненного ответа или завершения завершенной попытки (200), версия (412), состояние (409 `state_conflict`), затем доменные правила (400 с pointer вроде `/answer/option_ids/0`). По соглашению об Idempotency-Key 404 и 409 `state_conflict` сохраняются под ключом и повторяются, а 400 (включая доменные правила), 412, 429 и 5xx - нет. Создание и ответы ограничены по частоте (429 с `Retry-After`), что ограничивает и нагрузку на песочницу. `TestAssessmentSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер. + +Результат: + +- `GetMyAssessmentResult` отвечает для терминальной попытки и дает 409 `state_conflict` для активной, включая `additional_practice_pending`. `outcome` - это `confirmed`, `not_confirmed` или `not_determined` с `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). Результат никогда не понижает подтвержденный грейд: если попытка ничего не подтвердила, действует `previous_confirmed_grade`. +- `calibration_status` и `limitations` описывают метод. Поля, которые метод не вычисляет, равны null, а не нулю: у `demo_basic` null в `uncertainty` и `strength`, у `adaptive` - null в `basic_score`. `uncertainty` содержит `theta`, `standard_error`, `interval_95` и `p_grade`. `practices` перечисляет вердикты по видам. `durations` - отдельная метка, которая не входит в решение. +- `next_steps` приходят с сервера: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (команда запланирована) и `take_higher_grade`. Первое подтверждение - не повышение, поэтому `take_higher_grade` после него имеет null в `available_at`; после повышения следующее ждет 90-дневный интервал повышения. +- Результат никогда не содержит ответы, правильность отдельных заданий, ключи, seed, скрытые проверки или античит-сигналы. + +Запланировано, добавляется без ломающих изменений: краткое описание подхода до 1500 знаков рядом с практикой, которое не определяет грейд (FR05 в PRD); операция отладочных запусков практики; уведомление о собираемых античит-сигналах (время, переключение фокуса, вставки, параллельные сессии) и их хранение; сигналы ведут к перепроверке и апелляции, а не к публичному ярлыку, и работодателю не показываются (FR05 в PRD). + ### Проверки генераторов `testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core. @@ -190,4 +264,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Zod-схемы Orval игнорируют `uniqueItems` и не отклоняют неизвестные поля объектов с `additionalProperties: false`; в обоих случаях решает сервер. - Orval очищает `src/shared/api/endpoints/` и `src/shared/api/schemas/` перед генерацией (`clean: true`), потому что схема, используемая несколькими тегами, переезжает из каталога тега в корень схем. +#### Объединения форматов + +- Объединения форматов, например `ItemContent` и `AssessmentAnswer`, - это `oneOf` без объекта `discriminator`. Redocly разрешает значения `discriminator.mapping` как ссылки, а `scripts/merge-schemas.py` переписывает только `$ref`, поэтому mapping из отдельного файла схем не разрешается в объединенном `components/schemas.yml`. Каждый вариант фиксирует `format` перечислением из одного значения; ogen различает варианты по этому значению и по полям, уникальным для варианта, и отклоняет тело, подходящее под несколько вариантов, а Orval генерирует Zod-объединение. +- Orval называет константы встроенного свойства ``, поэтому имя свойства, повторяющее имя другой схемы, дает конфликт в `index.ts` (TS2308). Поэтому объединение форматов задания называется `ItemContent`, а не `AssessmentItemContent`, рядом со свойством `AssessmentItem.content`. + +Сгенерированный Zod не строгий. Тело, смешивающее поля двух форматов или содержащее лишние `score` или `seed`, принимается после молчаливого удаления неизвестных ключей, а `uniqueItems` не проверяется; такие тела отклоняет только сервер. `frontend/src/shared/api/assessment-contract.test.ts` закрепляет принимаемые форматы и отсутствие в DTO ответа и задания полей балла, ключа, seed или правильности. + Подробнее: [разработка](../docs/ru/DEVELOPMENT.md). diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index 36ded00..e614017 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -425,3 +425,919 @@ QuestionnaireRepeatedSpecialization: pointer: /specializations/1/specialization code: invalid message: The value does not match the contract. +AssessmentAvailability: + summary: Backend open in demo_basic, Network Engineer blocked + description: >- + Illustrative values. Backend junior and middle can start in the + demo_basic mode, with their limits shown before the start; intern and + senior have no sufficient bank. Network Engineer junior waits for its + same-grade retry interval after an unconfirmed attempt. + value: + specializations: + - specialization: backend + confirmed_grade: null + active_attempt_id: null + grades: + - grade: intern + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - grade: junior + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 12 + practice_required: false + - grade: middle + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 12 + practice_required: false + - grade: senior + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - specialization: network_engineer + confirmed_grade: null + active_attempt_id: null + grades: + - grade: intern + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - grade: junior + status: cooldown + mode: demo_basic + available_at: "2026-11-12T00:00:00Z" + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 10 + practice_required: false + - grade: middle + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 10 + practice_required: false + - grade: senior + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null +AssessmentAttemptCreateBackendJunior: + summary: Start Backend junior with Go tasks + value: + specialization: backend + target_grade: junior + task_language: go +AssessmentAttemptCreated: + summary: New demo_basic attempt with its first item + description: >- + The server chose demo_basic from the published bank and fixed the policy, + bank, and algorithm versions; creation started session 1. A retry of + this create with the same Idempotency-Key and body within 24 hours + replays exactly this 201 response and creates nothing; read the attempt + for its current state. The attempt has no practice, because code + practice stays disabled until the sandbox isolation is verified. + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 1 + specialization: backend + target_grade: junior + task_language: go + mode: demo_basic + state: in_progress + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: "2026-10-08T10:00:00Z" + expires_at: "2026-10-11T10:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 0 + max_items: 12 + current_item: + id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01 + sequence: 1 + prompt: "Какой HTTP-статус вернуть, если запрос валиден, но ресурс находится в состоянии, не допускающем операцию?" + content: + format: choice + multiple: false + options: + - id: k7 + text: "400" + - id: p2 + text: "404" + - id: x9 + text: "409" + - id: c4 + text: "500" + practices: [] +AssessmentAnswerAccepted: + summary: Answer to item 1 stored; item 2 follows + description: >- + The answer of AssessmentChoiceAnswer was stored and the version advanced + from 1 to 2. The response does not say whether the answer was correct. + A retry with the same Idempotency-Key replays exactly this response. + Sending the same answer to item 1 again, even with a new key or the + older expected_version 1, stores nothing and returns 200 with the + current attempt. AssessmentOrderAnswer answers item 2 next. + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 2 + specialization: backend + target_grade: junior + task_language: go + mode: demo_basic + state: in_progress + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: "2026-10-08T10:00:00Z" + expires_at: "2026-10-11T10:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 1 + max_items: 12 + current_item: + id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02 + sequence: 2 + prompt: "Упорядочите шаги обработки запроса в обработчике HTTP." + content: + format: order + elements: + - id: d3 + text: Записать ответ + - id: a7 + text: Проверить сессию + - id: c2 + text: Выполнить операцию + - id: b1 + text: Разобрать и проверить тело + practices: [] +AssessmentAttemptCompleted: + summary: demo_basic attempt finalized; read the result next + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 14 + specialization: backend + target_grade: junior + task_language: go + mode: demo_basic + state: completed + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: "2026-10-08T10:00:00Z" + expires_at: "2026-10-11T10:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: "2026-10-08T10:24:00Z" + progress: + answered_items: 12 + max_items: 12 + current_item: null + practices: [] +AssessmentAttemptResumed: + summary: Adaptive attempt resumed on its sixth item in session 2 + description: >- + A reload or a new session returns the same item instance with the same + lines; nothing tells whether the five earlier answers were correct, and + seed items look like scored ones. The retest started from the previous + ability estimate of the specialization. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 7 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: in_progress + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 5 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06 + sequence: 6 + prompt: "Найдите строку, из-за которой соединения с базой данных не возвращаются в пул." + content: + format: find_error + syntax: python + max_selections: 1 + lines: + - number: 1 + text: "def load_user(pool, user_id):" + - number: 2 + text: " conn = pool.acquire()" + - number: 3 + text: " row = conn.fetchrow(QUERY, user_id)" + - number: 4 + text: " if row is None:" + - number: 5 + text: " raise NotFound(user_id)" + - number: 6 + text: " pool.release(conn)" + - number: 7 + text: " return row" + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null +AssessmentAttemptPracticePending: + summary: Item part finished, main practice not submitted + description: >- + The adaptive stop rule ended the item part after 14 items, but no grade + is decided until the main practice has a finished verdict. The current + item is the practice; hidden checks and seeds are not part of it. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 16 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + sequence: 15 + prompt: "Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу." + content: + format: practice + languages: [python] + max_source_length: 20000 + public_examples: + - input: "[[1,3],[2,6],[8,10]]" + expected_output: "[[1,6],[8,10]]" + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null +AssessmentAttemptPracticeVerdictPending: + summary: Practice submitted, verdict pending in the sandbox + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 17 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: pending + submitted_at: "2026-11-20T10:05:00Z" + verdict: null + failure_reason: null +AssessmentAttemptSandboxFailed: + summary: Sandbox queue was full; the practice can be submitted again + description: >- + The failure does not depend on the solution and consumes nothing. The + practice item is current again; a resubmission, with the same or a + different solution, queues it again and advances the version. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 18 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + sequence: 15 + prompt: "Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу." + content: + format: practice + languages: [python] + max_source_length: 20000 + public_examples: + - input: "[[1,3],[2,6],[8,10]]" + expected_output: "[[1,6],[8,10]]" + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: failed + submitted_at: "2026-11-20T10:05:00Z" + verdict: null + failure_reason: sandbox_busy +AssessmentAttemptReadyToFinalize: + summary: Main practice verdict finished, ready to finalize + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 20 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: ready_to_finalize + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: finished + submitted_at: "2026-11-20T10:09:00Z" + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + failure_reason: null +AssessmentAttemptAdditionalPracticePending: + summary: Finalize offered an additional practice in the same attempt + description: >- + The probability of reaching middle was in the band below confirmation, + so finalize decided nothing yet: it appended an additional practice and + returned the attempt instead of a result. The attempt keeps its time and + session limits and spends no new attempt. Submitting the additional + practice leads back to ready_to_finalize; finalizing now declines it + and gives not_confirmed. A retry of that finalize with a new key and + the old expected_version 20 answers 412 and cannot decline by accident. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 21 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: additional_practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0 + sequence: 16 + prompt: "Реализуйте LRU-кеш с операциями get и put за O(1)." + content: + format: practice + languages: [python] + max_source_length: 20000 + public_examples: + - input: "put(1,1); put(2,2); get(1); put(3,3); get(2)" + expected_output: "1, -1" + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: finished + submitted_at: "2026-11-20T10:09:00Z" + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + failure_reason: null + - kind: additional + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0 + status: not_started + submitted_at: null + verdict: null + failure_reason: null +AssessmentAttemptInsufficientBank: + summary: Attempt ended because the bank could not cover the blueprint + description: >- + The bank ran out of unseen families for a required domain within the + item limit. The attempt ended without a confirmed grade instead of + repeating a family; its result has outcome not_determined, and it does + not count against the retry rules. + value: + id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d + version: 10 + specialization: network_engineer + target_grade: middle + task_language: null + mode: adaptive + state: insufficient_bank + versions: + policy_version: 2 + bank_version: network.2026-11.1 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-21T12:00:00Z" + expires_at: "2026-11-24T12:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: "2026-11-21T12:31:00Z" + progress: + answered_items: 8 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null +AssessmentChoiceAnswer: + summary: Answer item 1 of version 1 + value: + expected_version: 1 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01 + answer: + format: choice + option_ids: [x9] +AssessmentOrderAnswer: + summary: Answer item 2 with every element once + value: + expected_version: 2 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02 + answer: + format: order + element_ids: [a7, b1, c2, d3] +AssessmentNumberAnswer: + summary: Number answer + value: + expected_version: 3 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03 + answer: + format: number + number: 254 +AssessmentStringAnswer: + summary: String answer + value: + expected_version: 4 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d04 + answer: + format: string + text: Retry-After +AssessmentFindErrorAnswer: + summary: Find-error answer for the resumed item + value: + expected_version: 7 + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06 + answer: + format: find_error + line_numbers: [5] +AssessmentConfigurationAnswer: + summary: Configuration answer + value: + expected_version: 7 + item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c07 + answer: + format: configuration + config: |- + interface GigabitEthernet0/1 + ip access-group BLOCK_TELNET in +AssessmentPracticeAnswer: + summary: Main practice solution + description: >- + Sent with expected_version 16 for the first submission. After a failed + verdict the client sends it again with the current version, such as 18 + in AssessmentAttemptSandboxFailed; the same source then queues again. + value: + expected_version: 16 + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + answer: + format: practice + language: python + source_code: |- + def merge_intervals(intervals): + result = [] + for start, end in sorted(intervals): + if result and start <= result[-1][1]: + result[-1][1] = max(result[-1][1], end) + else: + result.append([start, end]) + return result +AssessmentFinalization: + summary: Finalize version 20 + value: + expected_version: 20 +AssessmentDemoBasicResult: + summary: demo_basic result with a confirmed grade and no uncertainty + description: >- + demo_basic computes no ability estimate, so `uncertainty` and `strength` + are null rather than zero, and no percentile is shown. The pass mark + comes from basic grading policy version 1, and the limitations name the + uncalibrated thresholds, the demo bank, and the missing practice. A + first confirmation is not a promotion, so the higher grade can be + tested at once. The result never changes; a repeated finalize returns + the completed attempt, and this read returns the same result. + value: + attempt_id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + specialization: backend + target_grade: junior + task_language: go + mode: demo_basic + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + outcome: confirmed + not_determined_reason: null + confirmed_grade: junior + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: + [uncalibrated_thresholds, demo_bank, practice_not_included, unproctored] + uncertainty: null + basic_score: + points: 9 + max_points: 12 + pass_points: 8 + practices: [] + gaps: [] + durations: + items_seconds: 1260 + practice_seconds: null + next_steps: + - action: take_higher_grade + grade: middle + available_at: null + decided_at: "2026-10-08T10:24:00Z" +AssessmentAdaptiveResult: + summary: Adaptive promotion confirmed with medium strength + description: >- + Illustrative values, continuing AssessmentAttemptAdditionalPracticePending. + The additional practice raised P_G to 0.84, in the medium band of the + policy version, so the grade is confirmed with medium strength. The + candidate already had junior, so this is a + promotion, and the next one waits for the promotion interval. The + thresholds are uncalibrated until the pilot. + value: + attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: confirmed + not_determined_reason: null + confirmed_grade: middle + previous_confirmed_grade: junior + strength: medium + calibration_status: uncalibrated + limitations: [uncalibrated_thresholds, unproctored] + uncertainty: + theta: 0.62 + standard_error: 0.24 + interval_95: + low: 0.15 + high: 1.09 + p_grade: 0.84 + basic_score: null + practices: + - kind: main + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + - kind: additional + verdict: + score: 3 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: true + gaps: + - domain: concurrency + title: Конкурентность + durations: + items_seconds: 1980 + practice_seconds: 1500 + next_steps: + - action: take_higher_grade + grade: senior + available_at: "2027-02-18T10:30:00Z" + decided_at: "2026-11-20T10:30:00Z" +AssessmentNotConfirmedResult: + summary: Adaptive attempt not confirmed after the additional practice + description: >- + P_G stayed below 0.80 after the additional practice, so middle is not + confirmed, and the candidate keeps no confirmed grade. After a failure, + including the first test, junior can be tested at once; accepting junior + on the evidence of this attempt is offered; middle opens again after the + same-grade retry interval. + value: + attempt_id: 01928f7d-7777-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + task_language: go + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: not_confirmed + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: [uncalibrated_thresholds, unproctored] + uncertainty: + theta: 0.21 + standard_error: 0.25 + interval_95: + low: -0.28 + high: 0.70 + p_grade: 0.62 + basic_score: null + practices: + - kind: main + verdict: + score: 1 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: false + - group: 3 + passed: false + - kind: additional + verdict: + score: 1 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: false + - group: 3 + passed: false + gaps: + - domain: databases + title: Базы данных + durations: + items_seconds: 2100 + practice_seconds: 1800 + next_steps: + - action: take_lower_grade + grade: junior + available_at: null + - action: accept_lower_grade + grade: junior + available_at: null + - action: retake_same_grade + grade: middle + available_at: "2026-12-22T11:00:00Z" + decided_at: "2026-11-22T11:00:00Z" +AssessmentInsufficientBankResult: + summary: Attempt without a decision because the bank was insufficient + value: + attempt_id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d + specialization: network_engineer + target_grade: middle + task_language: null + mode: adaptive + versions: + policy_version: 2 + bank_version: network.2026-11.1 + algorithm_version: irt-1pl-eap.1 + outcome: not_determined + not_determined_reason: insufficient_bank + confirmed_grade: null + previous_confirmed_grade: junior + strength: null + calibration_status: uncalibrated + limitations: [uncalibrated_thresholds, unproctored] + uncertainty: null + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 1860 + practice_seconds: null + next_steps: [] + decided_at: "2026-11-21T12:31:00Z" +AssessmentSpecializationNotInQuestionnaire: + summary: The specialization is not in the questionnaire + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c + errors: + - in: body + pointer: /specialization + code: invalid + message: The value does not match the contract. +AssessmentAnswerUnknownOption: + summary: The selected option does not belong to the item + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 0a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d + errors: + - in: body + pointer: /answer/option_ids/0 + code: invalid + message: The value does not match the contract. +AssessmentAnswerUnknownField: + summary: The client sent its own score + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 1b2c3d4e-5f6a-4b7c-8d8e-9f0a1b2c3d4e + errors: + - in: body + pointer: "" + code: invalid + message: The value does not match the contract. +AssessmentItemNotCurrent: + summary: The answered item is not the current item, or it already has another answer + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 2c3d4e5f-6a7b-4c8d-9e9f-0a1b2c3d4e5f +AssessmentFinalizeNotReady: + summary: Premature finalize; the problem does not list the unfinished parts + description: >- + Problem has no extension fields. The client reads what remains from the + attempt: `state`, `progress`, `current_item`, and `practices`. + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e +AssessmentAttemptNotAvailable: + summary: No attempt can start for the category now + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 3d4e5f6a-7b8c-4d9e-8f0a-1b2c3d4e5f6a +AssessmentResultNotReady: + summary: The attempt has no result yet + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 4e5f6a7b-8c9d-4e0f-9a1b-2c3d4e5f6a7b +AssessmentStaleVersion: + summary: The command carried a stale expected_version + description: >- + Another tab or device changed the attempt after the client read version + 1. Nothing was stored; the client reads the attempt again and continues + from its current item. The repository answers a stale version with 412, + not 409. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c diff --git a/api/core/components/parameters.yml b/api/core/components/parameters.yml index 5d5a111..f6d6f6b 100644 --- a/api/core/components/parameters.yml +++ b/api/core/components/parameters.yml @@ -56,3 +56,15 @@ PageCursor: minLength: 1 maxLength: 512 pattern: "^[A-Za-z0-9_-]+$" +AssessmentAttemptId: + name: attempt_id + in: path + required: true + description: >- + Identifier of an assessment attempt of the current candidate. An attempt + of another candidate and an unknown identifier both answer 404 + not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index 7e798cd..4892849 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -261,3 +261,116 @@ QuestionnaireVersionConflict: examples: version_conflict: $ref: ./examples.yml#/VersionConflict +AssessmentAttemptCreateValidationFailed: + description: >- + The body does not match the contract or violates an assessment rule: an + unknown specialization, grade, or task language, an unknown field such + as mode or seed, a specialization that is not in the questionnaire, or + a task language that the published bank does not offer; code + validation_failed with body pointers. Nothing was created, and the + outcome is not stored under the Idempotency-Key. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + specialization_not_in_questionnaire: + $ref: ./examples.yml#/AssessmentSpecializationNotInQuestionnaire +AssessmentAnswerValidationFailed: + description: >- + The body does not match the contract or the answer does not fit the + item: a format other than the item format, an option, element, or line + that the item does not have, an order that is not a permutation of every + element, more selections than the item allows, a text longer than the + item allows, a language that the practice does not offer, or an unknown + field such as score or duration; code validation_failed with body + pointers. When the decoder does not record the path of a nested field, + the pointer is the whole body. Nothing was stored, and the outcome is + not stored under the Idempotency-Key. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + unknown_option: + $ref: ./examples.yml#/AssessmentAnswerUnknownOption + score_sent_by_client: + $ref: ./examples.yml#/AssessmentAnswerUnknownField +AssessmentCommandConflict: + description: >- + The attempt state does not allow the answer at the current version, code + state_conflict: the attempt is terminal or past its limits, the item is + not the current item, the item already has a different answer, or the + practice has a pending or finished verdict and the submission differs. + Or a request with the same Idempotency-Key is still running, code + idempotency_in_progress. Nothing was changed in either case; read the + attempt to see its state. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/AssessmentItemNotCurrent + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +AssessmentFinalizeConflict: + description: >- + The attempt state does not allow finalize at the current version, code + state_conflict: items or the main practice are unfinished, a practice + verdict is pending, or the attempt ended as expired or insufficient_bank. + The problem does not list the unfinished parts, because Problem allows + no extension fields; the attempt shows them in `state`, `progress`, + `current_item`, and `practices`. Or a request with the same + Idempotency-Key is still running, code idempotency_in_progress. Nothing + was changed in either case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/AssessmentFinalizeNotReady + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +AssessmentCreateConflict: + description: >- + No attempt can start for the category now, code state_conflict: the + specialization already has an active attempt, a retry or promotion + interval or the attempt limit blocks the grade, or the bank is + insufficient. GetMyAssessmentAvailability tells which, with the date + when a blocked attempt opens. Or a request with the same Idempotency-Key + is still running, code idempotency_in_progress. Nothing was created in + either case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/AssessmentAttemptNotAvailable + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +AssessmentResultNotReady: + description: >- + The attempt is still active, so it has no result yet; code + state_conflict. The attempt state tells what remains to be done. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/AssessmentResultNotReady +AssessmentVersionConflict: + description: >- + `expected_version` is not the current attempt version; code + version_conflict. Nothing was changed, and the outcome is not stored + under the Idempotency-Key; read the attempt again before retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/AssessmentStaleVersion diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 2a692d5..680ed31 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -23,6 +23,1181 @@ PageInfo: maxLength: 512 pattern: ^[A-Za-z0-9_-]+$ description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. +AssessmentMode: + type: string + description: 'Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it. + + + - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice. + + - adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt. + + + Adding a value is a contract change.' + enum: + - demo_basic + - adaptive +AssessmentAttemptVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.' + examples: + - 4 +AssessmentAttemptState: + type: string + description: 'Lifecycle state of an attempt and the commands it accepts. + + + - in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item. + + - practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part. + + - additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence. + + - ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt. + + - completed: a decision was made; the result is available. + + - expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade. + + - insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available. + + + When `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate''s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.' + enum: + - in_progress + - practice_pending + - additional_practice_pending + - ready_to_finalize + - completed + - expired + - insufficient_bank +AssessmentVersionLabel: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it. +AssessmentVersions: + type: object + description: Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it. + additionalProperties: false + required: + - policy_version + - bank_version + - algorithm_version + properties: + policy_version: + type: integer + format: int32 + minimum: 1 + description: 'Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.' + bank_version: + $ref: '#/AssessmentVersionLabel' + algorithm_version: + $ref: '#/AssessmentVersionLabel' +AssessmentSessions: + type: object + description: 'Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit. + + + A session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session.' + additionalProperties: false + required: + - used + - max + - idle_timeout_seconds + properties: + used: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Sessions started so far, including the current one. + max: + type: integer + format: int32 + minimum: 1 + maximum: 10 + idle_timeout_seconds: + type: integer + format: int32 + minimum: 60 + maximum: 86400 + description: Inactivity after which the current session ends. +AssessmentAttemptCreate: + type: object + description: 'Category to assess: a specialization and the target grade, with the task language. The candidate comes from the session. The mode and versions are chosen by the server; unknown fields such as `mode`, `seed`, or `score` are rejected.' + additionalProperties: false + required: + - specialization + - target_grade + - task_language + properties: + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + task_language: + description: Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first. + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' +AssessmentItemId: + type: string + format: uuid + description: Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed. +AssessmentOptionId: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option. +AssessmentOption: + type: object + description: Choice option or order element. Plain text. + additionalProperties: false + required: + - id + - text + properties: + id: + $ref: '#/AssessmentOptionId' + text: + type: string + minLength: 1 + maxLength: 2000 + description: Text of the option; the client shows it as text, never as HTML. +ChoiceItemContent: + type: object + description: Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are. + additionalProperties: false + required: + - format + - options + - multiple + properties: + format: + type: string + enum: + - choice + options: + type: array + minItems: 2 + maxItems: 10 + description: Options in the order of this instance. + items: + $ref: '#/AssessmentOption' + multiple: + type: boolean + description: 'Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.' +NumberItemContent: + type: object + description: Enter a number, optionally in the given unit. + additionalProperties: false + required: + - format + - unit + properties: + format: + type: string + enum: + - number + unit: + type: + - string + - 'null' + minLength: 1 + maxLength: 32 + description: Unit of the expected value, for example `ms`, or null. +StringItemContent: + type: object + description: Enter a short string, such as a command, a header name, or an address. + additionalProperties: false + required: + - format + - max_length + properties: + format: + type: string + enum: + - string + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 500 + description: Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer. +OrderItemContent: + type: object + description: Put every element into the right order. The elements arrive in the order of this instance, which is never the answer. + additionalProperties: false + required: + - format + - elements + properties: + format: + type: string + enum: + - order + elements: + type: array + minItems: 2 + maxItems: 20 + items: + $ref: '#/AssessmentOption' +CodeLine: + type: object + description: One numbered line of a code or configuration fragment. Plain text. + additionalProperties: false + required: + - number + - text + properties: + number: + type: integer + format: int32 + minimum: 1 + maximum: 500 + text: + type: string + maxLength: 1000 +FindErrorItemContent: + type: object + description: Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers. + additionalProperties: false + required: + - format + - syntax + - lines + - max_selections + properties: + format: + type: string + enum: + - find_error + syntax: + type: + - string + - 'null' + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9_+-]+$ + description: Highlighting hint such as `go`, `python`, or `cisco_ios`, or null. + lines: + type: array + minItems: 1 + maxItems: 500 + description: Lines numbered from 1 in order. + items: + $ref: '#/CodeLine' + max_selections: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines. +ConfigurationItemContent: + type: object + description: Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code. + additionalProperties: false + required: + - format + - syntax + - initial_config + - max_length + properties: + format: + type: string + enum: + - configuration + syntax: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9_+-]+$ + description: Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`. + initial_config: + type: string + maxLength: 20000 + description: Starting text to edit; empty when the candidate writes it from scratch. + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 20000 + description: Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key. +PracticeExample: + type: object + description: 'Public example of the practice task: an input and its expected output. Hidden checks are never listed.' + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 +PracticeItemContent: + type: object + description: Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client. + additionalProperties: false + required: + - format + - languages + - public_examples + - max_source_length + properties: + format: + type: string + enum: + - practice + languages: + type: array + maxItems: 2 + uniqueItems: true + description: Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language. + items: + $ref: '#/TaskLanguage' + public_examples: + type: array + maxItems: 10 + items: + $ref: '#/PracticeExample' + max_source_length: + type: integer + format: int32 + minimum: 1 + maximum: 65536 + description: Maximum length of the solution source in characters. +ItemContent: + description: 'Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.' + oneOf: + - $ref: '#/ChoiceItemContent' + - $ref: '#/NumberItemContent' + - $ref: '#/StringItemContent' + - $ref: '#/OrderItemContent' + - $ref: '#/FindErrorItemContent' + - $ref: '#/ConfigurationItemContent' + - $ref: '#/PracticeItemContent' +AssessmentItem: + type: object + description: 'Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.' + additionalProperties: false + required: + - id + - sequence + - prompt + - content + properties: + id: + $ref: '#/AssessmentItemId' + sequence: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: Position of the item in the attempt, from 1. + prompt: + type: string + minLength: 1 + maxLength: 20000 + description: Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML. + content: + $ref: '#/ItemContent' +AssessmentProgress: + type: object + description: Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`. + additionalProperties: false + required: + - answered_items + - max_items + properties: + answered_items: + type: integer + format: int32 + minimum: 0 + maximum: 100 + max_items: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: 'Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.' +PracticeKind: + type: string + description: 'Role of a practice in the attempt. + + + - main: the practice that every attempt with practice requires before a decision. + + - additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt. + + + Adding a value is a contract change.' + enum: + - main + - additional +PracticeStatus: + type: string + description: 'State of a practice. + + + - not_started: no solution was submitted yet. + + - pending: the submitted solution is queued or running in the sandbox. + + - finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed. + + - failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate''s and consumes nothing; the practice can be submitted again.' + enum: + - not_started + - pending + - finished + - failed +PracticeFailureReason: + type: string + description: 'Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.' + enum: + - sandbox_busy + - sandbox_error +PracticeGroupResult: + type: object + description: Outcome of one hidden check group. It never contains the checks themselves. + additionalProperties: false + required: + - group + - passed + properties: + group: + type: integer + format: int32 + minimum: 1 + maximum: 3 + passed: + type: boolean +PracticeVerdict: + type: object + description: 'Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.' + additionalProperties: false + required: + - score + - max_score + - groups + properties: + score: + type: integer + format: int32 + minimum: 0 + maximum: 3 + max_score: + type: integer + format: int32 + minimum: 3 + maximum: 3 + groups: + type: array + minItems: 3 + maxItems: 3 + items: + $ref: '#/PracticeGroupResult' +AssessmentPractice: + type: object + description: Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision. + additionalProperties: false + required: + - kind + - item_id + - status + - submitted_at + - verdict + - failure_reason + properties: + kind: + $ref: '#/PracticeKind' + item_id: + $ref: '#/AssessmentItemId' + status: + $ref: '#/PracticeStatus' + submitted_at: + description: Time of the latest submission, or null before the first one. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + verdict: + description: The verdict when `status` is `finished`, otherwise null. + oneOf: + - $ref: '#/PracticeVerdict' + - type: 'null' + failure_reason: + description: The reason when `status` is `failed`, otherwise null. + oneOf: + - $ref: '#/PracticeFailureReason' + - type: 'null' +AssessmentAttempt: + type: object + description: Assessment attempt of the current candidate for one category, a specialization and a target grade. It shows the state, the fixed versions, the server deadline `expires_at` from the policy version, which the client clock never extends, the session limit, the progress, the item to answer now, and the practices. It never contains answer keys, the correctness of submitted answers, scores of single items, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + additionalProperties: false + required: + - id + - version + - specialization + - target_grade + - task_language + - mode + - state + - versions + - started_at + - expires_at + - sessions + - finished_at + - progress + - current_item + - practices + properties: + id: + type: string + format: uuid + description: Attempt identifier. + version: + $ref: '#/AssessmentAttemptVersion' + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + task_language: + description: Task language of the attempt, or null when the bank offers no choice. + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' + mode: + $ref: '#/AssessmentMode' + state: + $ref: '#/AssessmentAttemptState' + versions: + $ref: '#/AssessmentVersions' + started_at: + $ref: '#/Timestamp' + expires_at: + $ref: '#/Timestamp' + sessions: + description: Session limit of the attempt, or null when its policy version defines none. + oneOf: + - $ref: '#/AssessmentSessions' + - type: 'null' + finished_at: + description: Time the attempt reached a terminal state, or null while it is active. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + progress: + $ref: '#/AssessmentProgress' + current_item: + description: 'Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.' + oneOf: + - $ref: '#/AssessmentItem' + - type: 'null' + practices: + type: array + maxItems: 5 + description: 'Practices in the order they were assigned: the `main` practice first, then an `additional` practice once finalize offers it. Empty only for a demo_basic attempt while code practice is disabled until the sandbox isolation is verified; its result then lists the `practice_not_included` limitation. A list rather than one field leaves room for more practices without a breaking change.' + items: + $ref: '#/AssessmentPractice' +ChoiceAnswer: + type: object + description: 'Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.' + additionalProperties: false + required: + - format + - option_ids + properties: + format: + type: string + enum: + - choice + option_ids: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + $ref: '#/AssessmentOptionId' +NumberAnswer: + type: object + description: Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer. + additionalProperties: false + required: + - format + - number + properties: + format: + type: string + enum: + - number + number: + type: number + format: double +StringAnswer: + type: object + description: String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison. + additionalProperties: false + required: + - format + - text + properties: + format: + type: string + enum: + - string + text: + type: string + minLength: 1 + maxLength: 500 +OrderAnswer: + type: object + description: Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical. + additionalProperties: false + required: + - format + - element_ids + properties: + format: + type: string + enum: + - order + element_ids: + type: array + minItems: 2 + maxItems: 20 + uniqueItems: true + items: + $ref: '#/AssessmentOptionId' +FindErrorAnswer: + type: object + description: Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order. + additionalProperties: false + required: + - format + - line_numbers + properties: + format: + type: string + enum: + - find_error + line_numbers: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + type: integer + format: int32 + minimum: 1 + maximum: 500 +ConfigurationAnswer: + type: object + description: Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks. + additionalProperties: false + required: + - format + - config + properties: + format: + type: string + enum: + - configuration + config: + type: string + minLength: 1 + maxLength: 20000 +PracticeAnswer: + type: object + description: Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem. + additionalProperties: false + required: + - format + - language + - source_code + properties: + format: + type: string + enum: + - practice + language: + description: One of the `languages` of the practice item, or null when the item offers none. + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' + source_code: + type: string + minLength: 1 + maxLength: 65536 +AssessmentAnswer: + description: 'Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.' + oneOf: + - $ref: '#/ChoiceAnswer' + - $ref: '#/NumberAnswer' + - $ref: '#/StringAnswer' + - $ref: '#/OrderAnswer' + - $ref: '#/FindErrorAnswer' + - $ref: '#/ConfigurationAnswer' + - $ref: '#/PracticeAnswer' +AssessmentAnswerSubmission: + type: object + description: Answer to one item of the attempt. Unknown fields are rejected, so a request cannot send a score, a duration, or a correctness flag. + additionalProperties: false + required: + - expected_version + - item_id + - answer + properties: + expected_version: + $ref: '#/AssessmentAttemptVersion' + item_id: + $ref: '#/AssessmentItemId' + answer: + $ref: '#/AssessmentAnswer' +AssessmentFinalization: + type: object + description: Command to finalize the attempt. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/AssessmentAttemptVersion' +AssessmentOutcome: + type: string + description: 'Grade decision of the attempt. + + + - confirmed: the target grade is confirmed by the rule of the recorded policy version. + + - not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force. + + - not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force. + + + A failed, expired, or flagged attempt never lowers a confirmed grade.' + enum: + - confirmed + - not_confirmed + - not_determined +AssessmentNotDeterminedReason: + type: string + description: 'Why an attempt gives no decision, and whether it counts against the retry rules. + + + - expired: the time or session limit passed before the candidate finished the item part. It is the candidate''s attempt: it counts toward the attempt limit and starts the same-grade retry interval. + + - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`. + + - insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval. + + - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval.' + enum: + - expired + - practice_incomplete + - insufficient_bank + - sandbox_unavailable +AssessmentStrength: + type: string + description: 'Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.' + enum: + - high + - medium +CalibrationStatus: + type: string + description: 'Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.' + enum: + - uncalibrated + - calibrated +AssessmentLimitation: + type: string + description: 'Known limitation of the method behind a result, shown with the result. + + + - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. + + - demo_bank: the result comes from the small reviewed demo bank. + + - practice_not_included: the attempt had no code practice because the sandbox was not enabled. + + - unproctored: the attempt was taken online without supervision. + + + Adding a value is a contract change.' + enum: + - uncalibrated_thresholds + - demo_bank + - practice_not_included + - unproctored +AssessmentInterval: + type: object + description: Interval on the ability scale. + additionalProperties: false + required: + - low + - high + properties: + low: + type: number + format: double + high: + type: number + format: double +AssessmentUncertainty: + type: object + description: 'Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.' + additionalProperties: false + required: + - theta + - standard_error + - interval_95 + - p_grade + properties: + theta: + type: number + format: double + standard_error: + type: number + format: double + minimum: 0 + interval_95: + $ref: '#/AssessmentInterval' + p_grade: + type: number + format: double + minimum: 0 + maximum: 1 + description: Probability of reaching the threshold of the target grade. +BasicScore: + type: object + description: Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass mark comes from that policy version and never from the handler. + additionalProperties: false + required: + - points + - max_points + - pass_points + properties: + points: + type: integer + format: int32 + minimum: 0 + max_points: + type: integer + format: int32 + minimum: 1 + pass_points: + type: integer + format: int32 + minimum: 1 +AssessmentGap: + type: object + description: Domain of the specialization where the evidence was weak. + additionalProperties: false + required: + - domain + - title + properties: + domain: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9_]+$ + description: Stable domain code of the bank blueprint. + title: + type: string + minLength: 1 + maxLength: 200 + description: Display name in Russian. Plain text. +AssessmentDurations: + type: object + description: 'Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.' + additionalProperties: false + required: + - items_seconds + - practice_seconds + properties: + items_seconds: + type: integer + format: int32 + minimum: 0 + practice_seconds: + type: + - integer + - 'null' + format: int32 + minimum: 0 + description: Time on all practices with a verdict, or null when no practice has one. +AssessmentPracticeResult: + type: object + description: Verdict of one practice of the attempt. + additionalProperties: false + required: + - kind + - verdict + properties: + kind: + $ref: '#/PracticeKind' + verdict: + $ref: '#/PracticeVerdict' +AssessmentNextAction: + type: string + description: 'Step that the candidate may take next. + + + - retake_same_grade: test the same grade again from `available_at`. + + - take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval. + + - accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned). + + - take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.' + enum: + - retake_same_grade + - take_lower_grade + - accept_lower_grade + - take_higher_grade +AssessmentNextStep: + type: object + description: Step that the server allows after this result, computed when it was decided. + additionalProperties: false + required: + - action + - grade + - available_at + properties: + action: + $ref: '#/AssessmentNextAction' + grade: + $ref: '#/GradeCode' + available_at: + description: First time the step is allowed, or null when it is allowed now. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' +AssessmentResult: + type: object + description: 'Immutable result of a terminal attempt, visible only to its candidate. It records the method, the versions, the decision, its uncertainty, and its limitations; a later policy, bank, or algorithm version never changes it. It never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. Fields that the method does not compute are null, never zero: demo_basic has null `uncertainty` and `strength`, and adaptive has null `basic_score`.' + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + task_language: + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' + mode: + $ref: '#/AssessmentMode' + versions: + $ref: '#/AssessmentVersions' + outcome: + $ref: '#/AssessmentOutcome' + not_determined_reason: + description: The reason when `outcome` is `not_determined`, otherwise null. + oneOf: + - $ref: '#/AssessmentNotDeterminedReason' + - type: 'null' + confirmed_grade: + description: Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + previous_confirmed_grade: + description: Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + strength: + description: Strength of an adaptive confirmation, otherwise null. + oneOf: + - $ref: '#/AssessmentStrength' + - type: 'null' + calibration_status: + $ref: '#/CalibrationStatus' + limitations: + type: array + maxItems: 10 + uniqueItems: true + items: + $ref: '#/AssessmentLimitation' + uncertainty: + description: Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision. + oneOf: + - $ref: '#/AssessmentUncertainty' + - type: 'null' + basic_score: + description: Raw score of a demo_basic attempt with a decision, otherwise null. + oneOf: + - $ref: '#/BasicScore' + - type: 'null' + practices: + type: array + maxItems: 5 + description: Verdicts of the practices that have one, main first. + items: + $ref: '#/AssessmentPracticeResult' + gaps: + type: array + maxItems: 20 + description: Domains with weak evidence; empty when none were found or the method finds none. + items: + $ref: '#/AssessmentGap' + durations: + $ref: '#/AssessmentDurations' + next_steps: + type: array + maxItems: 5 + items: + $ref: '#/AssessmentNextStep' + decided_at: + $ref: '#/Timestamp' +AssessmentGradeAvailabilityStatus: + type: string + description: 'Whether an attempt for the grade can start now. + + + - available: CreateMyAssessmentAttempt can start it. + + - active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`. + + - cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it. + + - insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families.' + enum: + - available + - active_attempt + - cooldown + - insufficient_bank +AssessmentGradeAvailability: + type: object + description: Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit. + additionalProperties: false + required: + - grade + - status + - mode + - available_at + - time_limit_seconds + - max_sessions + - max_items + - practice_required + properties: + grade: + $ref: '#/GradeCode' + status: + $ref: '#/AssessmentGradeAvailabilityStatus' + mode: + description: Mode that an attempt would use, or null when the status is `insufficient_bank`. + oneOf: + - $ref: '#/AssessmentMode' + - type: 'null' + available_at: + description: When the status is `cooldown`, the first time the attempt can start; otherwise null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + time_limit_seconds: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: Time from the start to `expires_at`. + max_sessions: + type: + - integer + - 'null' + format: int32 + minimum: 1 + maximum: 10 + description: Session limit within the time limit. + max_items: + type: + - integer + - 'null' + format: int32 + minimum: 1 + maximum: 100 + description: Item limit, as in `AssessmentProgress.max_items`. + practice_required: + type: + - boolean + - 'null' + description: Whether the attempt would include a main code practice. +AssessmentSpecializationAvailability: + type: object + description: Assessment state of one questionnaire specialization. Specializations are assessed independently, with independent retry intervals. + additionalProperties: false + required: + - specialization + - confirmed_grade + - active_attempt_id + - grades + properties: + specialization: + $ref: '#/SpecializationCode' + confirmed_grade: + description: Currently confirmed grade of the specialization, or null. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + active_attempt_id: + type: + - string + - 'null' + format: uuid + description: Identifier of the active attempt of the specialization, or null. + grades: + type: array + maxItems: 10 + description: Every grade of the scale in ascending order. + items: + $ref: '#/AssessmentGradeAvailability' +AssessmentAvailability: + type: object + description: Assessment availability for the specializations of the current candidate's questionnaire, derived at the time of the request. + additionalProperties: false + required: + - specializations + properties: + specializations: + type: array + maxItems: 2 + description: Questionnaire specializations in questionnaire order. + items: + $ref: '#/AssessmentSpecializationAvailability' DirectionCode: type: string description: 'Stable code of a professional direction, the group that a specialization belongs to. diff --git a/api/core/components/schemas/assessment_schemas.yml b/api/core/components/schemas/assessment_schemas.yml new file mode 100644 index 0000000..ecfec44 --- /dev/null +++ b/api/core/components/schemas/assessment_schemas.yml @@ -0,0 +1,1333 @@ +schemas: + AssessmentMode: + type: string + description: |- + Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it. + + - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice. + - adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt. + + Adding a value is a contract change. + enum: + - demo_basic + - adaptive + AssessmentAttemptVersion: + type: integer + format: int64 + minimum: 1 + description: >- + Version of an assessment attempt. A new attempt has version 1, and each + committed change advances it by exactly one: an accepted answer, a + practice submission or resubmission, a verdict, a decision of + finalize, a session start, and a server-side transition such as + expiry or automatic finalization. A transition that the server applies + when the attempt is read is committed before the response and also + advances it. A rejected command and a repeat that stores nothing leave + it unchanged. Commands send the version they read as + `expected_version`. + examples: + - 4 + AssessmentAttemptState: + type: string + description: |- + Lifecycle state of an attempt and the commands it accepts. + + - in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item. + - practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part. + - additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence. + - ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt. + - completed: a decision was made; the result is available. + - expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade. + - insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available. + + When `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change. + enum: + - in_progress + - practice_pending + - additional_practice_pending + - ready_to_finalize + - completed + - expired + - insufficient_bank + AssessmentVersionLabel: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Opaque identifier of a published version, for example + `backend-demo.2026-10.1`. Clients show it as text and never parse it. + AssessmentVersions: + type: object + description: >- + Versions fixed when the attempt was created. They never change during + the attempt, and a result is always reproduced from the stored answers + with these versions; a later policy, bank, or algorithm version does + not rewrite it. + additionalProperties: false + required: + - policy_version + - bank_version + - algorithm_version + properties: + policy_version: + type: integer + format: int32 + minimum: 1 + description: >- + Number of the `product` policy version whose assessment rules + apply: thresholds, stop rules, item limits, time and session + limits, and retry intervals. + bank_version: + $ref: "#/schemas/AssessmentVersionLabel" + algorithm_version: + $ref: "#/schemas/AssessmentVersionLabel" + AssessmentSessions: + type: object + description: |- + Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit. + + A session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session. + additionalProperties: false + required: + - used + - max + - idle_timeout_seconds + properties: + used: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Sessions started so far, including the current one. + max: + type: integer + format: int32 + minimum: 1 + maximum: 10 + idle_timeout_seconds: + type: integer + format: int32 + minimum: 60 + maximum: 86400 + description: Inactivity after which the current session ends. + AssessmentAttemptCreate: + type: object + description: >- + Category to assess: a specialization and the target grade, with the + task language. The candidate comes from the session. The mode and + versions are chosen by the server; unknown fields such as `mode`, + `seed`, or `score` are rejected. + additionalProperties: false + required: + - specialization + - target_grade + - task_language + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + task_language: + description: >- + Task language of the attempt, one of the `task_languages` of the + published bank, or null when the bank offers no choice of + language. The questionnaire choice is the value the client offers + first. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + AssessmentItemId: + type: string + format: uuid + description: >- + Identifier of an item instance in one attempt. It identifies the fixed + variant served to this candidate and reveals neither the task family, + its version, nor the variant seed. + AssessmentOptionId: + type: string + minLength: 1 + maxLength: 32 + pattern: "^[A-Za-z0-9_-]+$" + description: >- + Opaque identifier of a choice option or an order element within one + item instance. It is unrelated to the position or correctness of the + option. + AssessmentOption: + type: object + description: Choice option or order element. Plain text. + additionalProperties: false + required: + - id + - text + properties: + id: + $ref: "#/schemas/AssessmentOptionId" + text: + type: string + minLength: 1 + maxLength: 2000 + description: Text of the option; the client shows it as text, never as HTML. + ChoiceItemContent: + type: object + description: >- + Choose one option, or several when `multiple` is true. The content + never says which options are correct or how many are. + additionalProperties: false + required: + - format + - options + - multiple + properties: + format: + type: string + enum: + - choice + options: + type: array + minItems: 2 + maxItems: 10 + description: Options in the order of this instance. + items: + $ref: "#/schemas/AssessmentOption" + multiple: + type: boolean + description: >- + Whether more than one option may be selected. It is a property of + the task family, fixed for every variant, and never derived from + the key: a multiple-choice variant may have a single correct + option. + NumberItemContent: + type: object + description: Enter a number, optionally in the given unit. + additionalProperties: false + required: + - format + - unit + properties: + format: + type: string + enum: + - number + unit: + type: + - string + - "null" + minLength: 1 + maxLength: 32 + description: Unit of the expected value, for example `ms`, or null. + StringItemContent: + type: object + description: Enter a short string, such as a command, a header name, or an address. + additionalProperties: false + required: + - format + - max_length + properties: + format: + type: string + enum: + - string + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 500 + description: >- + Maximum length of the answer in characters. It is an input limit + of the task family, never derived from the key, so it does not + reveal the length of the correct answer. + OrderItemContent: + type: object + description: >- + Put every element into the right order. The elements arrive in the + order of this instance, which is never the answer. + additionalProperties: false + required: + - format + - elements + properties: + format: + type: string + enum: + - order + elements: + type: array + minItems: 2 + maxItems: 20 + items: + $ref: "#/schemas/AssessmentOption" + CodeLine: + type: object + description: One numbered line of a code or configuration fragment. Plain text. + additionalProperties: false + required: + - number + - text + properties: + number: + type: integer + format: int32 + minimum: 1 + maximum: 500 + text: + type: string + maxLength: 1000 + FindErrorItemContent: + type: object + description: >- + Find the lines with the error in a code or configuration fragment and + select up to `max_selections` line numbers. + additionalProperties: false + required: + - format + - syntax + - lines + - max_selections + properties: + format: + type: string + enum: + - find_error + syntax: + type: + - string + - "null" + minLength: 1 + maxLength: 32 + pattern: "^[a-z0-9_+-]+$" + description: Highlighting hint such as `go`, `python`, or `cisco_ios`, or null. + lines: + type: array + minItems: 1 + maxItems: 500 + description: Lines numbered from 1 in order. + items: + $ref: "#/schemas/CodeLine" + max_selections: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: >- + Maximum number of lines the answer may select. It is a limit of + the task family, fixed for every variant and never derived from the + key; it is not the number of wrong lines. + ConfigurationItemContent: + type: object + description: >- + Write or fix a configuration. The server checks the submitted text + with the computed key or reference check of the task family; it never + executes it as code. + additionalProperties: false + required: + - format + - syntax + - initial_config + - max_length + properties: + format: + type: string + enum: + - configuration + syntax: + type: string + minLength: 1 + maxLength: 32 + pattern: "^[a-z0-9_+-]+$" + description: Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`. + initial_config: + type: string + maxLength: 20000 + description: Starting text to edit; empty when the candidate writes it from scratch. + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 20000 + description: >- + Maximum length of the submitted configuration in characters, an + input limit of the task family that is never derived from the key. + PracticeExample: + type: object + description: >- + Public example of the practice task: an input and its expected output. + Hidden checks are never listed. + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 + PracticeItemContent: + type: object + description: >- + Code practice. The candidate submits one final solution, which runs in + the isolated sandbox against three groups of hidden checks. The content + lists only the statement, the allowed languages, and public examples; + hidden checks, their inputs, and seeds never reach the client. + additionalProperties: false + required: + - format + - languages + - public_examples + - max_source_length + properties: + format: + type: string + enum: + - practice + languages: + type: array + maxItems: 2 + uniqueItems: true + description: >- + Languages the solution may use. Empty when the task does not offer + a choice; the submission then sends a null language. + items: + $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + public_examples: + type: array + maxItems: 10 + items: + $ref: "#/schemas/PracticeExample" + max_source_length: + type: integer + format: int32 + minimum: 1 + maximum: 65536 + description: Maximum length of the solution source in characters. + ItemContent: + description: >- + Format-specific part of an item, selected by `format`. It holds only + what the candidate needs to answer: never an answer key, a correct + option, a score, a family or variant identifier, a seed, or a hidden + check. Limits such as `multiple`, `max_selections`, and `max_length` + belong to the format or the task family and never reveal the key. + oneOf: + - $ref: "#/schemas/ChoiceItemContent" + - $ref: "#/schemas/NumberItemContent" + - $ref: "#/schemas/StringItemContent" + - $ref: "#/schemas/OrderItemContent" + - $ref: "#/schemas/FindErrorItemContent" + - $ref: "#/schemas/ConfigurationItemContent" + - $ref: "#/schemas/PracticeItemContent" + AssessmentItem: + type: object + description: >- + Item instance served to the candidate. The variant is fixed when it is + first served: a reload, a retried request, or a resumed session returns + the same instance with the same text and option order. The item never + says whether an earlier answer was correct, and seed items, which are + not scored, are indistinguishable from scored ones. + additionalProperties: false + required: + - id + - sequence + - prompt + - content + properties: + id: + $ref: "#/schemas/AssessmentItemId" + sequence: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: Position of the item in the attempt, from 1. + prompt: + type: string + minLength: 1 + maxLength: 20000 + description: >- + Statement in Russian. Plain text with line breaks; the client shows + it as text, never as HTML. + content: + $ref: "#/schemas/ItemContent" + AssessmentProgress: + type: object + description: >- + Progress of the item part. It counts seed items like scored ones, so it + does not reveal which items are scored. An adaptive attempt may end its + item part before `max_items` by its stop rule. A finalize refused as + premature does not list the unfinished parts; the client reads them + here, in `current_item`, and in `practices`. + additionalProperties: false + required: + - answered_items + - max_items + properties: + answered_items: + type: integer + format: int32 + minimum: 0 + maximum: 100 + max_items: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: >- + Item limit of the attempt: the form size in demo_basic, or the + policy limit of scored and seed items together in adaptive. + PracticeKind: + type: string + description: |- + Role of a practice in the attempt. + + - main: the practice that every attempt with practice requires before a decision. + - additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt. + + Adding a value is a contract change. + enum: + - main + - additional + PracticeStatus: + type: string + description: |- + State of a practice. + + - not_started: no solution was submitted yet. + - pending: the submitted solution is queued or running in the sandbox. + - finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed. + - failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate's and consumes nothing; the practice can be submitted again. + enum: + - not_started + - pending + - finished + - failed + PracticeFailureReason: + type: string + description: >- + Why the sandbox infrastructure returned no verdict: `sandbox_busy` + when its queue was full, `sandbox_error` for an infrastructure failure + such as a broken executor. Neither depends on the solution; a + solution that fails to compile, crashes, or exceeds a limit gets a + `finished` verdict instead, so a failure never acts as an oracle for + hidden checks. + enum: + - sandbox_busy + - sandbox_error + PracticeGroupResult: + type: object + description: Outcome of one hidden check group. It never contains the checks themselves. + additionalProperties: false + required: + - group + - passed + properties: + group: + type: integer + format: int32 + minimum: 1 + maximum: 3 + passed: + type: boolean + PracticeVerdict: + type: object + description: >- + Verdict of a practice solution on the hidden checks: the score 0-3, + one point for each passed group. The hidden checks, their inputs and + outputs, error output, and seeds are never returned. + additionalProperties: false + required: + - score + - max_score + - groups + properties: + score: + type: integer + format: int32 + minimum: 0 + maximum: 3 + max_score: + type: integer + format: int32 + minimum: 3 + maximum: 3 + groups: + type: array + minItems: 3 + maxItems: 3 + items: + $ref: "#/schemas/PracticeGroupResult" + AssessmentPractice: + type: object + description: >- + Practice of the attempt. Its verdict is shown only after the + submission; the solution time is kept as a separate label and never + enters the ability estimate or the grade decision. + additionalProperties: false + required: + - kind + - item_id + - status + - submitted_at + - verdict + - failure_reason + properties: + kind: + $ref: "#/schemas/PracticeKind" + item_id: + $ref: "#/schemas/AssessmentItemId" + status: + $ref: "#/schemas/PracticeStatus" + submitted_at: + description: Time of the latest submission, or null before the first one. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + verdict: + description: The verdict when `status` is `finished`, otherwise null. + oneOf: + - $ref: "#/schemas/PracticeVerdict" + - type: "null" + failure_reason: + description: The reason when `status` is `failed`, otherwise null. + oneOf: + - $ref: "#/schemas/PracticeFailureReason" + - type: "null" + AssessmentAttempt: + type: object + description: >- + Assessment attempt of the current candidate for one category, a + specialization and a target grade. It shows the state, the fixed + versions, the server deadline `expires_at` from the policy version, + which the client clock never extends, the session limit, the + progress, the item + to answer now, and the practices. It never contains answer keys, the + correctness of submitted answers, scores of single items, family or + variant identifiers, seeds, hidden checks, or anti-cheat signals. + additionalProperties: false + required: + - id + - version + - specialization + - target_grade + - task_language + - mode + - state + - versions + - started_at + - expires_at + - sessions + - finished_at + - progress + - current_item + - practices + properties: + id: + type: string + format: uuid + description: Attempt identifier. + version: + $ref: "#/schemas/AssessmentAttemptVersion" + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + task_language: + description: Task language of the attempt, or null when the bank offers no choice. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + mode: + $ref: "#/schemas/AssessmentMode" + state: + $ref: "#/schemas/AssessmentAttemptState" + versions: + $ref: "#/schemas/AssessmentVersions" + started_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + expires_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + sessions: + description: >- + Session limit of the attempt, or null when its policy version + defines none. + oneOf: + - $ref: "#/schemas/AssessmentSessions" + - type: "null" + finished_at: + description: >- + Time the attempt reached a terminal state, or null while it is + active. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + progress: + $ref: "#/schemas/AssessmentProgress" + current_item: + description: >- + Item to answer now: a test item in `in_progress`, the practice item + to submit in `practice_pending` or `additional_practice_pending` + while that practice is `not_started` or `failed`, and null + otherwise. + oneOf: + - $ref: "#/schemas/AssessmentItem" + - type: "null" + practices: + type: array + maxItems: 5 + description: >- + Practices in the order they were assigned: the `main` practice + first, then an `additional` practice once finalize offers it. Empty + only for a demo_basic attempt while code practice is disabled until + the sandbox isolation is verified; its result then lists the + `practice_not_included` limitation. A list rather than one field + leaves room for more practices without a breaking change. + items: + $ref: "#/schemas/AssessmentPractice" + ChoiceAnswer: + type: object + description: >- + Selected options of a choice item: exactly one unless the item allows + several. Two answers are equal when they select the same set of + options, in any order. + additionalProperties: false + required: + - format + - option_ids + properties: + format: + type: string + enum: + - choice + option_ids: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + $ref: "#/schemas/AssessmentOptionId" + NumberAnswer: + type: object + description: >- + Numeric answer in the unit of the item. Two answers are equal when + their decoded values are numerically equal, so 254 and 254.0 are the + same answer. + additionalProperties: false + required: + - format + - number + properties: + format: + type: string + enum: + - number + number: + type: number + format: double + StringAnswer: + type: object + description: >- + String answer, at most the `max_length` of the item. Two answers are + equal only when their texts are identical; no trimming, case folding, + or Unicode normalization applies to that comparison. + additionalProperties: false + required: + - format + - text + properties: + format: + type: string + enum: + - string + text: + type: string + minLength: 1 + maxLength: 500 + OrderAnswer: + type: object + description: >- + Every element of the item exactly once, in the chosen order. Two + answers are equal only when the sequences are identical. + additionalProperties: false + required: + - format + - element_ids + properties: + format: + type: string + enum: + - order + element_ids: + type: array + minItems: 2 + maxItems: 20 + uniqueItems: true + items: + $ref: "#/schemas/AssessmentOptionId" + FindErrorAnswer: + type: object + description: >- + Selected line numbers, at most the `max_selections` of the item. Two + answers are equal when they select the same set of lines, in any + order. + additionalProperties: false + required: + - format + - line_numbers + properties: + format: + type: string + enum: + - find_error + line_numbers: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + type: integer + format: int32 + minimum: 1 + maximum: 500 + ConfigurationAnswer: + type: object + description: >- + Submitted configuration text, at most the `max_length` of the item. + Two answers are equal only when their texts are identical, including + whitespace and line breaks. + additionalProperties: false + required: + - format + - config + properties: + format: + type: string + enum: + - configuration + config: + type: string + minLength: 1 + maxLength: 20000 + PracticeAnswer: + type: object + description: >- + Practice solution. It runs in the isolated sandbox without network + access, secrets, or business data. Two submissions are equal only when + the language is the same and the source texts are identical. The + source is never echoed in a response or a problem. + additionalProperties: false + required: + - format + - language + - source_code + properties: + format: + type: string + enum: + - practice + language: + description: >- + One of the `languages` of the practice item, or null when the item + offers none. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + source_code: + type: string + minLength: 1 + maxLength: 65536 + AssessmentAnswer: + description: >- + Candidate answer, selected by `format`, which must equal the format of + the answered item. It carries only the answer: no score, duration, + correctness flag, or seed. The server records the times itself and + scores the answer with the key of the fixed item instance. Each format + defines when two answers are equal, which decides whether a repeated + submission is the same answer. + oneOf: + - $ref: "#/schemas/ChoiceAnswer" + - $ref: "#/schemas/NumberAnswer" + - $ref: "#/schemas/StringAnswer" + - $ref: "#/schemas/OrderAnswer" + - $ref: "#/schemas/FindErrorAnswer" + - $ref: "#/schemas/ConfigurationAnswer" + - $ref: "#/schemas/PracticeAnswer" + AssessmentAnswerSubmission: + type: object + description: >- + Answer to one item of the attempt. Unknown fields are rejected, so a + request cannot send a score, a duration, or a correctness flag. + additionalProperties: false + required: + - expected_version + - item_id + - answer + properties: + expected_version: + $ref: "#/schemas/AssessmentAttemptVersion" + item_id: + $ref: "#/schemas/AssessmentItemId" + answer: + $ref: "#/schemas/AssessmentAnswer" + AssessmentFinalization: + type: object + description: Command to finalize the attempt. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: "#/schemas/AssessmentAttemptVersion" + AssessmentOutcome: + type: string + description: |- + Grade decision of the attempt. + + - confirmed: the target grade is confirmed by the rule of the recorded policy version. + - not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force. + - not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force. + + A failed, expired, or flagged attempt never lowers a confirmed grade. + enum: + - confirmed + - not_confirmed + - not_determined + AssessmentNotDeterminedReason: + type: string + description: |- + Why an attempt gives no decision, and whether it counts against the retry rules. + + - expired: the time or session limit passed before the candidate finished the item part. It is the candidate's attempt: it counts toward the attempt limit and starts the same-grade retry interval. + - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`. + - insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval. + - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval. + enum: + - expired + - practice_incomplete + - insufficient_bank + - sandbox_unavailable + AssessmentStrength: + type: string + description: >- + Strength of an adaptive confirmation: `high` or `medium`, by the + probability bands of the recorded policy version. + enum: + - high + - medium + CalibrationStatus: + type: string + description: >- + Whether the thresholds of the recorded policy version are empirically + calibrated. `uncalibrated` results are provisional: their thresholds + come from expert judgement, and their probabilities are not claimed to + be calibrated. + enum: + - uncalibrated + - calibrated + AssessmentLimitation: + type: string + description: |- + Known limitation of the method behind a result, shown with the result. + + - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. + - demo_bank: the result comes from the small reviewed demo bank. + - practice_not_included: the attempt had no code practice because the sandbox was not enabled. + - unproctored: the attempt was taken online without supervision. + + Adding a value is a contract change. + enum: + - uncalibrated_thresholds + - demo_bank + - practice_not_included + - unproctored + AssessmentInterval: + type: object + description: Interval on the ability scale. + additionalProperties: false + required: + - low + - high + properties: + low: + type: number + format: double + high: + type: number + format: double + AssessmentUncertainty: + type: object + description: >- + Ability estimate of an adaptive attempt and its uncertainty: the EAP + estimate on the specialization scale, its standard error, the 95% + interval, and the probability of reaching the target grade threshold. + The interval is reported but is not a separate stop condition. + additionalProperties: false + required: + - theta + - standard_error + - interval_95 + - p_grade + properties: + theta: + type: number + format: double + standard_error: + type: number + format: double + minimum: 0 + interval_95: + $ref: "#/schemas/AssessmentInterval" + p_grade: + type: number + format: double + minimum: 0 + maximum: 1 + description: Probability of reaching the threshold of the target grade. + BasicScore: + type: object + description: >- + Raw score of a demo_basic attempt and the pass mark of the recorded + basic grading policy. The pass mark comes from that policy version and + never from the handler. + additionalProperties: false + required: + - points + - max_points + - pass_points + properties: + points: + type: integer + format: int32 + minimum: 0 + max_points: + type: integer + format: int32 + minimum: 1 + pass_points: + type: integer + format: int32 + minimum: 1 + AssessmentGap: + type: object + description: Domain of the specialization where the evidence was weak. + additionalProperties: false + required: + - domain + - title + properties: + domain: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z0-9_]+$" + description: Stable domain code of the bank blueprint. + title: + type: string + minLength: 1 + maxLength: 200 + description: Display name in Russian. Plain text. + AssessmentDurations: + type: object + description: >- + Working time recorded by the server. It is a separate label: it never + enters the ability estimate or the grade decision. + additionalProperties: false + required: + - items_seconds + - practice_seconds + properties: + items_seconds: + type: integer + format: int32 + minimum: 0 + practice_seconds: + type: + - integer + - "null" + format: int32 + minimum: 0 + description: >- + Time on all practices with a verdict, or null when no practice has + one. + AssessmentPracticeResult: + type: object + description: Verdict of one practice of the attempt. + additionalProperties: false + required: + - kind + - verdict + properties: + kind: + $ref: "#/schemas/PracticeKind" + verdict: + $ref: "#/schemas/PracticeVerdict" + AssessmentNextAction: + type: string + description: |- + Step that the candidate may take next. + + - retake_same_grade: test the same grade again from `available_at`. + - take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval. + - accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned). + - take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy. + enum: + - retake_same_grade + - take_lower_grade + - accept_lower_grade + - take_higher_grade + AssessmentNextStep: + type: object + description: Step that the server allows after this result, computed when it was decided. + additionalProperties: false + required: + - action + - grade + - available_at + properties: + action: + $ref: "#/schemas/AssessmentNextAction" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + available_at: + description: First time the step is allowed, or null when it is allowed now. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + AssessmentResult: + type: object + description: >- + Immutable result of a terminal attempt, visible only to its candidate. + It records the method, the versions, the decision, its uncertainty, + and its limitations; a later policy, bank, or algorithm version never + changes it. It never contains answers, per-item correctness, answer + keys, seeds, hidden checks, or anti-cheat signals. Fields that the + method does not compute are null, never zero: demo_basic has null + `uncertainty` and `strength`, and adaptive has null `basic_score`. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + task_language: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + mode: + $ref: "#/schemas/AssessmentMode" + versions: + $ref: "#/schemas/AssessmentVersions" + outcome: + $ref: "#/schemas/AssessmentOutcome" + not_determined_reason: + description: The reason when `outcome` is `not_determined`, otherwise null. + oneOf: + - $ref: "#/schemas/AssessmentNotDeterminedReason" + - type: "null" + confirmed_grade: + description: >- + Grade that this attempt confirmed, the target grade, or null when + it confirmed none. Together with the specialization it forms the + category. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + previous_confirmed_grade: + description: >- + Confirmed grade of the specialization before this attempt, or null. + When the attempt confirmed nothing, this grade stays in force. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + strength: + description: Strength of an adaptive confirmation, otherwise null. + oneOf: + - $ref: "#/schemas/AssessmentStrength" + - type: "null" + calibration_status: + $ref: "#/schemas/CalibrationStatus" + limitations: + type: array + maxItems: 10 + uniqueItems: true + items: + $ref: "#/schemas/AssessmentLimitation" + uncertainty: + description: >- + Ability estimate and uncertainty of an adaptive attempt with a + decision; null for demo_basic, which computes none, and for an + attempt without a decision. + oneOf: + - $ref: "#/schemas/AssessmentUncertainty" + - type: "null" + basic_score: + description: Raw score of a demo_basic attempt with a decision, otherwise null. + oneOf: + - $ref: "#/schemas/BasicScore" + - type: "null" + practices: + type: array + maxItems: 5 + description: Verdicts of the practices that have one, main first. + items: + $ref: "#/schemas/AssessmentPracticeResult" + gaps: + type: array + maxItems: 20 + description: Domains with weak evidence; empty when none were found or the method finds none. + items: + $ref: "#/schemas/AssessmentGap" + durations: + $ref: "#/schemas/AssessmentDurations" + next_steps: + type: array + maxItems: 5 + items: + $ref: "#/schemas/AssessmentNextStep" + decided_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + AssessmentGradeAvailabilityStatus: + type: string + description: |- + Whether an attempt for the grade can start now. + + - available: CreateMyAssessmentAttempt can start it. + - active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`. + - cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it. + - insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families. + enum: + - available + - active_attempt + - cooldown + - insufficient_bank + AssessmentGradeAvailability: + type: object + description: >- + Availability of an attempt for one grade of a specialization, with the + limits that an attempt would have, so the client can show them before + the start. The limit fields are null when the status is + `insufficient_bank` or the policy defines no such limit. + additionalProperties: false + required: + - grade + - status + - mode + - available_at + - time_limit_seconds + - max_sessions + - max_items + - practice_required + properties: + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + status: + $ref: "#/schemas/AssessmentGradeAvailabilityStatus" + mode: + description: >- + Mode that an attempt would use, or null when the status is + `insufficient_bank`. + oneOf: + - $ref: "#/schemas/AssessmentMode" + - type: "null" + available_at: + description: When the status is `cooldown`, the first time the attempt can start; otherwise null. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + time_limit_seconds: + type: + - integer + - "null" + format: int32 + minimum: 1 + description: Time from the start to `expires_at`. + max_sessions: + type: + - integer + - "null" + format: int32 + minimum: 1 + maximum: 10 + description: Session limit within the time limit. + max_items: + type: + - integer + - "null" + format: int32 + minimum: 1 + maximum: 100 + description: Item limit, as in `AssessmentProgress.max_items`. + practice_required: + type: + - boolean + - "null" + description: Whether the attempt would include a main code practice. + AssessmentSpecializationAvailability: + type: object + description: >- + Assessment state of one questionnaire specialization. Specializations + are assessed independently, with independent retry intervals. + additionalProperties: false + required: + - specialization + - confirmed_grade + - active_attempt_id + - grades + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + confirmed_grade: + description: Currently confirmed grade of the specialization, or null. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + active_attempt_id: + type: + - string + - "null" + format: uuid + description: Identifier of the active attempt of the specialization, or null. + grades: + type: array + maxItems: 10 + description: Every grade of the scale in ascending order. + items: + $ref: "#/schemas/AssessmentGradeAvailability" + AssessmentAvailability: + type: object + description: >- + Assessment availability for the specializations of the current + candidate's questionnaire, derived at the time of the request. + additionalProperties: false + required: + - specializations + properties: + specializations: + type: array + maxItems: 2 + description: Questionnaire specializations in questionnaire order. + items: + $ref: "#/schemas/AssessmentSpecializationAvailability" diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index a5a03fc..80a92c6 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -15,6 +15,8 @@ tags: description: 'Public reference data: directions, specializations with their assessment availability, and the grade scale.' - name: candidate description: Data of the current candidate, such as the questionnaire with the chosen specializations and self-assessed grades. Confirmed grades and categories come only from assessment results. + - name: assessment + description: 'Assessment attempts of the current candidate: availability, start and resume, answers and the code practice, finalization, and the result. Answers, keys, and attempt history are visible only to the candidate.' paths: /api/v1/healthz: get: @@ -483,6 +485,339 @@ paths: $ref: '#/components/responses/QuestionnaireVersionConflict' default: $ref: '#/components/responses/Problem' + /api/v1/me/assessment-availability: + get: + operationId: GetMyAssessmentAvailability + summary: Read which assessment attempts the current candidate can start. + description: |- + Requires the session cookie of a candidate account; the candidate comes from the session. For each specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every grade whether an attempt can start now, in which mode, and with which limits: the time limit, the session limit, the item limit, and whether a code practice is required. The client shows them before the start, together with the method and the signals that are collected, and resumes an active attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt. + + `insufficient_bank` is the state of a category whose bank is not published or has too few families that this candidate has not seen; the server limits attempts instead of repeating families. `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with that date and offer support. Specializations and their retry intervals are independent. Attempts that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations and never cause a `cooldown`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - assessment + responses: + '200': + description: Assessment availability of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAvailability' + examples: + backend_and_network_engineer: + $ref: '#/components/examples/AssessmentAvailability' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts: + post: + operationId: CreateMyAssessmentAttempt + summary: Start an assessment attempt for a category of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the questionnaire and a target grade, and the task language. The server picks the mode from the published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the time and session limits, and the item variants in one transaction; the client never sends a mode, a seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. + + A specialization has at most one active attempt. A new attempt cannot start while one is active, during a retry or promotion interval or past the attempt limit of the policy, or when the bank is insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a failure, including the first test, a lower grade can be tested at once. An attempt that ends as `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the same-grade retry interval; one that ends as `insufficient_bank` or with the reason `sandbox_unavailable` counts toward neither. + + The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no command. Within them the attempt is also bounded by the item limit of the policy. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 state_conflict response and creates nothing, so a lost response never creates a second attempt. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` for a specialization that is not in the questionnaire or `/task_language` for a language that the bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with Retry-After before any of them; it is not stored. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttemptCreate' + examples: + backend_junior_go: + $ref: '#/components/examples/AssessmentAttemptCreateBackendJunior' + responses: + '201': + description: The attempt was created, or a retry with the same Idempotency-Key replayed its creation. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + demo_basic_created: + $ref: '#/components/examples/AssessmentAttemptCreated' + '400': + $ref: '#/components/responses/AssessmentAttemptCreateValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '409': + $ref: '#/components/responses/AssessmentCreateConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}: + get: + operationId: GetMyAssessmentAttempt + summary: Read or resume an assessment attempt of the current candidate. + description: |- + Requires the session cookie of a candidate account. Returns the attempt with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + + Reading an active attempt counts as activity: after the previous session ended it starts the next session, and when that would exceed the session limit it starts none and the attempt becomes `expired`. Before it answers, the server commits any transition that is due, with a new version: past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is declined and the attempt becomes `completed`, and the other active states become `expired`; a practice still `pending` is graded first. The client polls this operation while a practice is `pending`. Reading a terminal attempt changes nothing. + + The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers or the attempt history. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + responses: + '200': + description: The attempt. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + adaptive_resumed: + $ref: '#/components/examples/AssessmentAttemptResumed' + practice_pending: + $ref: '#/components/examples/AssessmentAttemptPracticePending' + practice_verdict_pending: + $ref: '#/components/examples/AssessmentAttemptPracticeVerdictPending' + sandbox_failed: + $ref: '#/components/examples/AssessmentAttemptSandboxFailed' + ready_to_finalize: + $ref: '#/components/examples/AssessmentAttemptReadyToFinalize' + additional_practice_pending: + $ref: '#/components/examples/AssessmentAttemptAdditionalPracticePending' + completed: + $ref: '#/components/examples/AssessmentAttemptCompleted' + insufficient_bank: + $ref: '#/components/examples/AssessmentAttemptInsufficientBank' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/answers: + post: + operationId: SubmitMyAssessmentAnswer + summary: Answer the current item or submit a practice of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision. + + The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. + + Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation. + + Repeats and conflicts, per item: + - A retry with the same Idempotency-Key and body within 24 hours replays the stored response. + - Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. + - A different answer for an item that already has one answers 409 state_conflict when `expected_version` is current; with a stale version the version check comes first and answers 412. + - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A submission with the same or a different solution, with the current `expected_version`, queues it again and advances the version. + + Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is kept for commands that the attempt state does not allow at the current version. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; the server first commits any due transition such as expiry, and the request counts as activity for the session limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAnswerSubmission' + examples: + choice: + $ref: '#/components/examples/AssessmentChoiceAnswer' + order: + $ref: '#/components/examples/AssessmentOrderAnswer' + number: + $ref: '#/components/examples/AssessmentNumberAnswer' + string: + $ref: '#/components/examples/AssessmentStringAnswer' + find_error: + $ref: '#/components/examples/AssessmentFindErrorAnswer' + configuration: + $ref: '#/components/examples/AssessmentConfigurationAnswer' + practice: + $ref: '#/components/examples/AssessmentPracticeAnswer' + responses: + '200': + description: The answer was stored, or this exact answer was already stored, and the response is the attempt with the next item. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + accepted: + $ref: '#/components/examples/AssessmentAnswerAccepted' + practice_submitted: + $ref: '#/components/examples/AssessmentAttemptPracticeVerdictPending' + '400': + $ref: '#/components/responses/AssessmentAnswerValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentCommandConflict' + '412': + $ref: '#/components/responses/AssessmentVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/finalize: + post: + operationId: FinalizeMyAssessmentAttempt + summary: Ask for the grade decision of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the result: the decision may continue the attempt, and one response type keeps that unambiguous for every generated client. When the returned state is `completed`, the client reads the result with GetMyAssessmentResult. + + Allowed in `ready_to_finalize`, where every required part is done, and in `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: + - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and completes the attempt. It never offers an additional practice. + - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the demo policy) on the first finalize, while time and sessions remain, completes nothing: the server appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no new attempt. The next finalize, after its verdict, decides with the added evidence; a probability still below confirmation gives `not_confirmed`. An attempt offers at most one additional practice. + - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the current evidence. A retry of the first finalize with a new key cannot decline by accident: it carries the version from before the offer and answers 412. + + A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, the server finalizes `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also answers 200 with the `completed` attempt. + + An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentFinalization' + examples: + finalize: + $ref: '#/components/examples/AssessmentFinalization' + responses: + '200': + description: 'The attempt after the decision: `completed`, with the result available from GetMyAssessmentResult, or `additional_practice_pending` when an adaptive attempt offers an additional practice.' + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + demo_basic_completed: + $ref: '#/components/examples/AssessmentAttemptCompleted' + additional_practice_offered: + $ref: '#/components/examples/AssessmentAttemptAdditionalPracticePending' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentFinalizeConflict' + '412': + $ref: '#/components/responses/AssessmentVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/result: + get: + operationId: GetMyAssessmentResult + summary: Read the result of an assessment attempt of the current candidate. + description: |- + Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and algorithm versions, the decision, the previously confirmed grade, the calibration status and limitations of the method, the uncertainty where the method computes it, the practice verdicts, the weak domains, the working time as a separate label, and the next steps that the server allows. A later policy, bank, or algorithm version never changes it. + + Fields that the method does not compute are null and never zero: a `demo_basic` result has null `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. + + An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. The server first commits any due transition, so an attempt past its limits is read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + responses: + '200': + description: The result. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentResult' + examples: + demo_basic: + $ref: '#/components/examples/AssessmentDemoBasicResult' + adaptive_confirmed: + $ref: '#/components/examples/AssessmentAdaptiveResult' + adaptive_not_confirmed: + $ref: '#/components/examples/AssessmentNotConfirmedResult' + insufficient_bank: + $ref: '#/components/examples/AssessmentInsufficientBankResult' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentResultNotReady' + default: + $ref: '#/components/responses/Problem' components: schemas: Problem: @@ -1175,6 +1510,1151 @@ components: $ref: '#/components/schemas/QuestionnaireSpecialization' work_context: $ref: '#/components/schemas/WorkContext' + AssessmentMode: + type: string + description: |- + Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it. + + - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice. + - adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt. + + Adding a value is a contract change. + enum: + - demo_basic + - adaptive + AssessmentAttemptVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.' + examples: + - 4 + AssessmentAttemptState: + type: string + description: |- + Lifecycle state of an attempt and the commands it accepts. + + - in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item. + - practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part. + - additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence. + - ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt. + - completed: a decision was made; the result is available. + - expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade. + - insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available. + + When `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change. + enum: + - in_progress + - practice_pending + - additional_practice_pending + - ready_to_finalize + - completed + - expired + - insufficient_bank + AssessmentVersionLabel: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it. + AssessmentVersions: + type: object + description: Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it. + additionalProperties: false + required: + - policy_version + - bank_version + - algorithm_version + properties: + policy_version: + type: integer + format: int32 + minimum: 1 + description: 'Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.' + bank_version: + $ref: '#/components/schemas/AssessmentVersionLabel' + algorithm_version: + $ref: '#/components/schemas/AssessmentVersionLabel' + AssessmentSessions: + type: object + description: |- + Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit. + + A session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session. + additionalProperties: false + required: + - used + - max + - idle_timeout_seconds + properties: + used: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Sessions started so far, including the current one. + max: + type: integer + format: int32 + minimum: 1 + maximum: 10 + idle_timeout_seconds: + type: integer + format: int32 + minimum: 60 + maximum: 86400 + description: Inactivity after which the current session ends. + AssessmentAttemptCreate: + type: object + description: 'Category to assess: a specialization and the target grade, with the task language. The candidate comes from the session. The mode and versions are chosen by the server; unknown fields such as `mode`, `seed`, or `score` are rejected.' + additionalProperties: false + required: + - specialization + - target_grade + - task_language + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + task_language: + description: Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + AssessmentItemId: + type: string + format: uuid + description: Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed. + AssessmentOptionId: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option. + AssessmentOption: + type: object + description: Choice option or order element. Plain text. + additionalProperties: false + required: + - id + - text + properties: + id: + $ref: '#/components/schemas/AssessmentOptionId' + text: + type: string + minLength: 1 + maxLength: 2000 + description: Text of the option; the client shows it as text, never as HTML. + ChoiceItemContent: + type: object + description: Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are. + additionalProperties: false + required: + - format + - options + - multiple + properties: + format: + type: string + enum: + - choice + options: + type: array + minItems: 2 + maxItems: 10 + description: Options in the order of this instance. + items: + $ref: '#/components/schemas/AssessmentOption' + multiple: + type: boolean + description: 'Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.' + NumberItemContent: + type: object + description: Enter a number, optionally in the given unit. + additionalProperties: false + required: + - format + - unit + properties: + format: + type: string + enum: + - number + unit: + type: + - string + - 'null' + minLength: 1 + maxLength: 32 + description: Unit of the expected value, for example `ms`, or null. + StringItemContent: + type: object + description: Enter a short string, such as a command, a header name, or an address. + additionalProperties: false + required: + - format + - max_length + properties: + format: + type: string + enum: + - string + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 500 + description: Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer. + OrderItemContent: + type: object + description: Put every element into the right order. The elements arrive in the order of this instance, which is never the answer. + additionalProperties: false + required: + - format + - elements + properties: + format: + type: string + enum: + - order + elements: + type: array + minItems: 2 + maxItems: 20 + items: + $ref: '#/components/schemas/AssessmentOption' + CodeLine: + type: object + description: One numbered line of a code or configuration fragment. Plain text. + additionalProperties: false + required: + - number + - text + properties: + number: + type: integer + format: int32 + minimum: 1 + maximum: 500 + text: + type: string + maxLength: 1000 + FindErrorItemContent: + type: object + description: Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers. + additionalProperties: false + required: + - format + - syntax + - lines + - max_selections + properties: + format: + type: string + enum: + - find_error + syntax: + type: + - string + - 'null' + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9_+-]+$ + description: Highlighting hint such as `go`, `python`, or `cisco_ios`, or null. + lines: + type: array + minItems: 1 + maxItems: 500 + description: Lines numbered from 1 in order. + items: + $ref: '#/components/schemas/CodeLine' + max_selections: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines. + ConfigurationItemContent: + type: object + description: Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code. + additionalProperties: false + required: + - format + - syntax + - initial_config + - max_length + properties: + format: + type: string + enum: + - configuration + syntax: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9_+-]+$ + description: Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`. + initial_config: + type: string + maxLength: 20000 + description: Starting text to edit; empty when the candidate writes it from scratch. + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 20000 + description: Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key. + PracticeExample: + type: object + description: 'Public example of the practice task: an input and its expected output. Hidden checks are never listed.' + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 + PracticeItemContent: + type: object + description: Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client. + additionalProperties: false + required: + - format + - languages + - public_examples + - max_source_length + properties: + format: + type: string + enum: + - practice + languages: + type: array + maxItems: 2 + uniqueItems: true + description: Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language. + items: + $ref: '#/components/schemas/TaskLanguage' + public_examples: + type: array + maxItems: 10 + items: + $ref: '#/components/schemas/PracticeExample' + max_source_length: + type: integer + format: int32 + minimum: 1 + maximum: 65536 + description: Maximum length of the solution source in characters. + ItemContent: + description: 'Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.' + oneOf: + - $ref: '#/components/schemas/ChoiceItemContent' + - $ref: '#/components/schemas/NumberItemContent' + - $ref: '#/components/schemas/StringItemContent' + - $ref: '#/components/schemas/OrderItemContent' + - $ref: '#/components/schemas/FindErrorItemContent' + - $ref: '#/components/schemas/ConfigurationItemContent' + - $ref: '#/components/schemas/PracticeItemContent' + AssessmentItem: + type: object + description: 'Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.' + additionalProperties: false + required: + - id + - sequence + - prompt + - content + properties: + id: + $ref: '#/components/schemas/AssessmentItemId' + sequence: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: Position of the item in the attempt, from 1. + prompt: + type: string + minLength: 1 + maxLength: 20000 + description: Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML. + content: + $ref: '#/components/schemas/ItemContent' + AssessmentProgress: + type: object + description: Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`. + additionalProperties: false + required: + - answered_items + - max_items + properties: + answered_items: + type: integer + format: int32 + minimum: 0 + maximum: 100 + max_items: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: 'Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.' + PracticeKind: + type: string + description: |- + Role of a practice in the attempt. + + - main: the practice that every attempt with practice requires before a decision. + - additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt. + + Adding a value is a contract change. + enum: + - main + - additional + PracticeStatus: + type: string + description: |- + State of a practice. + + - not_started: no solution was submitted yet. + - pending: the submitted solution is queued or running in the sandbox. + - finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed. + - failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate's and consumes nothing; the practice can be submitted again. + enum: + - not_started + - pending + - finished + - failed + PracticeFailureReason: + type: string + description: 'Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.' + enum: + - sandbox_busy + - sandbox_error + PracticeGroupResult: + type: object + description: Outcome of one hidden check group. It never contains the checks themselves. + additionalProperties: false + required: + - group + - passed + properties: + group: + type: integer + format: int32 + minimum: 1 + maximum: 3 + passed: + type: boolean + PracticeVerdict: + type: object + description: 'Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.' + additionalProperties: false + required: + - score + - max_score + - groups + properties: + score: + type: integer + format: int32 + minimum: 0 + maximum: 3 + max_score: + type: integer + format: int32 + minimum: 3 + maximum: 3 + groups: + type: array + minItems: 3 + maxItems: 3 + items: + $ref: '#/components/schemas/PracticeGroupResult' + AssessmentPractice: + type: object + description: Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision. + additionalProperties: false + required: + - kind + - item_id + - status + - submitted_at + - verdict + - failure_reason + properties: + kind: + $ref: '#/components/schemas/PracticeKind' + item_id: + $ref: '#/components/schemas/AssessmentItemId' + status: + $ref: '#/components/schemas/PracticeStatus' + submitted_at: + description: Time of the latest submission, or null before the first one. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + verdict: + description: The verdict when `status` is `finished`, otherwise null. + oneOf: + - $ref: '#/components/schemas/PracticeVerdict' + - type: 'null' + failure_reason: + description: The reason when `status` is `failed`, otherwise null. + oneOf: + - $ref: '#/components/schemas/PracticeFailureReason' + - type: 'null' + AssessmentAttempt: + type: object + description: Assessment attempt of the current candidate for one category, a specialization and a target grade. It shows the state, the fixed versions, the server deadline `expires_at` from the policy version, which the client clock never extends, the session limit, the progress, the item to answer now, and the practices. It never contains answer keys, the correctness of submitted answers, scores of single items, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + additionalProperties: false + required: + - id + - version + - specialization + - target_grade + - task_language + - mode + - state + - versions + - started_at + - expires_at + - sessions + - finished_at + - progress + - current_item + - practices + properties: + id: + type: string + format: uuid + description: Attempt identifier. + version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + task_language: + description: Task language of the attempt, or null when the bank offers no choice. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + mode: + $ref: '#/components/schemas/AssessmentMode' + state: + $ref: '#/components/schemas/AssessmentAttemptState' + versions: + $ref: '#/components/schemas/AssessmentVersions' + started_at: + $ref: '#/components/schemas/Timestamp' + expires_at: + $ref: '#/components/schemas/Timestamp' + sessions: + description: Session limit of the attempt, or null when its policy version defines none. + oneOf: + - $ref: '#/components/schemas/AssessmentSessions' + - type: 'null' + finished_at: + description: Time the attempt reached a terminal state, or null while it is active. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + progress: + $ref: '#/components/schemas/AssessmentProgress' + current_item: + description: 'Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.' + oneOf: + - $ref: '#/components/schemas/AssessmentItem' + - type: 'null' + practices: + type: array + maxItems: 5 + description: 'Practices in the order they were assigned: the `main` practice first, then an `additional` practice once finalize offers it. Empty only for a demo_basic attempt while code practice is disabled until the sandbox isolation is verified; its result then lists the `practice_not_included` limitation. A list rather than one field leaves room for more practices without a breaking change.' + items: + $ref: '#/components/schemas/AssessmentPractice' + ChoiceAnswer: + type: object + description: 'Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.' + additionalProperties: false + required: + - format + - option_ids + properties: + format: + type: string + enum: + - choice + option_ids: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + $ref: '#/components/schemas/AssessmentOptionId' + NumberAnswer: + type: object + description: Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer. + additionalProperties: false + required: + - format + - number + properties: + format: + type: string + enum: + - number + number: + type: number + format: double + StringAnswer: + type: object + description: String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison. + additionalProperties: false + required: + - format + - text + properties: + format: + type: string + enum: + - string + text: + type: string + minLength: 1 + maxLength: 500 + OrderAnswer: + type: object + description: Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical. + additionalProperties: false + required: + - format + - element_ids + properties: + format: + type: string + enum: + - order + element_ids: + type: array + minItems: 2 + maxItems: 20 + uniqueItems: true + items: + $ref: '#/components/schemas/AssessmentOptionId' + FindErrorAnswer: + type: object + description: Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order. + additionalProperties: false + required: + - format + - line_numbers + properties: + format: + type: string + enum: + - find_error + line_numbers: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + type: integer + format: int32 + minimum: 1 + maximum: 500 + ConfigurationAnswer: + type: object + description: Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks. + additionalProperties: false + required: + - format + - config + properties: + format: + type: string + enum: + - configuration + config: + type: string + minLength: 1 + maxLength: 20000 + PracticeAnswer: + type: object + description: Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem. + additionalProperties: false + required: + - format + - language + - source_code + properties: + format: + type: string + enum: + - practice + language: + description: One of the `languages` of the practice item, or null when the item offers none. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + source_code: + type: string + minLength: 1 + maxLength: 65536 + AssessmentAnswer: + description: 'Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.' + oneOf: + - $ref: '#/components/schemas/ChoiceAnswer' + - $ref: '#/components/schemas/NumberAnswer' + - $ref: '#/components/schemas/StringAnswer' + - $ref: '#/components/schemas/OrderAnswer' + - $ref: '#/components/schemas/FindErrorAnswer' + - $ref: '#/components/schemas/ConfigurationAnswer' + - $ref: '#/components/schemas/PracticeAnswer' + AssessmentAnswerSubmission: + type: object + description: Answer to one item of the attempt. Unknown fields are rejected, so a request cannot send a score, a duration, or a correctness flag. + additionalProperties: false + required: + - expected_version + - item_id + - answer + properties: + expected_version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + item_id: + $ref: '#/components/schemas/AssessmentItemId' + answer: + $ref: '#/components/schemas/AssessmentAnswer' + AssessmentFinalization: + type: object + description: Command to finalize the attempt. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + AssessmentOutcome: + type: string + description: |- + Grade decision of the attempt. + + - confirmed: the target grade is confirmed by the rule of the recorded policy version. + - not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force. + - not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force. + + A failed, expired, or flagged attempt never lowers a confirmed grade. + enum: + - confirmed + - not_confirmed + - not_determined + AssessmentNotDeterminedReason: + type: string + description: |- + Why an attempt gives no decision, and whether it counts against the retry rules. + + - expired: the time or session limit passed before the candidate finished the item part. It is the candidate's attempt: it counts toward the attempt limit and starts the same-grade retry interval. + - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`. + - insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval. + - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval. + enum: + - expired + - practice_incomplete + - insufficient_bank + - sandbox_unavailable + AssessmentStrength: + type: string + description: 'Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.' + enum: + - high + - medium + CalibrationStatus: + type: string + description: 'Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.' + enum: + - uncalibrated + - calibrated + AssessmentLimitation: + type: string + description: |- + Known limitation of the method behind a result, shown with the result. + + - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. + - demo_bank: the result comes from the small reviewed demo bank. + - practice_not_included: the attempt had no code practice because the sandbox was not enabled. + - unproctored: the attempt was taken online without supervision. + + Adding a value is a contract change. + enum: + - uncalibrated_thresholds + - demo_bank + - practice_not_included + - unproctored + AssessmentInterval: + type: object + description: Interval on the ability scale. + additionalProperties: false + required: + - low + - high + properties: + low: + type: number + format: double + high: + type: number + format: double + AssessmentUncertainty: + type: object + description: 'Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.' + additionalProperties: false + required: + - theta + - standard_error + - interval_95 + - p_grade + properties: + theta: + type: number + format: double + standard_error: + type: number + format: double + minimum: 0 + interval_95: + $ref: '#/components/schemas/AssessmentInterval' + p_grade: + type: number + format: double + minimum: 0 + maximum: 1 + description: Probability of reaching the threshold of the target grade. + BasicScore: + type: object + description: Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass mark comes from that policy version and never from the handler. + additionalProperties: false + required: + - points + - max_points + - pass_points + properties: + points: + type: integer + format: int32 + minimum: 0 + max_points: + type: integer + format: int32 + minimum: 1 + pass_points: + type: integer + format: int32 + minimum: 1 + AssessmentGap: + type: object + description: Domain of the specialization where the evidence was weak. + additionalProperties: false + required: + - domain + - title + properties: + domain: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9_]+$ + description: Stable domain code of the bank blueprint. + title: + type: string + minLength: 1 + maxLength: 200 + description: Display name in Russian. Plain text. + AssessmentDurations: + type: object + description: 'Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.' + additionalProperties: false + required: + - items_seconds + - practice_seconds + properties: + items_seconds: + type: integer + format: int32 + minimum: 0 + practice_seconds: + type: + - integer + - 'null' + format: int32 + minimum: 0 + description: Time on all practices with a verdict, or null when no practice has one. + AssessmentPracticeResult: + type: object + description: Verdict of one practice of the attempt. + additionalProperties: false + required: + - kind + - verdict + properties: + kind: + $ref: '#/components/schemas/PracticeKind' + verdict: + $ref: '#/components/schemas/PracticeVerdict' + AssessmentNextAction: + type: string + description: |- + Step that the candidate may take next. + + - retake_same_grade: test the same grade again from `available_at`. + - take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval. + - accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned). + - take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy. + enum: + - retake_same_grade + - take_lower_grade + - accept_lower_grade + - take_higher_grade + AssessmentNextStep: + type: object + description: Step that the server allows after this result, computed when it was decided. + additionalProperties: false + required: + - action + - grade + - available_at + properties: + action: + $ref: '#/components/schemas/AssessmentNextAction' + grade: + $ref: '#/components/schemas/GradeCode' + available_at: + description: First time the step is allowed, or null when it is allowed now. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + AssessmentResult: + type: object + description: 'Immutable result of a terminal attempt, visible only to its candidate. It records the method, the versions, the decision, its uncertainty, and its limitations; a later policy, bank, or algorithm version never changes it. It never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. Fields that the method does not compute are null, never zero: demo_basic has null `uncertainty` and `strength`, and adaptive has null `basic_score`.' + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + task_language: + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + mode: + $ref: '#/components/schemas/AssessmentMode' + versions: + $ref: '#/components/schemas/AssessmentVersions' + outcome: + $ref: '#/components/schemas/AssessmentOutcome' + not_determined_reason: + description: The reason when `outcome` is `not_determined`, otherwise null. + oneOf: + - $ref: '#/components/schemas/AssessmentNotDeterminedReason' + - type: 'null' + confirmed_grade: + description: Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + previous_confirmed_grade: + description: Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + strength: + description: Strength of an adaptive confirmation, otherwise null. + oneOf: + - $ref: '#/components/schemas/AssessmentStrength' + - type: 'null' + calibration_status: + $ref: '#/components/schemas/CalibrationStatus' + limitations: + type: array + maxItems: 10 + uniqueItems: true + items: + $ref: '#/components/schemas/AssessmentLimitation' + uncertainty: + description: Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision. + oneOf: + - $ref: '#/components/schemas/AssessmentUncertainty' + - type: 'null' + basic_score: + description: Raw score of a demo_basic attempt with a decision, otherwise null. + oneOf: + - $ref: '#/components/schemas/BasicScore' + - type: 'null' + practices: + type: array + maxItems: 5 + description: Verdicts of the practices that have one, main first. + items: + $ref: '#/components/schemas/AssessmentPracticeResult' + gaps: + type: array + maxItems: 20 + description: Domains with weak evidence; empty when none were found or the method finds none. + items: + $ref: '#/components/schemas/AssessmentGap' + durations: + $ref: '#/components/schemas/AssessmentDurations' + next_steps: + type: array + maxItems: 5 + items: + $ref: '#/components/schemas/AssessmentNextStep' + decided_at: + $ref: '#/components/schemas/Timestamp' + AssessmentGradeAvailabilityStatus: + type: string + description: |- + Whether an attempt for the grade can start now. + + - available: CreateMyAssessmentAttempt can start it. + - active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`. + - cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it. + - insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families. + enum: + - available + - active_attempt + - cooldown + - insufficient_bank + AssessmentGradeAvailability: + type: object + description: Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit. + additionalProperties: false + required: + - grade + - status + - mode + - available_at + - time_limit_seconds + - max_sessions + - max_items + - practice_required + properties: + grade: + $ref: '#/components/schemas/GradeCode' + status: + $ref: '#/components/schemas/AssessmentGradeAvailabilityStatus' + mode: + description: Mode that an attempt would use, or null when the status is `insufficient_bank`. + oneOf: + - $ref: '#/components/schemas/AssessmentMode' + - type: 'null' + available_at: + description: When the status is `cooldown`, the first time the attempt can start; otherwise null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + time_limit_seconds: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: Time from the start to `expires_at`. + max_sessions: + type: + - integer + - 'null' + format: int32 + minimum: 1 + maximum: 10 + description: Session limit within the time limit. + max_items: + type: + - integer + - 'null' + format: int32 + minimum: 1 + maximum: 100 + description: Item limit, as in `AssessmentProgress.max_items`. + practice_required: + type: + - boolean + - 'null' + description: Whether the attempt would include a main code practice. + AssessmentSpecializationAvailability: + type: object + description: Assessment state of one questionnaire specialization. Specializations are assessed independently, with independent retry intervals. + additionalProperties: false + required: + - specialization + - confirmed_grade + - active_attempt_id + - grades + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + confirmed_grade: + description: Currently confirmed grade of the specialization, or null. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + active_attempt_id: + type: + - string + - 'null' + format: uuid + description: Identifier of the active attempt of the specialization, or null. + grades: + type: array + maxItems: 10 + description: Every grade of the scale in ascending order. + items: + $ref: '#/components/schemas/AssessmentGradeAvailability' + AssessmentAvailability: + type: object + description: Assessment availability for the specializations of the current candidate's questionnaire, derived at the time of the request. + additionalProperties: false + required: + - specializations + properties: + specializations: + type: array + maxItems: 2 + description: Questionnaire specializations in questionnaire order. + items: + $ref: '#/components/schemas/AssessmentSpecializationAvailability' HealthResponse: type: object additionalProperties: false @@ -1239,6 +2719,15 @@ components: minLength: 1 maxLength: 512 pattern: ^[A-Za-z0-9_-]+$ + AssessmentAttemptId: + name: attempt_id + in: path + required: true + description: Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b headers: ETag: description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version. @@ -1494,6 +2983,77 @@ components: examples: version_conflict: $ref: '#/components/examples/VersionConflict' + AssessmentAttemptCreateValidationFailed: + description: 'The body does not match the contract or violates an assessment rule: an unknown specialization, grade, or task language, an unknown field such as mode or seed, a specialization that is not in the questionnaire, or a task language that the published bank does not offer; code validation_failed with body pointers. Nothing was created, and the outcome is not stored under the Idempotency-Key.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + specialization_not_in_questionnaire: + $ref: '#/components/examples/AssessmentSpecializationNotInQuestionnaire' + AssessmentAnswerValidationFailed: + description: 'The body does not match the contract or the answer does not fit the item: a format other than the item format, an option, element, or line that the item does not have, an order that is not a permutation of every element, more selections than the item allows, a text longer than the item allows, a language that the practice does not offer, or an unknown field such as score or duration; code validation_failed with body pointers. When the decoder does not record the path of a nested field, the pointer is the whole body. Nothing was stored, and the outcome is not stored under the Idempotency-Key.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + unknown_option: + $ref: '#/components/examples/AssessmentAnswerUnknownOption' + score_sent_by_client: + $ref: '#/components/examples/AssessmentAnswerUnknownField' + AssessmentCommandConflict: + description: 'The attempt state does not allow the answer at the current version, code state_conflict: the attempt is terminal or past its limits, the item is not the current item, the item already has a different answer, or the practice has a pending or finished verdict and the submission differs. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was changed in either case; read the attempt to see its state.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/AssessmentItemNotCurrent' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + AssessmentFinalizeConflict: + description: 'The attempt state does not allow finalize at the current version, code state_conflict: items or the main practice are unfinished, a practice verdict is pending, or the attempt ended as expired or insufficient_bank. The problem does not list the unfinished parts, because Problem allows no extension fields; the attempt shows them in `state`, `progress`, `current_item`, and `practices`. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was changed in either case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/AssessmentFinalizeNotReady' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + AssessmentCreateConflict: + description: 'No attempt can start for the category now, code state_conflict: the specialization already has an active attempt, a retry or promotion interval or the attempt limit blocks the grade, or the bank is insufficient. GetMyAssessmentAvailability tells which, with the date when a blocked attempt opens. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was created in either case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/AssessmentAttemptNotAvailable' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + AssessmentResultNotReady: + description: The attempt is still active, so it has no result yet; code state_conflict. The attempt state tells what remains to be done. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/AssessmentResultNotReady' + AssessmentVersionConflict: + description: '`expected_version` is not the current attempt version; code version_conflict. Nothing was changed, and the outcome is not stored under the Idempotency-Key; read the attempt again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/AssessmentStaleVersion' securitySchemes: sessionCookie: type: apiKey @@ -1924,6 +3484,876 @@ components: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 3e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b + AssessmentAvailability: + summary: Backend open in demo_basic, Network Engineer blocked + description: Illustrative values. Backend junior and middle can start in the demo_basic mode, with their limits shown before the start; intern and senior have no sufficient bank. Network Engineer junior waits for its same-grade retry interval after an unconfirmed attempt. + value: + specializations: + - specialization: backend + confirmed_grade: null + active_attempt_id: null + grades: + - grade: intern + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - grade: junior + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 12 + practice_required: false + - grade: middle + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 12 + practice_required: false + - grade: senior + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - specialization: network_engineer + confirmed_grade: null + active_attempt_id: null + grades: + - grade: intern + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - grade: junior + status: cooldown + mode: demo_basic + available_at: '2026-11-12T00:00:00Z' + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 10 + practice_required: false + - grade: middle + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 10 + practice_required: false + - grade: senior + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + AssessmentAttemptCreateBackendJunior: + summary: Start Backend junior with Go tasks + value: + specialization: backend + target_grade: junior + task_language: go + AssessmentAttemptCreated: + summary: New demo_basic attempt with its first item + description: The server chose demo_basic from the published bank and fixed the policy, bank, and algorithm versions; creation started session 1. A retry of this create with the same Idempotency-Key and body within 24 hours replays exactly this 201 response and creates nothing; read the attempt for its current state. The attempt has no practice, because code practice stays disabled until the sandbox isolation is verified. + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 1 + specialization: backend + target_grade: junior + task_language: go + mode: demo_basic + state: in_progress + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: '2026-10-08T10:00:00Z' + expires_at: '2026-10-11T10:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 0 + max_items: 12 + current_item: + id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01 + sequence: 1 + prompt: Какой HTTP-статус вернуть, если запрос валиден, но ресурс находится в состоянии, не допускающем операцию? + content: + format: choice + multiple: false + options: + - id: k7 + text: '400' + - id: p2 + text: '404' + - id: x9 + text: '409' + - id: c4 + text: '500' + practices: [] + AssessmentSpecializationNotInQuestionnaire: + summary: The specialization is not in the questionnaire + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c + errors: + - in: body + pointer: /specialization + code: invalid + message: The value does not match the contract. + AssessmentAttemptNotAvailable: + summary: No attempt can start for the category now + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 3d4e5f6a-7b8c-4d9e-8f0a-1b2c3d4e5f6a + AssessmentAttemptResumed: + summary: Adaptive attempt resumed on its sixth item in session 2 + description: A reload or a new session returns the same item instance with the same lines; nothing tells whether the five earlier answers were correct, and seed items look like scored ones. The retest started from the previous ability estimate of the specialization. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 7 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: in_progress + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 5 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06 + sequence: 6 + prompt: Найдите строку, из-за которой соединения с базой данных не возвращаются в пул. + content: + format: find_error + syntax: python + max_selections: 1 + lines: + - number: 1 + text: 'def load_user(pool, user_id):' + - number: 2 + text: ' conn = pool.acquire()' + - number: 3 + text: ' row = conn.fetchrow(QUERY, user_id)' + - number: 4 + text: ' if row is None:' + - number: 5 + text: ' raise NotFound(user_id)' + - number: 6 + text: ' pool.release(conn)' + - number: 7 + text: ' return row' + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null + AssessmentAttemptPracticePending: + summary: Item part finished, main practice not submitted + description: The adaptive stop rule ended the item part after 14 items, but no grade is decided until the main practice has a finished verdict. The current item is the practice; hidden checks and seeds are not part of it. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 16 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + sequence: 15 + prompt: 'Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу.' + content: + format: practice + languages: + - python + max_source_length: 20000 + public_examples: + - input: '[[1,3],[2,6],[8,10]]' + expected_output: '[[1,6],[8,10]]' + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null + AssessmentAttemptPracticeVerdictPending: + summary: Practice submitted, verdict pending in the sandbox + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 17 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: pending + submitted_at: '2026-11-20T10:05:00Z' + verdict: null + failure_reason: null + AssessmentAttemptSandboxFailed: + summary: Sandbox queue was full; the practice can be submitted again + description: The failure does not depend on the solution and consumes nothing. The practice item is current again; a resubmission, with the same or a different solution, queues it again and advances the version. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 18 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + sequence: 15 + prompt: 'Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу.' + content: + format: practice + languages: + - python + max_source_length: 20000 + public_examples: + - input: '[[1,3],[2,6],[8,10]]' + expected_output: '[[1,6],[8,10]]' + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: failed + submitted_at: '2026-11-20T10:05:00Z' + verdict: null + failure_reason: sandbox_busy + AssessmentAttemptReadyToFinalize: + summary: Main practice verdict finished, ready to finalize + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 20 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: ready_to_finalize + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: finished + submitted_at: '2026-11-20T10:09:00Z' + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + failure_reason: null + AssessmentAttemptAdditionalPracticePending: + summary: Finalize offered an additional practice in the same attempt + description: 'The probability of reaching middle was in the band below confirmation, so finalize decided nothing yet: it appended an additional practice and returned the attempt instead of a result. The attempt keeps its time and session limits and spends no new attempt. Submitting the additional practice leads back to ready_to_finalize; finalizing now declines it and gives not_confirmed. A retry of that finalize with a new key and the old expected_version 20 answers 412 and cannot decline by accident.' + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 21 + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + state: additional_practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0 + sequence: 16 + prompt: Реализуйте LRU-кеш с операциями get и put за O(1). + content: + format: practice + languages: + - python + max_source_length: 20000 + public_examples: + - input: put(1,1); put(2,2); get(1); put(3,3); get(2) + expected_output: 1, -1 + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: finished + submitted_at: '2026-11-20T10:09:00Z' + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + failure_reason: null + - kind: additional + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0 + status: not_started + submitted_at: null + verdict: null + failure_reason: null + AssessmentAttemptCompleted: + summary: demo_basic attempt finalized; read the result next + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 14 + specialization: backend + target_grade: junior + task_language: go + mode: demo_basic + state: completed + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: '2026-10-08T10:00:00Z' + expires_at: '2026-10-11T10:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: '2026-10-08T10:24:00Z' + progress: + answered_items: 12 + max_items: 12 + current_item: null + practices: [] + AssessmentAttemptInsufficientBank: + summary: Attempt ended because the bank could not cover the blueprint + description: The bank ran out of unseen families for a required domain within the item limit. The attempt ended without a confirmed grade instead of repeating a family; its result has outcome not_determined, and it does not count against the retry rules. + value: + id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d + version: 10 + specialization: network_engineer + target_grade: middle + task_language: null + mode: adaptive + state: insufficient_bank + versions: + policy_version: 2 + bank_version: network.2026-11.1 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-21T12:00:00Z' + expires_at: '2026-11-24T12:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: '2026-11-21T12:31:00Z' + progress: + answered_items: 8 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null + AssessmentChoiceAnswer: + summary: Answer item 1 of version 1 + value: + expected_version: 1 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01 + answer: + format: choice + option_ids: + - x9 + AssessmentOrderAnswer: + summary: Answer item 2 with every element once + value: + expected_version: 2 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02 + answer: + format: order + element_ids: + - a7 + - b1 + - c2 + - d3 + AssessmentNumberAnswer: + summary: Number answer + value: + expected_version: 3 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03 + answer: + format: number + number: 254 + AssessmentStringAnswer: + summary: String answer + value: + expected_version: 4 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d04 + answer: + format: string + text: Retry-After + AssessmentFindErrorAnswer: + summary: Find-error answer for the resumed item + value: + expected_version: 7 + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06 + answer: + format: find_error + line_numbers: + - 5 + AssessmentConfigurationAnswer: + summary: Configuration answer + value: + expected_version: 7 + item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c07 + answer: + format: configuration + config: |- + interface GigabitEthernet0/1 + ip access-group BLOCK_TELNET in + AssessmentPracticeAnswer: + summary: Main practice solution + description: Sent with expected_version 16 for the first submission. After a failed verdict the client sends it again with the current version, such as 18 in AssessmentAttemptSandboxFailed; the same source then queues again. + value: + expected_version: 16 + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + answer: + format: practice + language: python + source_code: |- + def merge_intervals(intervals): + result = [] + for start, end in sorted(intervals): + if result and start <= result[-1][1]: + result[-1][1] = max(result[-1][1], end) + else: + result.append([start, end]) + return result + AssessmentAnswerAccepted: + summary: Answer to item 1 stored; item 2 follows + description: The answer of AssessmentChoiceAnswer was stored and the version advanced from 1 to 2. The response does not say whether the answer was correct. A retry with the same Idempotency-Key replays exactly this response. Sending the same answer to item 1 again, even with a new key or the older expected_version 1, stores nothing and returns 200 with the current attempt. AssessmentOrderAnswer answers item 2 next. + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 2 + specialization: backend + target_grade: junior + task_language: go + mode: demo_basic + state: in_progress + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: '2026-10-08T10:00:00Z' + expires_at: '2026-10-11T10:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 1 + max_items: 12 + current_item: + id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02 + sequence: 2 + prompt: Упорядочите шаги обработки запроса в обработчике HTTP. + content: + format: order + elements: + - id: d3 + text: Записать ответ + - id: a7 + text: Проверить сессию + - id: c2 + text: Выполнить операцию + - id: b1 + text: Разобрать и проверить тело + practices: [] + AssessmentAnswerUnknownOption: + summary: The selected option does not belong to the item + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 0a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d + errors: + - in: body + pointer: /answer/option_ids/0 + code: invalid + message: The value does not match the contract. + AssessmentAnswerUnknownField: + summary: The client sent its own score + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 1b2c3d4e-5f6a-4b7c-8d8e-9f0a1b2c3d4e + errors: + - in: body + pointer: '' + code: invalid + message: The value does not match the contract. + AssessmentItemNotCurrent: + summary: The answered item is not the current item, or it already has another answer + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 2c3d4e5f-6a7b-4c8d-9e9f-0a1b2c3d4e5f + AssessmentStaleVersion: + summary: The command carried a stale expected_version + description: Another tab or device changed the attempt after the client read version 1. Nothing was stored; the client reads the attempt again and continues from its current item. The repository answers a stale version with 412, not 409. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c + AssessmentFinalization: + summary: Finalize version 20 + value: + expected_version: 20 + AssessmentFinalizeNotReady: + summary: Premature finalize; the problem does not list the unfinished parts + description: 'Problem has no extension fields. The client reads what remains from the attempt: `state`, `progress`, `current_item`, and `practices`.' + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e + AssessmentDemoBasicResult: + summary: demo_basic result with a confirmed grade and no uncertainty + description: demo_basic computes no ability estimate, so `uncertainty` and `strength` are null rather than zero, and no percentile is shown. The pass mark comes from basic grading policy version 1, and the limitations name the uncalibrated thresholds, the demo bank, and the missing practice. A first confirmation is not a promotion, so the higher grade can be tested at once. The result never changes; a repeated finalize returns the completed attempt, and this read returns the same result. + value: + attempt_id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + specialization: backend + target_grade: junior + task_language: go + mode: demo_basic + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + outcome: confirmed + not_determined_reason: null + confirmed_grade: junior + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - demo_bank + - practice_not_included + - unproctored + uncertainty: null + basic_score: + points: 9 + max_points: 12 + pass_points: 8 + practices: [] + gaps: [] + durations: + items_seconds: 1260 + practice_seconds: null + next_steps: + - action: take_higher_grade + grade: middle + available_at: null + decided_at: '2026-10-08T10:24:00Z' + AssessmentAdaptiveResult: + summary: Adaptive promotion confirmed with medium strength + description: Illustrative values, continuing AssessmentAttemptAdditionalPracticePending. The additional practice raised P_G to 0.84, in the medium band of the policy version, so the grade is confirmed with medium strength. The candidate already had junior, so this is a promotion, and the next one waits for the promotion interval. The thresholds are uncalibrated until the pilot. + value: + attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + task_language: python + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: confirmed + not_determined_reason: null + confirmed_grade: middle + previous_confirmed_grade: junior + strength: medium + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - unproctored + uncertainty: + theta: 0.62 + standard_error: 0.24 + interval_95: + low: 0.15 + high: 1.09 + p_grade: 0.84 + basic_score: null + practices: + - kind: main + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + - kind: additional + verdict: + score: 3 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: true + gaps: + - domain: concurrency + title: Конкурентность + durations: + items_seconds: 1980 + practice_seconds: 1500 + next_steps: + - action: take_higher_grade + grade: senior + available_at: '2027-02-18T10:30:00Z' + decided_at: '2026-11-20T10:30:00Z' + AssessmentNotConfirmedResult: + summary: Adaptive attempt not confirmed after the additional practice + description: P_G stayed below 0.80 after the additional practice, so middle is not confirmed, and the candidate keeps no confirmed grade. After a failure, including the first test, junior can be tested at once; accepting junior on the evidence of this attempt is offered; middle opens again after the same-grade retry interval. + value: + attempt_id: 01928f7d-7777-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + task_language: go + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: not_confirmed + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - unproctored + uncertainty: + theta: 0.21 + standard_error: 0.25 + interval_95: + low: -0.28 + high: 0.7 + p_grade: 0.62 + basic_score: null + practices: + - kind: main + verdict: + score: 1 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: false + - group: 3 + passed: false + - kind: additional + verdict: + score: 1 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: false + - group: 3 + passed: false + gaps: + - domain: databases + title: Базы данных + durations: + items_seconds: 2100 + practice_seconds: 1800 + next_steps: + - action: take_lower_grade + grade: junior + available_at: null + - action: accept_lower_grade + grade: junior + available_at: null + - action: retake_same_grade + grade: middle + available_at: '2026-12-22T11:00:00Z' + decided_at: '2026-11-22T11:00:00Z' + AssessmentInsufficientBankResult: + summary: Attempt without a decision because the bank was insufficient + value: + attempt_id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d + specialization: network_engineer + target_grade: middle + task_language: null + mode: adaptive + versions: + policy_version: 2 + bank_version: network.2026-11.1 + algorithm_version: irt-1pl-eap.1 + outcome: not_determined + not_determined_reason: insufficient_bank + confirmed_grade: null + previous_confirmed_grade: junior + strength: null + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - unproctored + uncertainty: null + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 1860 + practice_seconds: null + next_steps: [] + decided_at: '2026-11-21T12:31:00Z' + AssessmentResultNotReady: + summary: The attempt has no result yet + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 4e5f6a7b-8c9d-4e0f-9a1b-2c3d4e5f6a7b StateConflict: summary: The resource state does not allow the operation value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 07ca05f..88b9272 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -21,6 +21,11 @@ tags: Data of the current candidate, such as the questionnaire with the chosen specializations and self-assessed grades. Confirmed grades and categories come only from assessment results. + - name: assessment + description: >- + Assessment attempts of the current candidate: availability, start and + resume, answers and the code practice, finalization, and the result. + Answers, keys, and attempt history are visible only to the candidate. # Operations require a session unless they declare `security: []`, so a new # operation that omits security is protected by default. security: @@ -46,6 +51,18 @@ paths: $ref: ./routes/catalog_specializations.yml /api/v1/me/questionnaire: $ref: ./routes/candidate_questionnaire.yml + /api/v1/me/assessment-availability: + $ref: ./routes/candidate_assessment_availability.yml + /api/v1/me/assessment-attempts: + $ref: ./routes/candidate_assessment_attempts.yml + /api/v1/me/assessment-attempts/{attempt_id}: + $ref: ./routes/candidate_assessment_attempt.yml + /api/v1/me/assessment-attempts/{attempt_id}/answers: + $ref: ./routes/candidate_assessment_attempt_answers.yml + /api/v1/me/assessment-attempts/{attempt_id}/finalize: + $ref: ./routes/candidate_assessment_attempt_finalize.yml + /api/v1/me/assessment-attempts/{attempt_id}/result: + $ref: ./routes/candidate_assessment_attempt_result.yml components: schemas: Problem: @@ -134,6 +151,120 @@ components: $ref: ./components/schemas.yml#/CandidateQuestionnaire CandidateQuestionnaireUpdate: $ref: ./components/schemas.yml#/CandidateQuestionnaireUpdate + AssessmentMode: + $ref: ./components/schemas.yml#/AssessmentMode + AssessmentAttemptVersion: + $ref: ./components/schemas.yml#/AssessmentAttemptVersion + AssessmentAttemptState: + $ref: ./components/schemas.yml#/AssessmentAttemptState + AssessmentVersionLabel: + $ref: ./components/schemas.yml#/AssessmentVersionLabel + AssessmentVersions: + $ref: ./components/schemas.yml#/AssessmentVersions + AssessmentSessions: + $ref: ./components/schemas.yml#/AssessmentSessions + AssessmentAttemptCreate: + $ref: ./components/schemas.yml#/AssessmentAttemptCreate + AssessmentItemId: + $ref: ./components/schemas.yml#/AssessmentItemId + AssessmentOptionId: + $ref: ./components/schemas.yml#/AssessmentOptionId + AssessmentOption: + $ref: ./components/schemas.yml#/AssessmentOption + ChoiceItemContent: + $ref: ./components/schemas.yml#/ChoiceItemContent + NumberItemContent: + $ref: ./components/schemas.yml#/NumberItemContent + StringItemContent: + $ref: ./components/schemas.yml#/StringItemContent + OrderItemContent: + $ref: ./components/schemas.yml#/OrderItemContent + CodeLine: + $ref: ./components/schemas.yml#/CodeLine + FindErrorItemContent: + $ref: ./components/schemas.yml#/FindErrorItemContent + ConfigurationItemContent: + $ref: ./components/schemas.yml#/ConfigurationItemContent + PracticeExample: + $ref: ./components/schemas.yml#/PracticeExample + PracticeItemContent: + $ref: ./components/schemas.yml#/PracticeItemContent + ItemContent: + $ref: ./components/schemas.yml#/ItemContent + AssessmentItem: + $ref: ./components/schemas.yml#/AssessmentItem + AssessmentProgress: + $ref: ./components/schemas.yml#/AssessmentProgress + PracticeKind: + $ref: ./components/schemas.yml#/PracticeKind + PracticeStatus: + $ref: ./components/schemas.yml#/PracticeStatus + PracticeFailureReason: + $ref: ./components/schemas.yml#/PracticeFailureReason + PracticeGroupResult: + $ref: ./components/schemas.yml#/PracticeGroupResult + PracticeVerdict: + $ref: ./components/schemas.yml#/PracticeVerdict + AssessmentPractice: + $ref: ./components/schemas.yml#/AssessmentPractice + AssessmentAttempt: + $ref: ./components/schemas.yml#/AssessmentAttempt + ChoiceAnswer: + $ref: ./components/schemas.yml#/ChoiceAnswer + NumberAnswer: + $ref: ./components/schemas.yml#/NumberAnswer + StringAnswer: + $ref: ./components/schemas.yml#/StringAnswer + OrderAnswer: + $ref: ./components/schemas.yml#/OrderAnswer + FindErrorAnswer: + $ref: ./components/schemas.yml#/FindErrorAnswer + ConfigurationAnswer: + $ref: ./components/schemas.yml#/ConfigurationAnswer + PracticeAnswer: + $ref: ./components/schemas.yml#/PracticeAnswer + AssessmentAnswer: + $ref: ./components/schemas.yml#/AssessmentAnswer + AssessmentAnswerSubmission: + $ref: ./components/schemas.yml#/AssessmentAnswerSubmission + AssessmentFinalization: + $ref: ./components/schemas.yml#/AssessmentFinalization + AssessmentOutcome: + $ref: ./components/schemas.yml#/AssessmentOutcome + AssessmentNotDeterminedReason: + $ref: ./components/schemas.yml#/AssessmentNotDeterminedReason + AssessmentStrength: + $ref: ./components/schemas.yml#/AssessmentStrength + CalibrationStatus: + $ref: ./components/schemas.yml#/CalibrationStatus + AssessmentLimitation: + $ref: ./components/schemas.yml#/AssessmentLimitation + AssessmentInterval: + $ref: ./components/schemas.yml#/AssessmentInterval + AssessmentUncertainty: + $ref: ./components/schemas.yml#/AssessmentUncertainty + BasicScore: + $ref: ./components/schemas.yml#/BasicScore + AssessmentGap: + $ref: ./components/schemas.yml#/AssessmentGap + AssessmentDurations: + $ref: ./components/schemas.yml#/AssessmentDurations + AssessmentPracticeResult: + $ref: ./components/schemas.yml#/AssessmentPracticeResult + AssessmentNextAction: + $ref: ./components/schemas.yml#/AssessmentNextAction + AssessmentNextStep: + $ref: ./components/schemas.yml#/AssessmentNextStep + AssessmentResult: + $ref: ./components/schemas.yml#/AssessmentResult + AssessmentGradeAvailabilityStatus: + $ref: ./components/schemas.yml#/AssessmentGradeAvailabilityStatus + AssessmentGradeAvailability: + $ref: ./components/schemas.yml#/AssessmentGradeAvailability + AssessmentSpecializationAvailability: + $ref: ./components/schemas.yml#/AssessmentSpecializationAvailability + AssessmentAvailability: + $ref: ./components/schemas.yml#/AssessmentAvailability parameters: IdempotencyKey: $ref: ./components/parameters.yml#/IdempotencyKey @@ -143,6 +274,8 @@ components: $ref: ./components/parameters.yml#/PageLimit PageCursor: $ref: ./components/parameters.yml#/PageCursor + AssessmentAttemptId: + $ref: ./components/parameters.yml#/AssessmentAttemptId headers: ETag: $ref: ./components/headers.yml#/ETag @@ -197,6 +330,20 @@ components: $ref: ./components/responses.yml#/QuestionnaireValidationFailed QuestionnaireVersionConflict: $ref: ./components/responses.yml#/QuestionnaireVersionConflict + AssessmentAttemptCreateValidationFailed: + $ref: ./components/responses.yml#/AssessmentAttemptCreateValidationFailed + AssessmentAnswerValidationFailed: + $ref: ./components/responses.yml#/AssessmentAnswerValidationFailed + AssessmentCommandConflict: + $ref: ./components/responses.yml#/AssessmentCommandConflict + AssessmentFinalizeConflict: + $ref: ./components/responses.yml#/AssessmentFinalizeConflict + AssessmentCreateConflict: + $ref: ./components/responses.yml#/AssessmentCreateConflict + AssessmentResultNotReady: + $ref: ./components/responses.yml#/AssessmentResultNotReady + AssessmentVersionConflict: + $ref: ./components/responses.yml#/AssessmentVersionConflict securitySchemes: sessionCookie: type: apiKey diff --git a/api/core/routes/candidate_assessment_attempt.yml b/api/core/routes/candidate_assessment_attempt.yml new file mode 100644 index 0000000..77c2e6d --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt.yml @@ -0,0 +1,50 @@ +get: + operationId: GetMyAssessmentAttempt + summary: Read or resume an assessment attempt of the current candidate. + description: |- + Requires the session cookie of a candidate account. Returns the attempt with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + + Reading an active attempt counts as activity: after the previous session ended it starts the next session, and when that would exceed the session limit it starts none and the attempt becomes `expired`. Before it answers, the server commits any transition that is due, with a new version: past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is declined and the attempt becomes `completed`, and the other active states become `expired`; a practice still `pending` is graded first. The client polls this operation while a practice is `pending`. Reading a terminal attempt changes nothing. + + The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers or the attempt history. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + responses: + "200": + description: The attempt. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + adaptive_resumed: + $ref: ../components/examples.yml#/AssessmentAttemptResumed + practice_pending: + $ref: ../components/examples.yml#/AssessmentAttemptPracticePending + practice_verdict_pending: + $ref: ../components/examples.yml#/AssessmentAttemptPracticeVerdictPending + sandbox_failed: + $ref: ../components/examples.yml#/AssessmentAttemptSandboxFailed + ready_to_finalize: + $ref: ../components/examples.yml#/AssessmentAttemptReadyToFinalize + additional_practice_pending: + $ref: ../components/examples.yml#/AssessmentAttemptAdditionalPracticePending + completed: + $ref: ../components/examples.yml#/AssessmentAttemptCompleted + insufficient_bank: + $ref: ../components/examples.yml#/AssessmentAttemptInsufficientBank + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_answers.yml b/api/core/routes/candidate_assessment_attempt_answers.yml new file mode 100644 index 0000000..9e27268 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_answers.yml @@ -0,0 +1,83 @@ +post: + operationId: SubmitMyAssessmentAnswer + summary: Answer the current item or submit a practice of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision. + + The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. + + Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation. + + Repeats and conflicts, per item: + - A retry with the same Idempotency-Key and body within 24 hours replays the stored response. + - Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. + - A different answer for an item that already has one answers 409 state_conflict when `expected_version` is current; with a stale version the version check comes first and answers 412. + - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A submission with the same or a different solution, with the current `expected_version`, queues it again and advances the version. + + Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is kept for commands that the attempt state does not allow at the current version. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; the server first commits any due transition such as expiry, and the request counts as activity for the session limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAnswerSubmission + examples: + choice: + $ref: ../components/examples.yml#/AssessmentChoiceAnswer + order: + $ref: ../components/examples.yml#/AssessmentOrderAnswer + number: + $ref: ../components/examples.yml#/AssessmentNumberAnswer + string: + $ref: ../components/examples.yml#/AssessmentStringAnswer + find_error: + $ref: ../components/examples.yml#/AssessmentFindErrorAnswer + configuration: + $ref: ../components/examples.yml#/AssessmentConfigurationAnswer + practice: + $ref: ../components/examples.yml#/AssessmentPracticeAnswer + responses: + "200": + description: >- + The answer was stored, or this exact answer was already stored, and + the response is the attempt with the next item. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + accepted: + $ref: ../components/examples.yml#/AssessmentAnswerAccepted + practice_submitted: + $ref: ../components/examples.yml#/AssessmentAttemptPracticeVerdictPending + "400": + $ref: ../components/responses.yml#/AssessmentAnswerValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentCommandConflict + "412": + $ref: ../components/responses.yml#/AssessmentVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_finalize.yml b/api/core/routes/candidate_assessment_attempt_finalize.yml new file mode 100644 index 0000000..b4cad86 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_finalize.yml @@ -0,0 +1,67 @@ +post: + operationId: FinalizeMyAssessmentAttempt + summary: Ask for the grade decision of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the result: the decision may continue the attempt, and one response type keeps that unambiguous for every generated client. When the returned state is `completed`, the client reads the result with GetMyAssessmentResult. + + Allowed in `ready_to_finalize`, where every required part is done, and in `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: + - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and completes the attempt. It never offers an additional practice. + - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the demo policy) on the first finalize, while time and sessions remain, completes nothing: the server appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no new attempt. The next finalize, after its verdict, decides with the added evidence; a probability still below confirmation gives `not_confirmed`. An attempt offers at most one additional practice. + - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the current evidence. A retry of the first finalize with a new key cannot decline by accident: it carries the version from before the offer and answers 412. + + A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, the server finalizes `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also answers 200 with the `completed` attempt. + + An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentFinalization + examples: + finalize: + $ref: ../components/examples.yml#/AssessmentFinalization + responses: + "200": + description: >- + The attempt after the decision: `completed`, with the result available + from GetMyAssessmentResult, or `additional_practice_pending` when an + adaptive attempt offers an additional practice. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + demo_basic_completed: + $ref: ../components/examples.yml#/AssessmentAttemptCompleted + additional_practice_offered: + $ref: ../components/examples.yml#/AssessmentAttemptAdditionalPracticePending + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentFinalizeConflict + "412": + $ref: ../components/responses.yml#/AssessmentVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_result.yml b/api/core/routes/candidate_assessment_attempt_result.yml new file mode 100644 index 0000000..e42f3c3 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_result.yml @@ -0,0 +1,44 @@ +get: + operationId: GetMyAssessmentResult + summary: Read the result of an assessment attempt of the current candidate. + description: |- + Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and algorithm versions, the decision, the previously confirmed grade, the calibration status and limitations of the method, the uncertainty where the method computes it, the practice verdicts, the weak domains, the working time as a separate label, and the next steps that the server allows. A later policy, bank, or algorithm version never changes it. + + Fields that the method does not compute are null and never zero: a `demo_basic` result has null `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. + + An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. The server first commits any due transition, so an attempt past its limits is read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + responses: + "200": + description: The result. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentResult + examples: + demo_basic: + $ref: ../components/examples.yml#/AssessmentDemoBasicResult + adaptive_confirmed: + $ref: ../components/examples.yml#/AssessmentAdaptiveResult + adaptive_not_confirmed: + $ref: ../components/examples.yml#/AssessmentNotConfirmedResult + insufficient_bank: + $ref: ../components/examples.yml#/AssessmentInsufficientBankResult + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentResultNotReady + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempts.yml b/api/core/routes/candidate_assessment_attempts.yml new file mode 100644 index 0000000..426670d --- /dev/null +++ b/api/core/routes/candidate_assessment_attempts.yml @@ -0,0 +1,58 @@ +post: + operationId: CreateMyAssessmentAttempt + summary: Start an assessment attempt for a category of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the questionnaire and a target grade, and the task language. The server picks the mode from the published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the time and session limits, and the item variants in one transaction; the client never sends a mode, a seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. + + A specialization has at most one active attempt. A new attempt cannot start while one is active, during a retry or promotion interval or past the attempt limit of the policy, or when the bank is insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a failure, including the first test, a lower grade can be tested at once. An attempt that ends as `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the same-grade retry interval; one that ends as `insufficient_bank` or with the reason `sandbox_unavailable` counts toward neither. + + The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no command. Within them the attempt is also bounded by the item limit of the policy. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 state_conflict response and creates nothing, so a lost response never creates a second attempt. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` for a specialization that is not in the questionnaire or `/task_language` for a language that the bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with Retry-After before any of them; it is not stored. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttemptCreate + examples: + backend_junior_go: + $ref: ../components/examples.yml#/AssessmentAttemptCreateBackendJunior + responses: + "201": + description: >- + The attempt was created, or a retry with the same Idempotency-Key + replayed its creation. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + demo_basic_created: + $ref: ../components/examples.yml#/AssessmentAttemptCreated + "400": + $ref: ../components/responses.yml#/AssessmentAttemptCreateValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "409": + $ref: ../components/responses.yml#/AssessmentCreateConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_availability.yml b/api/core/routes/candidate_assessment_availability.yml new file mode 100644 index 0000000..7350905 --- /dev/null +++ b/api/core/routes/candidate_assessment_availability.yml @@ -0,0 +1,32 @@ +get: + operationId: GetMyAssessmentAvailability + summary: Read which assessment attempts the current candidate can start. + description: |- + Requires the session cookie of a candidate account; the candidate comes from the session. For each specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every grade whether an attempt can start now, in which mode, and with which limits: the time limit, the session limit, the item limit, and whether a code practice is required. The client shows them before the start, together with the method and the signals that are collected, and resumes an active attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt. + + `insufficient_bank` is the state of a category whose bank is not published or has too few families that this candidate has not seen; the server limits attempts instead of repeating families. `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with that date and offer support. Specializations and their retry intervals are independent. Attempts that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations and never cause a `cooldown`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - assessment + responses: + "200": + description: Assessment availability of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAvailability + examples: + backend_and_network_engineer: + $ref: ../components/examples.yml#/AssessmentAvailability + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index 7527ae9..133a8be 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -21,6 +21,8 @@ var regexMap = map[string]ogenregex.Regexp{ "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), "^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"), "^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"), + "^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"), + "^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"), "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), "^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"), "^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="), diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index dc2760b..94326c1 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -208,6 +208,549 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h } } +// handleCreateMyAssessmentAttemptRequest handles CreateMyAssessmentAttempt operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the +// questionnaire and a target grade, and the task language. The server picks the mode from the +// published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the +// time and session limits, and the item variants in one transaction; the client never sends a mode, a +// seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test +// starts and adds no points. An adaptive retest starts from the previous ability estimate of the +// specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the +// measurement over. +// +// A specialization has at most one active attempt. A new attempt cannot start while one is active, +// during a retry or promotion interval or past the attempt limit of the policy, or when the bank is +// insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. +// GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a +// failure, including the first test, a lower grade can be tested at once. An attempt that ends as +// `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the +// same-grade retry interval; one that ends as `insufficient_bank` or with the reason +// `sandbox_unavailable` counts toward neither. +// +// The limits are server-side: `expires_at` and `sessions` come from the policy version, the client +// clock never extends them, and after them the attempt accepts no command. Within them the attempt is +// also bounded by the item limit of the policy. +// +// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 +// state_conflict response and creates nothing, so a lost response never creates a second attempt. A +// different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a +// corrected retry is evaluated again. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 +// idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` +// for a specialization that is not in the questionnaire or `/task_language` for a language that the +// bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with +// Retry-After before any of them; it is not stored. +// +// POST /api/v1/me/assessment-attempts +func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CreateMyAssessmentAttempt"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateMyAssessmentAttemptOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: CreateMyAssessmentAttemptOperation, + ID: "CreateMyAssessmentAttempt", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, CreateMyAssessmentAttemptOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, CreateMyAssessmentAttemptOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeCreateMyAssessmentAttemptParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeCreateMyAssessmentAttemptRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response CreateMyAssessmentAttemptRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CreateMyAssessmentAttemptOperation, + OperationSummary: "Start an assessment attempt for a category of the current candidate.", + OperationID: "CreateMyAssessmentAttempt", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *AssessmentAttemptCreate + Params = CreateMyAssessmentAttemptParams + Response = CreateMyAssessmentAttemptRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackCreateMyAssessmentAttemptParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.CreateMyAssessmentAttempt(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.CreateMyAssessmentAttempt(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeCreateMyAssessmentAttemptResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleFinalizeMyAssessmentAttemptRequest handles FinalizeMyAssessmentAttempt operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the +// result: the decision may continue the attempt, and one response type keeps that unambiguous for +// every generated client. When the returned state is `completed`, the client reads the result with +// GetMyAssessmentResult. +// +// Allowed in `ready_to_finalize`, where every required part is done, and in +// `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server +// decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: +// +// - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and +// completes the attempt. It never offers an additional practice. +// - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection +// completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the +// demo policy) on the first finalize, while time and sessions remain, completes nothing: the server +// appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers +// 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no +// new attempt. The next finalize, after its verdict, decides with the added evidence; a probability +// still below confirmation gives `not_confirmed`. An attempt offers at most one additional +// practice. +// - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the +// current evidence. A retry of the first finalize with a new key cannot decline by accident: it +// carries the version from before the offer and answers 412. +// +// A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the +// same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers +// 200 with that attempt even with a new key or an older `expected_version`; the result is computed +// once. When `expires_at` passes or the session limit is reached, the server finalizes +// `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also +// answers 200 with the `completed` attempt. +// +// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one +// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list +// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A +// stale `expected_version` answers 412 version_conflict, the repository status for a stale version. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), +// the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), +// the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under +// the key; 400 and 412 are not. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/finalize +func (s *Server) handleFinalizeMyAssessmentAttemptRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("FinalizeMyAssessmentAttempt"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/finalize"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), FinalizeMyAssessmentAttemptOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: FinalizeMyAssessmentAttemptOperation, + ID: "FinalizeMyAssessmentAttempt", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, FinalizeMyAssessmentAttemptOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, FinalizeMyAssessmentAttemptOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeFinalizeMyAssessmentAttemptParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeFinalizeMyAssessmentAttemptRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response FinalizeMyAssessmentAttemptRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: FinalizeMyAssessmentAttemptOperation, + OperationSummary: "Ask for the grade decision of an assessment attempt.", + OperationID: "FinalizeMyAssessmentAttempt", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "attempt_id", + In: "path", + }: params.AttemptID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *AssessmentFinalization + Params = FinalizeMyAssessmentAttemptParams + Response = FinalizeMyAssessmentAttemptRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackFinalizeMyAssessmentAttemptParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.FinalizeMyAssessmentAttempt(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.FinalizeMyAssessmentAttempt(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeFinalizeMyAssessmentAttemptResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetConsentTextRequest handles GetConsentText operation. // // Public operation without a session. Returns the current text of a consent that is given before an @@ -879,6 +1422,638 @@ func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w htt } } +// handleGetMyAssessmentAttemptRequest handles GetMyAssessmentAttempt operation. +// +// Requires the session cookie of a candidate account. Returns the attempt with its state, fixed +// versions, time and session limits, progress, the item to answer now, and the practices. A reload, a +// retried request, or a new session returns the same item instance with the same text and option +// order; a lost connection never creates a new attempt. The response never says whether an earlier +// answer was correct and never contains answer keys, item scores, family or variant identifiers, +// seeds, hidden checks, or anti-cheat signals. +// +// Reading an active attempt counts as activity: after the previous session ended it starts the next +// session, and when that would exceed the session limit it starts none and the attempt becomes +// `expired`. Before it answers, the server commits any transition that is due, with a new version: +// past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is +// declined and the attempt becomes `completed`, and the other active states become `expired`; a +// practice still `pending` is graded first. The client polls this operation while a practice is +// `pending`. Reading a terminal attempt changes nothing. +// +// The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 +// not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account +// answers 403 forbidden; no operation gives an employer the answers or the attempt history. +// +// GET /api/v1/me/assessment-attempts/{attempt_id} +func (s *Server) handleGetMyAssessmentAttemptRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyAssessmentAttempt"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyAssessmentAttemptOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetMyAssessmentAttemptOperation, + ID: "GetMyAssessmentAttempt", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentAttemptOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeGetMyAssessmentAttemptParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response GetMyAssessmentAttemptRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyAssessmentAttemptOperation, + OperationSummary: "Read or resume an assessment attempt of the current candidate.", + OperationID: "GetMyAssessmentAttempt", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "attempt_id", + In: "path", + }: params.AttemptID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetMyAssessmentAttemptParams + Response = GetMyAssessmentAttemptRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetMyAssessmentAttemptParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyAssessmentAttempt(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetMyAssessmentAttempt(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetMyAssessmentAttemptResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetMyAssessmentAvailabilityRequest handles GetMyAssessmentAvailability operation. +// +// Requires the session cookie of a candidate account; the candidate comes from the session. For each +// specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every +// grade whether an attempt can start now, in which mode, and with which limits: the time limit, the +// session limit, the item limit, and whether a code practice is required. The client shows them before +// the start, together with the method and the signals that are collected, and resumes an active +// attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt. +// +// `insufficient_bank` is the state of a category whose bank is not published or has too few families +// that this candidate has not seen; the server limits attempts instead of repeating families. +// `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with +// that date and offer support. Specializations and their retry intervals are independent. Attempts +// that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations +// and never cause a `cooldown`. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. +// +// GET /api/v1/me/assessment-availability +func (s *Server) handleGetMyAssessmentAvailabilityRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyAssessmentAvailability"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-availability"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyAssessmentAvailabilityOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetMyAssessmentAvailabilityOperation, + ID: "GetMyAssessmentAvailability", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentAvailabilityOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + + var response GetMyAssessmentAvailabilityRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyAssessmentAvailabilityOperation, + OperationSummary: "Read which assessment attempts the current candidate can start.", + OperationID: "GetMyAssessmentAvailability", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = GetMyAssessmentAvailabilityRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyAssessmentAvailability(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetMyAssessmentAvailability(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetMyAssessmentAvailabilityResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetMyAssessmentResultRequest handles GetMyAssessmentResult operation. +// +// Requires the session cookie of a candidate account. Returns the immutable result of a terminal +// attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and +// algorithm versions, the decision, the previously confirmed grade, the calibration status and +// limitations of the method, the uncertainty where the method computes it, the practice verdicts, the +// weak domains, the working time as a separate label, and the next steps that the server allows. A +// later policy, bank, or algorithm version never changes it. +// +// Fields that the method does not compute are null and never zero: a `demo_basic` result has null +// `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, +// seeds, hidden checks, or anti-cheat signals. +// +// An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active +// and has no result yet. The server first commits any due transition, so an attempt past its limits is +// read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown +// identifier. An employer account answers 403 forbidden; employers see only the current category +// through a separate projection, never this result or the attempt history. +// +// GET /api/v1/me/assessment-attempts/{attempt_id}/result +func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyAssessmentResult"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/result"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyAssessmentResultOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetMyAssessmentResultOperation, + ID: "GetMyAssessmentResult", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentResultOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeGetMyAssessmentResultParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response GetMyAssessmentResultRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyAssessmentResultOperation, + OperationSummary: "Read the result of an assessment attempt of the current candidate.", + OperationID: "GetMyAssessmentResult", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "attempt_id", + In: "path", + }: params.AttemptID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetMyAssessmentResultParams + Response = GetMyAssessmentResultRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetMyAssessmentResultParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyAssessmentResult(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetMyAssessmentResult(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetMyAssessmentResultResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetMyQuestionnaireRequest handles GetMyQuestionnaire operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -2217,3 +3392,291 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo return } } + +// handleSubmitMyAssessmentAnswerRequest handles SubmitMyAssessmentAnswer operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the +// format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or +// `practice`. It never carries a score, a duration, or a correctness flag; the server records the +// times itself and scores the answer with the key of the fixed item instance. Time never enters the +// ability estimate or the grade decision. +// +// The response is the attempt with the next item to answer. It never says whether the answer was +// correct. Items are answered in order and each answer is final. +// +// Practice: an answer with format `practice` submits the solution of the main or the additional +// practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the +// response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. +// Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or +// seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or +// memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure +// could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so +// hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the +// public examples are unlimited apart from the sandbox rate limit and never show hidden group results; +// they are planned as a separate operation. +// +// Repeats and conflicts, per item: +// +// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response. +// - Sending the answer already stored for the item again, even with a new key or an older +// `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. +// Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence +// for `element_ids`, numeric equality for `number`, identical text without normalization for `text` +// and `config`, and the same language with identical source for a practice. +// - A different answer for an item that already has one answers 409 state_conflict when +// `expected_version` is current; with a stale version the version check comes first and answers +// 412. +// - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A +// submission with the same or a different solution, with the current `expected_version`, queues it +// again and advances the version. +// +// Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the +// server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is +// the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is +// kept for commands that the attempt state does not allow at the current version. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), +// the attempt (404 not_found for an unknown attempt or one of another candidate; the server first +// commits any due transition such as expiry, and the request counts as activity for the session +// limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is +// `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is +// not current, the item has a different answer, or the practice verdict is pending or finished), then +// the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). +// Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and +// replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any +// check. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/answers +func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("SubmitMyAssessmentAnswer"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/answers"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), SubmitMyAssessmentAnswerOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: SubmitMyAssessmentAnswerOperation, + ID: "SubmitMyAssessmentAnswer", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, SubmitMyAssessmentAnswerOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, SubmitMyAssessmentAnswerOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeSubmitMyAssessmentAnswerParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeSubmitMyAssessmentAnswerRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response SubmitMyAssessmentAnswerRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: SubmitMyAssessmentAnswerOperation, + OperationSummary: "Answer the current item or submit a practice of an assessment attempt.", + OperationID: "SubmitMyAssessmentAnswer", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "attempt_id", + In: "path", + }: params.AttemptID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *AssessmentAnswerSubmission + Params = SubmitMyAssessmentAnswerParams + Response = SubmitMyAssessmentAnswerRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackSubmitMyAssessmentAnswerParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.SubmitMyAssessmentAnswer(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.SubmitMyAssessmentAnswer(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeSubmitMyAssessmentAnswerResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index cea35aa..ebb886e 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -5,6 +5,14 @@ type ConfirmEmailRes interface { confirmEmailRes() } +type CreateMyAssessmentAttemptRes interface { + createMyAssessmentAttemptRes() +} + +type FinalizeMyAssessmentAttemptRes interface { + finalizeMyAssessmentAttemptRes() +} + type GetConsentTextRes interface { getConsentTextRes() } @@ -17,6 +25,18 @@ type GetCurrentSessionRes interface { getCurrentSessionRes() } +type GetMyAssessmentAttemptRes interface { + getMyAssessmentAttemptRes() +} + +type GetMyAssessmentAvailabilityRes interface { + getMyAssessmentAvailabilityRes() +} + +type GetMyAssessmentResultRes interface { + getMyAssessmentResultRes() +} + type GetMyQuestionnaireRes interface { getMyQuestionnaireRes() } @@ -40,3 +60,7 @@ type ResendEmailVerificationRes interface { type SaveMyQuestionnaireRes interface { saveMyQuestionnaireRes() } + +type SubmitMyAssessmentAnswerRes interface { + submitMyAssessmentAnswerRes() +} diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index 5f86e46..f783799 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -9,6 +9,7 @@ import ( "github.com/go-faster/errors" "github.com/go-faster/jx" + "github.com/google/uuid" "github.com/ogen-go/ogen/json" "github.com/ogen-go/ogen/validate" ) @@ -226,6 +227,4024 @@ func (s *AccountScenario) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AssessmentAnswer as json. +func (s AssessmentAnswer) Encode(e *jx.Encoder) { + switch s.Type { + case ChoiceAnswerAssessmentAnswer: + s.ChoiceAnswer.Encode(e) + case NumberAnswerAssessmentAnswer: + s.NumberAnswer.Encode(e) + case StringAnswerAssessmentAnswer: + s.StringAnswer.Encode(e) + case OrderAnswerAssessmentAnswer: + s.OrderAnswer.Encode(e) + case FindErrorAnswerAssessmentAnswer: + s.FindErrorAnswer.Encode(e) + case ConfigurationAnswerAssessmentAnswer: + s.ConfigurationAnswer.Encode(e) + case PracticeAnswerAssessmentAnswer: + s.PracticeAnswer.Encode(e) + } +} + +func (s AssessmentAnswer) encodeFields(e *jx.Encoder) { + switch s.Type { + case ChoiceAnswerAssessmentAnswer: + s.ChoiceAnswer.encodeFields(e) + case NumberAnswerAssessmentAnswer: + s.NumberAnswer.encodeFields(e) + case StringAnswerAssessmentAnswer: + s.StringAnswer.encodeFields(e) + case OrderAnswerAssessmentAnswer: + s.OrderAnswer.encodeFields(e) + case FindErrorAnswerAssessmentAnswer: + s.FindErrorAnswer.encodeFields(e) + case ConfigurationAnswerAssessmentAnswer: + s.ConfigurationAnswer.encodeFields(e) + case PracticeAnswerAssessmentAnswer: + s.PracticeAnswer.encodeFields(e) + } +} + +// Decode decodes AssessmentAnswer from json. +func (s *AssessmentAnswer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentAnswer to nil") + } + // Sum type fields. + if typ := d.Next(); typ != jx.Object { + return errors.Errorf("unexpected json type %q", typ) + } + + var found bool + if err := d.Capture(func(d *jx.Decoder) error { + return d.ObjBytes(func(d *jx.Decoder, key []byte) error { + switch string(key) { + case "config": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.String { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := ConfigurationAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "element_ids": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Array { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := OrderAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "language": + // Type-based discrimination: check if field has expected JSON type (nullable) + typ := d.Next() + if typ != jx.String && typ != jx.Null { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := PracticeAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "line_numbers": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Array { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := FindErrorAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "number": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Number { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := NumberAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "option_ids": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Array { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := ChoiceAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "source_code": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.String { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := PracticeAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "text": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.String { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := StringAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "format": + // Value-based discrimination: check enum value + if typ := d.Next(); typ != jx.String { + return d.Skip() + } + value, err := d.StrBytes() + if err != nil { + return err + } + switch string(value) { + case "choice": + match := ChoiceAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "configuration": + match := ConfigurationAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "find_error": + match := FindErrorAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "number": + match := NumberAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "order": + match := OrderAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "practice": + match := PracticeAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "string": + match := StringAnswerAssessmentAnswer + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + default: + // Unknown enum value, ignore and continue + } + return nil + } + return d.Skip() + }) + }); err != nil { + return errors.Wrap(err, "capture") + } + if !found { + return errors.New("unable to detect sum type variant") + } + switch s.Type { + case ChoiceAnswerAssessmentAnswer: + if err := s.ChoiceAnswer.Decode(d); err != nil { + return err + } + case NumberAnswerAssessmentAnswer: + if err := s.NumberAnswer.Decode(d); err != nil { + return err + } + case StringAnswerAssessmentAnswer: + if err := s.StringAnswer.Decode(d); err != nil { + return err + } + case OrderAnswerAssessmentAnswer: + if err := s.OrderAnswer.Decode(d); err != nil { + return err + } + case FindErrorAnswerAssessmentAnswer: + if err := s.FindErrorAnswer.Decode(d); err != nil { + return err + } + case ConfigurationAnswerAssessmentAnswer: + if err := s.ConfigurationAnswer.Decode(d); err != nil { + return err + } + case PracticeAnswerAssessmentAnswer: + if err := s.PracticeAnswer.Decode(d); err != nil { + return err + } + default: + return errors.Errorf("inferred invalid type: %s", s.Type) + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentAnswer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentAnswer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentAnswerSubmission) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentAnswerSubmission) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + e.FieldStart("item_id") + s.ItemID.Encode(e) + } + { + e.FieldStart("answer") + s.Answer.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentAnswerSubmission = [3]string{ + 0: "expected_version", + 1: "item_id", + 2: "answer", +} + +// Decode decodes AssessmentAnswerSubmission from json. +func (s *AssessmentAnswerSubmission) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentAnswerSubmission to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "item_id": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.ItemID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"item_id\"") + } + case "answer": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Answer.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"answer\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentAnswerSubmission") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentAnswerSubmission) { + name = jsonFieldsNameOfAssessmentAnswerSubmission[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentAnswerSubmission) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentAnswerSubmission) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentAttempt) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentAttempt) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("started_at") + s.StartedAt.Encode(e) + } + { + e.FieldStart("expires_at") + s.ExpiresAt.Encode(e) + } + { + e.FieldStart("sessions") + s.Sessions.Encode(e) + } + { + e.FieldStart("finished_at") + s.FinishedAt.Encode(e) + } + { + e.FieldStart("progress") + s.Progress.Encode(e) + } + { + e.FieldStart("current_item") + s.CurrentItem.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfAssessmentAttempt = [15]string{ + 0: "id", + 1: "version", + 2: "specialization", + 3: "target_grade", + 4: "task_language", + 5: "mode", + 6: "state", + 7: "versions", + 8: "started_at", + 9: "expires_at", + 10: "sessions", + 11: "finished_at", + 12: "progress", + 13: "current_item", + 14: "practices", +} + +// Decode decodes AssessmentAttempt from json. +func (s *AssessmentAttempt) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentAttempt to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "version": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.TargetGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.TaskLanguage.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + case "mode": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Mode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"mode\"") + } + case "state": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "versions": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.Versions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"versions\"") + } + case "started_at": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.StartedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"started_at\"") + } + case "expires_at": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.ExpiresAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expires_at\"") + } + case "sessions": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.Sessions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"sessions\"") + } + case "finished_at": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.FinishedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"finished_at\"") + } + case "progress": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.Progress.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"progress\"") + } + case "current_item": + requiredBitSet[1] |= 1 << 5 + if err := func() error { + if err := s.CurrentItem.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"current_item\"") + } + case "practices": + requiredBitSet[1] |= 1 << 6 + if err := func() error { + s.Practices = make([]AssessmentPractice, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentPractice + if err := elem.Decode(d); err != nil { + return err + } + s.Practices = append(s.Practices, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"practices\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentAttempt") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b01111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentAttempt) { + name = jsonFieldsNameOfAssessmentAttempt[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentAttempt) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentAttempt) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentAttemptCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentAttemptCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentAttemptCreate = [3]string{ + 0: "specialization", + 1: "target_grade", + 2: "task_language", +} + +// Decode decodes AssessmentAttemptCreate from json. +func (s *AssessmentAttemptCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentAttemptCreate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specialization": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.TargetGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.TaskLanguage.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentAttemptCreate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentAttemptCreate) { + name = jsonFieldsNameOfAssessmentAttemptCreate[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentAttemptCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentAttemptCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentAttemptState as json. +func (s AssessmentAttemptState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentAttemptState from json. +func (s *AssessmentAttemptState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentAttemptState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentAttemptState(v) { + case AssessmentAttemptStateInProgress: + *s = AssessmentAttemptStateInProgress + case AssessmentAttemptStatePracticePending: + *s = AssessmentAttemptStatePracticePending + case AssessmentAttemptStateAdditionalPracticePending: + *s = AssessmentAttemptStateAdditionalPracticePending + case AssessmentAttemptStateReadyToFinalize: + *s = AssessmentAttemptStateReadyToFinalize + case AssessmentAttemptStateCompleted: + *s = AssessmentAttemptStateCompleted + case AssessmentAttemptStateExpired: + *s = AssessmentAttemptStateExpired + case AssessmentAttemptStateInsufficientBank: + *s = AssessmentAttemptStateInsufficientBank + default: + *s = AssessmentAttemptState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentAttemptState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentAttemptState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentAttemptVersion as json. +func (s AssessmentAttemptVersion) Encode(e *jx.Encoder) { + unwrapped := int64(s) + + e.Int64(unwrapped) +} + +// Decode decodes AssessmentAttemptVersion from json. +func (s *AssessmentAttemptVersion) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentAttemptVersion to nil") + } + var unwrapped int64 + if err := func() error { + v, err := d.Int64() + unwrapped = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AssessmentAttemptVersion(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentAttemptVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentAttemptVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentAvailability) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentAvailability) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specializations") + e.ArrStart() + for _, elem := range s.Specializations { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfAssessmentAvailability = [1]string{ + 0: "specializations", +} + +// Decode decodes AssessmentAvailability from json. +func (s *AssessmentAvailability) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentAvailability to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specializations": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Specializations = make([]AssessmentSpecializationAvailability, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentSpecializationAvailability + if err := elem.Decode(d); err != nil { + return err + } + s.Specializations = append(s.Specializations, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specializations\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentAvailability") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentAvailability) { + name = jsonFieldsNameOfAssessmentAvailability[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentAvailability) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentAvailability) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentDurations) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentDurations) encodeFields(e *jx.Encoder) { + { + e.FieldStart("items_seconds") + e.Int32(s.ItemsSeconds) + } + { + e.FieldStart("practice_seconds") + s.PracticeSeconds.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentDurations = [2]string{ + 0: "items_seconds", + 1: "practice_seconds", +} + +// Decode decodes AssessmentDurations from json. +func (s *AssessmentDurations) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentDurations to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "items_seconds": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.ItemsSeconds = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"items_seconds\"") + } + case "practice_seconds": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.PracticeSeconds.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"practice_seconds\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentDurations") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentDurations) { + name = jsonFieldsNameOfAssessmentDurations[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentDurations) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentDurations) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentFinalization) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentFinalization) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentFinalization = [1]string{ + 0: "expected_version", +} + +// Decode decodes AssessmentFinalization from json. +func (s *AssessmentFinalization) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentFinalization to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentFinalization") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentFinalization) { + name = jsonFieldsNameOfAssessmentFinalization[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentFinalization) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentFinalization) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentGap) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentGap) encodeFields(e *jx.Encoder) { + { + e.FieldStart("domain") + e.Str(s.Domain) + } + { + e.FieldStart("title") + e.Str(s.Title) + } +} + +var jsonFieldsNameOfAssessmentGap = [2]string{ + 0: "domain", + 1: "title", +} + +// Decode decodes AssessmentGap from json. +func (s *AssessmentGap) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentGap to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "domain": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Domain = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"domain\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentGap") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentGap) { + name = jsonFieldsNameOfAssessmentGap[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentGap) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentGap) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentGradeAvailability) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentGradeAvailability) encodeFields(e *jx.Encoder) { + { + e.FieldStart("grade") + s.Grade.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("available_at") + s.AvailableAt.Encode(e) + } + { + e.FieldStart("time_limit_seconds") + s.TimeLimitSeconds.Encode(e) + } + { + e.FieldStart("max_sessions") + s.MaxSessions.Encode(e) + } + { + e.FieldStart("max_items") + s.MaxItems.Encode(e) + } + { + e.FieldStart("practice_required") + s.PracticeRequired.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentGradeAvailability = [8]string{ + 0: "grade", + 1: "status", + 2: "mode", + 3: "available_at", + 4: "time_limit_seconds", + 5: "max_sessions", + 6: "max_items", + 7: "practice_required", +} + +// Decode decodes AssessmentGradeAvailability from json. +func (s *AssessmentGradeAvailability) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentGradeAvailability to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "grade": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Grade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"grade\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "mode": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Mode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"mode\"") + } + case "available_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.AvailableAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"available_at\"") + } + case "time_limit_seconds": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.TimeLimitSeconds.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"time_limit_seconds\"") + } + case "max_sessions": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.MaxSessions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_sessions\"") + } + case "max_items": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.MaxItems.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_items\"") + } + case "practice_required": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.PracticeRequired.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"practice_required\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentGradeAvailability") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b11111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentGradeAvailability) { + name = jsonFieldsNameOfAssessmentGradeAvailability[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentGradeAvailability) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentGradeAvailability) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentGradeAvailabilityStatus as json. +func (s AssessmentGradeAvailabilityStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentGradeAvailabilityStatus from json. +func (s *AssessmentGradeAvailabilityStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentGradeAvailabilityStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentGradeAvailabilityStatus(v) { + case AssessmentGradeAvailabilityStatusAvailable: + *s = AssessmentGradeAvailabilityStatusAvailable + case AssessmentGradeAvailabilityStatusActiveAttempt: + *s = AssessmentGradeAvailabilityStatusActiveAttempt + case AssessmentGradeAvailabilityStatusCooldown: + *s = AssessmentGradeAvailabilityStatusCooldown + case AssessmentGradeAvailabilityStatusInsufficientBank: + *s = AssessmentGradeAvailabilityStatusInsufficientBank + default: + *s = AssessmentGradeAvailabilityStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentGradeAvailabilityStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentGradeAvailabilityStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentInterval) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentInterval) encodeFields(e *jx.Encoder) { + { + e.FieldStart("low") + e.Float64(s.Low) + } + { + e.FieldStart("high") + e.Float64(s.High) + } +} + +var jsonFieldsNameOfAssessmentInterval = [2]string{ + 0: "low", + 1: "high", +} + +// Decode decodes AssessmentInterval from json. +func (s *AssessmentInterval) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentInterval to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "low": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Float64() + s.Low = float64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"low\"") + } + case "high": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Float64() + s.High = float64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"high\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentInterval") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentInterval) { + name = jsonFieldsNameOfAssessmentInterval[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentInterval) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentInterval) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentItem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentItem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("sequence") + e.Int32(s.Sequence) + } + { + e.FieldStart("prompt") + e.Str(s.Prompt) + } + { + e.FieldStart("content") + s.Content.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentItem = [4]string{ + 0: "id", + 1: "sequence", + 2: "prompt", + 3: "content", +} + +// Decode decodes AssessmentItem from json. +func (s *AssessmentItem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentItem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "sequence": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.Sequence = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"sequence\"") + } + case "prompt": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Prompt = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"prompt\"") + } + case "content": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Content.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"content\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentItem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentItem) { + name = jsonFieldsNameOfAssessmentItem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentItemId as json. +func (s AssessmentItemId) Encode(e *jx.Encoder) { + unwrapped := uuid.UUID(s) + + json.EncodeUUID(e, unwrapped) +} + +// Decode decodes AssessmentItemId from json. +func (s *AssessmentItemId) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentItemId to nil") + } + var unwrapped uuid.UUID + if err := func() error { + v, err := json.DecodeUUID(d) + unwrapped = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AssessmentItemId(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentItemId) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentItemId) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentLimitation as json. +func (s AssessmentLimitation) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentLimitation from json. +func (s *AssessmentLimitation) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLimitation to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentLimitation(v) { + case AssessmentLimitationUncalibratedThresholds: + *s = AssessmentLimitationUncalibratedThresholds + case AssessmentLimitationDemoBank: + *s = AssessmentLimitationDemoBank + case AssessmentLimitationPracticeNotIncluded: + *s = AssessmentLimitationPracticeNotIncluded + case AssessmentLimitationUnproctored: + *s = AssessmentLimitationUnproctored + default: + *s = AssessmentLimitation(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentLimitation) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLimitation) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentMode as json. +func (s AssessmentMode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentMode from json. +func (s *AssessmentMode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentMode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentMode(v) { + case AssessmentModeDemoBasic: + *s = AssessmentModeDemoBasic + case AssessmentModeAdaptive: + *s = AssessmentModeAdaptive + default: + *s = AssessmentMode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentNextAction as json. +func (s AssessmentNextAction) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentNextAction from json. +func (s *AssessmentNextAction) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentNextAction to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentNextAction(v) { + case AssessmentNextActionRetakeSameGrade: + *s = AssessmentNextActionRetakeSameGrade + case AssessmentNextActionTakeLowerGrade: + *s = AssessmentNextActionTakeLowerGrade + case AssessmentNextActionAcceptLowerGrade: + *s = AssessmentNextActionAcceptLowerGrade + case AssessmentNextActionTakeHigherGrade: + *s = AssessmentNextActionTakeHigherGrade + default: + *s = AssessmentNextAction(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentNextAction) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentNextAction) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentNextStep) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentNextStep) encodeFields(e *jx.Encoder) { + { + e.FieldStart("action") + s.Action.Encode(e) + } + { + e.FieldStart("grade") + s.Grade.Encode(e) + } + { + e.FieldStart("available_at") + s.AvailableAt.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentNextStep = [3]string{ + 0: "action", + 1: "grade", + 2: "available_at", +} + +// Decode decodes AssessmentNextStep from json. +func (s *AssessmentNextStep) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentNextStep to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "action": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Action.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"action\"") + } + case "grade": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Grade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"grade\"") + } + case "available_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.AvailableAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"available_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentNextStep") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentNextStep) { + name = jsonFieldsNameOfAssessmentNextStep[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentNextStep) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentNextStep) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentNotDeterminedReason as json. +func (s AssessmentNotDeterminedReason) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentNotDeterminedReason from json. +func (s *AssessmentNotDeterminedReason) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentNotDeterminedReason to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentNotDeterminedReason(v) { + case AssessmentNotDeterminedReasonExpired: + *s = AssessmentNotDeterminedReasonExpired + case AssessmentNotDeterminedReasonPracticeIncomplete: + *s = AssessmentNotDeterminedReasonPracticeIncomplete + case AssessmentNotDeterminedReasonInsufficientBank: + *s = AssessmentNotDeterminedReasonInsufficientBank + case AssessmentNotDeterminedReasonSandboxUnavailable: + *s = AssessmentNotDeterminedReasonSandboxUnavailable + default: + *s = AssessmentNotDeterminedReason(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentNotDeterminedReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentNotDeterminedReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentOption) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentOption) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("text") + e.Str(s.Text) + } +} + +var jsonFieldsNameOfAssessmentOption = [2]string{ + 0: "id", + 1: "text", +} + +// Decode decodes AssessmentOption from json. +func (s *AssessmentOption) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentOption to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "text": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Text = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentOption") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentOption) { + name = jsonFieldsNameOfAssessmentOption[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentOption) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentOption) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentOptionId as json. +func (s AssessmentOptionId) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes AssessmentOptionId from json. +func (s *AssessmentOptionId) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentOptionId to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AssessmentOptionId(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentOptionId) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentOptionId) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentOutcome as json. +func (s AssessmentOutcome) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentOutcome from json. +func (s *AssessmentOutcome) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentOutcome to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentOutcome(v) { + case AssessmentOutcomeConfirmed: + *s = AssessmentOutcomeConfirmed + case AssessmentOutcomeNotConfirmed: + *s = AssessmentOutcomeNotConfirmed + case AssessmentOutcomeNotDetermined: + *s = AssessmentOutcomeNotDetermined + default: + *s = AssessmentOutcome(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentOutcome) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentOutcome) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentPractice) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentPractice) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("item_id") + s.ItemID.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("submitted_at") + s.SubmittedAt.Encode(e) + } + { + e.FieldStart("verdict") + s.Verdict.Encode(e) + } + { + e.FieldStart("failure_reason") + s.FailureReason.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentPractice = [6]string{ + 0: "kind", + 1: "item_id", + 2: "status", + 3: "submitted_at", + 4: "verdict", + 5: "failure_reason", +} + +// Decode decodes AssessmentPractice from json. +func (s *AssessmentPractice) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentPractice to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "item_id": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.ItemID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"item_id\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "submitted_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.SubmittedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"submitted_at\"") + } + case "verdict": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Verdict.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"verdict\"") + } + case "failure_reason": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.FailureReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"failure_reason\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentPractice") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentPractice) { + name = jsonFieldsNameOfAssessmentPractice[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentPractice) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentPractice) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentPracticeResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentPracticeResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("verdict") + s.Verdict.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentPracticeResult = [2]string{ + 0: "kind", + 1: "verdict", +} + +// Decode decodes AssessmentPracticeResult from json. +func (s *AssessmentPracticeResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentPracticeResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "verdict": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Verdict.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"verdict\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentPracticeResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentPracticeResult) { + name = jsonFieldsNameOfAssessmentPracticeResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentPracticeResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentPracticeResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentProgress) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentProgress) encodeFields(e *jx.Encoder) { + { + e.FieldStart("answered_items") + e.Int32(s.AnsweredItems) + } + { + e.FieldStart("max_items") + e.Int32(s.MaxItems) + } +} + +var jsonFieldsNameOfAssessmentProgress = [2]string{ + 0: "answered_items", + 1: "max_items", +} + +// Decode decodes AssessmentProgress from json. +func (s *AssessmentProgress) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentProgress to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "answered_items": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.AnsweredItems = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"answered_items\"") + } + case "max_items": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.MaxItems = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_items\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentProgress") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentProgress) { + name = jsonFieldsNameOfAssessmentProgress[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentProgress) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentProgress) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("attempt_id") + json.EncodeUUID(e, s.AttemptID) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("not_determined_reason") + s.NotDeterminedReason.Encode(e) + } + { + e.FieldStart("confirmed_grade") + s.ConfirmedGrade.Encode(e) + } + { + e.FieldStart("previous_confirmed_grade") + s.PreviousConfirmedGrade.Encode(e) + } + { + e.FieldStart("strength") + s.Strength.Encode(e) + } + { + e.FieldStart("calibration_status") + s.CalibrationStatus.Encode(e) + } + { + e.FieldStart("limitations") + e.ArrStart() + for _, elem := range s.Limitations { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("uncertainty") + s.Uncertainty.Encode(e) + } + { + e.FieldStart("basic_score") + s.BasicScore.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("gaps") + e.ArrStart() + for _, elem := range s.Gaps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("durations") + s.Durations.Encode(e) + } + { + e.FieldStart("next_steps") + e.ArrStart() + for _, elem := range s.NextSteps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("decided_at") + s.DecidedAt.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentResult = [20]string{ + 0: "attempt_id", + 1: "specialization", + 2: "target_grade", + 3: "task_language", + 4: "mode", + 5: "versions", + 6: "outcome", + 7: "not_determined_reason", + 8: "confirmed_grade", + 9: "previous_confirmed_grade", + 10: "strength", + 11: "calibration_status", + 12: "limitations", + 13: "uncertainty", + 14: "basic_score", + 15: "practices", + 16: "gaps", + 17: "durations", + 18: "next_steps", + 19: "decided_at", +} + +// Decode decodes AssessmentResult from json. +func (s *AssessmentResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentResult to nil") + } + var requiredBitSet [3]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "attempt_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.AttemptID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"attempt_id\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.TargetGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.TaskLanguage.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + case "mode": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Mode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"mode\"") + } + case "versions": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Versions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"versions\"") + } + case "outcome": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "not_determined_reason": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.NotDeterminedReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"not_determined_reason\"") + } + case "confirmed_grade": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.ConfirmedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmed_grade\"") + } + case "previous_confirmed_grade": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.PreviousConfirmedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"previous_confirmed_grade\"") + } + case "strength": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.Strength.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"strength\"") + } + case "calibration_status": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.CalibrationStatus.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"calibration_status\"") + } + case "limitations": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + s.Limitations = make([]AssessmentLimitation, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentLimitation + if err := elem.Decode(d); err != nil { + return err + } + s.Limitations = append(s.Limitations, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"limitations\"") + } + case "uncertainty": + requiredBitSet[1] |= 1 << 5 + if err := func() error { + if err := s.Uncertainty.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"uncertainty\"") + } + case "basic_score": + requiredBitSet[1] |= 1 << 6 + if err := func() error { + if err := s.BasicScore.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"basic_score\"") + } + case "practices": + requiredBitSet[1] |= 1 << 7 + if err := func() error { + s.Practices = make([]AssessmentPracticeResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentPracticeResult + if err := elem.Decode(d); err != nil { + return err + } + s.Practices = append(s.Practices, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"practices\"") + } + case "gaps": + requiredBitSet[2] |= 1 << 0 + if err := func() error { + s.Gaps = make([]AssessmentGap, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentGap + if err := elem.Decode(d); err != nil { + return err + } + s.Gaps = append(s.Gaps, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"gaps\"") + } + case "durations": + requiredBitSet[2] |= 1 << 1 + if err := func() error { + if err := s.Durations.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"durations\"") + } + case "next_steps": + requiredBitSet[2] |= 1 << 2 + if err := func() error { + s.NextSteps = make([]AssessmentNextStep, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentNextStep + if err := elem.Decode(d); err != nil { + return err + } + s.NextSteps = append(s.NextSteps, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"next_steps\"") + } + case "decided_at": + requiredBitSet[2] |= 1 << 3 + if err := func() error { + if err := s.DecidedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"decided_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [3]uint8{ + 0b11111111, + 0b11111111, + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentResult) { + name = jsonFieldsNameOfAssessmentResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentSessions) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentSessions) encodeFields(e *jx.Encoder) { + { + e.FieldStart("used") + e.Int32(s.Used) + } + { + e.FieldStart("max") + e.Int32(s.Max) + } + { + e.FieldStart("idle_timeout_seconds") + e.Int32(s.IdleTimeoutSeconds) + } +} + +var jsonFieldsNameOfAssessmentSessions = [3]string{ + 0: "used", + 1: "max", + 2: "idle_timeout_seconds", +} + +// Decode decodes AssessmentSessions from json. +func (s *AssessmentSessions) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentSessions to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "used": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.Used = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"used\"") + } + case "max": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.Max = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max\"") + } + case "idle_timeout_seconds": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.IdleTimeoutSeconds = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"idle_timeout_seconds\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentSessions") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentSessions) { + name = jsonFieldsNameOfAssessmentSessions[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentSessions) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentSessions) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentSpecializationAvailability) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentSpecializationAvailability) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("confirmed_grade") + s.ConfirmedGrade.Encode(e) + } + { + e.FieldStart("active_attempt_id") + s.ActiveAttemptID.Encode(e) + } + { + e.FieldStart("grades") + e.ArrStart() + for _, elem := range s.Grades { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfAssessmentSpecializationAvailability = [4]string{ + 0: "specialization", + 1: "confirmed_grade", + 2: "active_attempt_id", + 3: "grades", +} + +// Decode decodes AssessmentSpecializationAvailability from json. +func (s *AssessmentSpecializationAvailability) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentSpecializationAvailability to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specialization": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "confirmed_grade": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.ConfirmedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmed_grade\"") + } + case "active_attempt_id": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.ActiveAttemptID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"active_attempt_id\"") + } + case "grades": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + s.Grades = make([]AssessmentGradeAvailability, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentGradeAvailability + if err := elem.Decode(d); err != nil { + return err + } + s.Grades = append(s.Grades, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"grades\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentSpecializationAvailability") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentSpecializationAvailability) { + name = jsonFieldsNameOfAssessmentSpecializationAvailability[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentSpecializationAvailability) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentSpecializationAvailability) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentStrength as json. +func (s AssessmentStrength) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentStrength from json. +func (s *AssessmentStrength) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentStrength to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentStrength(v) { + case AssessmentStrengthHigh: + *s = AssessmentStrengthHigh + case AssessmentStrengthMedium: + *s = AssessmentStrengthMedium + default: + *s = AssessmentStrength(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentStrength) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentStrength) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentUncertainty) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentUncertainty) encodeFields(e *jx.Encoder) { + { + e.FieldStart("theta") + e.Float64(s.Theta) + } + { + e.FieldStart("standard_error") + e.Float64(s.StandardError) + } + { + e.FieldStart("interval_95") + s.Interval95.Encode(e) + } + { + e.FieldStart("p_grade") + e.Float64(s.PGrade) + } +} + +var jsonFieldsNameOfAssessmentUncertainty = [4]string{ + 0: "theta", + 1: "standard_error", + 2: "interval_95", + 3: "p_grade", +} + +// Decode decodes AssessmentUncertainty from json. +func (s *AssessmentUncertainty) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentUncertainty to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "theta": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Float64() + s.Theta = float64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"theta\"") + } + case "standard_error": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Float64() + s.StandardError = float64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"standard_error\"") + } + case "interval_95": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Interval95.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"interval_95\"") + } + case "p_grade": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Float64() + s.PGrade = float64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"p_grade\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentUncertainty") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentUncertainty) { + name = jsonFieldsNameOfAssessmentUncertainty[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentUncertainty) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentUncertainty) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentVersionLabel as json. +func (s AssessmentVersionLabel) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes AssessmentVersionLabel from json. +func (s *AssessmentVersionLabel) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentVersionLabel to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AssessmentVersionLabel(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentVersionLabel) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentVersionLabel) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentVersions) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentVersions) encodeFields(e *jx.Encoder) { + { + e.FieldStart("policy_version") + e.Int32(s.PolicyVersion) + } + { + e.FieldStart("bank_version") + s.BankVersion.Encode(e) + } + { + e.FieldStart("algorithm_version") + s.AlgorithmVersion.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentVersions = [3]string{ + 0: "policy_version", + 1: "bank_version", + 2: "algorithm_version", +} + +// Decode decodes AssessmentVersions from json. +func (s *AssessmentVersions) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentVersions to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "policy_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.PolicyVersion = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"policy_version\"") + } + case "bank_version": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.BankVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"bank_version\"") + } + case "algorithm_version": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.AlgorithmVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"algorithm_version\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentVersions") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentVersions) { + name = jsonFieldsNameOfAssessmentVersions[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentVersions) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentVersions) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *BasicScore) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *BasicScore) encodeFields(e *jx.Encoder) { + { + e.FieldStart("points") + e.Int32(s.Points) + } + { + e.FieldStart("max_points") + e.Int32(s.MaxPoints) + } + { + e.FieldStart("pass_points") + e.Int32(s.PassPoints) + } +} + +var jsonFieldsNameOfBasicScore = [3]string{ + 0: "points", + 1: "max_points", + 2: "pass_points", +} + +// Decode decodes BasicScore from json. +func (s *BasicScore) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode BasicScore to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "points": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.Points = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"points\"") + } + case "max_points": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.MaxPoints = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_points\"") + } + case "pass_points": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.PassPoints = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"pass_points\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode BasicScore") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfBasicScore) { + name = jsonFieldsNameOfBasicScore[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *BasicScore) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *BasicScore) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CalibrationStatus as json. +func (s CalibrationStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CalibrationStatus from json. +func (s *CalibrationStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CalibrationStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CalibrationStatus(v) { + case CalibrationStatusUncalibrated: + *s = CalibrationStatusUncalibrated + case CalibrationStatusCalibrated: + *s = CalibrationStatusCalibrated + default: + *s = CalibrationStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CalibrationStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CalibrationStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *CandidateExperience) Encode(e *jx.Encoder) { e.ObjStart() @@ -1001,6 +5020,786 @@ func (s *CatalogSpecialization) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *ChoiceAnswer) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ChoiceAnswer) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("option_ids") + e.ArrStart() + for _, elem := range s.OptionIds { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfChoiceAnswer = [2]string{ + 0: "format", + 1: "option_ids", +} + +// Decode decodes ChoiceAnswer from json. +func (s *ChoiceAnswer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ChoiceAnswer to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "option_ids": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.OptionIds = make([]AssessmentOptionId, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentOptionId + if err := elem.Decode(d); err != nil { + return err + } + s.OptionIds = append(s.OptionIds, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"option_ids\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ChoiceAnswer") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfChoiceAnswer) { + name = jsonFieldsNameOfChoiceAnswer[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ChoiceAnswer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ChoiceAnswer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ChoiceAnswerFormat as json. +func (s ChoiceAnswerFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ChoiceAnswerFormat from json. +func (s *ChoiceAnswerFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ChoiceAnswerFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ChoiceAnswerFormat(v) { + case ChoiceAnswerFormatChoice: + *s = ChoiceAnswerFormatChoice + default: + *s = ChoiceAnswerFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ChoiceAnswerFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ChoiceAnswerFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ChoiceItemContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ChoiceItemContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("options") + e.ArrStart() + for _, elem := range s.Options { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("multiple") + e.Bool(s.Multiple) + } +} + +var jsonFieldsNameOfChoiceItemContent = [3]string{ + 0: "format", + 1: "options", + 2: "multiple", +} + +// Decode decodes ChoiceItemContent from json. +func (s *ChoiceItemContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ChoiceItemContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "options": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Options = make([]AssessmentOption, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentOption + if err := elem.Decode(d); err != nil { + return err + } + s.Options = append(s.Options, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"options\"") + } + case "multiple": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Bool() + s.Multiple = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"multiple\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ChoiceItemContent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfChoiceItemContent) { + name = jsonFieldsNameOfChoiceItemContent[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ChoiceItemContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ChoiceItemContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ChoiceItemContentFormat as json. +func (s ChoiceItemContentFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ChoiceItemContentFormat from json. +func (s *ChoiceItemContentFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ChoiceItemContentFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ChoiceItemContentFormat(v) { + case ChoiceItemContentFormatChoice: + *s = ChoiceItemContentFormatChoice + default: + *s = ChoiceItemContentFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ChoiceItemContentFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ChoiceItemContentFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CodeLine) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CodeLine) encodeFields(e *jx.Encoder) { + { + e.FieldStart("number") + e.Int32(s.Number) + } + { + e.FieldStart("text") + e.Str(s.Text) + } +} + +var jsonFieldsNameOfCodeLine = [2]string{ + 0: "number", + 1: "text", +} + +// Decode decodes CodeLine from json. +func (s *CodeLine) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CodeLine to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "number": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.Number = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"number\"") + } + case "text": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Text = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CodeLine") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCodeLine) { + name = jsonFieldsNameOfCodeLine[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CodeLine) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CodeLine) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ConfigurationAnswer) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConfigurationAnswer) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("config") + e.Str(s.Config) + } +} + +var jsonFieldsNameOfConfigurationAnswer = [2]string{ + 0: "format", + 1: "config", +} + +// Decode decodes ConfigurationAnswer from json. +func (s *ConfigurationAnswer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConfigurationAnswer to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "config": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Config = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"config\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConfigurationAnswer") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfConfigurationAnswer) { + name = jsonFieldsNameOfConfigurationAnswer[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ConfigurationAnswer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConfigurationAnswer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConfigurationAnswerFormat as json. +func (s ConfigurationAnswerFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ConfigurationAnswerFormat from json. +func (s *ConfigurationAnswerFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConfigurationAnswerFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ConfigurationAnswerFormat(v) { + case ConfigurationAnswerFormatConfiguration: + *s = ConfigurationAnswerFormatConfiguration + default: + *s = ConfigurationAnswerFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConfigurationAnswerFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConfigurationAnswerFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ConfigurationItemContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConfigurationItemContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("syntax") + e.Str(s.Syntax) + } + { + e.FieldStart("initial_config") + e.Str(s.InitialConfig) + } + { + e.FieldStart("max_length") + e.Int32(s.MaxLength) + } +} + +var jsonFieldsNameOfConfigurationItemContent = [4]string{ + 0: "format", + 1: "syntax", + 2: "initial_config", + 3: "max_length", +} + +// Decode decodes ConfigurationItemContent from json. +func (s *ConfigurationItemContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConfigurationItemContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "syntax": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Syntax = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"syntax\"") + } + case "initial_config": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.InitialConfig = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"initial_config\"") + } + case "max_length": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.MaxLength = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_length\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConfigurationItemContent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfConfigurationItemContent) { + name = jsonFieldsNameOfConfigurationItemContent[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ConfigurationItemContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConfigurationItemContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConfigurationItemContentFormat as json. +func (s ConfigurationItemContentFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ConfigurationItemContentFormat from json. +func (s *ConfigurationItemContentFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConfigurationItemContentFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ConfigurationItemContentFormat(v) { + case ConfigurationItemContentFormatConfiguration: + *s = ConfigurationItemContentFormatConfiguration + default: + *s = ConfigurationItemContentFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConfigurationItemContentFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConfigurationItemContentFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ConfirmEmailBadRequest as json. func (s *ConfirmEmailBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -1296,6 +6095,196 @@ func (s *ConsentTextVersion) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes CreateMyAssessmentAttemptBadRequest as json. +func (s *CreateMyAssessmentAttemptBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentAttemptBadRequest from json. +func (s *CreateMyAssessmentAttemptBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentAttemptBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateMyAssessmentAttemptBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentAttemptBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentAttemptBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentAttemptConflict as json. +func (s *CreateMyAssessmentAttemptConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentAttemptConflict from json. +func (s *CreateMyAssessmentAttemptConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentAttemptConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateMyAssessmentAttemptConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentAttemptConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentAttemptConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentAttemptForbidden as json. +func (s *CreateMyAssessmentAttemptForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentAttemptForbidden from json. +func (s *CreateMyAssessmentAttemptForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentAttemptForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateMyAssessmentAttemptForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentAttemptForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentAttemptForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentAttemptUnauthorized as json. +func (s *CreateMyAssessmentAttemptUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentAttemptUnauthorized from json. +func (s *CreateMyAssessmentAttemptUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentAttemptUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateMyAssessmentAttemptUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentAttemptUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentAttemptUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentAttemptUnprocessableEntity as json. +func (s *CreateMyAssessmentAttemptUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentAttemptUnprocessableEntity from json. +func (s *CreateMyAssessmentAttemptUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentAttemptUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateMyAssessmentAttemptUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentAttemptUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentAttemptUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CsrfToken as json. func (s CsrfToken) Encode(e *jx.Encoder) { unwrapped := string(s) @@ -1766,6 +6755,966 @@ func (s *EmailVerificationResultEmailVerified) UnmarshalJSON(data []byte) error return s.Decode(d) } +// Encode encodes FinalizeMyAssessmentAttemptBadRequest as json. +func (s *FinalizeMyAssessmentAttemptBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes FinalizeMyAssessmentAttemptBadRequest from json. +func (s *FinalizeMyAssessmentAttemptBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FinalizeMyAssessmentAttemptBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = FinalizeMyAssessmentAttemptBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *FinalizeMyAssessmentAttemptBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FinalizeMyAssessmentAttemptBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes FinalizeMyAssessmentAttemptConflict as json. +func (s *FinalizeMyAssessmentAttemptConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes FinalizeMyAssessmentAttemptConflict from json. +func (s *FinalizeMyAssessmentAttemptConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FinalizeMyAssessmentAttemptConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = FinalizeMyAssessmentAttemptConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *FinalizeMyAssessmentAttemptConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FinalizeMyAssessmentAttemptConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes FinalizeMyAssessmentAttemptForbidden as json. +func (s *FinalizeMyAssessmentAttemptForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes FinalizeMyAssessmentAttemptForbidden from json. +func (s *FinalizeMyAssessmentAttemptForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FinalizeMyAssessmentAttemptForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = FinalizeMyAssessmentAttemptForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *FinalizeMyAssessmentAttemptForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FinalizeMyAssessmentAttemptForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes FinalizeMyAssessmentAttemptNotFound as json. +func (s *FinalizeMyAssessmentAttemptNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes FinalizeMyAssessmentAttemptNotFound from json. +func (s *FinalizeMyAssessmentAttemptNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FinalizeMyAssessmentAttemptNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = FinalizeMyAssessmentAttemptNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *FinalizeMyAssessmentAttemptNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FinalizeMyAssessmentAttemptNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes FinalizeMyAssessmentAttemptPreconditionFailed as json. +func (s *FinalizeMyAssessmentAttemptPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes FinalizeMyAssessmentAttemptPreconditionFailed from json. +func (s *FinalizeMyAssessmentAttemptPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FinalizeMyAssessmentAttemptPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = FinalizeMyAssessmentAttemptPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *FinalizeMyAssessmentAttemptPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FinalizeMyAssessmentAttemptPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes FinalizeMyAssessmentAttemptUnauthorized as json. +func (s *FinalizeMyAssessmentAttemptUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes FinalizeMyAssessmentAttemptUnauthorized from json. +func (s *FinalizeMyAssessmentAttemptUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FinalizeMyAssessmentAttemptUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = FinalizeMyAssessmentAttemptUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *FinalizeMyAssessmentAttemptUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FinalizeMyAssessmentAttemptUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes FinalizeMyAssessmentAttemptUnprocessableEntity as json. +func (s *FinalizeMyAssessmentAttemptUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes FinalizeMyAssessmentAttemptUnprocessableEntity from json. +func (s *FinalizeMyAssessmentAttemptUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FinalizeMyAssessmentAttemptUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = FinalizeMyAssessmentAttemptUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *FinalizeMyAssessmentAttemptUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FinalizeMyAssessmentAttemptUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *FindErrorAnswer) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *FindErrorAnswer) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("line_numbers") + e.ArrStart() + for _, elem := range s.LineNumbers { + e.Int32(elem) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfFindErrorAnswer = [2]string{ + 0: "format", + 1: "line_numbers", +} + +// Decode decodes FindErrorAnswer from json. +func (s *FindErrorAnswer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FindErrorAnswer to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "line_numbers": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.LineNumbers = make([]int32, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem int32 + v, err := d.Int32() + elem = int32(v) + if err != nil { + return err + } + s.LineNumbers = append(s.LineNumbers, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"line_numbers\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode FindErrorAnswer") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfFindErrorAnswer) { + name = jsonFieldsNameOfFindErrorAnswer[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *FindErrorAnswer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FindErrorAnswer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes FindErrorAnswerFormat as json. +func (s FindErrorAnswerFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes FindErrorAnswerFormat from json. +func (s *FindErrorAnswerFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FindErrorAnswerFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch FindErrorAnswerFormat(v) { + case FindErrorAnswerFormatFindError: + *s = FindErrorAnswerFormatFindError + default: + *s = FindErrorAnswerFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s FindErrorAnswerFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FindErrorAnswerFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *FindErrorItemContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *FindErrorItemContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("syntax") + s.Syntax.Encode(e) + } + { + e.FieldStart("lines") + e.ArrStart() + for _, elem := range s.Lines { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("max_selections") + e.Int32(s.MaxSelections) + } +} + +var jsonFieldsNameOfFindErrorItemContent = [4]string{ + 0: "format", + 1: "syntax", + 2: "lines", + 3: "max_selections", +} + +// Decode decodes FindErrorItemContent from json. +func (s *FindErrorItemContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FindErrorItemContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "syntax": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Syntax.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"syntax\"") + } + case "lines": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.Lines = make([]CodeLine, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CodeLine + if err := elem.Decode(d); err != nil { + return err + } + s.Lines = append(s.Lines, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"lines\"") + } + case "max_selections": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.MaxSelections = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_selections\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode FindErrorItemContent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfFindErrorItemContent) { + name = jsonFieldsNameOfFindErrorItemContent[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *FindErrorItemContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FindErrorItemContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes FindErrorItemContentFormat as json. +func (s FindErrorItemContentFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes FindErrorItemContentFormat from json. +func (s *FindErrorItemContentFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode FindErrorItemContentFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch FindErrorItemContentFormat(v) { + case FindErrorItemContentFormatFindError: + *s = FindErrorItemContentFormatFindError + default: + *s = FindErrorItemContentFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s FindErrorItemContentFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *FindErrorItemContentFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentAttemptForbidden as json. +func (s *GetMyAssessmentAttemptForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentAttemptForbidden from json. +func (s *GetMyAssessmentAttemptForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentAttemptForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentAttemptForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentAttemptForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentAttemptForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentAttemptNotFound as json. +func (s *GetMyAssessmentAttemptNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentAttemptNotFound from json. +func (s *GetMyAssessmentAttemptNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentAttemptNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentAttemptNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentAttemptNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentAttemptNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentAttemptUnauthorized as json. +func (s *GetMyAssessmentAttemptUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentAttemptUnauthorized from json. +func (s *GetMyAssessmentAttemptUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentAttemptUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentAttemptUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentAttemptUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentAttemptUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentAvailabilityForbidden as json. +func (s *GetMyAssessmentAvailabilityForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentAvailabilityForbidden from json. +func (s *GetMyAssessmentAvailabilityForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentAvailabilityForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentAvailabilityForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentAvailabilityForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentAvailabilityForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentAvailabilityUnauthorized as json. +func (s *GetMyAssessmentAvailabilityUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentAvailabilityUnauthorized from json. +func (s *GetMyAssessmentAvailabilityUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentAvailabilityUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentAvailabilityUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentAvailabilityUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentAvailabilityUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentResultConflict as json. +func (s *GetMyAssessmentResultConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentResultConflict from json. +func (s *GetMyAssessmentResultConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentResultConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentResultConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentResultConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentResultConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentResultForbidden as json. +func (s *GetMyAssessmentResultForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentResultForbidden from json. +func (s *GetMyAssessmentResultForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentResultForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentResultForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentResultForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentResultForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentResultNotFound as json. +func (s *GetMyAssessmentResultNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentResultNotFound from json. +func (s *GetMyAssessmentResultNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentResultNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentResultNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentResultNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentResultNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentResultUnauthorized as json. +func (s *GetMyAssessmentResultUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentResultUnauthorized from json. +func (s *GetMyAssessmentResultUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentResultUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentResultUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentResultUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentResultUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetMyQuestionnaireForbidden as json. func (s *GetMyQuestionnaireForbidden) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -2150,6 +8099,317 @@ func (s *IdentityRequestAcceptedStatus) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ItemContent as json. +func (s ItemContent) Encode(e *jx.Encoder) { + switch s.Type { + case ChoiceItemContentItemContent: + s.ChoiceItemContent.Encode(e) + case NumberItemContentItemContent: + s.NumberItemContent.Encode(e) + case StringItemContentItemContent: + s.StringItemContent.Encode(e) + case OrderItemContentItemContent: + s.OrderItemContent.Encode(e) + case FindErrorItemContentItemContent: + s.FindErrorItemContent.Encode(e) + case ConfigurationItemContentItemContent: + s.ConfigurationItemContent.Encode(e) + case PracticeItemContentItemContent: + s.PracticeItemContent.Encode(e) + } +} + +func (s ItemContent) encodeFields(e *jx.Encoder) { + switch s.Type { + case ChoiceItemContentItemContent: + s.ChoiceItemContent.encodeFields(e) + case NumberItemContentItemContent: + s.NumberItemContent.encodeFields(e) + case StringItemContentItemContent: + s.StringItemContent.encodeFields(e) + case OrderItemContentItemContent: + s.OrderItemContent.encodeFields(e) + case FindErrorItemContentItemContent: + s.FindErrorItemContent.encodeFields(e) + case ConfigurationItemContentItemContent: + s.ConfigurationItemContent.encodeFields(e) + case PracticeItemContentItemContent: + s.PracticeItemContent.encodeFields(e) + } +} + +// Decode decodes ItemContent from json. +func (s *ItemContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ItemContent to nil") + } + // Sum type fields. + if typ := d.Next(); typ != jx.Object { + return errors.Errorf("unexpected json type %q", typ) + } + + var found bool + if err := d.Capture(func(d *jx.Decoder) error { + return d.ObjBytes(func(d *jx.Decoder, key []byte) error { + switch string(key) { + case "elements": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Array { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := OrderItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "initial_config": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.String { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := ConfigurationItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "languages": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Array { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := PracticeItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "lines": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Array { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := FindErrorItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "max_selections": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Number { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := FindErrorItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "max_source_length": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Number { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := PracticeItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "multiple": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Bool { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := ChoiceItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "options": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Array { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := ChoiceItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "public_examples": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Array { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := PracticeItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "unit": + // Type-based discrimination: check if field has expected JSON type (nullable) + typ := d.Next() + if typ != jx.String && typ != jx.Null { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := NumberItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "format": + // Value-based discrimination: check enum value + if typ := d.Next(); typ != jx.String { + return d.Skip() + } + value, err := d.StrBytes() + if err != nil { + return err + } + switch string(value) { + case "choice": + match := ChoiceItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "configuration": + match := ConfigurationItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "find_error": + match := FindErrorItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "number": + match := NumberItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "order": + match := OrderItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "practice": + match := PracticeItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "string": + match := StringItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + default: + // Unknown enum value, ignore and continue + } + return nil + } + return d.Skip() + }) + }); err != nil { + return errors.Wrap(err, "capture") + } + if !found { + return errors.New("unable to detect sum type variant") + } + switch s.Type { + case ChoiceItemContentItemContent: + if err := s.ChoiceItemContent.Decode(d); err != nil { + return err + } + case NumberItemContentItemContent: + if err := s.NumberItemContent.Decode(d); err != nil { + return err + } + case StringItemContentItemContent: + if err := s.StringItemContent.Decode(d); err != nil { + return err + } + case OrderItemContentItemContent: + if err := s.OrderItemContent.Decode(d); err != nil { + return err + } + case FindErrorItemContentItemContent: + if err := s.FindErrorItemContent.Decode(d); err != nil { + return err + } + case ConfigurationItemContentItemContent: + if err := s.ConfigurationItemContent.Decode(d); err != nil { + return err + } + case PracticeItemContentItemContent: + if err := s.PracticeItemContent.Decode(d); err != nil { + return err + } + default: + return errors.Errorf("inferred invalid type: %s", s.Type) + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ItemContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ItemContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes LoginBadRequest as json. func (s *LoginBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -2453,6 +8713,360 @@ func (s *NewPassword) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AssessmentItem as json. +func (o NilAssessmentItem) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes AssessmentItem from json. +func (o *NilAssessmentItem) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentItem to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentItem + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAssessmentItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentMode as json. +func (o NilAssessmentMode) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes AssessmentMode from json. +func (o *NilAssessmentMode) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentMode to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentMode + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAssessmentMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentNotDeterminedReason as json. +func (o NilAssessmentNotDeterminedReason) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes AssessmentNotDeterminedReason from json. +func (o *NilAssessmentNotDeterminedReason) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentNotDeterminedReason to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentNotDeterminedReason + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAssessmentNotDeterminedReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentNotDeterminedReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentSessions as json. +func (o NilAssessmentSessions) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes AssessmentSessions from json. +func (o *NilAssessmentSessions) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentSessions to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentSessions + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAssessmentSessions) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentSessions) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentStrength as json. +func (o NilAssessmentStrength) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes AssessmentStrength from json. +func (o *NilAssessmentStrength) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentStrength to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentStrength + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAssessmentStrength) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentStrength) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentUncertainty as json. +func (o NilAssessmentUncertainty) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes AssessmentUncertainty from json. +func (o *NilAssessmentUncertainty) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentUncertainty to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentUncertainty + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAssessmentUncertainty) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentUncertainty) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes BasicScore as json. +func (o NilBasicScore) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes BasicScore from json. +func (o *NilBasicScore) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilBasicScore to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v BasicScore + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilBasicScore) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilBasicScore) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes bool as json. +func (o NilBool) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Bool(bool(o.Value)) +} + +// Decode decodes bool from json. +func (o *NilBool) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilBool to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v bool + o.Value = v + o.Null = true + return nil + } + o.Null = false + v, err := d.Bool() + if err != nil { + return err + } + o.Value = bool(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilBool) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilBool) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CandidateExperience as json. func (o NilCandidateExperience) Encode(e *jx.Encoder) { if o.Null { @@ -2497,6 +9111,184 @@ func (s *NilCandidateExperience) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GradeCode as json. +func (o NilGradeCode) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes GradeCode from json. +func (o *NilGradeCode) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilGradeCode to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v GradeCode + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilGradeCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilGradeCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes int32 as json. +func (o NilInt32) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Int32(int32(o.Value)) +} + +// Decode decodes int32 from json. +func (o *NilInt32) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilInt32 to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v int32 + o.Value = v + o.Null = true + return nil + } + o.Null = false + v, err := d.Int32() + if err != nil { + return err + } + o.Value = int32(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilInt32) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilInt32) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeFailureReason as json. +func (o NilPracticeFailureReason) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes PracticeFailureReason from json. +func (o *NilPracticeFailureReason) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilPracticeFailureReason to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v PracticeFailureReason + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilPracticeFailureReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilPracticeFailureReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeVerdict as json. +func (o NilPracticeVerdict) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes PracticeVerdict from json. +func (o *NilPracticeVerdict) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilPracticeVerdict to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v PracticeVerdict + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilPracticeVerdict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilPracticeVerdict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes string as json. func (o NilString) Encode(e *jx.Encoder) { if o.Null { @@ -2543,6 +9335,50 @@ func (s *NilString) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes TaskLanguage as json. +func (o NilTaskLanguage) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes TaskLanguage from json. +func (o *NilTaskLanguage) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilTaskLanguage to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v TaskLanguage + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilTaskLanguage) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilTaskLanguage) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes Timestamp as json. func (o NilTimestamp) Encode(e *jx.Encoder) { if o.Null { @@ -2587,6 +9423,52 @@ func (s *NilTimestamp) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes uuid.UUID as json. +func (o NilUUID) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + json.EncodeUUID(e, o.Value) +} + +// Decode decodes uuid.UUID from json. +func (o *NilUUID) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilUUID to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v uuid.UUID + o.Value = v + o.Null = true + return nil + } + o.Null = false + v, err := json.DecodeUUID(d) + if err != nil { + return err + } + o.Value = v + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilUUID) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilUUID) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes WorkContext as json. func (o NilWorkContext) Encode(e *jx.Encoder) { if o.Null { @@ -2631,6 +9513,302 @@ func (s *NilWorkContext) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *NumberAnswer) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *NumberAnswer) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("number") + e.Float64(s.Number) + } +} + +var jsonFieldsNameOfNumberAnswer = [2]string{ + 0: "format", + 1: "number", +} + +// Decode decodes NumberAnswer from json. +func (s *NumberAnswer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NumberAnswer to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "number": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Float64() + s.Number = float64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"number\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode NumberAnswer") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfNumberAnswer) { + name = jsonFieldsNameOfNumberAnswer[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *NumberAnswer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NumberAnswer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes NumberAnswerFormat as json. +func (s NumberAnswerFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes NumberAnswerFormat from json. +func (s *NumberAnswerFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NumberAnswerFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch NumberAnswerFormat(v) { + case NumberAnswerFormatNumber: + *s = NumberAnswerFormatNumber + default: + *s = NumberAnswerFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NumberAnswerFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NumberAnswerFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *NumberItemContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *NumberItemContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("unit") + s.Unit.Encode(e) + } +} + +var jsonFieldsNameOfNumberItemContent = [2]string{ + 0: "format", + 1: "unit", +} + +// Decode decodes NumberItemContent from json. +func (s *NumberItemContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NumberItemContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "unit": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Unit.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"unit\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode NumberItemContent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfNumberItemContent) { + name = jsonFieldsNameOfNumberItemContent[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *NumberItemContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NumberItemContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes NumberItemContentFormat as json. +func (s NumberItemContentFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes NumberItemContentFormat from json. +func (s *NumberItemContentFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NumberItemContentFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch NumberItemContentFormat(v) { + case NumberItemContentFormatNumber: + *s = NumberItemContentFormatNumber + default: + *s = NumberItemContentFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NumberItemContentFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NumberItemContentFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes OnboardingStep as json. func (s OnboardingStep) Encode(e *jx.Encoder) { e.Str(string(s)) @@ -2714,6 +9892,324 @@ func (s *OptString) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *OrderAnswer) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *OrderAnswer) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("element_ids") + e.ArrStart() + for _, elem := range s.ElementIds { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfOrderAnswer = [2]string{ + 0: "format", + 1: "element_ids", +} + +// Decode decodes OrderAnswer from json. +func (s *OrderAnswer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OrderAnswer to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "element_ids": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.ElementIds = make([]AssessmentOptionId, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentOptionId + if err := elem.Decode(d); err != nil { + return err + } + s.ElementIds = append(s.ElementIds, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"element_ids\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode OrderAnswer") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfOrderAnswer) { + name = jsonFieldsNameOfOrderAnswer[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *OrderAnswer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OrderAnswer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes OrderAnswerFormat as json. +func (s OrderAnswerFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes OrderAnswerFormat from json. +func (s *OrderAnswerFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OrderAnswerFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch OrderAnswerFormat(v) { + case OrderAnswerFormatOrder: + *s = OrderAnswerFormatOrder + default: + *s = OrderAnswerFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OrderAnswerFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OrderAnswerFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *OrderItemContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *OrderItemContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("elements") + e.ArrStart() + for _, elem := range s.Elements { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfOrderItemContent = [2]string{ + 0: "format", + 1: "elements", +} + +// Decode decodes OrderItemContent from json. +func (s *OrderItemContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OrderItemContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "elements": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Elements = make([]AssessmentOption, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentOption + if err := elem.Decode(d); err != nil { + return err + } + s.Elements = append(s.Elements, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"elements\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode OrderItemContent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfOrderItemContent) { + name = jsonFieldsNameOfOrderItemContent[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *OrderItemContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OrderItemContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes OrderItemContentFormat as json. +func (s OrderItemContentFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes OrderItemContentFormat from json. +func (s *OrderItemContentFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OrderItemContentFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch OrderItemContentFormat(v) { + case OrderItemContentFormatOrder: + *s = OrderItemContentFormatOrder + default: + *s = OrderItemContentFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OrderItemContentFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OrderItemContentFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *PersonalDataConsentAcceptance) Encode(e *jx.Encoder) { e.ObjStart() @@ -2855,6 +10351,863 @@ func (s *PersonalDataConsentAcceptanceAccepted) UnmarshalJSON(data []byte) error return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *PracticeAnswer) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeAnswer) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("language") + s.Language.Encode(e) + } + { + e.FieldStart("source_code") + e.Str(s.SourceCode) + } +} + +var jsonFieldsNameOfPracticeAnswer = [3]string{ + 0: "format", + 1: "language", + 2: "source_code", +} + +// Decode decodes PracticeAnswer from json. +func (s *PracticeAnswer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeAnswer to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "language": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Language.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"language\"") + } + case "source_code": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.SourceCode = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source_code\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PracticeAnswer") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPracticeAnswer) { + name = jsonFieldsNameOfPracticeAnswer[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PracticeAnswer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeAnswer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeAnswerFormat as json. +func (s PracticeAnswerFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PracticeAnswerFormat from json. +func (s *PracticeAnswerFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeAnswerFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PracticeAnswerFormat(v) { + case PracticeAnswerFormatPractice: + *s = PracticeAnswerFormatPractice + default: + *s = PracticeAnswerFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PracticeAnswerFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeAnswerFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PracticeExample) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeExample) encodeFields(e *jx.Encoder) { + { + e.FieldStart("input") + e.Str(s.Input) + } + { + e.FieldStart("expected_output") + e.Str(s.ExpectedOutput) + } +} + +var jsonFieldsNameOfPracticeExample = [2]string{ + 0: "input", + 1: "expected_output", +} + +// Decode decodes PracticeExample from json. +func (s *PracticeExample) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeExample to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "input": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Input = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"input\"") + } + case "expected_output": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.ExpectedOutput = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_output\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PracticeExample") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPracticeExample) { + name = jsonFieldsNameOfPracticeExample[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PracticeExample) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeExample) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeFailureReason as json. +func (s PracticeFailureReason) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PracticeFailureReason from json. +func (s *PracticeFailureReason) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeFailureReason to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PracticeFailureReason(v) { + case PracticeFailureReasonSandboxBusy: + *s = PracticeFailureReasonSandboxBusy + case PracticeFailureReasonSandboxError: + *s = PracticeFailureReasonSandboxError + default: + *s = PracticeFailureReason(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PracticeFailureReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeFailureReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PracticeGroupResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeGroupResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("group") + e.Int32(s.Group) + } + { + e.FieldStart("passed") + e.Bool(s.Passed) + } +} + +var jsonFieldsNameOfPracticeGroupResult = [2]string{ + 0: "group", + 1: "passed", +} + +// Decode decodes PracticeGroupResult from json. +func (s *PracticeGroupResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeGroupResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "group": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.Group = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"group\"") + } + case "passed": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Bool() + s.Passed = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"passed\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PracticeGroupResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPracticeGroupResult) { + name = jsonFieldsNameOfPracticeGroupResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PracticeGroupResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeGroupResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PracticeItemContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeItemContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("languages") + e.ArrStart() + for _, elem := range s.Languages { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("public_examples") + e.ArrStart() + for _, elem := range s.PublicExamples { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("max_source_length") + e.Int32(s.MaxSourceLength) + } +} + +var jsonFieldsNameOfPracticeItemContent = [4]string{ + 0: "format", + 1: "languages", + 2: "public_examples", + 3: "max_source_length", +} + +// Decode decodes PracticeItemContent from json. +func (s *PracticeItemContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeItemContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "languages": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Languages = make([]TaskLanguage, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TaskLanguage + if err := elem.Decode(d); err != nil { + return err + } + s.Languages = append(s.Languages, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"languages\"") + } + case "public_examples": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.PublicExamples = make([]PracticeExample, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem PracticeExample + if err := elem.Decode(d); err != nil { + return err + } + s.PublicExamples = append(s.PublicExamples, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"public_examples\"") + } + case "max_source_length": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.MaxSourceLength = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_source_length\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PracticeItemContent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPracticeItemContent) { + name = jsonFieldsNameOfPracticeItemContent[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PracticeItemContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeItemContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeItemContentFormat as json. +func (s PracticeItemContentFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PracticeItemContentFormat from json. +func (s *PracticeItemContentFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeItemContentFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PracticeItemContentFormat(v) { + case PracticeItemContentFormatPractice: + *s = PracticeItemContentFormatPractice + default: + *s = PracticeItemContentFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PracticeItemContentFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeItemContentFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeKind as json. +func (s PracticeKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PracticeKind from json. +func (s *PracticeKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PracticeKind(v) { + case PracticeKindMain: + *s = PracticeKindMain + case PracticeKindAdditional: + *s = PracticeKindAdditional + default: + *s = PracticeKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PracticeKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeStatus as json. +func (s PracticeStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PracticeStatus from json. +func (s *PracticeStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PracticeStatus(v) { + case PracticeStatusNotStarted: + *s = PracticeStatusNotStarted + case PracticeStatusPending: + *s = PracticeStatusPending + case PracticeStatusFinished: + *s = PracticeStatusFinished + case PracticeStatusFailed: + *s = PracticeStatusFailed + default: + *s = PracticeStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PracticeStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PracticeVerdict) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeVerdict) encodeFields(e *jx.Encoder) { + { + e.FieldStart("score") + e.Int32(s.Score) + } + { + e.FieldStart("max_score") + e.Int32(s.MaxScore) + } + { + e.FieldStart("groups") + e.ArrStart() + for _, elem := range s.Groups { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfPracticeVerdict = [3]string{ + 0: "score", + 1: "max_score", + 2: "groups", +} + +// Decode decodes PracticeVerdict from json. +func (s *PracticeVerdict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeVerdict to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "score": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.Score = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"score\"") + } + case "max_score": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.MaxScore = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_score\"") + } + case "groups": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.Groups = make([]PracticeGroupResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem PracticeGroupResult + if err := elem.Decode(d); err != nil { + return err + } + s.Groups = append(s.Groups, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"groups\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PracticeVerdict") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPracticeVerdict) { + name = jsonFieldsNameOfPracticeVerdict[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PracticeVerdict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeVerdict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *Problem) Encode(e *jx.Encoder) { e.ObjStart() @@ -4419,6 +12772,570 @@ func (s *StackTag) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *StringAnswer) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *StringAnswer) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("text") + e.Str(s.Text) + } +} + +var jsonFieldsNameOfStringAnswer = [2]string{ + 0: "format", + 1: "text", +} + +// Decode decodes StringAnswer from json. +func (s *StringAnswer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StringAnswer to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "text": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Text = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode StringAnswer") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfStringAnswer) { + name = jsonFieldsNameOfStringAnswer[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *StringAnswer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StringAnswer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes StringAnswerFormat as json. +func (s StringAnswerFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes StringAnswerFormat from json. +func (s *StringAnswerFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StringAnswerFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch StringAnswerFormat(v) { + case StringAnswerFormatString: + *s = StringAnswerFormatString + default: + *s = StringAnswerFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s StringAnswerFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StringAnswerFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *StringItemContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *StringItemContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("max_length") + e.Int32(s.MaxLength) + } +} + +var jsonFieldsNameOfStringItemContent = [2]string{ + 0: "format", + 1: "max_length", +} + +// Decode decodes StringItemContent from json. +func (s *StringItemContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StringItemContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "max_length": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.MaxLength = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_length\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode StringItemContent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfStringItemContent) { + name = jsonFieldsNameOfStringItemContent[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *StringItemContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StringItemContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes StringItemContentFormat as json. +func (s StringItemContentFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes StringItemContentFormat from json. +func (s *StringItemContentFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StringItemContentFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch StringItemContentFormat(v) { + case StringItemContentFormatString: + *s = StringItemContentFormatString + default: + *s = StringItemContentFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s StringItemContentFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StringItemContentFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentAnswerBadRequest as json. +func (s *SubmitMyAssessmentAnswerBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentAnswerBadRequest from json. +func (s *SubmitMyAssessmentAnswerBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentAnswerBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitMyAssessmentAnswerBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentAnswerBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentAnswerBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentAnswerConflict as json. +func (s *SubmitMyAssessmentAnswerConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentAnswerConflict from json. +func (s *SubmitMyAssessmentAnswerConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentAnswerConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitMyAssessmentAnswerConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentAnswerConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentAnswerConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentAnswerForbidden as json. +func (s *SubmitMyAssessmentAnswerForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentAnswerForbidden from json. +func (s *SubmitMyAssessmentAnswerForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentAnswerForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitMyAssessmentAnswerForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentAnswerForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentAnswerForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentAnswerNotFound as json. +func (s *SubmitMyAssessmentAnswerNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentAnswerNotFound from json. +func (s *SubmitMyAssessmentAnswerNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentAnswerNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitMyAssessmentAnswerNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentAnswerNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentAnswerNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentAnswerPreconditionFailed as json. +func (s *SubmitMyAssessmentAnswerPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentAnswerPreconditionFailed from json. +func (s *SubmitMyAssessmentAnswerPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentAnswerPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitMyAssessmentAnswerPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentAnswerPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentAnswerPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentAnswerUnauthorized as json. +func (s *SubmitMyAssessmentAnswerUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentAnswerUnauthorized from json. +func (s *SubmitMyAssessmentAnswerUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentAnswerUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitMyAssessmentAnswerUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentAnswerUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentAnswerUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentAnswerUnprocessableEntity as json. +func (s *SubmitMyAssessmentAnswerUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentAnswerUnprocessableEntity from json. +func (s *SubmitMyAssessmentAnswerUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentAnswerUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitMyAssessmentAnswerUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentAnswerUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentAnswerUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes TaskLanguage as json. func (s TaskLanguage) Encode(e *jx.Encoder) { e.Str(string(s)) diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index f34be9a..7201adb 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -6,16 +6,22 @@ package api type OperationName = string const ( - ConfirmEmailOperation OperationName = "ConfirmEmail" - GetConsentTextOperation OperationName = "GetConsentText" - GetCurrentAccountOperation OperationName = "GetCurrentAccount" - GetCurrentSessionOperation OperationName = "GetCurrentSession" - GetHealthzOperation OperationName = "GetHealthz" - GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire" - GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog" - LoginOperation OperationName = "Login" - LogoutOperation OperationName = "Logout" - RegisterAccountOperation OperationName = "RegisterAccount" - ResendEmailVerificationOperation OperationName = "ResendEmailVerification" - SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire" + ConfirmEmailOperation OperationName = "ConfirmEmail" + CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt" + FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt" + GetConsentTextOperation OperationName = "GetConsentText" + GetCurrentAccountOperation OperationName = "GetCurrentAccount" + GetCurrentSessionOperation OperationName = "GetCurrentSession" + GetHealthzOperation OperationName = "GetHealthz" + GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt" + GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability" + GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult" + GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire" + GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog" + LoginOperation OperationName = "Login" + LogoutOperation OperationName = "Logout" + RegisterAccountOperation OperationName = "RegisterAccount" + ResendEmailVerificationOperation OperationName = "ResendEmailVerification" + SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire" + SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer" ) diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go index e493d22..9e70a75 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -7,6 +7,7 @@ import ( "net/url" "github.com/go-faster/errors" + "github.com/google/uuid" "github.com/ogen-go/ogen/conv" "github.com/ogen-go/ogen/middleware" "github.com/ogen-go/ogen/ogenerrors" @@ -14,6 +15,249 @@ import ( "github.com/ogen-go/ogen/validate" ) +// CreateMyAssessmentAttemptParams is parameters of CreateMyAssessmentAttempt operation. +type CreateMyAssessmentAttemptParams struct { + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackCreateMyAssessmentAttemptParams(packed middleware.Parameters) (params CreateMyAssessmentAttemptParams) { + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeCreateMyAssessmentAttemptParams(args [0]string, argsEscaped bool, r *http.Request) (params CreateMyAssessmentAttemptParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} + +// FinalizeMyAssessmentAttemptParams is parameters of FinalizeMyAssessmentAttempt operation. +type FinalizeMyAssessmentAttemptParams struct { + // Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an + // unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. + AttemptID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackFinalizeMyAssessmentAttemptParams(packed middleware.Parameters) (params FinalizeMyAssessmentAttemptParams) { + { + key := middleware.ParameterKey{ + Name: "attempt_id", + In: "path", + } + params.AttemptID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeFinalizeMyAssessmentAttemptParams(args [1]string, argsEscaped bool, r *http.Request) (params FinalizeMyAssessmentAttemptParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: attempt_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "attempt_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.AttemptID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "attempt_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} + // GetConsentTextParams is parameters of GetConsentText operation. type GetConsentTextParams struct { // Consent whose text is requested. @@ -88,6 +332,140 @@ func decodeGetConsentTextParams(args [1]string, argsEscaped bool, r *http.Reques return params, nil } +// GetMyAssessmentAttemptParams is parameters of GetMyAssessmentAttempt operation. +type GetMyAssessmentAttemptParams struct { + // Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an + // unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. + AttemptID uuid.UUID +} + +func unpackGetMyAssessmentAttemptParams(packed middleware.Parameters) (params GetMyAssessmentAttemptParams) { + { + key := middleware.ParameterKey{ + Name: "attempt_id", + In: "path", + } + params.AttemptID = packed[key].(uuid.UUID) + } + return params +} + +func decodeGetMyAssessmentAttemptParams(args [1]string, argsEscaped bool, r *http.Request) (params GetMyAssessmentAttemptParams, _ error) { + // Decode path: attempt_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "attempt_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.AttemptID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "attempt_id", + In: "path", + Err: err, + } + } + return params, nil +} + +// GetMyAssessmentResultParams is parameters of GetMyAssessmentResult operation. +type GetMyAssessmentResultParams struct { + // Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an + // unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. + AttemptID uuid.UUID +} + +func unpackGetMyAssessmentResultParams(packed middleware.Parameters) (params GetMyAssessmentResultParams) { + { + key := middleware.ParameterKey{ + Name: "attempt_id", + In: "path", + } + params.AttemptID = packed[key].(uuid.UUID) + } + return params +} + +func decodeGetMyAssessmentResultParams(args [1]string, argsEscaped bool, r *http.Request) (params GetMyAssessmentResultParams, _ error) { + // Decode path: attempt_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "attempt_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.AttemptID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "attempt_id", + In: "path", + Err: err, + } + } + return params, nil +} + // RegisterAccountParams is parameters of RegisterAccount operation. type RegisterAccountParams struct { // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value @@ -181,3 +559,152 @@ func decodeRegisterAccountParams(args [0]string, argsEscaped bool, r *http.Reque } return params, nil } + +// SubmitMyAssessmentAnswerParams is parameters of SubmitMyAssessmentAnswer operation. +type SubmitMyAssessmentAnswerParams struct { + // Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an + // unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. + AttemptID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackSubmitMyAssessmentAnswerParams(packed middleware.Parameters) (params SubmitMyAssessmentAnswerParams) { + { + key := middleware.ParameterKey{ + Name: "attempt_id", + In: "path", + } + params.AttemptID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *http.Request) (params SubmitMyAssessmentAnswerParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: attempt_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "attempt_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.AttemptID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "attempt_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index 404eda8..a910081 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -93,6 +93,164 @@ func (s *Server) decodeConfirmEmailRequest(r *http.Request) ( } } +func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) ( + req *AssessmentAttemptCreate, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request AssessmentAttemptCreate + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + +func (s *Server) decodeFinalizeMyAssessmentAttemptRequest(r *http.Request) ( + req *AssessmentFinalization, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request AssessmentFinalization + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + func (s *Server) decodeLoginRequest(r *http.Request) ( req *LoginRequest, rawBody []byte, @@ -408,3 +566,82 @@ func (s *Server) decodeSaveMyQuestionnaireRequest(r *http.Request) ( return req, rawBody, close, validate.InvalidContentType(ct) } } + +func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) ( + req *AssessmentAnswerSubmission, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request AssessmentAnswerSubmission + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index 048e78c..072e94a 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -89,6 +89,252 @@ func encodeConfirmEmailResponse(response ConfirmEmailRes, w http.ResponseWriter, } } +func encodeCreateMyAssessmentAttemptResponse(response CreateMyAssessmentAttemptRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentAttemptHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(201) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateMyAssessmentAttemptBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateMyAssessmentAttemptUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateMyAssessmentAttemptForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateMyAssessmentAttemptConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateMyAssessmentAttemptUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeFinalizeMyAssessmentAttemptResponse(response FinalizeMyAssessmentAttemptRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentAttemptHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *FinalizeMyAssessmentAttemptBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *FinalizeMyAssessmentAttemptUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *FinalizeMyAssessmentAttemptForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *FinalizeMyAssessmentAttemptNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *FinalizeMyAssessmentAttemptConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *FinalizeMyAssessmentAttemptPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *FinalizeMyAssessmentAttemptUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeGetConsentTextResponse(response GetConsentTextRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *ConsentText: @@ -227,6 +473,219 @@ func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, s return nil } +func encodeGetMyAssessmentAttemptResponse(response GetMyAssessmentAttemptRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentAttemptHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentAttemptUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentAttemptForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentAttemptNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeGetMyAssessmentAvailabilityResponse(response GetMyAssessmentAvailabilityRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentAvailabilityHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentAvailabilityUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentAvailabilityForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeGetMyAssessmentResultResponse(response GetMyAssessmentResultRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentResultHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentResultUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentResultForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentResultNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentResultConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeGetMyQuestionnaireResponse(response GetMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CandidateQuestionnaireHeaders: @@ -742,6 +1201,157 @@ func encodeSaveMyQuestionnaireResponse(response SaveMyQuestionnaireRes, w http.R } } +func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentAttemptHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SubmitMyAssessmentAnswerBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SubmitMyAssessmentAnswerUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SubmitMyAssessmentAnswerForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SubmitMyAssessmentAnswerNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SubmitMyAssessmentAnswerConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SubmitMyAssessmentAnswerPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SubmitMyAssessmentAnswerUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error { w.Header().Set("Content-Type", "application/problem+json") code := response.StatusCode diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index 4577762..6bf06b0 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,22 +11,31 @@ import ( ) var ( - rn14AllowedHeaders = map[string]string{ + rn23AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn1AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn12AllowedHeaders = map[string]string{ + rn21AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn11AllowedHeaders = map[string]string{ + rn20AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn6AllowedHeaders = map[string]string{ + rn11AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } - rn9AllowedHeaders = map[string]string{ + rn3AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn24AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn6AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn18AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } ) @@ -183,7 +192,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn14AllowedHeaders, + allowedHeaders: rn23AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -260,7 +269,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn12AllowedHeaders, + allowedHeaders: rn21AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -284,7 +293,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn11AllowedHeaders, + allowedHeaders: rn20AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -311,7 +320,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,GET", - allowedHeaders: rn6AllowedHeaders, + allowedHeaders: rn11AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -324,31 +333,242 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } - case 'm': // Prefix: "me/questionnaire" + case 'm': // Prefix: "me/" - if l := len("me/questionnaire"); len(elem) >= l && elem[0:l] == "me/questionnaire" { + if l := len("me/"); len(elem) >= l && elem[0:l] == "me/" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "GET": - s.handleGetMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r) - case "PUT": - s.handleSaveMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET,PUT", - allowedHeaders: rn9AllowedHeaders, - acceptPost: "", - acceptPatch: "", - }) + break + } + switch elem[0] { + case 'a': // Prefix: "assessment-a" + + if l := len("assessment-a"); len(elem) >= l && elem[0:l] == "assessment-a" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 't': // Prefix: "ttempts" + + if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "POST": + s.handleCreateMyAssessmentAttemptRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn3AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "attempt_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleGetMyAssessmentAttemptRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'a': // Prefix: "answers" + + if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleSubmitMyAssessmentAnswerRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn24AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 'f': // Prefix: "finalize" + + if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleFinalizeMyAssessmentAttemptRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn6AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 'r': // Prefix: "result" + + if l := len("result"); len(elem) >= l && elem[0:l] == "result" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyAssessmentResultRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + } + + } + + case 'v': // Prefix: "vailability" + + if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyAssessmentAvailabilityRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + case 'q': // Prefix: "questionnaire" + + if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r) + case "PUT": + s.handleSaveMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,PUT", + allowedHeaders: rn18AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return } - return } case 's': // Prefix: "specializations" @@ -723,38 +943,241 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } - case 'm': // Prefix: "me/questionnaire" + case 'm': // Prefix: "me/" - if l := len("me/questionnaire"); len(elem) >= l && elem[0:l] == "me/questionnaire" { + if l := len("me/"); len(elem) >= l && elem[0:l] == "me/" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. - switch method { - case "GET": - r.name = GetMyQuestionnaireOperation - r.summary = "Read the questionnaire of the current candidate." - r.operationID = "GetMyQuestionnaire" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/questionnaire" - r.args = args - r.count = 0 - return r, true - case "PUT": - r.name = SaveMyQuestionnaireOperation - r.summary = "Replace the questionnaire of the current candidate." - r.operationID = "SaveMyQuestionnaire" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/questionnaire" - r.args = args - r.count = 0 - return r, true - default: - return + break + } + switch elem[0] { + case 'a': // Prefix: "assessment-a" + + if l := len("assessment-a"); len(elem) >= l && elem[0:l] == "assessment-a" { + elem = elem[l:] + } else { + break } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 't': // Prefix: "ttempts" + + if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "POST": + r.name = CreateMyAssessmentAttemptOperation + r.summary = "Start an assessment attempt for a category of the current candidate." + r.operationID = "CreateMyAssessmentAttempt" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "attempt_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + switch method { + case "GET": + r.name = GetMyAssessmentAttemptOperation + r.summary = "Read or resume an assessment attempt of the current candidate." + r.operationID = "GetMyAssessmentAttempt" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'a': // Prefix: "answers" + + if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = SubmitMyAssessmentAnswerOperation + r.summary = "Answer the current item or submit a practice of an assessment attempt." + r.operationID = "SubmitMyAssessmentAnswer" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/answers" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 'f': // Prefix: "finalize" + + if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = FinalizeMyAssessmentAttemptOperation + r.summary = "Ask for the grade decision of an assessment attempt." + r.operationID = "FinalizeMyAssessmentAttempt" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/finalize" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 'r': // Prefix: "result" + + if l := len("result"); len(elem) >= l && elem[0:l] == "result" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyAssessmentResultOperation + r.summary = "Read the result of an assessment attempt of the current candidate." + r.operationID = "GetMyAssessmentResult" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/result" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + } + + } + + } + + case 'v': // Prefix: "vailability" + + if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyAssessmentAvailabilityOperation + r.summary = "Read which assessment attempts the current candidate can start." + r.operationID = "GetMyAssessmentAvailability" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-availability" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + } + + case 'q': // Prefix: "questionnaire" + + if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyQuestionnaireOperation + r.summary = "Read the questionnaire of the current candidate." + r.operationID = "GetMyQuestionnaire" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/questionnaire" + r.args = args + r.count = 0 + return r, true + case "PUT": + r.name = SaveMyQuestionnaireOperation + r.summary = "Replace the questionnaire of the current candidate." + r.operationID = "SaveMyQuestionnaire" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/questionnaire" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + } case 's': // Prefix: "specializations" diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 8f214dd..507afca 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -162,6 +162,2049 @@ func (s *AccountScenario) UnmarshalText(data []byte) error { } } +// Candidate answer, selected by `format`, which must equal the format of the answered item. It carries +// only the answer: no score, duration, correctness flag, or seed. The server records the times itself +// and scores the answer with the key of the fixed item instance. Each format defines when two answers +// are equal, which decides whether a repeated submission is the same answer. +// Ref: #/components/schemas/AssessmentAnswer +// AssessmentAnswer represents sum type. +type AssessmentAnswer struct { + // Type selects the active sum variant, switch on this field. + Type AssessmentAnswerType + ChoiceAnswer ChoiceAnswer + NumberAnswer NumberAnswer + StringAnswer StringAnswer + OrderAnswer OrderAnswer + FindErrorAnswer FindErrorAnswer + ConfigurationAnswer ConfigurationAnswer + PracticeAnswer PracticeAnswer +} + +// AssessmentAnswerType is oneOf type of AssessmentAnswer. +type AssessmentAnswerType string + +// Possible values for AssessmentAnswerType. +const ( + ChoiceAnswerAssessmentAnswer AssessmentAnswerType = "ChoiceAnswer" + NumberAnswerAssessmentAnswer AssessmentAnswerType = "NumberAnswer" + StringAnswerAssessmentAnswer AssessmentAnswerType = "StringAnswer" + OrderAnswerAssessmentAnswer AssessmentAnswerType = "OrderAnswer" + FindErrorAnswerAssessmentAnswer AssessmentAnswerType = "FindErrorAnswer" + ConfigurationAnswerAssessmentAnswer AssessmentAnswerType = "ConfigurationAnswer" + PracticeAnswerAssessmentAnswer AssessmentAnswerType = "PracticeAnswer" +) + +// IsChoiceAnswer reports whether AssessmentAnswer is ChoiceAnswer. +func (s AssessmentAnswer) IsChoiceAnswer() bool { return s.Type == ChoiceAnswerAssessmentAnswer } + +// IsNumberAnswer reports whether AssessmentAnswer is NumberAnswer. +func (s AssessmentAnswer) IsNumberAnswer() bool { return s.Type == NumberAnswerAssessmentAnswer } + +// IsStringAnswer reports whether AssessmentAnswer is StringAnswer. +func (s AssessmentAnswer) IsStringAnswer() bool { return s.Type == StringAnswerAssessmentAnswer } + +// IsOrderAnswer reports whether AssessmentAnswer is OrderAnswer. +func (s AssessmentAnswer) IsOrderAnswer() bool { return s.Type == OrderAnswerAssessmentAnswer } + +// IsFindErrorAnswer reports whether AssessmentAnswer is FindErrorAnswer. +func (s AssessmentAnswer) IsFindErrorAnswer() bool { return s.Type == FindErrorAnswerAssessmentAnswer } + +// IsConfigurationAnswer reports whether AssessmentAnswer is ConfigurationAnswer. +func (s AssessmentAnswer) IsConfigurationAnswer() bool { + return s.Type == ConfigurationAnswerAssessmentAnswer +} + +// IsPracticeAnswer reports whether AssessmentAnswer is PracticeAnswer. +func (s AssessmentAnswer) IsPracticeAnswer() bool { return s.Type == PracticeAnswerAssessmentAnswer } + +// SetChoiceAnswer sets AssessmentAnswer to ChoiceAnswer. +func (s *AssessmentAnswer) SetChoiceAnswer(v ChoiceAnswer) { + s.Type = ChoiceAnswerAssessmentAnswer + s.ChoiceAnswer = v +} + +// GetChoiceAnswer returns ChoiceAnswer and true boolean if AssessmentAnswer is ChoiceAnswer. +func (s AssessmentAnswer) GetChoiceAnswer() (v ChoiceAnswer, ok bool) { + if !s.IsChoiceAnswer() { + return v, false + } + return s.ChoiceAnswer, true +} + +// NewChoiceAnswerAssessmentAnswer returns new AssessmentAnswer from ChoiceAnswer. +func NewChoiceAnswerAssessmentAnswer(v ChoiceAnswer) AssessmentAnswer { + var s AssessmentAnswer + s.SetChoiceAnswer(v) + return s +} + +// SetNumberAnswer sets AssessmentAnswer to NumberAnswer. +func (s *AssessmentAnswer) SetNumberAnswer(v NumberAnswer) { + s.Type = NumberAnswerAssessmentAnswer + s.NumberAnswer = v +} + +// GetNumberAnswer returns NumberAnswer and true boolean if AssessmentAnswer is NumberAnswer. +func (s AssessmentAnswer) GetNumberAnswer() (v NumberAnswer, ok bool) { + if !s.IsNumberAnswer() { + return v, false + } + return s.NumberAnswer, true +} + +// NewNumberAnswerAssessmentAnswer returns new AssessmentAnswer from NumberAnswer. +func NewNumberAnswerAssessmentAnswer(v NumberAnswer) AssessmentAnswer { + var s AssessmentAnswer + s.SetNumberAnswer(v) + return s +} + +// SetStringAnswer sets AssessmentAnswer to StringAnswer. +func (s *AssessmentAnswer) SetStringAnswer(v StringAnswer) { + s.Type = StringAnswerAssessmentAnswer + s.StringAnswer = v +} + +// GetStringAnswer returns StringAnswer and true boolean if AssessmentAnswer is StringAnswer. +func (s AssessmentAnswer) GetStringAnswer() (v StringAnswer, ok bool) { + if !s.IsStringAnswer() { + return v, false + } + return s.StringAnswer, true +} + +// NewStringAnswerAssessmentAnswer returns new AssessmentAnswer from StringAnswer. +func NewStringAnswerAssessmentAnswer(v StringAnswer) AssessmentAnswer { + var s AssessmentAnswer + s.SetStringAnswer(v) + return s +} + +// SetOrderAnswer sets AssessmentAnswer to OrderAnswer. +func (s *AssessmentAnswer) SetOrderAnswer(v OrderAnswer) { + s.Type = OrderAnswerAssessmentAnswer + s.OrderAnswer = v +} + +// GetOrderAnswer returns OrderAnswer and true boolean if AssessmentAnswer is OrderAnswer. +func (s AssessmentAnswer) GetOrderAnswer() (v OrderAnswer, ok bool) { + if !s.IsOrderAnswer() { + return v, false + } + return s.OrderAnswer, true +} + +// NewOrderAnswerAssessmentAnswer returns new AssessmentAnswer from OrderAnswer. +func NewOrderAnswerAssessmentAnswer(v OrderAnswer) AssessmentAnswer { + var s AssessmentAnswer + s.SetOrderAnswer(v) + return s +} + +// SetFindErrorAnswer sets AssessmentAnswer to FindErrorAnswer. +func (s *AssessmentAnswer) SetFindErrorAnswer(v FindErrorAnswer) { + s.Type = FindErrorAnswerAssessmentAnswer + s.FindErrorAnswer = v +} + +// GetFindErrorAnswer returns FindErrorAnswer and true boolean if AssessmentAnswer is FindErrorAnswer. +func (s AssessmentAnswer) GetFindErrorAnswer() (v FindErrorAnswer, ok bool) { + if !s.IsFindErrorAnswer() { + return v, false + } + return s.FindErrorAnswer, true +} + +// NewFindErrorAnswerAssessmentAnswer returns new AssessmentAnswer from FindErrorAnswer. +func NewFindErrorAnswerAssessmentAnswer(v FindErrorAnswer) AssessmentAnswer { + var s AssessmentAnswer + s.SetFindErrorAnswer(v) + return s +} + +// SetConfigurationAnswer sets AssessmentAnswer to ConfigurationAnswer. +func (s *AssessmentAnswer) SetConfigurationAnswer(v ConfigurationAnswer) { + s.Type = ConfigurationAnswerAssessmentAnswer + s.ConfigurationAnswer = v +} + +// GetConfigurationAnswer returns ConfigurationAnswer and true boolean if AssessmentAnswer is ConfigurationAnswer. +func (s AssessmentAnswer) GetConfigurationAnswer() (v ConfigurationAnswer, ok bool) { + if !s.IsConfigurationAnswer() { + return v, false + } + return s.ConfigurationAnswer, true +} + +// NewConfigurationAnswerAssessmentAnswer returns new AssessmentAnswer from ConfigurationAnswer. +func NewConfigurationAnswerAssessmentAnswer(v ConfigurationAnswer) AssessmentAnswer { + var s AssessmentAnswer + s.SetConfigurationAnswer(v) + return s +} + +// SetPracticeAnswer sets AssessmentAnswer to PracticeAnswer. +func (s *AssessmentAnswer) SetPracticeAnswer(v PracticeAnswer) { + s.Type = PracticeAnswerAssessmentAnswer + s.PracticeAnswer = v +} + +// GetPracticeAnswer returns PracticeAnswer and true boolean if AssessmentAnswer is PracticeAnswer. +func (s AssessmentAnswer) GetPracticeAnswer() (v PracticeAnswer, ok bool) { + if !s.IsPracticeAnswer() { + return v, false + } + return s.PracticeAnswer, true +} + +// NewPracticeAnswerAssessmentAnswer returns new AssessmentAnswer from PracticeAnswer. +func NewPracticeAnswerAssessmentAnswer(v PracticeAnswer) AssessmentAnswer { + var s AssessmentAnswer + s.SetPracticeAnswer(v) + return s +} + +// Answer to one item of the attempt. Unknown fields are rejected, so a request cannot send a score, a +// duration, or a correctness flag. +// Ref: #/components/schemas/AssessmentAnswerSubmission +type AssessmentAnswerSubmission struct { + ExpectedVersion AssessmentAttemptVersion `json:"expected_version"` + ItemID AssessmentItemId `json:"item_id"` + Answer AssessmentAnswer `json:"answer"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *AssessmentAnswerSubmission) GetExpectedVersion() AssessmentAttemptVersion { + return s.ExpectedVersion +} + +// GetItemID returns the value of ItemID. +func (s *AssessmentAnswerSubmission) GetItemID() AssessmentItemId { + return s.ItemID +} + +// GetAnswer returns the value of Answer. +func (s *AssessmentAnswerSubmission) GetAnswer() AssessmentAnswer { + return s.Answer +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *AssessmentAnswerSubmission) SetExpectedVersion(val AssessmentAttemptVersion) { + s.ExpectedVersion = val +} + +// SetItemID sets the value of ItemID. +func (s *AssessmentAnswerSubmission) SetItemID(val AssessmentItemId) { + s.ItemID = val +} + +// SetAnswer sets the value of Answer. +func (s *AssessmentAnswerSubmission) SetAnswer(val AssessmentAnswer) { + s.Answer = val +} + +// Assessment attempt of the current candidate for one category, a specialization and a target grade. +// It shows the state, the fixed versions, the server deadline `expires_at` from the policy version, +// which the client clock never extends, the session limit, the progress, the item to answer now, and +// the practices. It never contains answer keys, the correctness of submitted answers, scores of single +// items, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. +// Ref: #/components/schemas/AssessmentAttempt +type AssessmentAttempt struct { + // Attempt identifier. + ID uuid.UUID `json:"id"` + Version AssessmentAttemptVersion `json:"version"` + Specialization SpecializationCode `json:"specialization"` + TargetGrade GradeCode `json:"target_grade"` + // Task language of the attempt, or null when the bank offers no choice. + TaskLanguage NilTaskLanguage `json:"task_language"` + Mode AssessmentMode `json:"mode"` + State AssessmentAttemptState `json:"state"` + Versions AssessmentVersions `json:"versions"` + StartedAt Timestamp `json:"started_at"` + ExpiresAt Timestamp `json:"expires_at"` + // Session limit of the attempt, or null when its policy version defines none. + Sessions NilAssessmentSessions `json:"sessions"` + // Time the attempt reached a terminal state, or null while it is active. + FinishedAt NilTimestamp `json:"finished_at"` + Progress AssessmentProgress `json:"progress"` + // Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` + // or `additional_practice_pending` while that practice is `not_started` or `failed`, and null + // otherwise. + CurrentItem NilAssessmentItem `json:"current_item"` + // Practices in the order they were assigned: the `main` practice first, then an `additional` practice + // once finalize offers it. Empty only for a demo_basic attempt while code practice is disabled until + // the sandbox isolation is verified; its result then lists the `practice_not_included` limitation. A + // list rather than one field leaves room for more practices without a breaking change. + Practices []AssessmentPractice `json:"practices"` +} + +// GetID returns the value of ID. +func (s *AssessmentAttempt) GetID() uuid.UUID { + return s.ID +} + +// GetVersion returns the value of Version. +func (s *AssessmentAttempt) GetVersion() AssessmentAttemptVersion { + return s.Version +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentAttempt) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentAttempt) GetTargetGrade() GradeCode { + return s.TargetGrade +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentAttempt) GetTaskLanguage() NilTaskLanguage { + return s.TaskLanguage +} + +// GetMode returns the value of Mode. +func (s *AssessmentAttempt) GetMode() AssessmentMode { + return s.Mode +} + +// GetState returns the value of State. +func (s *AssessmentAttempt) GetState() AssessmentAttemptState { + return s.State +} + +// GetVersions returns the value of Versions. +func (s *AssessmentAttempt) GetVersions() AssessmentVersions { + return s.Versions +} + +// GetStartedAt returns the value of StartedAt. +func (s *AssessmentAttempt) GetStartedAt() Timestamp { + return s.StartedAt +} + +// GetExpiresAt returns the value of ExpiresAt. +func (s *AssessmentAttempt) GetExpiresAt() Timestamp { + return s.ExpiresAt +} + +// GetSessions returns the value of Sessions. +func (s *AssessmentAttempt) GetSessions() NilAssessmentSessions { + return s.Sessions +} + +// GetFinishedAt returns the value of FinishedAt. +func (s *AssessmentAttempt) GetFinishedAt() NilTimestamp { + return s.FinishedAt +} + +// GetProgress returns the value of Progress. +func (s *AssessmentAttempt) GetProgress() AssessmentProgress { + return s.Progress +} + +// GetCurrentItem returns the value of CurrentItem. +func (s *AssessmentAttempt) GetCurrentItem() NilAssessmentItem { + return s.CurrentItem +} + +// GetPractices returns the value of Practices. +func (s *AssessmentAttempt) GetPractices() []AssessmentPractice { + return s.Practices +} + +// SetID sets the value of ID. +func (s *AssessmentAttempt) SetID(val uuid.UUID) { + s.ID = val +} + +// SetVersion sets the value of Version. +func (s *AssessmentAttempt) SetVersion(val AssessmentAttemptVersion) { + s.Version = val +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentAttempt) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentAttempt) SetTargetGrade(val GradeCode) { + s.TargetGrade = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentAttempt) SetTaskLanguage(val NilTaskLanguage) { + s.TaskLanguage = val +} + +// SetMode sets the value of Mode. +func (s *AssessmentAttempt) SetMode(val AssessmentMode) { + s.Mode = val +} + +// SetState sets the value of State. +func (s *AssessmentAttempt) SetState(val AssessmentAttemptState) { + s.State = val +} + +// SetVersions sets the value of Versions. +func (s *AssessmentAttempt) SetVersions(val AssessmentVersions) { + s.Versions = val +} + +// SetStartedAt sets the value of StartedAt. +func (s *AssessmentAttempt) SetStartedAt(val Timestamp) { + s.StartedAt = val +} + +// SetExpiresAt sets the value of ExpiresAt. +func (s *AssessmentAttempt) SetExpiresAt(val Timestamp) { + s.ExpiresAt = val +} + +// SetSessions sets the value of Sessions. +func (s *AssessmentAttempt) SetSessions(val NilAssessmentSessions) { + s.Sessions = val +} + +// SetFinishedAt sets the value of FinishedAt. +func (s *AssessmentAttempt) SetFinishedAt(val NilTimestamp) { + s.FinishedAt = val +} + +// SetProgress sets the value of Progress. +func (s *AssessmentAttempt) SetProgress(val AssessmentProgress) { + s.Progress = val +} + +// SetCurrentItem sets the value of CurrentItem. +func (s *AssessmentAttempt) SetCurrentItem(val NilAssessmentItem) { + s.CurrentItem = val +} + +// SetPractices sets the value of Practices. +func (s *AssessmentAttempt) SetPractices(val []AssessmentPractice) { + s.Practices = val +} + +// Category to assess: a specialization and the target grade, with the task language. The candidate +// comes from the session. The mode and versions are chosen by the server; unknown fields such as +// `mode`, `seed`, or `score` are rejected. +// Ref: #/components/schemas/AssessmentAttemptCreate +type AssessmentAttemptCreate struct { + Specialization SpecializationCode `json:"specialization"` + TargetGrade GradeCode `json:"target_grade"` + // Task language of the attempt, one of the `task_languages` of the published bank, or null when the + // bank offers no choice of language. The questionnaire choice is the value the client offers first. + TaskLanguage NilTaskLanguage `json:"task_language"` +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentAttemptCreate) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentAttemptCreate) GetTargetGrade() GradeCode { + return s.TargetGrade +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentAttemptCreate) GetTaskLanguage() NilTaskLanguage { + return s.TaskLanguage +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentAttemptCreate) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentAttemptCreate) SetTargetGrade(val GradeCode) { + s.TargetGrade = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentAttemptCreate) SetTaskLanguage(val NilTaskLanguage) { + s.TaskLanguage = val +} + +// AssessmentAttemptHeaders wraps AssessmentAttempt with response headers. +type AssessmentAttemptHeaders struct { + CacheControl CacheControlNoStore + Response AssessmentAttempt +} + +// GetCacheControl returns the value of CacheControl. +func (s *AssessmentAttemptHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AssessmentAttemptHeaders) GetResponse() AssessmentAttempt { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AssessmentAttemptHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AssessmentAttemptHeaders) SetResponse(val AssessmentAttempt) { + s.Response = val +} + +func (*AssessmentAttemptHeaders) createMyAssessmentAttemptRes() {} +func (*AssessmentAttemptHeaders) finalizeMyAssessmentAttemptRes() {} +func (*AssessmentAttemptHeaders) getMyAssessmentAttemptRes() {} +func (*AssessmentAttemptHeaders) submitMyAssessmentAnswerRes() {} + +// Lifecycle state of an attempt and the commands it accepts. +// +// - in_progress: items are being answered; `current_item` is the item to answer. Accepts +// SubmitMyAssessmentAnswer for that item. +// - practice_pending: the item part is finished, and the main practice has no finished verdict yet: +// it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the +// practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while +// its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, +// even when the adaptive stop rule has already ended the item part. +// - additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade +// in the band below confirmation, so the attempt offers one additional practice without spending a +// new attempt; it keeps the time and session limits of the attempt. Accepts +// SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or +// `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and +// decides `not_confirmed` with the current evidence. +// - ready_to_finalize: every required part is done, including a submitted additional practice with a +// finished verdict. Accepts FinalizeMyAssessmentAttempt. +// - completed: a decision was made; the result is available. +// - expired: the time or session limit passed before the candidate finished the required parts. The +// result is available and confirms no grade. +// - insufficient_bank: the published bank could not supply the items required for coverage within the +// limit, and the attempt ended without a confirmed grade instead of repeating families. The result +// is available. +// +// When `expires_at` passes or the session limit is reached, a practice submitted before that and still +// `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is +// finalized and becomes `completed`; `additional_practice_pending` with the additional practice not +// submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and +// `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and +// when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the +// reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and +// `insufficient_bank` are terminal and accept no command except the repeat of finalize described on +// FinalizeMyAssessmentAttempt. Adding a value is a contract change. +// Ref: #/components/schemas/AssessmentAttemptState +type AssessmentAttemptState string + +const ( + AssessmentAttemptStateInProgress AssessmentAttemptState = "in_progress" + AssessmentAttemptStatePracticePending AssessmentAttemptState = "practice_pending" + AssessmentAttemptStateAdditionalPracticePending AssessmentAttemptState = "additional_practice_pending" + AssessmentAttemptStateReadyToFinalize AssessmentAttemptState = "ready_to_finalize" + AssessmentAttemptStateCompleted AssessmentAttemptState = "completed" + AssessmentAttemptStateExpired AssessmentAttemptState = "expired" + AssessmentAttemptStateInsufficientBank AssessmentAttemptState = "insufficient_bank" +) + +// AllValues returns all AssessmentAttemptState values. +func (AssessmentAttemptState) AllValues() []AssessmentAttemptState { + return []AssessmentAttemptState{ + AssessmentAttemptStateInProgress, + AssessmentAttemptStatePracticePending, + AssessmentAttemptStateAdditionalPracticePending, + AssessmentAttemptStateReadyToFinalize, + AssessmentAttemptStateCompleted, + AssessmentAttemptStateExpired, + AssessmentAttemptStateInsufficientBank, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentAttemptState) MarshalText() ([]byte, error) { + switch s { + case AssessmentAttemptStateInProgress: + return []byte(s), nil + case AssessmentAttemptStatePracticePending: + return []byte(s), nil + case AssessmentAttemptStateAdditionalPracticePending: + return []byte(s), nil + case AssessmentAttemptStateReadyToFinalize: + return []byte(s), nil + case AssessmentAttemptStateCompleted: + return []byte(s), nil + case AssessmentAttemptStateExpired: + return []byte(s), nil + case AssessmentAttemptStateInsufficientBank: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentAttemptState) UnmarshalText(data []byte) error { + switch AssessmentAttemptState(data) { + case AssessmentAttemptStateInProgress: + *s = AssessmentAttemptStateInProgress + return nil + case AssessmentAttemptStatePracticePending: + *s = AssessmentAttemptStatePracticePending + return nil + case AssessmentAttemptStateAdditionalPracticePending: + *s = AssessmentAttemptStateAdditionalPracticePending + return nil + case AssessmentAttemptStateReadyToFinalize: + *s = AssessmentAttemptStateReadyToFinalize + return nil + case AssessmentAttemptStateCompleted: + *s = AssessmentAttemptStateCompleted + return nil + case AssessmentAttemptStateExpired: + *s = AssessmentAttemptStateExpired + return nil + case AssessmentAttemptStateInsufficientBank: + *s = AssessmentAttemptStateInsufficientBank + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentAttemptVersion int64 + +// Assessment availability for the specializations of the current candidate's questionnaire, derived at +// the time of the request. +// Ref: #/components/schemas/AssessmentAvailability +type AssessmentAvailability struct { + // Questionnaire specializations in questionnaire order. + Specializations []AssessmentSpecializationAvailability `json:"specializations"` +} + +// GetSpecializations returns the value of Specializations. +func (s *AssessmentAvailability) GetSpecializations() []AssessmentSpecializationAvailability { + return s.Specializations +} + +// SetSpecializations sets the value of Specializations. +func (s *AssessmentAvailability) SetSpecializations(val []AssessmentSpecializationAvailability) { + s.Specializations = val +} + +// AssessmentAvailabilityHeaders wraps AssessmentAvailability with response headers. +type AssessmentAvailabilityHeaders struct { + CacheControl CacheControlNoStore + Response AssessmentAvailability +} + +// GetCacheControl returns the value of CacheControl. +func (s *AssessmentAvailabilityHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AssessmentAvailabilityHeaders) GetResponse() AssessmentAvailability { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AssessmentAvailabilityHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AssessmentAvailabilityHeaders) SetResponse(val AssessmentAvailability) { + s.Response = val +} + +func (*AssessmentAvailabilityHeaders) getMyAssessmentAvailabilityRes() {} + +// Working time recorded by the server. It is a separate label: it never enters the ability estimate or +// the grade decision. +// Ref: #/components/schemas/AssessmentDurations +type AssessmentDurations struct { + ItemsSeconds int32 `json:"items_seconds"` + // Time on all practices with a verdict, or null when no practice has one. + PracticeSeconds NilInt32 `json:"practice_seconds"` +} + +// GetItemsSeconds returns the value of ItemsSeconds. +func (s *AssessmentDurations) GetItemsSeconds() int32 { + return s.ItemsSeconds +} + +// GetPracticeSeconds returns the value of PracticeSeconds. +func (s *AssessmentDurations) GetPracticeSeconds() NilInt32 { + return s.PracticeSeconds +} + +// SetItemsSeconds sets the value of ItemsSeconds. +func (s *AssessmentDurations) SetItemsSeconds(val int32) { + s.ItemsSeconds = val +} + +// SetPracticeSeconds sets the value of PracticeSeconds. +func (s *AssessmentDurations) SetPracticeSeconds(val NilInt32) { + s.PracticeSeconds = val +} + +// Command to finalize the attempt. +// Ref: #/components/schemas/AssessmentFinalization +type AssessmentFinalization struct { + ExpectedVersion AssessmentAttemptVersion `json:"expected_version"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *AssessmentFinalization) GetExpectedVersion() AssessmentAttemptVersion { + return s.ExpectedVersion +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *AssessmentFinalization) SetExpectedVersion(val AssessmentAttemptVersion) { + s.ExpectedVersion = val +} + +// Domain of the specialization where the evidence was weak. +// Ref: #/components/schemas/AssessmentGap +type AssessmentGap struct { + // Stable domain code of the bank blueprint. + Domain string `json:"domain"` + // Display name in Russian. Plain text. + Title string `json:"title"` +} + +// GetDomain returns the value of Domain. +func (s *AssessmentGap) GetDomain() string { + return s.Domain +} + +// GetTitle returns the value of Title. +func (s *AssessmentGap) GetTitle() string { + return s.Title +} + +// SetDomain sets the value of Domain. +func (s *AssessmentGap) SetDomain(val string) { + s.Domain = val +} + +// SetTitle sets the value of Title. +func (s *AssessmentGap) SetTitle(val string) { + s.Title = val +} + +// Availability of an attempt for one grade of a specialization, with the limits that an attempt would +// have, so the client can show them before the start. The limit fields are null when the status is +// `insufficient_bank` or the policy defines no such limit. +// Ref: #/components/schemas/AssessmentGradeAvailability +type AssessmentGradeAvailability struct { + Grade GradeCode `json:"grade"` + Status AssessmentGradeAvailabilityStatus `json:"status"` + // Mode that an attempt would use, or null when the status is `insufficient_bank`. + Mode NilAssessmentMode `json:"mode"` + // When the status is `cooldown`, the first time the attempt can start; otherwise null. + AvailableAt NilTimestamp `json:"available_at"` + // Time from the start to `expires_at`. + TimeLimitSeconds NilInt32 `json:"time_limit_seconds"` + // Session limit within the time limit. + MaxSessions NilInt32 `json:"max_sessions"` + // Item limit, as in `AssessmentProgress.max_items`. + MaxItems NilInt32 `json:"max_items"` + // Whether the attempt would include a main code practice. + PracticeRequired NilBool `json:"practice_required"` +} + +// GetGrade returns the value of Grade. +func (s *AssessmentGradeAvailability) GetGrade() GradeCode { + return s.Grade +} + +// GetStatus returns the value of Status. +func (s *AssessmentGradeAvailability) GetStatus() AssessmentGradeAvailabilityStatus { + return s.Status +} + +// GetMode returns the value of Mode. +func (s *AssessmentGradeAvailability) GetMode() NilAssessmentMode { + return s.Mode +} + +// GetAvailableAt returns the value of AvailableAt. +func (s *AssessmentGradeAvailability) GetAvailableAt() NilTimestamp { + return s.AvailableAt +} + +// GetTimeLimitSeconds returns the value of TimeLimitSeconds. +func (s *AssessmentGradeAvailability) GetTimeLimitSeconds() NilInt32 { + return s.TimeLimitSeconds +} + +// GetMaxSessions returns the value of MaxSessions. +func (s *AssessmentGradeAvailability) GetMaxSessions() NilInt32 { + return s.MaxSessions +} + +// GetMaxItems returns the value of MaxItems. +func (s *AssessmentGradeAvailability) GetMaxItems() NilInt32 { + return s.MaxItems +} + +// GetPracticeRequired returns the value of PracticeRequired. +func (s *AssessmentGradeAvailability) GetPracticeRequired() NilBool { + return s.PracticeRequired +} + +// SetGrade sets the value of Grade. +func (s *AssessmentGradeAvailability) SetGrade(val GradeCode) { + s.Grade = val +} + +// SetStatus sets the value of Status. +func (s *AssessmentGradeAvailability) SetStatus(val AssessmentGradeAvailabilityStatus) { + s.Status = val +} + +// SetMode sets the value of Mode. +func (s *AssessmentGradeAvailability) SetMode(val NilAssessmentMode) { + s.Mode = val +} + +// SetAvailableAt sets the value of AvailableAt. +func (s *AssessmentGradeAvailability) SetAvailableAt(val NilTimestamp) { + s.AvailableAt = val +} + +// SetTimeLimitSeconds sets the value of TimeLimitSeconds. +func (s *AssessmentGradeAvailability) SetTimeLimitSeconds(val NilInt32) { + s.TimeLimitSeconds = val +} + +// SetMaxSessions sets the value of MaxSessions. +func (s *AssessmentGradeAvailability) SetMaxSessions(val NilInt32) { + s.MaxSessions = val +} + +// SetMaxItems sets the value of MaxItems. +func (s *AssessmentGradeAvailability) SetMaxItems(val NilInt32) { + s.MaxItems = val +} + +// SetPracticeRequired sets the value of PracticeRequired. +func (s *AssessmentGradeAvailability) SetPracticeRequired(val NilBool) { + s.PracticeRequired = val +} + +// Whether an attempt for the grade can start now. +// +// - available: CreateMyAssessmentAttempt can start it. +// - active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`. +// - cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until +// `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause +// it. +// - insufficient_bank: no published bank of the category, or not enough unseen families to cover the +// blueprint for this candidate. The server never fills the gap by repeating families. +// +// Ref: #/components/schemas/AssessmentGradeAvailabilityStatus +type AssessmentGradeAvailabilityStatus string + +const ( + AssessmentGradeAvailabilityStatusAvailable AssessmentGradeAvailabilityStatus = "available" + AssessmentGradeAvailabilityStatusActiveAttempt AssessmentGradeAvailabilityStatus = "active_attempt" + AssessmentGradeAvailabilityStatusCooldown AssessmentGradeAvailabilityStatus = "cooldown" + AssessmentGradeAvailabilityStatusInsufficientBank AssessmentGradeAvailabilityStatus = "insufficient_bank" +) + +// AllValues returns all AssessmentGradeAvailabilityStatus values. +func (AssessmentGradeAvailabilityStatus) AllValues() []AssessmentGradeAvailabilityStatus { + return []AssessmentGradeAvailabilityStatus{ + AssessmentGradeAvailabilityStatusAvailable, + AssessmentGradeAvailabilityStatusActiveAttempt, + AssessmentGradeAvailabilityStatusCooldown, + AssessmentGradeAvailabilityStatusInsufficientBank, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentGradeAvailabilityStatus) MarshalText() ([]byte, error) { + switch s { + case AssessmentGradeAvailabilityStatusAvailable: + return []byte(s), nil + case AssessmentGradeAvailabilityStatusActiveAttempt: + return []byte(s), nil + case AssessmentGradeAvailabilityStatusCooldown: + return []byte(s), nil + case AssessmentGradeAvailabilityStatusInsufficientBank: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentGradeAvailabilityStatus) UnmarshalText(data []byte) error { + switch AssessmentGradeAvailabilityStatus(data) { + case AssessmentGradeAvailabilityStatusAvailable: + *s = AssessmentGradeAvailabilityStatusAvailable + return nil + case AssessmentGradeAvailabilityStatusActiveAttempt: + *s = AssessmentGradeAvailabilityStatusActiveAttempt + return nil + case AssessmentGradeAvailabilityStatusCooldown: + *s = AssessmentGradeAvailabilityStatusCooldown + return nil + case AssessmentGradeAvailabilityStatusInsufficientBank: + *s = AssessmentGradeAvailabilityStatusInsufficientBank + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Interval on the ability scale. +// Ref: #/components/schemas/AssessmentInterval +type AssessmentInterval struct { + Low float64 `json:"low"` + High float64 `json:"high"` +} + +// GetLow returns the value of Low. +func (s *AssessmentInterval) GetLow() float64 { + return s.Low +} + +// GetHigh returns the value of High. +func (s *AssessmentInterval) GetHigh() float64 { + return s.High +} + +// SetLow sets the value of Low. +func (s *AssessmentInterval) SetLow(val float64) { + s.Low = val +} + +// SetHigh sets the value of High. +func (s *AssessmentInterval) SetHigh(val float64) { + s.High = val +} + +// Item instance served to the candidate. The variant is fixed when it is first served: a reload, a +// retried request, or a resumed session returns the same instance with the same text and option order. +// The item never says whether an earlier answer was correct, and seed items, which are not scored, are +// indistinguishable from scored ones. +// Ref: #/components/schemas/AssessmentItem +type AssessmentItem struct { + ID AssessmentItemId `json:"id"` + // Position of the item in the attempt, from 1. + Sequence int32 `json:"sequence"` + // Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML. + Prompt string `json:"prompt"` + Content ItemContent `json:"content"` +} + +// GetID returns the value of ID. +func (s *AssessmentItem) GetID() AssessmentItemId { + return s.ID +} + +// GetSequence returns the value of Sequence. +func (s *AssessmentItem) GetSequence() int32 { + return s.Sequence +} + +// GetPrompt returns the value of Prompt. +func (s *AssessmentItem) GetPrompt() string { + return s.Prompt +} + +// GetContent returns the value of Content. +func (s *AssessmentItem) GetContent() ItemContent { + return s.Content +} + +// SetID sets the value of ID. +func (s *AssessmentItem) SetID(val AssessmentItemId) { + s.ID = val +} + +// SetSequence sets the value of Sequence. +func (s *AssessmentItem) SetSequence(val int32) { + s.Sequence = val +} + +// SetPrompt sets the value of Prompt. +func (s *AssessmentItem) SetPrompt(val string) { + s.Prompt = val +} + +// SetContent sets the value of Content. +func (s *AssessmentItem) SetContent(val ItemContent) { + s.Content = val +} + +type AssessmentItemId uuid.UUID + +// Known limitation of the method behind a result, shown with the result. +// +// - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. +// - demo_bank: the result comes from the small reviewed demo bank. +// - practice_not_included: the attempt had no code practice because the sandbox was not enabled. +// - unproctored: the attempt was taken online without supervision. +// +// Adding a value is a contract change. +// Ref: #/components/schemas/AssessmentLimitation +type AssessmentLimitation string + +const ( + AssessmentLimitationUncalibratedThresholds AssessmentLimitation = "uncalibrated_thresholds" + AssessmentLimitationDemoBank AssessmentLimitation = "demo_bank" + AssessmentLimitationPracticeNotIncluded AssessmentLimitation = "practice_not_included" + AssessmentLimitationUnproctored AssessmentLimitation = "unproctored" +) + +// AllValues returns all AssessmentLimitation values. +func (AssessmentLimitation) AllValues() []AssessmentLimitation { + return []AssessmentLimitation{ + AssessmentLimitationUncalibratedThresholds, + AssessmentLimitationDemoBank, + AssessmentLimitationPracticeNotIncluded, + AssessmentLimitationUnproctored, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentLimitation) MarshalText() ([]byte, error) { + switch s { + case AssessmentLimitationUncalibratedThresholds: + return []byte(s), nil + case AssessmentLimitationDemoBank: + return []byte(s), nil + case AssessmentLimitationPracticeNotIncluded: + return []byte(s), nil + case AssessmentLimitationUnproctored: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentLimitation) UnmarshalText(data []byte) error { + switch AssessmentLimitation(data) { + case AssessmentLimitationUncalibratedThresholds: + *s = AssessmentLimitationUncalibratedThresholds + return nil + case AssessmentLimitationDemoBank: + *s = AssessmentLimitationDemoBank + return nil + case AssessmentLimitationPracticeNotIncluded: + *s = AssessmentLimitationPracticeNotIncluded + return nil + case AssessmentLimitationUnproctored: + *s = AssessmentLimitationUnproctored + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Measurement method of an attempt. The server selects it from the published task bank of the +// category; the client never chooses it. +// +// - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the +// versioned basic grading policy. It computes no ability estimate, standard error, or probability, +// so every uncertainty field of its result is null, its thresholds are uncalibrated, and its +// decision is binary: it never offers an additional practice. +// - adaptive: the adaptive test on task families with an ability estimate, its standard error, and +// the probability of reaching the grade threshold, as the versioned assessment policy defines them. +// A probability in the band below confirmation offers one additional practice in the same attempt. +// +// Adding a value is a contract change. +// Ref: #/components/schemas/AssessmentMode +type AssessmentMode string + +const ( + AssessmentModeDemoBasic AssessmentMode = "demo_basic" + AssessmentModeAdaptive AssessmentMode = "adaptive" +) + +// AllValues returns all AssessmentMode values. +func (AssessmentMode) AllValues() []AssessmentMode { + return []AssessmentMode{ + AssessmentModeDemoBasic, + AssessmentModeAdaptive, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentMode) MarshalText() ([]byte, error) { + switch s { + case AssessmentModeDemoBasic: + return []byte(s), nil + case AssessmentModeAdaptive: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentMode) UnmarshalText(data []byte) error { + switch AssessmentMode(data) { + case AssessmentModeDemoBasic: + *s = AssessmentModeDemoBasic + return nil + case AssessmentModeAdaptive: + *s = AssessmentModeAdaptive + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Step that the candidate may take next. +// +// - retake_same_grade: test the same grade again from `available_at`. +// - take_lower_grade: test the lower `grade`. After a failure, including the first test, it is +// allowed at once, outside the same-grade retry interval. +// - accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are +// sufficient (the command is planned). +// - take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a +// promotion, so after it `available_at` is null; after a promotion the next one waits for the +// promotion interval of the policy. +// +// Ref: #/components/schemas/AssessmentNextAction +type AssessmentNextAction string + +const ( + AssessmentNextActionRetakeSameGrade AssessmentNextAction = "retake_same_grade" + AssessmentNextActionTakeLowerGrade AssessmentNextAction = "take_lower_grade" + AssessmentNextActionAcceptLowerGrade AssessmentNextAction = "accept_lower_grade" + AssessmentNextActionTakeHigherGrade AssessmentNextAction = "take_higher_grade" +) + +// AllValues returns all AssessmentNextAction values. +func (AssessmentNextAction) AllValues() []AssessmentNextAction { + return []AssessmentNextAction{ + AssessmentNextActionRetakeSameGrade, + AssessmentNextActionTakeLowerGrade, + AssessmentNextActionAcceptLowerGrade, + AssessmentNextActionTakeHigherGrade, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentNextAction) MarshalText() ([]byte, error) { + switch s { + case AssessmentNextActionRetakeSameGrade: + return []byte(s), nil + case AssessmentNextActionTakeLowerGrade: + return []byte(s), nil + case AssessmentNextActionAcceptLowerGrade: + return []byte(s), nil + case AssessmentNextActionTakeHigherGrade: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentNextAction) UnmarshalText(data []byte) error { + switch AssessmentNextAction(data) { + case AssessmentNextActionRetakeSameGrade: + *s = AssessmentNextActionRetakeSameGrade + return nil + case AssessmentNextActionTakeLowerGrade: + *s = AssessmentNextActionTakeLowerGrade + return nil + case AssessmentNextActionAcceptLowerGrade: + *s = AssessmentNextActionAcceptLowerGrade + return nil + case AssessmentNextActionTakeHigherGrade: + *s = AssessmentNextActionTakeHigherGrade + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Step that the server allows after this result, computed when it was decided. +// Ref: #/components/schemas/AssessmentNextStep +type AssessmentNextStep struct { + Action AssessmentNextAction `json:"action"` + Grade GradeCode `json:"grade"` + // First time the step is allowed, or null when it is allowed now. + AvailableAt NilTimestamp `json:"available_at"` +} + +// GetAction returns the value of Action. +func (s *AssessmentNextStep) GetAction() AssessmentNextAction { + return s.Action +} + +// GetGrade returns the value of Grade. +func (s *AssessmentNextStep) GetGrade() GradeCode { + return s.Grade +} + +// GetAvailableAt returns the value of AvailableAt. +func (s *AssessmentNextStep) GetAvailableAt() NilTimestamp { + return s.AvailableAt +} + +// SetAction sets the value of Action. +func (s *AssessmentNextStep) SetAction(val AssessmentNextAction) { + s.Action = val +} + +// SetGrade sets the value of Grade. +func (s *AssessmentNextStep) SetGrade(val GradeCode) { + s.Grade = val +} + +// SetAvailableAt sets the value of AvailableAt. +func (s *AssessmentNextStep) SetAvailableAt(val NilTimestamp) { + s.AvailableAt = val +} + +// Why an attempt gives no decision, and whether it counts against the retry rules. +// +// - expired: the time or session limit passed before the candidate finished the item part. It is the +// candidate's attempt: it counts toward the attempt limit and starts the same-grade retry interval. +// - practice_incomplete: the item part was done, but the candidate did not submit the main practice +// before the limit. It counts like `expired`. +// - insufficient_bank: the bank could not supply the required coverage within the limit. It is a +// platform limitation: it never counts toward the attempt limit and starts no retry interval. +// - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` +// because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform +// fault: it never counts toward the attempt limit and starts no retry interval. +// +// Ref: #/components/schemas/AssessmentNotDeterminedReason +type AssessmentNotDeterminedReason string + +const ( + AssessmentNotDeterminedReasonExpired AssessmentNotDeterminedReason = "expired" + AssessmentNotDeterminedReasonPracticeIncomplete AssessmentNotDeterminedReason = "practice_incomplete" + AssessmentNotDeterminedReasonInsufficientBank AssessmentNotDeterminedReason = "insufficient_bank" + AssessmentNotDeterminedReasonSandboxUnavailable AssessmentNotDeterminedReason = "sandbox_unavailable" +) + +// AllValues returns all AssessmentNotDeterminedReason values. +func (AssessmentNotDeterminedReason) AllValues() []AssessmentNotDeterminedReason { + return []AssessmentNotDeterminedReason{ + AssessmentNotDeterminedReasonExpired, + AssessmentNotDeterminedReasonPracticeIncomplete, + AssessmentNotDeterminedReasonInsufficientBank, + AssessmentNotDeterminedReasonSandboxUnavailable, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentNotDeterminedReason) MarshalText() ([]byte, error) { + switch s { + case AssessmentNotDeterminedReasonExpired: + return []byte(s), nil + case AssessmentNotDeterminedReasonPracticeIncomplete: + return []byte(s), nil + case AssessmentNotDeterminedReasonInsufficientBank: + return []byte(s), nil + case AssessmentNotDeterminedReasonSandboxUnavailable: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentNotDeterminedReason) UnmarshalText(data []byte) error { + switch AssessmentNotDeterminedReason(data) { + case AssessmentNotDeterminedReasonExpired: + *s = AssessmentNotDeterminedReasonExpired + return nil + case AssessmentNotDeterminedReasonPracticeIncomplete: + *s = AssessmentNotDeterminedReasonPracticeIncomplete + return nil + case AssessmentNotDeterminedReasonInsufficientBank: + *s = AssessmentNotDeterminedReasonInsufficientBank + return nil + case AssessmentNotDeterminedReasonSandboxUnavailable: + *s = AssessmentNotDeterminedReasonSandboxUnavailable + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Choice option or order element. Plain text. +// Ref: #/components/schemas/AssessmentOption +type AssessmentOption struct { + ID AssessmentOptionId `json:"id"` + // Text of the option; the client shows it as text, never as HTML. + Text string `json:"text"` +} + +// GetID returns the value of ID. +func (s *AssessmentOption) GetID() AssessmentOptionId { + return s.ID +} + +// GetText returns the value of Text. +func (s *AssessmentOption) GetText() string { + return s.Text +} + +// SetID sets the value of ID. +func (s *AssessmentOption) SetID(val AssessmentOptionId) { + s.ID = val +} + +// SetText sets the value of Text. +func (s *AssessmentOption) SetText(val string) { + s.Text = val +} + +type AssessmentOptionId string + +// Grade decision of the attempt. +// +// - confirmed: the target grade is confirmed by the rule of the recorded policy version. +// - not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability +// stayed below confirmation after the additional practice, or whose additional practice was +// declined or not submitted in time. The previously confirmed grade, if any, stays in force. +// - not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously +// confirmed grade stays in force. +// +// A failed, expired, or flagged attempt never lowers a confirmed grade. +// Ref: #/components/schemas/AssessmentOutcome +type AssessmentOutcome string + +const ( + AssessmentOutcomeConfirmed AssessmentOutcome = "confirmed" + AssessmentOutcomeNotConfirmed AssessmentOutcome = "not_confirmed" + AssessmentOutcomeNotDetermined AssessmentOutcome = "not_determined" +) + +// AllValues returns all AssessmentOutcome values. +func (AssessmentOutcome) AllValues() []AssessmentOutcome { + return []AssessmentOutcome{ + AssessmentOutcomeConfirmed, + AssessmentOutcomeNotConfirmed, + AssessmentOutcomeNotDetermined, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentOutcome) MarshalText() ([]byte, error) { + switch s { + case AssessmentOutcomeConfirmed: + return []byte(s), nil + case AssessmentOutcomeNotConfirmed: + return []byte(s), nil + case AssessmentOutcomeNotDetermined: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentOutcome) UnmarshalText(data []byte) error { + switch AssessmentOutcome(data) { + case AssessmentOutcomeConfirmed: + *s = AssessmentOutcomeConfirmed + return nil + case AssessmentOutcomeNotConfirmed: + *s = AssessmentOutcomeNotConfirmed + return nil + case AssessmentOutcomeNotDetermined: + *s = AssessmentOutcomeNotDetermined + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept +// as a separate label and never enters the ability estimate or the grade decision. +// Ref: #/components/schemas/AssessmentPractice +type AssessmentPractice struct { + Kind PracticeKind `json:"kind"` + ItemID AssessmentItemId `json:"item_id"` + Status PracticeStatus `json:"status"` + // Time of the latest submission, or null before the first one. + SubmittedAt NilTimestamp `json:"submitted_at"` + // The verdict when `status` is `finished`, otherwise null. + Verdict NilPracticeVerdict `json:"verdict"` + // The reason when `status` is `failed`, otherwise null. + FailureReason NilPracticeFailureReason `json:"failure_reason"` +} + +// GetKind returns the value of Kind. +func (s *AssessmentPractice) GetKind() PracticeKind { + return s.Kind +} + +// GetItemID returns the value of ItemID. +func (s *AssessmentPractice) GetItemID() AssessmentItemId { + return s.ItemID +} + +// GetStatus returns the value of Status. +func (s *AssessmentPractice) GetStatus() PracticeStatus { + return s.Status +} + +// GetSubmittedAt returns the value of SubmittedAt. +func (s *AssessmentPractice) GetSubmittedAt() NilTimestamp { + return s.SubmittedAt +} + +// GetVerdict returns the value of Verdict. +func (s *AssessmentPractice) GetVerdict() NilPracticeVerdict { + return s.Verdict +} + +// GetFailureReason returns the value of FailureReason. +func (s *AssessmentPractice) GetFailureReason() NilPracticeFailureReason { + return s.FailureReason +} + +// SetKind sets the value of Kind. +func (s *AssessmentPractice) SetKind(val PracticeKind) { + s.Kind = val +} + +// SetItemID sets the value of ItemID. +func (s *AssessmentPractice) SetItemID(val AssessmentItemId) { + s.ItemID = val +} + +// SetStatus sets the value of Status. +func (s *AssessmentPractice) SetStatus(val PracticeStatus) { + s.Status = val +} + +// SetSubmittedAt sets the value of SubmittedAt. +func (s *AssessmentPractice) SetSubmittedAt(val NilTimestamp) { + s.SubmittedAt = val +} + +// SetVerdict sets the value of Verdict. +func (s *AssessmentPractice) SetVerdict(val NilPracticeVerdict) { + s.Verdict = val +} + +// SetFailureReason sets the value of FailureReason. +func (s *AssessmentPractice) SetFailureReason(val NilPracticeFailureReason) { + s.FailureReason = val +} + +// Verdict of one practice of the attempt. +// Ref: #/components/schemas/AssessmentPracticeResult +type AssessmentPracticeResult struct { + Kind PracticeKind `json:"kind"` + Verdict PracticeVerdict `json:"verdict"` +} + +// GetKind returns the value of Kind. +func (s *AssessmentPracticeResult) GetKind() PracticeKind { + return s.Kind +} + +// GetVerdict returns the value of Verdict. +func (s *AssessmentPracticeResult) GetVerdict() PracticeVerdict { + return s.Verdict +} + +// SetKind sets the value of Kind. +func (s *AssessmentPracticeResult) SetKind(val PracticeKind) { + s.Kind = val +} + +// SetVerdict sets the value of Verdict. +func (s *AssessmentPracticeResult) SetVerdict(val PracticeVerdict) { + s.Verdict = val +} + +// Progress of the item part. It counts seed items like scored ones, so it does not reveal which items +// are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A +// finalize refused as premature does not list the unfinished parts; the client reads them here, in +// `current_item`, and in `practices`. +// Ref: #/components/schemas/AssessmentProgress +type AssessmentProgress struct { + AnsweredItems int32 `json:"answered_items"` + // Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items + // together in adaptive. + MaxItems int32 `json:"max_items"` +} + +// GetAnsweredItems returns the value of AnsweredItems. +func (s *AssessmentProgress) GetAnsweredItems() int32 { + return s.AnsweredItems +} + +// GetMaxItems returns the value of MaxItems. +func (s *AssessmentProgress) GetMaxItems() int32 { + return s.MaxItems +} + +// SetAnsweredItems sets the value of AnsweredItems. +func (s *AssessmentProgress) SetAnsweredItems(val int32) { + s.AnsweredItems = val +} + +// SetMaxItems sets the value of MaxItems. +func (s *AssessmentProgress) SetMaxItems(val int32) { + s.MaxItems = val +} + +// Immutable result of a terminal attempt, visible only to its candidate. It records the method, the +// versions, the decision, its uncertainty, and its limitations; a later policy, bank, or algorithm +// version never changes it. It never contains answers, per-item correctness, answer keys, seeds, +// hidden checks, or anti-cheat signals. Fields that the method does not compute are null, never zero: +// demo_basic has null `uncertainty` and `strength`, and adaptive has null `basic_score`. +// Ref: #/components/schemas/AssessmentResult +type AssessmentResult struct { + AttemptID uuid.UUID `json:"attempt_id"` + Specialization SpecializationCode `json:"specialization"` + TargetGrade GradeCode `json:"target_grade"` + TaskLanguage NilTaskLanguage `json:"task_language"` + Mode AssessmentMode `json:"mode"` + Versions AssessmentVersions `json:"versions"` + Outcome AssessmentOutcome `json:"outcome"` + // The reason when `outcome` is `not_determined`, otherwise null. + NotDeterminedReason NilAssessmentNotDeterminedReason `json:"not_determined_reason"` + // Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with + // the specialization it forms the category. + ConfirmedGrade NilGradeCode `json:"confirmed_grade"` + // Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed + // nothing, this grade stays in force. + PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"` + // Strength of an adaptive confirmation, otherwise null. + Strength NilAssessmentStrength `json:"strength"` + CalibrationStatus CalibrationStatus `json:"calibration_status"` + Limitations []AssessmentLimitation `json:"limitations"` + // Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which + // computes none, and for an attempt without a decision. + Uncertainty NilAssessmentUncertainty `json:"uncertainty"` + // Raw score of a demo_basic attempt with a decision, otherwise null. + BasicScore NilBasicScore `json:"basic_score"` + // Verdicts of the practices that have one, main first. + Practices []AssessmentPracticeResult `json:"practices"` + // Domains with weak evidence; empty when none were found or the method finds none. + Gaps []AssessmentGap `json:"gaps"` + Durations AssessmentDurations `json:"durations"` + NextSteps []AssessmentNextStep `json:"next_steps"` + DecidedAt Timestamp `json:"decided_at"` +} + +// GetAttemptID returns the value of AttemptID. +func (s *AssessmentResult) GetAttemptID() uuid.UUID { + return s.AttemptID +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentResult) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentResult) GetTargetGrade() GradeCode { + return s.TargetGrade +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentResult) GetTaskLanguage() NilTaskLanguage { + return s.TaskLanguage +} + +// GetMode returns the value of Mode. +func (s *AssessmentResult) GetMode() AssessmentMode { + return s.Mode +} + +// GetVersions returns the value of Versions. +func (s *AssessmentResult) GetVersions() AssessmentVersions { + return s.Versions +} + +// GetOutcome returns the value of Outcome. +func (s *AssessmentResult) GetOutcome() AssessmentOutcome { + return s.Outcome +} + +// GetNotDeterminedReason returns the value of NotDeterminedReason. +func (s *AssessmentResult) GetNotDeterminedReason() NilAssessmentNotDeterminedReason { + return s.NotDeterminedReason +} + +// GetConfirmedGrade returns the value of ConfirmedGrade. +func (s *AssessmentResult) GetConfirmedGrade() NilGradeCode { + return s.ConfirmedGrade +} + +// GetPreviousConfirmedGrade returns the value of PreviousConfirmedGrade. +func (s *AssessmentResult) GetPreviousConfirmedGrade() NilGradeCode { + return s.PreviousConfirmedGrade +} + +// GetStrength returns the value of Strength. +func (s *AssessmentResult) GetStrength() NilAssessmentStrength { + return s.Strength +} + +// GetCalibrationStatus returns the value of CalibrationStatus. +func (s *AssessmentResult) GetCalibrationStatus() CalibrationStatus { + return s.CalibrationStatus +} + +// GetLimitations returns the value of Limitations. +func (s *AssessmentResult) GetLimitations() []AssessmentLimitation { + return s.Limitations +} + +// GetUncertainty returns the value of Uncertainty. +func (s *AssessmentResult) GetUncertainty() NilAssessmentUncertainty { + return s.Uncertainty +} + +// GetBasicScore returns the value of BasicScore. +func (s *AssessmentResult) GetBasicScore() NilBasicScore { + return s.BasicScore +} + +// GetPractices returns the value of Practices. +func (s *AssessmentResult) GetPractices() []AssessmentPracticeResult { + return s.Practices +} + +// GetGaps returns the value of Gaps. +func (s *AssessmentResult) GetGaps() []AssessmentGap { + return s.Gaps +} + +// GetDurations returns the value of Durations. +func (s *AssessmentResult) GetDurations() AssessmentDurations { + return s.Durations +} + +// GetNextSteps returns the value of NextSteps. +func (s *AssessmentResult) GetNextSteps() []AssessmentNextStep { + return s.NextSteps +} + +// GetDecidedAt returns the value of DecidedAt. +func (s *AssessmentResult) GetDecidedAt() Timestamp { + return s.DecidedAt +} + +// SetAttemptID sets the value of AttemptID. +func (s *AssessmentResult) SetAttemptID(val uuid.UUID) { + s.AttemptID = val +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentResult) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentResult) SetTargetGrade(val GradeCode) { + s.TargetGrade = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentResult) SetTaskLanguage(val NilTaskLanguage) { + s.TaskLanguage = val +} + +// SetMode sets the value of Mode. +func (s *AssessmentResult) SetMode(val AssessmentMode) { + s.Mode = val +} + +// SetVersions sets the value of Versions. +func (s *AssessmentResult) SetVersions(val AssessmentVersions) { + s.Versions = val +} + +// SetOutcome sets the value of Outcome. +func (s *AssessmentResult) SetOutcome(val AssessmentOutcome) { + s.Outcome = val +} + +// SetNotDeterminedReason sets the value of NotDeterminedReason. +func (s *AssessmentResult) SetNotDeterminedReason(val NilAssessmentNotDeterminedReason) { + s.NotDeterminedReason = val +} + +// SetConfirmedGrade sets the value of ConfirmedGrade. +func (s *AssessmentResult) SetConfirmedGrade(val NilGradeCode) { + s.ConfirmedGrade = val +} + +// SetPreviousConfirmedGrade sets the value of PreviousConfirmedGrade. +func (s *AssessmentResult) SetPreviousConfirmedGrade(val NilGradeCode) { + s.PreviousConfirmedGrade = val +} + +// SetStrength sets the value of Strength. +func (s *AssessmentResult) SetStrength(val NilAssessmentStrength) { + s.Strength = val +} + +// SetCalibrationStatus sets the value of CalibrationStatus. +func (s *AssessmentResult) SetCalibrationStatus(val CalibrationStatus) { + s.CalibrationStatus = val +} + +// SetLimitations sets the value of Limitations. +func (s *AssessmentResult) SetLimitations(val []AssessmentLimitation) { + s.Limitations = val +} + +// SetUncertainty sets the value of Uncertainty. +func (s *AssessmentResult) SetUncertainty(val NilAssessmentUncertainty) { + s.Uncertainty = val +} + +// SetBasicScore sets the value of BasicScore. +func (s *AssessmentResult) SetBasicScore(val NilBasicScore) { + s.BasicScore = val +} + +// SetPractices sets the value of Practices. +func (s *AssessmentResult) SetPractices(val []AssessmentPracticeResult) { + s.Practices = val +} + +// SetGaps sets the value of Gaps. +func (s *AssessmentResult) SetGaps(val []AssessmentGap) { + s.Gaps = val +} + +// SetDurations sets the value of Durations. +func (s *AssessmentResult) SetDurations(val AssessmentDurations) { + s.Durations = val +} + +// SetNextSteps sets the value of NextSteps. +func (s *AssessmentResult) SetNextSteps(val []AssessmentNextStep) { + s.NextSteps = val +} + +// SetDecidedAt sets the value of DecidedAt. +func (s *AssessmentResult) SetDecidedAt(val Timestamp) { + s.DecidedAt = val +} + +// AssessmentResultHeaders wraps AssessmentResult with response headers. +type AssessmentResultHeaders struct { + CacheControl CacheControlNoStore + Response AssessmentResult +} + +// GetCacheControl returns the value of CacheControl. +func (s *AssessmentResultHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AssessmentResultHeaders) GetResponse() AssessmentResult { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AssessmentResultHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AssessmentResultHeaders) SetResponse(val AssessmentResult) { + s.Response = val +} + +func (*AssessmentResultHeaders) getMyAssessmentResultRes() {} + +// Work sessions of the attempt, as the policy version limits them, for example two sessions within the +// time limit. +// +// A session starts with the creation of the attempt or, after the previous session ended, with the +// next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` +// without such a request. A request that would start a session beyond `max_sessions` starts none: the +// server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a +// command). Reading a terminal attempt or a result never starts a session. +// Ref: #/components/schemas/AssessmentSessions +type AssessmentSessions struct { + // Sessions started so far, including the current one. + Used int32 `json:"used"` + Max int32 `json:"max"` + // Inactivity after which the current session ends. + IdleTimeoutSeconds int32 `json:"idle_timeout_seconds"` +} + +// GetUsed returns the value of Used. +func (s *AssessmentSessions) GetUsed() int32 { + return s.Used +} + +// GetMax returns the value of Max. +func (s *AssessmentSessions) GetMax() int32 { + return s.Max +} + +// GetIdleTimeoutSeconds returns the value of IdleTimeoutSeconds. +func (s *AssessmentSessions) GetIdleTimeoutSeconds() int32 { + return s.IdleTimeoutSeconds +} + +// SetUsed sets the value of Used. +func (s *AssessmentSessions) SetUsed(val int32) { + s.Used = val +} + +// SetMax sets the value of Max. +func (s *AssessmentSessions) SetMax(val int32) { + s.Max = val +} + +// SetIdleTimeoutSeconds sets the value of IdleTimeoutSeconds. +func (s *AssessmentSessions) SetIdleTimeoutSeconds(val int32) { + s.IdleTimeoutSeconds = val +} + +// Assessment state of one questionnaire specialization. Specializations are assessed independently, +// with independent retry intervals. +// Ref: #/components/schemas/AssessmentSpecializationAvailability +type AssessmentSpecializationAvailability struct { + Specialization SpecializationCode `json:"specialization"` + // Currently confirmed grade of the specialization, or null. + ConfirmedGrade NilGradeCode `json:"confirmed_grade"` + // Identifier of the active attempt of the specialization, or null. + ActiveAttemptID NilUUID `json:"active_attempt_id"` + // Every grade of the scale in ascending order. + Grades []AssessmentGradeAvailability `json:"grades"` +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentSpecializationAvailability) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetConfirmedGrade returns the value of ConfirmedGrade. +func (s *AssessmentSpecializationAvailability) GetConfirmedGrade() NilGradeCode { + return s.ConfirmedGrade +} + +// GetActiveAttemptID returns the value of ActiveAttemptID. +func (s *AssessmentSpecializationAvailability) GetActiveAttemptID() NilUUID { + return s.ActiveAttemptID +} + +// GetGrades returns the value of Grades. +func (s *AssessmentSpecializationAvailability) GetGrades() []AssessmentGradeAvailability { + return s.Grades +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentSpecializationAvailability) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetConfirmedGrade sets the value of ConfirmedGrade. +func (s *AssessmentSpecializationAvailability) SetConfirmedGrade(val NilGradeCode) { + s.ConfirmedGrade = val +} + +// SetActiveAttemptID sets the value of ActiveAttemptID. +func (s *AssessmentSpecializationAvailability) SetActiveAttemptID(val NilUUID) { + s.ActiveAttemptID = val +} + +// SetGrades sets the value of Grades. +func (s *AssessmentSpecializationAvailability) SetGrades(val []AssessmentGradeAvailability) { + s.Grades = val +} + +// Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded +// policy version. +// Ref: #/components/schemas/AssessmentStrength +type AssessmentStrength string + +const ( + AssessmentStrengthHigh AssessmentStrength = "high" + AssessmentStrengthMedium AssessmentStrength = "medium" +) + +// AllValues returns all AssessmentStrength values. +func (AssessmentStrength) AllValues() []AssessmentStrength { + return []AssessmentStrength{ + AssessmentStrengthHigh, + AssessmentStrengthMedium, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentStrength) MarshalText() ([]byte, error) { + switch s { + case AssessmentStrengthHigh: + return []byte(s), nil + case AssessmentStrengthMedium: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentStrength) UnmarshalText(data []byte) error { + switch AssessmentStrength(data) { + case AssessmentStrengthHigh: + *s = AssessmentStrengthHigh + return nil + case AssessmentStrengthMedium: + *s = AssessmentStrengthMedium + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization +// scale, its standard error, the 95% interval, and the probability of reaching the target grade +// threshold. The interval is reported but is not a separate stop condition. +// Ref: #/components/schemas/AssessmentUncertainty +type AssessmentUncertainty struct { + Theta float64 `json:"theta"` + StandardError float64 `json:"standard_error"` + Interval95 AssessmentInterval `json:"interval_95"` + // Probability of reaching the threshold of the target grade. + PGrade float64 `json:"p_grade"` +} + +// GetTheta returns the value of Theta. +func (s *AssessmentUncertainty) GetTheta() float64 { + return s.Theta +} + +// GetStandardError returns the value of StandardError. +func (s *AssessmentUncertainty) GetStandardError() float64 { + return s.StandardError +} + +// GetInterval95 returns the value of Interval95. +func (s *AssessmentUncertainty) GetInterval95() AssessmentInterval { + return s.Interval95 +} + +// GetPGrade returns the value of PGrade. +func (s *AssessmentUncertainty) GetPGrade() float64 { + return s.PGrade +} + +// SetTheta sets the value of Theta. +func (s *AssessmentUncertainty) SetTheta(val float64) { + s.Theta = val +} + +// SetStandardError sets the value of StandardError. +func (s *AssessmentUncertainty) SetStandardError(val float64) { + s.StandardError = val +} + +// SetInterval95 sets the value of Interval95. +func (s *AssessmentUncertainty) SetInterval95(val AssessmentInterval) { + s.Interval95 = val +} + +// SetPGrade sets the value of PGrade. +func (s *AssessmentUncertainty) SetPGrade(val float64) { + s.PGrade = val +} + +type AssessmentVersionLabel string + +// Versions fixed when the attempt was created. They never change during the attempt, and a result is +// always reproduced from the stored answers with these versions; a later policy, bank, or algorithm +// version does not rewrite it. +// Ref: #/components/schemas/AssessmentVersions +type AssessmentVersions struct { + // Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item + // limits, time and session limits, and retry intervals. + PolicyVersion int32 `json:"policy_version"` + BankVersion AssessmentVersionLabel `json:"bank_version"` + AlgorithmVersion AssessmentVersionLabel `json:"algorithm_version"` +} + +// GetPolicyVersion returns the value of PolicyVersion. +func (s *AssessmentVersions) GetPolicyVersion() int32 { + return s.PolicyVersion +} + +// GetBankVersion returns the value of BankVersion. +func (s *AssessmentVersions) GetBankVersion() AssessmentVersionLabel { + return s.BankVersion +} + +// GetAlgorithmVersion returns the value of AlgorithmVersion. +func (s *AssessmentVersions) GetAlgorithmVersion() AssessmentVersionLabel { + return s.AlgorithmVersion +} + +// SetPolicyVersion sets the value of PolicyVersion. +func (s *AssessmentVersions) SetPolicyVersion(val int32) { + s.PolicyVersion = val +} + +// SetBankVersion sets the value of BankVersion. +func (s *AssessmentVersions) SetBankVersion(val AssessmentVersionLabel) { + s.BankVersion = val +} + +// SetAlgorithmVersion sets the value of AlgorithmVersion. +func (s *AssessmentVersions) SetAlgorithmVersion(val AssessmentVersionLabel) { + s.AlgorithmVersion = val +} + +// Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass +// mark comes from that policy version and never from the handler. +// Ref: #/components/schemas/BasicScore +type BasicScore struct { + Points int32 `json:"points"` + MaxPoints int32 `json:"max_points"` + PassPoints int32 `json:"pass_points"` +} + +// GetPoints returns the value of Points. +func (s *BasicScore) GetPoints() int32 { + return s.Points +} + +// GetMaxPoints returns the value of MaxPoints. +func (s *BasicScore) GetMaxPoints() int32 { + return s.MaxPoints +} + +// GetPassPoints returns the value of PassPoints. +func (s *BasicScore) GetPassPoints() int32 { + return s.PassPoints +} + +// SetPoints sets the value of Points. +func (s *BasicScore) SetPoints(val int32) { + s.Points = val +} + +// SetMaxPoints sets the value of MaxPoints. +func (s *BasicScore) SetMaxPoints(val int32) { + s.MaxPoints = val +} + +// SetPassPoints sets the value of PassPoints. +func (s *BasicScore) SetPassPoints(val int32) { + s.PassPoints = val +} + type CacheControlNoStore string const ( @@ -196,6 +2239,51 @@ func (s *CacheControlNoStore) UnmarshalText(data []byte) error { } } +// Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` +// results are provisional: their thresholds come from expert judgement, and their probabilities are +// not claimed to be calibrated. +// Ref: #/components/schemas/CalibrationStatus +type CalibrationStatus string + +const ( + CalibrationStatusUncalibrated CalibrationStatus = "uncalibrated" + CalibrationStatusCalibrated CalibrationStatus = "calibrated" +) + +// AllValues returns all CalibrationStatus values. +func (CalibrationStatus) AllValues() []CalibrationStatus { + return []CalibrationStatus{ + CalibrationStatusUncalibrated, + CalibrationStatusCalibrated, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CalibrationStatus) MarshalText() ([]byte, error) { + switch s { + case CalibrationStatusUncalibrated: + return []byte(s), nil + case CalibrationStatusCalibrated: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CalibrationStatus) UnmarshalText(data []byte) error { + switch CalibrationStatus(data) { + case CalibrationStatusUncalibrated: + *s = CalibrationStatusUncalibrated + return nil + case CalibrationStatusCalibrated: + *s = CalibrationStatusCalibrated + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Experience that the candidate states for one specialization, in whole months. It is self-reported // context: it never adds assessment points and never confirms a grade. // Ref: #/components/schemas/CandidateExperience @@ -461,6 +2549,321 @@ func (s *CatalogSpecialization) SetTestAvailability(val TestAvailability) { s.TestAvailability = val } +// Selected options of a choice item: exactly one unless the item allows several. Two answers are equal +// when they select the same set of options, in any order. +// Ref: #/components/schemas/ChoiceAnswer +type ChoiceAnswer struct { + Format ChoiceAnswerFormat `json:"format"` + OptionIds []AssessmentOptionId `json:"option_ids"` +} + +// GetFormat returns the value of Format. +func (s *ChoiceAnswer) GetFormat() ChoiceAnswerFormat { + return s.Format +} + +// GetOptionIds returns the value of OptionIds. +func (s *ChoiceAnswer) GetOptionIds() []AssessmentOptionId { + return s.OptionIds +} + +// SetFormat sets the value of Format. +func (s *ChoiceAnswer) SetFormat(val ChoiceAnswerFormat) { + s.Format = val +} + +// SetOptionIds sets the value of OptionIds. +func (s *ChoiceAnswer) SetOptionIds(val []AssessmentOptionId) { + s.OptionIds = val +} + +type ChoiceAnswerFormat string + +const ( + ChoiceAnswerFormatChoice ChoiceAnswerFormat = "choice" +) + +// AllValues returns all ChoiceAnswerFormat values. +func (ChoiceAnswerFormat) AllValues() []ChoiceAnswerFormat { + return []ChoiceAnswerFormat{ + ChoiceAnswerFormatChoice, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ChoiceAnswerFormat) MarshalText() ([]byte, error) { + switch s { + case ChoiceAnswerFormatChoice: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ChoiceAnswerFormat) UnmarshalText(data []byte) error { + switch ChoiceAnswerFormat(data) { + case ChoiceAnswerFormatChoice: + *s = ChoiceAnswerFormatChoice + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Choose one option, or several when `multiple` is true. The content never says which options are +// correct or how many are. +// Ref: #/components/schemas/ChoiceItemContent +type ChoiceItemContent struct { + Format ChoiceItemContentFormat `json:"format"` + // Options in the order of this instance. + Options []AssessmentOption `json:"options"` + // Whether more than one option may be selected. It is a property of the task family, fixed for every + // variant, and never derived from the key: a multiple-choice variant may have a single correct option. + Multiple bool `json:"multiple"` +} + +// GetFormat returns the value of Format. +func (s *ChoiceItemContent) GetFormat() ChoiceItemContentFormat { + return s.Format +} + +// GetOptions returns the value of Options. +func (s *ChoiceItemContent) GetOptions() []AssessmentOption { + return s.Options +} + +// GetMultiple returns the value of Multiple. +func (s *ChoiceItemContent) GetMultiple() bool { + return s.Multiple +} + +// SetFormat sets the value of Format. +func (s *ChoiceItemContent) SetFormat(val ChoiceItemContentFormat) { + s.Format = val +} + +// SetOptions sets the value of Options. +func (s *ChoiceItemContent) SetOptions(val []AssessmentOption) { + s.Options = val +} + +// SetMultiple sets the value of Multiple. +func (s *ChoiceItemContent) SetMultiple(val bool) { + s.Multiple = val +} + +type ChoiceItemContentFormat string + +const ( + ChoiceItemContentFormatChoice ChoiceItemContentFormat = "choice" +) + +// AllValues returns all ChoiceItemContentFormat values. +func (ChoiceItemContentFormat) AllValues() []ChoiceItemContentFormat { + return []ChoiceItemContentFormat{ + ChoiceItemContentFormatChoice, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ChoiceItemContentFormat) MarshalText() ([]byte, error) { + switch s { + case ChoiceItemContentFormatChoice: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ChoiceItemContentFormat) UnmarshalText(data []byte) error { + switch ChoiceItemContentFormat(data) { + case ChoiceItemContentFormatChoice: + *s = ChoiceItemContentFormatChoice + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One numbered line of a code or configuration fragment. Plain text. +// Ref: #/components/schemas/CodeLine +type CodeLine struct { + Number int32 `json:"number"` + Text string `json:"text"` +} + +// GetNumber returns the value of Number. +func (s *CodeLine) GetNumber() int32 { + return s.Number +} + +// GetText returns the value of Text. +func (s *CodeLine) GetText() string { + return s.Text +} + +// SetNumber sets the value of Number. +func (s *CodeLine) SetNumber(val int32) { + s.Number = val +} + +// SetText sets the value of Text. +func (s *CodeLine) SetText(val string) { + s.Text = val +} + +// Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when +// their texts are identical, including whitespace and line breaks. +// Ref: #/components/schemas/ConfigurationAnswer +type ConfigurationAnswer struct { + Format ConfigurationAnswerFormat `json:"format"` + Config string `json:"config"` +} + +// GetFormat returns the value of Format. +func (s *ConfigurationAnswer) GetFormat() ConfigurationAnswerFormat { + return s.Format +} + +// GetConfig returns the value of Config. +func (s *ConfigurationAnswer) GetConfig() string { + return s.Config +} + +// SetFormat sets the value of Format. +func (s *ConfigurationAnswer) SetFormat(val ConfigurationAnswerFormat) { + s.Format = val +} + +// SetConfig sets the value of Config. +func (s *ConfigurationAnswer) SetConfig(val string) { + s.Config = val +} + +type ConfigurationAnswerFormat string + +const ( + ConfigurationAnswerFormatConfiguration ConfigurationAnswerFormat = "configuration" +) + +// AllValues returns all ConfigurationAnswerFormat values. +func (ConfigurationAnswerFormat) AllValues() []ConfigurationAnswerFormat { + return []ConfigurationAnswerFormat{ + ConfigurationAnswerFormatConfiguration, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConfigurationAnswerFormat) MarshalText() ([]byte, error) { + switch s { + case ConfigurationAnswerFormatConfiguration: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConfigurationAnswerFormat) UnmarshalText(data []byte) error { + switch ConfigurationAnswerFormat(data) { + case ConfigurationAnswerFormatConfiguration: + *s = ConfigurationAnswerFormatConfiguration + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Write or fix a configuration. The server checks the submitted text with the computed key or +// reference check of the task family; it never executes it as code. +// Ref: #/components/schemas/ConfigurationItemContent +type ConfigurationItemContent struct { + Format ConfigurationItemContentFormat `json:"format"` + // Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`. + Syntax string `json:"syntax"` + // Starting text to edit; empty when the candidate writes it from scratch. + InitialConfig string `json:"initial_config"` + // Maximum length of the submitted configuration in characters, an input limit of the task family that + // is never derived from the key. + MaxLength int32 `json:"max_length"` +} + +// GetFormat returns the value of Format. +func (s *ConfigurationItemContent) GetFormat() ConfigurationItemContentFormat { + return s.Format +} + +// GetSyntax returns the value of Syntax. +func (s *ConfigurationItemContent) GetSyntax() string { + return s.Syntax +} + +// GetInitialConfig returns the value of InitialConfig. +func (s *ConfigurationItemContent) GetInitialConfig() string { + return s.InitialConfig +} + +// GetMaxLength returns the value of MaxLength. +func (s *ConfigurationItemContent) GetMaxLength() int32 { + return s.MaxLength +} + +// SetFormat sets the value of Format. +func (s *ConfigurationItemContent) SetFormat(val ConfigurationItemContentFormat) { + s.Format = val +} + +// SetSyntax sets the value of Syntax. +func (s *ConfigurationItemContent) SetSyntax(val string) { + s.Syntax = val +} + +// SetInitialConfig sets the value of InitialConfig. +func (s *ConfigurationItemContent) SetInitialConfig(val string) { + s.InitialConfig = val +} + +// SetMaxLength sets the value of MaxLength. +func (s *ConfigurationItemContent) SetMaxLength(val int32) { + s.MaxLength = val +} + +type ConfigurationItemContentFormat string + +const ( + ConfigurationItemContentFormatConfiguration ConfigurationItemContentFormat = "configuration" +) + +// AllValues returns all ConfigurationItemContentFormat values. +func (ConfigurationItemContentFormat) AllValues() []ConfigurationItemContentFormat { + return []ConfigurationItemContentFormat{ + ConfigurationItemContentFormatConfiguration, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConfigurationItemContentFormat) MarshalText() ([]byte, error) { + switch s { + case ConfigurationItemContentFormatConfiguration: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConfigurationItemContentFormat) UnmarshalText(data []byte) error { + switch ConfigurationItemContentFormat(data) { + case ConfigurationItemContentFormatConfiguration: + *s = ConfigurationItemContentFormatConfiguration + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + type ConfirmEmailBadRequest Problem func (*ConfirmEmailBadRequest) confirmEmailRes() {} @@ -562,6 +2965,26 @@ func (*ConsentText) getConsentTextRes() {} type ConsentTextVersion string +type CreateMyAssessmentAttemptBadRequest Problem + +func (*CreateMyAssessmentAttemptBadRequest) createMyAssessmentAttemptRes() {} + +type CreateMyAssessmentAttemptConflict Problem + +func (*CreateMyAssessmentAttemptConflict) createMyAssessmentAttemptRes() {} + +type CreateMyAssessmentAttemptForbidden Problem + +func (*CreateMyAssessmentAttemptForbidden) createMyAssessmentAttemptRes() {} + +type CreateMyAssessmentAttemptUnauthorized Problem + +func (*CreateMyAssessmentAttemptUnauthorized) createMyAssessmentAttemptRes() {} + +type CreateMyAssessmentAttemptUnprocessableEntity Problem + +func (*CreateMyAssessmentAttemptUnprocessableEntity) createMyAssessmentAttemptRes() {} + type CsrfToken string // Stable code of a professional direction, the group that a specialization belongs to. @@ -726,6 +3149,184 @@ func (EmailVerificationResultEmailVerified) AllValues() []EmailVerificationResul } } +type FinalizeMyAssessmentAttemptBadRequest Problem + +func (*FinalizeMyAssessmentAttemptBadRequest) finalizeMyAssessmentAttemptRes() {} + +type FinalizeMyAssessmentAttemptConflict Problem + +func (*FinalizeMyAssessmentAttemptConflict) finalizeMyAssessmentAttemptRes() {} + +type FinalizeMyAssessmentAttemptForbidden Problem + +func (*FinalizeMyAssessmentAttemptForbidden) finalizeMyAssessmentAttemptRes() {} + +type FinalizeMyAssessmentAttemptNotFound Problem + +func (*FinalizeMyAssessmentAttemptNotFound) finalizeMyAssessmentAttemptRes() {} + +type FinalizeMyAssessmentAttemptPreconditionFailed Problem + +func (*FinalizeMyAssessmentAttemptPreconditionFailed) finalizeMyAssessmentAttemptRes() {} + +type FinalizeMyAssessmentAttemptUnauthorized Problem + +func (*FinalizeMyAssessmentAttemptUnauthorized) finalizeMyAssessmentAttemptRes() {} + +type FinalizeMyAssessmentAttemptUnprocessableEntity Problem + +func (*FinalizeMyAssessmentAttemptUnprocessableEntity) finalizeMyAssessmentAttemptRes() {} + +// Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they +// select the same set of lines, in any order. +// Ref: #/components/schemas/FindErrorAnswer +type FindErrorAnswer struct { + Format FindErrorAnswerFormat `json:"format"` + LineNumbers []int32 `json:"line_numbers"` +} + +// GetFormat returns the value of Format. +func (s *FindErrorAnswer) GetFormat() FindErrorAnswerFormat { + return s.Format +} + +// GetLineNumbers returns the value of LineNumbers. +func (s *FindErrorAnswer) GetLineNumbers() []int32 { + return s.LineNumbers +} + +// SetFormat sets the value of Format. +func (s *FindErrorAnswer) SetFormat(val FindErrorAnswerFormat) { + s.Format = val +} + +// SetLineNumbers sets the value of LineNumbers. +func (s *FindErrorAnswer) SetLineNumbers(val []int32) { + s.LineNumbers = val +} + +type FindErrorAnswerFormat string + +const ( + FindErrorAnswerFormatFindError FindErrorAnswerFormat = "find_error" +) + +// AllValues returns all FindErrorAnswerFormat values. +func (FindErrorAnswerFormat) AllValues() []FindErrorAnswerFormat { + return []FindErrorAnswerFormat{ + FindErrorAnswerFormatFindError, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s FindErrorAnswerFormat) MarshalText() ([]byte, error) { + switch s { + case FindErrorAnswerFormatFindError: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *FindErrorAnswerFormat) UnmarshalText(data []byte) error { + switch FindErrorAnswerFormat(data) { + case FindErrorAnswerFormatFindError: + *s = FindErrorAnswerFormatFindError + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Find the lines with the error in a code or configuration fragment and select up to `max_selections` +// line numbers. +// Ref: #/components/schemas/FindErrorItemContent +type FindErrorItemContent struct { + Format FindErrorItemContentFormat `json:"format"` + // Highlighting hint such as `go`, `python`, or `cisco_ios`, or null. + Syntax NilString `json:"syntax"` + // Lines numbered from 1 in order. + Lines []CodeLine `json:"lines"` + // Maximum number of lines the answer may select. It is a limit of the task family, fixed for every + // variant and never derived from the key; it is not the number of wrong lines. + MaxSelections int32 `json:"max_selections"` +} + +// GetFormat returns the value of Format. +func (s *FindErrorItemContent) GetFormat() FindErrorItemContentFormat { + return s.Format +} + +// GetSyntax returns the value of Syntax. +func (s *FindErrorItemContent) GetSyntax() NilString { + return s.Syntax +} + +// GetLines returns the value of Lines. +func (s *FindErrorItemContent) GetLines() []CodeLine { + return s.Lines +} + +// GetMaxSelections returns the value of MaxSelections. +func (s *FindErrorItemContent) GetMaxSelections() int32 { + return s.MaxSelections +} + +// SetFormat sets the value of Format. +func (s *FindErrorItemContent) SetFormat(val FindErrorItemContentFormat) { + s.Format = val +} + +// SetSyntax sets the value of Syntax. +func (s *FindErrorItemContent) SetSyntax(val NilString) { + s.Syntax = val +} + +// SetLines sets the value of Lines. +func (s *FindErrorItemContent) SetLines(val []CodeLine) { + s.Lines = val +} + +// SetMaxSelections sets the value of MaxSelections. +func (s *FindErrorItemContent) SetMaxSelections(val int32) { + s.MaxSelections = val +} + +type FindErrorItemContentFormat string + +const ( + FindErrorItemContentFormatFindError FindErrorItemContentFormat = "find_error" +) + +// AllValues returns all FindErrorItemContentFormat values. +func (FindErrorItemContentFormat) AllValues() []FindErrorItemContentFormat { + return []FindErrorItemContentFormat{ + FindErrorItemContentFormatFindError, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s FindErrorItemContentFormat) MarshalText() ([]byte, error) { + switch s { + case FindErrorItemContentFormatFindError: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *FindErrorItemContentFormat) UnmarshalText(data []byte) error { + switch FindErrorItemContentFormat(data) { + case FindErrorItemContentFormatFindError: + *s = FindErrorItemContentFormatFindError + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // GetCurrentSessionOKHeaders wraps Session with response headers. type GetCurrentSessionOKHeaders struct { CacheControl CacheControlNoStore @@ -754,6 +3355,42 @@ func (s *GetCurrentSessionOKHeaders) SetResponse(val Session) { func (*GetCurrentSessionOKHeaders) getCurrentSessionRes() {} +type GetMyAssessmentAttemptForbidden Problem + +func (*GetMyAssessmentAttemptForbidden) getMyAssessmentAttemptRes() {} + +type GetMyAssessmentAttemptNotFound Problem + +func (*GetMyAssessmentAttemptNotFound) getMyAssessmentAttemptRes() {} + +type GetMyAssessmentAttemptUnauthorized Problem + +func (*GetMyAssessmentAttemptUnauthorized) getMyAssessmentAttemptRes() {} + +type GetMyAssessmentAvailabilityForbidden Problem + +func (*GetMyAssessmentAvailabilityForbidden) getMyAssessmentAvailabilityRes() {} + +type GetMyAssessmentAvailabilityUnauthorized Problem + +func (*GetMyAssessmentAvailabilityUnauthorized) getMyAssessmentAvailabilityRes() {} + +type GetMyAssessmentResultConflict Problem + +func (*GetMyAssessmentResultConflict) getMyAssessmentResultRes() {} + +type GetMyAssessmentResultForbidden Problem + +func (*GetMyAssessmentResultForbidden) getMyAssessmentResultRes() {} + +type GetMyAssessmentResultNotFound Problem + +func (*GetMyAssessmentResultNotFound) getMyAssessmentResultRes() {} + +type GetMyAssessmentResultUnauthorized Problem + +func (*GetMyAssessmentResultUnauthorized) getMyAssessmentResultRes() {} + type GetMyQuestionnaireForbidden Problem func (*GetMyQuestionnaireForbidden) getMyQuestionnaireRes() {} @@ -926,6 +3563,208 @@ func (s *IdentityRequestAcceptedStatus) UnmarshalText(data []byte) error { } } +// Format-specific part of an item, selected by `format`. It holds only what the candidate needs to +// answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a +// hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or +// the task family and never reveal the key. +// Ref: #/components/schemas/ItemContent +// ItemContent represents sum type. +type ItemContent struct { + // Type selects the active sum variant, switch on this field. + Type ItemContentType + ChoiceItemContent ChoiceItemContent + NumberItemContent NumberItemContent + StringItemContent StringItemContent + OrderItemContent OrderItemContent + FindErrorItemContent FindErrorItemContent + ConfigurationItemContent ConfigurationItemContent + PracticeItemContent PracticeItemContent +} + +// ItemContentType is oneOf type of ItemContent. +type ItemContentType string + +// Possible values for ItemContentType. +const ( + ChoiceItemContentItemContent ItemContentType = "ChoiceItemContent" + NumberItemContentItemContent ItemContentType = "NumberItemContent" + StringItemContentItemContent ItemContentType = "StringItemContent" + OrderItemContentItemContent ItemContentType = "OrderItemContent" + FindErrorItemContentItemContent ItemContentType = "FindErrorItemContent" + ConfigurationItemContentItemContent ItemContentType = "ConfigurationItemContent" + PracticeItemContentItemContent ItemContentType = "PracticeItemContent" +) + +// IsChoiceItemContent reports whether ItemContent is ChoiceItemContent. +func (s ItemContent) IsChoiceItemContent() bool { return s.Type == ChoiceItemContentItemContent } + +// IsNumberItemContent reports whether ItemContent is NumberItemContent. +func (s ItemContent) IsNumberItemContent() bool { return s.Type == NumberItemContentItemContent } + +// IsStringItemContent reports whether ItemContent is StringItemContent. +func (s ItemContent) IsStringItemContent() bool { return s.Type == StringItemContentItemContent } + +// IsOrderItemContent reports whether ItemContent is OrderItemContent. +func (s ItemContent) IsOrderItemContent() bool { return s.Type == OrderItemContentItemContent } + +// IsFindErrorItemContent reports whether ItemContent is FindErrorItemContent. +func (s ItemContent) IsFindErrorItemContent() bool { return s.Type == FindErrorItemContentItemContent } + +// IsConfigurationItemContent reports whether ItemContent is ConfigurationItemContent. +func (s ItemContent) IsConfigurationItemContent() bool { + return s.Type == ConfigurationItemContentItemContent +} + +// IsPracticeItemContent reports whether ItemContent is PracticeItemContent. +func (s ItemContent) IsPracticeItemContent() bool { return s.Type == PracticeItemContentItemContent } + +// SetChoiceItemContent sets ItemContent to ChoiceItemContent. +func (s *ItemContent) SetChoiceItemContent(v ChoiceItemContent) { + s.Type = ChoiceItemContentItemContent + s.ChoiceItemContent = v +} + +// GetChoiceItemContent returns ChoiceItemContent and true boolean if ItemContent is ChoiceItemContent. +func (s ItemContent) GetChoiceItemContent() (v ChoiceItemContent, ok bool) { + if !s.IsChoiceItemContent() { + return v, false + } + return s.ChoiceItemContent, true +} + +// NewChoiceItemContentItemContent returns new ItemContent from ChoiceItemContent. +func NewChoiceItemContentItemContent(v ChoiceItemContent) ItemContent { + var s ItemContent + s.SetChoiceItemContent(v) + return s +} + +// SetNumberItemContent sets ItemContent to NumberItemContent. +func (s *ItemContent) SetNumberItemContent(v NumberItemContent) { + s.Type = NumberItemContentItemContent + s.NumberItemContent = v +} + +// GetNumberItemContent returns NumberItemContent and true boolean if ItemContent is NumberItemContent. +func (s ItemContent) GetNumberItemContent() (v NumberItemContent, ok bool) { + if !s.IsNumberItemContent() { + return v, false + } + return s.NumberItemContent, true +} + +// NewNumberItemContentItemContent returns new ItemContent from NumberItemContent. +func NewNumberItemContentItemContent(v NumberItemContent) ItemContent { + var s ItemContent + s.SetNumberItemContent(v) + return s +} + +// SetStringItemContent sets ItemContent to StringItemContent. +func (s *ItemContent) SetStringItemContent(v StringItemContent) { + s.Type = StringItemContentItemContent + s.StringItemContent = v +} + +// GetStringItemContent returns StringItemContent and true boolean if ItemContent is StringItemContent. +func (s ItemContent) GetStringItemContent() (v StringItemContent, ok bool) { + if !s.IsStringItemContent() { + return v, false + } + return s.StringItemContent, true +} + +// NewStringItemContentItemContent returns new ItemContent from StringItemContent. +func NewStringItemContentItemContent(v StringItemContent) ItemContent { + var s ItemContent + s.SetStringItemContent(v) + return s +} + +// SetOrderItemContent sets ItemContent to OrderItemContent. +func (s *ItemContent) SetOrderItemContent(v OrderItemContent) { + s.Type = OrderItemContentItemContent + s.OrderItemContent = v +} + +// GetOrderItemContent returns OrderItemContent and true boolean if ItemContent is OrderItemContent. +func (s ItemContent) GetOrderItemContent() (v OrderItemContent, ok bool) { + if !s.IsOrderItemContent() { + return v, false + } + return s.OrderItemContent, true +} + +// NewOrderItemContentItemContent returns new ItemContent from OrderItemContent. +func NewOrderItemContentItemContent(v OrderItemContent) ItemContent { + var s ItemContent + s.SetOrderItemContent(v) + return s +} + +// SetFindErrorItemContent sets ItemContent to FindErrorItemContent. +func (s *ItemContent) SetFindErrorItemContent(v FindErrorItemContent) { + s.Type = FindErrorItemContentItemContent + s.FindErrorItemContent = v +} + +// GetFindErrorItemContent returns FindErrorItemContent and true boolean if ItemContent is FindErrorItemContent. +func (s ItemContent) GetFindErrorItemContent() (v FindErrorItemContent, ok bool) { + if !s.IsFindErrorItemContent() { + return v, false + } + return s.FindErrorItemContent, true +} + +// NewFindErrorItemContentItemContent returns new ItemContent from FindErrorItemContent. +func NewFindErrorItemContentItemContent(v FindErrorItemContent) ItemContent { + var s ItemContent + s.SetFindErrorItemContent(v) + return s +} + +// SetConfigurationItemContent sets ItemContent to ConfigurationItemContent. +func (s *ItemContent) SetConfigurationItemContent(v ConfigurationItemContent) { + s.Type = ConfigurationItemContentItemContent + s.ConfigurationItemContent = v +} + +// GetConfigurationItemContent returns ConfigurationItemContent and true boolean if ItemContent is ConfigurationItemContent. +func (s ItemContent) GetConfigurationItemContent() (v ConfigurationItemContent, ok bool) { + if !s.IsConfigurationItemContent() { + return v, false + } + return s.ConfigurationItemContent, true +} + +// NewConfigurationItemContentItemContent returns new ItemContent from ConfigurationItemContent. +func NewConfigurationItemContentItemContent(v ConfigurationItemContent) ItemContent { + var s ItemContent + s.SetConfigurationItemContent(v) + return s +} + +// SetPracticeItemContent sets ItemContent to PracticeItemContent. +func (s *ItemContent) SetPracticeItemContent(v PracticeItemContent) { + s.Type = PracticeItemContentItemContent + s.PracticeItemContent = v +} + +// GetPracticeItemContent returns PracticeItemContent and true boolean if ItemContent is PracticeItemContent. +func (s ItemContent) GetPracticeItemContent() (v PracticeItemContent, ok bool) { + if !s.IsPracticeItemContent() { + return v, false + } + return s.PracticeItemContent, true +} + +// NewPracticeItemContentItemContent returns new ItemContent from PracticeItemContent. +func NewPracticeItemContentItemContent(v PracticeItemContent) ItemContent { + var s ItemContent + s.SetPracticeItemContent(v) + return s +} + type LoginBadRequest Problem func (*LoginBadRequest) loginRes() {} @@ -986,6 +3825,366 @@ func (*LogoutNoContent) logoutRes() {} type NewPassword string +// NewNilAssessmentItem returns new NilAssessmentItem with value set to v. +func NewNilAssessmentItem(v AssessmentItem) NilAssessmentItem { + return NilAssessmentItem{ + Value: v, + } +} + +// NilAssessmentItem is nullable AssessmentItem. +type NilAssessmentItem struct { + Value AssessmentItem + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentItem) SetTo(v AssessmentItem) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentItem) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentItem) SetToNull() { + o.Null = true + var v AssessmentItem + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentItem) Get() (v AssessmentItem, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilAssessmentItem) Or(d AssessmentItem) AssessmentItem { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilAssessmentMode returns new NilAssessmentMode with value set to v. +func NewNilAssessmentMode(v AssessmentMode) NilAssessmentMode { + return NilAssessmentMode{ + Value: v, + } +} + +// NilAssessmentMode is nullable AssessmentMode. +type NilAssessmentMode struct { + Value AssessmentMode + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentMode) SetTo(v AssessmentMode) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentMode) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentMode) SetToNull() { + o.Null = true + var v AssessmentMode + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentMode) Get() (v AssessmentMode, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilAssessmentMode) Or(d AssessmentMode) AssessmentMode { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilAssessmentNotDeterminedReason returns new NilAssessmentNotDeterminedReason with value set to v. +func NewNilAssessmentNotDeterminedReason(v AssessmentNotDeterminedReason) NilAssessmentNotDeterminedReason { + return NilAssessmentNotDeterminedReason{ + Value: v, + } +} + +// NilAssessmentNotDeterminedReason is nullable AssessmentNotDeterminedReason. +type NilAssessmentNotDeterminedReason struct { + Value AssessmentNotDeterminedReason + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentNotDeterminedReason) SetTo(v AssessmentNotDeterminedReason) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentNotDeterminedReason) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentNotDeterminedReason) SetToNull() { + o.Null = true + var v AssessmentNotDeterminedReason + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentNotDeterminedReason) Get() (v AssessmentNotDeterminedReason, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilAssessmentNotDeterminedReason) Or(d AssessmentNotDeterminedReason) AssessmentNotDeterminedReason { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilAssessmentSessions returns new NilAssessmentSessions with value set to v. +func NewNilAssessmentSessions(v AssessmentSessions) NilAssessmentSessions { + return NilAssessmentSessions{ + Value: v, + } +} + +// NilAssessmentSessions is nullable AssessmentSessions. +type NilAssessmentSessions struct { + Value AssessmentSessions + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentSessions) SetTo(v AssessmentSessions) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentSessions) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentSessions) SetToNull() { + o.Null = true + var v AssessmentSessions + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentSessions) Get() (v AssessmentSessions, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilAssessmentSessions) Or(d AssessmentSessions) AssessmentSessions { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilAssessmentStrength returns new NilAssessmentStrength with value set to v. +func NewNilAssessmentStrength(v AssessmentStrength) NilAssessmentStrength { + return NilAssessmentStrength{ + Value: v, + } +} + +// NilAssessmentStrength is nullable AssessmentStrength. +type NilAssessmentStrength struct { + Value AssessmentStrength + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentStrength) SetTo(v AssessmentStrength) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentStrength) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentStrength) SetToNull() { + o.Null = true + var v AssessmentStrength + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentStrength) Get() (v AssessmentStrength, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilAssessmentStrength) Or(d AssessmentStrength) AssessmentStrength { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilAssessmentUncertainty returns new NilAssessmentUncertainty with value set to v. +func NewNilAssessmentUncertainty(v AssessmentUncertainty) NilAssessmentUncertainty { + return NilAssessmentUncertainty{ + Value: v, + } +} + +// NilAssessmentUncertainty is nullable AssessmentUncertainty. +type NilAssessmentUncertainty struct { + Value AssessmentUncertainty + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentUncertainty) SetTo(v AssessmentUncertainty) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentUncertainty) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentUncertainty) SetToNull() { + o.Null = true + var v AssessmentUncertainty + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentUncertainty) Get() (v AssessmentUncertainty, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilAssessmentUncertainty) Or(d AssessmentUncertainty) AssessmentUncertainty { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilBasicScore returns new NilBasicScore with value set to v. +func NewNilBasicScore(v BasicScore) NilBasicScore { + return NilBasicScore{ + Value: v, + } +} + +// NilBasicScore is nullable BasicScore. +type NilBasicScore struct { + Value BasicScore + Null bool +} + +// SetTo sets value to v. +func (o *NilBasicScore) SetTo(v BasicScore) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilBasicScore) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilBasicScore) SetToNull() { + o.Null = true + var v BasicScore + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilBasicScore) Get() (v BasicScore, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilBasicScore) Or(d BasicScore) BasicScore { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilBool returns new NilBool with value set to v. +func NewNilBool(v bool) NilBool { + return NilBool{ + Value: v, + } +} + +// NilBool is nullable bool. +type NilBool struct { + Value bool + Null bool +} + +// SetTo sets value to v. +func (o *NilBool) SetTo(v bool) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilBool) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilBool) SetToNull() { + o.Null = true + var v bool + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilBool) Get() (v bool, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilBool) Or(d bool) bool { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilCandidateExperience returns new NilCandidateExperience with value set to v. func NewNilCandidateExperience(v CandidateExperience) NilCandidateExperience { return NilCandidateExperience{ @@ -1031,6 +4230,186 @@ func (o NilCandidateExperience) Or(d CandidateExperience) CandidateExperience { return d } +// NewNilGradeCode returns new NilGradeCode with value set to v. +func NewNilGradeCode(v GradeCode) NilGradeCode { + return NilGradeCode{ + Value: v, + } +} + +// NilGradeCode is nullable GradeCode. +type NilGradeCode struct { + Value GradeCode + Null bool +} + +// SetTo sets value to v. +func (o *NilGradeCode) SetTo(v GradeCode) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilGradeCode) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilGradeCode) SetToNull() { + o.Null = true + var v GradeCode + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilGradeCode) Get() (v GradeCode, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilGradeCode) Or(d GradeCode) GradeCode { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilInt32 returns new NilInt32 with value set to v. +func NewNilInt32(v int32) NilInt32 { + return NilInt32{ + Value: v, + } +} + +// NilInt32 is nullable int32. +type NilInt32 struct { + Value int32 + Null bool +} + +// SetTo sets value to v. +func (o *NilInt32) SetTo(v int32) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilInt32) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilInt32) SetToNull() { + o.Null = true + var v int32 + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilInt32) Get() (v int32, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilInt32) Or(d int32) int32 { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilPracticeFailureReason returns new NilPracticeFailureReason with value set to v. +func NewNilPracticeFailureReason(v PracticeFailureReason) NilPracticeFailureReason { + return NilPracticeFailureReason{ + Value: v, + } +} + +// NilPracticeFailureReason is nullable PracticeFailureReason. +type NilPracticeFailureReason struct { + Value PracticeFailureReason + Null bool +} + +// SetTo sets value to v. +func (o *NilPracticeFailureReason) SetTo(v PracticeFailureReason) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilPracticeFailureReason) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilPracticeFailureReason) SetToNull() { + o.Null = true + var v PracticeFailureReason + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilPracticeFailureReason) Get() (v PracticeFailureReason, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilPracticeFailureReason) Or(d PracticeFailureReason) PracticeFailureReason { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilPracticeVerdict returns new NilPracticeVerdict with value set to v. +func NewNilPracticeVerdict(v PracticeVerdict) NilPracticeVerdict { + return NilPracticeVerdict{ + Value: v, + } +} + +// NilPracticeVerdict is nullable PracticeVerdict. +type NilPracticeVerdict struct { + Value PracticeVerdict + Null bool +} + +// SetTo sets value to v. +func (o *NilPracticeVerdict) SetTo(v PracticeVerdict) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilPracticeVerdict) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilPracticeVerdict) SetToNull() { + o.Null = true + var v PracticeVerdict + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilPracticeVerdict) Get() (v PracticeVerdict, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilPracticeVerdict) Or(d PracticeVerdict) PracticeVerdict { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilString returns new NilString with value set to v. func NewNilString(v string) NilString { return NilString{ @@ -1076,6 +4455,51 @@ func (o NilString) Or(d string) string { return d } +// NewNilTaskLanguage returns new NilTaskLanguage with value set to v. +func NewNilTaskLanguage(v TaskLanguage) NilTaskLanguage { + return NilTaskLanguage{ + Value: v, + } +} + +// NilTaskLanguage is nullable TaskLanguage. +type NilTaskLanguage struct { + Value TaskLanguage + Null bool +} + +// SetTo sets value to v. +func (o *NilTaskLanguage) SetTo(v TaskLanguage) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilTaskLanguage) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilTaskLanguage) SetToNull() { + o.Null = true + var v TaskLanguage + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilTaskLanguage) Get() (v TaskLanguage, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilTaskLanguage) Or(d TaskLanguage) TaskLanguage { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilTimestamp returns new NilTimestamp with value set to v. func NewNilTimestamp(v Timestamp) NilTimestamp { return NilTimestamp{ @@ -1121,6 +4545,51 @@ func (o NilTimestamp) Or(d Timestamp) Timestamp { return d } +// NewNilUUID returns new NilUUID with value set to v. +func NewNilUUID(v uuid.UUID) NilUUID { + return NilUUID{ + Value: v, + } +} + +// NilUUID is nullable uuid.UUID. +type NilUUID struct { + Value uuid.UUID + Null bool +} + +// SetTo sets value to v. +func (o *NilUUID) SetTo(v uuid.UUID) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilUUID) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilUUID) SetToNull() { + o.Null = true + var v uuid.UUID + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilUUID) Get() (v uuid.UUID, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilUUID) Or(d uuid.UUID) uuid.UUID { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilWorkContext returns new NilWorkContext with value set to v. func NewNilWorkContext(v WorkContext) NilWorkContext { return NilWorkContext{ @@ -1166,6 +4635,130 @@ func (o NilWorkContext) Or(d WorkContext) WorkContext { return d } +// Numeric answer in the unit of the item. Two answers are equal when their decoded values are +// numerically equal, so 254 and 254.0 are the same answer. +// Ref: #/components/schemas/NumberAnswer +type NumberAnswer struct { + Format NumberAnswerFormat `json:"format"` + Number float64 `json:"number"` +} + +// GetFormat returns the value of Format. +func (s *NumberAnswer) GetFormat() NumberAnswerFormat { + return s.Format +} + +// GetNumber returns the value of Number. +func (s *NumberAnswer) GetNumber() float64 { + return s.Number +} + +// SetFormat sets the value of Format. +func (s *NumberAnswer) SetFormat(val NumberAnswerFormat) { + s.Format = val +} + +// SetNumber sets the value of Number. +func (s *NumberAnswer) SetNumber(val float64) { + s.Number = val +} + +type NumberAnswerFormat string + +const ( + NumberAnswerFormatNumber NumberAnswerFormat = "number" +) + +// AllValues returns all NumberAnswerFormat values. +func (NumberAnswerFormat) AllValues() []NumberAnswerFormat { + return []NumberAnswerFormat{ + NumberAnswerFormatNumber, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s NumberAnswerFormat) MarshalText() ([]byte, error) { + switch s { + case NumberAnswerFormatNumber: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *NumberAnswerFormat) UnmarshalText(data []byte) error { + switch NumberAnswerFormat(data) { + case NumberAnswerFormatNumber: + *s = NumberAnswerFormatNumber + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Enter a number, optionally in the given unit. +// Ref: #/components/schemas/NumberItemContent +type NumberItemContent struct { + Format NumberItemContentFormat `json:"format"` + // Unit of the expected value, for example `ms`, or null. + Unit NilString `json:"unit"` +} + +// GetFormat returns the value of Format. +func (s *NumberItemContent) GetFormat() NumberItemContentFormat { + return s.Format +} + +// GetUnit returns the value of Unit. +func (s *NumberItemContent) GetUnit() NilString { + return s.Unit +} + +// SetFormat sets the value of Format. +func (s *NumberItemContent) SetFormat(val NumberItemContentFormat) { + s.Format = val +} + +// SetUnit sets the value of Unit. +func (s *NumberItemContent) SetUnit(val NilString) { + s.Unit = val +} + +type NumberItemContentFormat string + +const ( + NumberItemContentFormatNumber NumberItemContentFormat = "number" +) + +// AllValues returns all NumberItemContentFormat values. +func (NumberItemContentFormat) AllValues() []NumberItemContentFormat { + return []NumberItemContentFormat{ + NumberItemContentFormatNumber, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s NumberItemContentFormat) MarshalText() ([]byte, error) { + switch s { + case NumberItemContentFormatNumber: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *NumberItemContentFormat) UnmarshalText(data []byte) error { + switch NumberItemContentFormat(data) { + case NumberItemContentFormatNumber: + *s = NumberItemContentFormatNumber + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Saved onboarding step that the account returns to after login. The server stores it and advances it // as each step completes; clients route by it and never set it directly. // @@ -1343,6 +4936,130 @@ func (o OptString) Or(d string) string { return d } +// Every element of the item exactly once, in the chosen order. Two answers are equal only when the +// sequences are identical. +// Ref: #/components/schemas/OrderAnswer +type OrderAnswer struct { + Format OrderAnswerFormat `json:"format"` + ElementIds []AssessmentOptionId `json:"element_ids"` +} + +// GetFormat returns the value of Format. +func (s *OrderAnswer) GetFormat() OrderAnswerFormat { + return s.Format +} + +// GetElementIds returns the value of ElementIds. +func (s *OrderAnswer) GetElementIds() []AssessmentOptionId { + return s.ElementIds +} + +// SetFormat sets the value of Format. +func (s *OrderAnswer) SetFormat(val OrderAnswerFormat) { + s.Format = val +} + +// SetElementIds sets the value of ElementIds. +func (s *OrderAnswer) SetElementIds(val []AssessmentOptionId) { + s.ElementIds = val +} + +type OrderAnswerFormat string + +const ( + OrderAnswerFormatOrder OrderAnswerFormat = "order" +) + +// AllValues returns all OrderAnswerFormat values. +func (OrderAnswerFormat) AllValues() []OrderAnswerFormat { + return []OrderAnswerFormat{ + OrderAnswerFormatOrder, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s OrderAnswerFormat) MarshalText() ([]byte, error) { + switch s { + case OrderAnswerFormatOrder: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *OrderAnswerFormat) UnmarshalText(data []byte) error { + switch OrderAnswerFormat(data) { + case OrderAnswerFormatOrder: + *s = OrderAnswerFormatOrder + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Put every element into the right order. The elements arrive in the order of this instance, which is +// never the answer. +// Ref: #/components/schemas/OrderItemContent +type OrderItemContent struct { + Format OrderItemContentFormat `json:"format"` + Elements []AssessmentOption `json:"elements"` +} + +// GetFormat returns the value of Format. +func (s *OrderItemContent) GetFormat() OrderItemContentFormat { + return s.Format +} + +// GetElements returns the value of Elements. +func (s *OrderItemContent) GetElements() []AssessmentOption { + return s.Elements +} + +// SetFormat sets the value of Format. +func (s *OrderItemContent) SetFormat(val OrderItemContentFormat) { + s.Format = val +} + +// SetElements sets the value of Elements. +func (s *OrderItemContent) SetElements(val []AssessmentOption) { + s.Elements = val +} + +type OrderItemContentFormat string + +const ( + OrderItemContentFormatOrder OrderItemContentFormat = "order" +) + +// AllValues returns all OrderItemContentFormat values. +func (OrderItemContentFormat) AllValues() []OrderItemContentFormat { + return []OrderItemContentFormat{ + OrderItemContentFormatOrder, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s OrderItemContentFormat) MarshalText() ([]byte, error) { + switch s { + case OrderItemContentFormatOrder: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *OrderItemContentFormat) UnmarshalText(data []byte) error { + switch OrderItemContentFormat(data) { + case OrderItemContentFormatOrder: + *s = OrderItemContentFormatOrder + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Consent C1 to the processing of personal data, given at registration. The client reads the current // text and its version with GetConsentText(c1) and sends that version here. A version that is not the // currently published one answers 400 validation_failed with the pointer `/consent_c1/text_version`; @@ -1390,6 +5107,425 @@ func (PersonalDataConsentAcceptanceAccepted) AllValues() []PersonalDataConsentAc } } +// Practice solution. It runs in the isolated sandbox without network access, secrets, or business +// data. Two submissions are equal only when the language is the same and the source texts are +// identical. The source is never echoed in a response or a problem. +// Ref: #/components/schemas/PracticeAnswer +type PracticeAnswer struct { + Format PracticeAnswerFormat `json:"format"` + // One of the `languages` of the practice item, or null when the item offers none. + Language NilTaskLanguage `json:"language"` + SourceCode string `json:"source_code"` +} + +// GetFormat returns the value of Format. +func (s *PracticeAnswer) GetFormat() PracticeAnswerFormat { + return s.Format +} + +// GetLanguage returns the value of Language. +func (s *PracticeAnswer) GetLanguage() NilTaskLanguage { + return s.Language +} + +// GetSourceCode returns the value of SourceCode. +func (s *PracticeAnswer) GetSourceCode() string { + return s.SourceCode +} + +// SetFormat sets the value of Format. +func (s *PracticeAnswer) SetFormat(val PracticeAnswerFormat) { + s.Format = val +} + +// SetLanguage sets the value of Language. +func (s *PracticeAnswer) SetLanguage(val NilTaskLanguage) { + s.Language = val +} + +// SetSourceCode sets the value of SourceCode. +func (s *PracticeAnswer) SetSourceCode(val string) { + s.SourceCode = val +} + +type PracticeAnswerFormat string + +const ( + PracticeAnswerFormatPractice PracticeAnswerFormat = "practice" +) + +// AllValues returns all PracticeAnswerFormat values. +func (PracticeAnswerFormat) AllValues() []PracticeAnswerFormat { + return []PracticeAnswerFormat{ + PracticeAnswerFormatPractice, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PracticeAnswerFormat) MarshalText() ([]byte, error) { + switch s { + case PracticeAnswerFormatPractice: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PracticeAnswerFormat) UnmarshalText(data []byte) error { + switch PracticeAnswerFormat(data) { + case PracticeAnswerFormatPractice: + *s = PracticeAnswerFormatPractice + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Public example of the practice task: an input and its expected output. Hidden checks are never +// listed. +// Ref: #/components/schemas/PracticeExample +type PracticeExample struct { + Input string `json:"input"` + ExpectedOutput string `json:"expected_output"` +} + +// GetInput returns the value of Input. +func (s *PracticeExample) GetInput() string { + return s.Input +} + +// GetExpectedOutput returns the value of ExpectedOutput. +func (s *PracticeExample) GetExpectedOutput() string { + return s.ExpectedOutput +} + +// SetInput sets the value of Input. +func (s *PracticeExample) SetInput(val string) { + s.Input = val +} + +// SetExpectedOutput sets the value of ExpectedOutput. +func (s *PracticeExample) SetExpectedOutput(val string) { + s.ExpectedOutput = val +} + +// Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, +// `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the +// solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict +// instead, so a failure never acts as an oracle for hidden checks. +// Ref: #/components/schemas/PracticeFailureReason +type PracticeFailureReason string + +const ( + PracticeFailureReasonSandboxBusy PracticeFailureReason = "sandbox_busy" + PracticeFailureReasonSandboxError PracticeFailureReason = "sandbox_error" +) + +// AllValues returns all PracticeFailureReason values. +func (PracticeFailureReason) AllValues() []PracticeFailureReason { + return []PracticeFailureReason{ + PracticeFailureReasonSandboxBusy, + PracticeFailureReasonSandboxError, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PracticeFailureReason) MarshalText() ([]byte, error) { + switch s { + case PracticeFailureReasonSandboxBusy: + return []byte(s), nil + case PracticeFailureReasonSandboxError: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PracticeFailureReason) UnmarshalText(data []byte) error { + switch PracticeFailureReason(data) { + case PracticeFailureReasonSandboxBusy: + *s = PracticeFailureReasonSandboxBusy + return nil + case PracticeFailureReasonSandboxError: + *s = PracticeFailureReasonSandboxError + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Outcome of one hidden check group. It never contains the checks themselves. +// Ref: #/components/schemas/PracticeGroupResult +type PracticeGroupResult struct { + Group int32 `json:"group"` + Passed bool `json:"passed"` +} + +// GetGroup returns the value of Group. +func (s *PracticeGroupResult) GetGroup() int32 { + return s.Group +} + +// GetPassed returns the value of Passed. +func (s *PracticeGroupResult) GetPassed() bool { + return s.Passed +} + +// SetGroup sets the value of Group. +func (s *PracticeGroupResult) SetGroup(val int32) { + s.Group = val +} + +// SetPassed sets the value of Passed. +func (s *PracticeGroupResult) SetPassed(val bool) { + s.Passed = val +} + +// Code practice. The candidate submits one final solution, which runs in the isolated sandbox against +// three groups of hidden checks. The content lists only the statement, the allowed languages, and +// public examples; hidden checks, their inputs, and seeds never reach the client. +// Ref: #/components/schemas/PracticeItemContent +type PracticeItemContent struct { + Format PracticeItemContentFormat `json:"format"` + // Languages the solution may use. Empty when the task does not offer a choice; the submission then + // sends a null language. + Languages []TaskLanguage `json:"languages"` + PublicExamples []PracticeExample `json:"public_examples"` + // Maximum length of the solution source in characters. + MaxSourceLength int32 `json:"max_source_length"` +} + +// GetFormat returns the value of Format. +func (s *PracticeItemContent) GetFormat() PracticeItemContentFormat { + return s.Format +} + +// GetLanguages returns the value of Languages. +func (s *PracticeItemContent) GetLanguages() []TaskLanguage { + return s.Languages +} + +// GetPublicExamples returns the value of PublicExamples. +func (s *PracticeItemContent) GetPublicExamples() []PracticeExample { + return s.PublicExamples +} + +// GetMaxSourceLength returns the value of MaxSourceLength. +func (s *PracticeItemContent) GetMaxSourceLength() int32 { + return s.MaxSourceLength +} + +// SetFormat sets the value of Format. +func (s *PracticeItemContent) SetFormat(val PracticeItemContentFormat) { + s.Format = val +} + +// SetLanguages sets the value of Languages. +func (s *PracticeItemContent) SetLanguages(val []TaskLanguage) { + s.Languages = val +} + +// SetPublicExamples sets the value of PublicExamples. +func (s *PracticeItemContent) SetPublicExamples(val []PracticeExample) { + s.PublicExamples = val +} + +// SetMaxSourceLength sets the value of MaxSourceLength. +func (s *PracticeItemContent) SetMaxSourceLength(val int32) { + s.MaxSourceLength = val +} + +type PracticeItemContentFormat string + +const ( + PracticeItemContentFormatPractice PracticeItemContentFormat = "practice" +) + +// AllValues returns all PracticeItemContentFormat values. +func (PracticeItemContentFormat) AllValues() []PracticeItemContentFormat { + return []PracticeItemContentFormat{ + PracticeItemContentFormatPractice, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PracticeItemContentFormat) MarshalText() ([]byte, error) { + switch s { + case PracticeItemContentFormatPractice: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PracticeItemContentFormat) UnmarshalText(data []byte) error { + switch PracticeItemContentFormat(data) { + case PracticeItemContentFormatPractice: + *s = PracticeItemContentFormatPractice + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Role of a practice in the attempt. +// +// - main: the practice that every attempt with practice requires before a decision. +// - additional: adaptive only; offered by finalize when the probability of reaching the grade is in +// the band below confirmation. It continues the same attempt and spends no new attempt. +// +// Adding a value is a contract change. +// Ref: #/components/schemas/PracticeKind +type PracticeKind string + +const ( + PracticeKindMain PracticeKind = "main" + PracticeKindAdditional PracticeKind = "additional" +) + +// AllValues returns all PracticeKind values. +func (PracticeKind) AllValues() []PracticeKind { + return []PracticeKind{ + PracticeKindMain, + PracticeKindAdditional, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PracticeKind) MarshalText() ([]byte, error) { + switch s { + case PracticeKindMain: + return []byte(s), nil + case PracticeKindAdditional: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PracticeKind) UnmarshalText(data []byte) error { + switch PracticeKind(data) { + case PracticeKindMain: + *s = PracticeKindMain + return nil + case PracticeKindAdditional: + *s = PracticeKindAdditional + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// State of a practice. +// +// - not_started: no solution was submitted yet. +// - pending: the submitted solution is queued or running in the sandbox. +// - finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome +// caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a +// memory limit, is `finished` with the affected groups not passed. +// - failed: the sandbox infrastructure could not run the solution, for example because its queue was +// full or an executor broke, independently of the solution. The failure is not the candidate's and +// consumes nothing; the practice can be submitted again. +// +// Ref: #/components/schemas/PracticeStatus +type PracticeStatus string + +const ( + PracticeStatusNotStarted PracticeStatus = "not_started" + PracticeStatusPending PracticeStatus = "pending" + PracticeStatusFinished PracticeStatus = "finished" + PracticeStatusFailed PracticeStatus = "failed" +) + +// AllValues returns all PracticeStatus values. +func (PracticeStatus) AllValues() []PracticeStatus { + return []PracticeStatus{ + PracticeStatusNotStarted, + PracticeStatusPending, + PracticeStatusFinished, + PracticeStatusFailed, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PracticeStatus) MarshalText() ([]byte, error) { + switch s { + case PracticeStatusNotStarted: + return []byte(s), nil + case PracticeStatusPending: + return []byte(s), nil + case PracticeStatusFinished: + return []byte(s), nil + case PracticeStatusFailed: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PracticeStatus) UnmarshalText(data []byte) error { + switch PracticeStatus(data) { + case PracticeStatusNotStarted: + *s = PracticeStatusNotStarted + return nil + case PracticeStatusPending: + *s = PracticeStatusPending + return nil + case PracticeStatusFinished: + *s = PracticeStatusFinished + return nil + case PracticeStatusFailed: + *s = PracticeStatusFailed + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. +// The hidden checks, their inputs and outputs, error output, and seeds are never returned. +// Ref: #/components/schemas/PracticeVerdict +type PracticeVerdict struct { + Score int32 `json:"score"` + MaxScore int32 `json:"max_score"` + Groups []PracticeGroupResult `json:"groups"` +} + +// GetScore returns the value of Score. +func (s *PracticeVerdict) GetScore() int32 { + return s.Score +} + +// GetMaxScore returns the value of MaxScore. +func (s *PracticeVerdict) GetMaxScore() int32 { + return s.MaxScore +} + +// GetGroups returns the value of Groups. +func (s *PracticeVerdict) GetGroups() []PracticeGroupResult { + return s.Groups +} + +// SetScore sets the value of Score. +func (s *PracticeVerdict) SetScore(val int32) { + s.Score = val +} + +// SetMaxScore sets the value of MaxScore. +func (s *PracticeVerdict) SetMaxScore(val int32) { + s.MaxScore = val +} + +// SetGroups sets the value of Groups. +func (s *PracticeVerdict) SetGroups(val []PracticeGroupResult) { + s.Groups = val +} + // Problem details (RFC 9457) returned with the application/problem+json media type for every error // response. `code` is the stable, machine-readable reason; clients branch on it rather than on // `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack @@ -2292,6 +6428,159 @@ func (s *SpecializationCode) UnmarshalText(data []byte) error { type StackTag string +// String answer, at most the `max_length` of the item. Two answers are equal only when their texts are +// identical; no trimming, case folding, or Unicode normalization applies to that comparison. +// Ref: #/components/schemas/StringAnswer +type StringAnswer struct { + Format StringAnswerFormat `json:"format"` + Text string `json:"text"` +} + +// GetFormat returns the value of Format. +func (s *StringAnswer) GetFormat() StringAnswerFormat { + return s.Format +} + +// GetText returns the value of Text. +func (s *StringAnswer) GetText() string { + return s.Text +} + +// SetFormat sets the value of Format. +func (s *StringAnswer) SetFormat(val StringAnswerFormat) { + s.Format = val +} + +// SetText sets the value of Text. +func (s *StringAnswer) SetText(val string) { + s.Text = val +} + +type StringAnswerFormat string + +const ( + StringAnswerFormatString StringAnswerFormat = "string" +) + +// AllValues returns all StringAnswerFormat values. +func (StringAnswerFormat) AllValues() []StringAnswerFormat { + return []StringAnswerFormat{ + StringAnswerFormatString, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s StringAnswerFormat) MarshalText() ([]byte, error) { + switch s { + case StringAnswerFormatString: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *StringAnswerFormat) UnmarshalText(data []byte) error { + switch StringAnswerFormat(data) { + case StringAnswerFormatString: + *s = StringAnswerFormatString + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Enter a short string, such as a command, a header name, or an address. +// Ref: #/components/schemas/StringItemContent +type StringItemContent struct { + Format StringItemContentFormat `json:"format"` + // Maximum length of the answer in characters. It is an input limit of the task family, never derived + // from the key, so it does not reveal the length of the correct answer. + MaxLength int32 `json:"max_length"` +} + +// GetFormat returns the value of Format. +func (s *StringItemContent) GetFormat() StringItemContentFormat { + return s.Format +} + +// GetMaxLength returns the value of MaxLength. +func (s *StringItemContent) GetMaxLength() int32 { + return s.MaxLength +} + +// SetFormat sets the value of Format. +func (s *StringItemContent) SetFormat(val StringItemContentFormat) { + s.Format = val +} + +// SetMaxLength sets the value of MaxLength. +func (s *StringItemContent) SetMaxLength(val int32) { + s.MaxLength = val +} + +type StringItemContentFormat string + +const ( + StringItemContentFormatString StringItemContentFormat = "string" +) + +// AllValues returns all StringItemContentFormat values. +func (StringItemContentFormat) AllValues() []StringItemContentFormat { + return []StringItemContentFormat{ + StringItemContentFormatString, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s StringItemContentFormat) MarshalText() ([]byte, error) { + switch s { + case StringItemContentFormatString: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *StringItemContentFormat) UnmarshalText(data []byte) error { + switch StringItemContentFormat(data) { + case StringItemContentFormatString: + *s = StringItemContentFormatString + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type SubmitMyAssessmentAnswerBadRequest Problem + +func (*SubmitMyAssessmentAnswerBadRequest) submitMyAssessmentAnswerRes() {} + +type SubmitMyAssessmentAnswerConflict Problem + +func (*SubmitMyAssessmentAnswerConflict) submitMyAssessmentAnswerRes() {} + +type SubmitMyAssessmentAnswerForbidden Problem + +func (*SubmitMyAssessmentAnswerForbidden) submitMyAssessmentAnswerRes() {} + +type SubmitMyAssessmentAnswerNotFound Problem + +func (*SubmitMyAssessmentAnswerNotFound) submitMyAssessmentAnswerRes() {} + +type SubmitMyAssessmentAnswerPreconditionFailed Problem + +func (*SubmitMyAssessmentAnswerPreconditionFailed) submitMyAssessmentAnswerRes() {} + +type SubmitMyAssessmentAnswerUnauthorized Problem + +func (*SubmitMyAssessmentAnswerUnauthorized) submitMyAssessmentAnswerRes() {} + +type SubmitMyAssessmentAnswerUnprocessableEntity Problem + +func (*SubmitMyAssessmentAnswerUnprocessableEntity) submitMyAssessmentAnswerRes() {} + // Programming language in which assessment tasks of a specialization are offered and solved. It is the // language of the task bank, not the candidate's platform stack, and it never forms a separate // category. Only banks that offer a choice of language define task languages; the first Backend bank @@ -2472,10 +6761,12 @@ func (s *TooManyRequestsHeaders) SetResponse(val Problem) { s.Response = val } -func (*TooManyRequestsHeaders) confirmEmailRes() {} -func (*TooManyRequestsHeaders) loginRes() {} -func (*TooManyRequestsHeaders) registerAccountRes() {} -func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} +func (*TooManyRequestsHeaders) confirmEmailRes() {} +func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {} +func (*TooManyRequestsHeaders) loginRes() {} +func (*TooManyRequestsHeaders) registerAccountRes() {} +func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} +func (*TooManyRequestsHeaders) submitMyAssessmentAnswerRes() {} type VerificationToken string diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index ea8dfd0..b47ad6f 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -56,11 +56,17 @@ func findAuthorization(h http.Header, prefix string) (string, bool) { // operationRolesSessionCookie is a private map storing roles per operation. var operationRolesSessionCookie = map[string][]string{ - GetCurrentAccountOperation: []string{}, - GetCurrentSessionOperation: []string{}, - GetMyQuestionnaireOperation: []string{}, - LogoutOperation: []string{}, - SaveMyQuestionnaireOperation: []string{}, + CreateMyAssessmentAttemptOperation: []string{}, + FinalizeMyAssessmentAttemptOperation: []string{}, + GetCurrentAccountOperation: []string{}, + GetCurrentSessionOperation: []string{}, + GetMyAssessmentAttemptOperation: []string{}, + GetMyAssessmentAvailabilityOperation: []string{}, + GetMyAssessmentResultOperation: []string{}, + GetMyQuestionnaireOperation: []string{}, + LogoutOperation: []string{}, + SaveMyQuestionnaireOperation: []string{}, + SubmitMyAssessmentAnswerOperation: []string{}, } // GetRolesForSessionCookie returns the required roles for the given operation. @@ -86,8 +92,11 @@ func GetRolesForSessionCookie(operation string) []string { // operationRolesSessionCsrf is a private map storing roles per operation. var operationRolesSessionCsrf = map[string][]string{ - LogoutOperation: []string{}, - SaveMyQuestionnaireOperation: []string{}, + CreateMyAssessmentAttemptOperation: []string{}, + FinalizeMyAssessmentAttemptOperation: []string{}, + LogoutOperation: []string{}, + SaveMyQuestionnaireOperation: []string{}, + SubmitMyAssessmentAnswerOperation: []string{}, } // GetRolesForSessionCsrf returns the required roles for the given operation. diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index 9c832cc..36d7735 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -35,6 +35,91 @@ type Handler interface { // // POST /api/v1/identity/email-verifications ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (ConfirmEmailRes, error) + // CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation. + // + // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, + // an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the + // questionnaire and a target grade, and the task language. The server picks the mode from the + // published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the + // time and session limits, and the item variants in one transaction; the client never sends a mode, a + // seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test + // starts and adds no points. An adaptive retest starts from the previous ability estimate of the + // specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the + // measurement over. + // + // A specialization has at most one active attempt. A new attempt cannot start while one is active, + // during a retry or promotion interval or past the attempt limit of the policy, or when the bank is + // insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. + // GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a + // failure, including the first test, a lower grade can be tested at once. An attempt that ends as + // `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the + // same-grade retry interval; one that ends as `insufficient_bank` or with the reason + // `sandbox_unavailable` counts toward neither. + // + // The limits are server-side: `expires_at` and `sessions` come from the policy version, the client + // clock never extends them, and after them the attempt accepts no command. Within them the attempt is + // also bounded by the item limit of the policy. + // + // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 + // state_conflict response and creates nothing, so a lost response never creates a second attempt. A + // different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a + // corrected retry is evaluated again. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 + // idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` + // for a specialization that is not in the questionnaire or `/task_language` for a language that the + // bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with + // Retry-After before any of them; it is not stored. + // + // POST /api/v1/me/assessment-attempts + CreateMyAssessmentAttempt(ctx context.Context, req *AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (CreateMyAssessmentAttemptRes, error) + // FinalizeMyAssessmentAttempt implements FinalizeMyAssessmentAttempt operation. + // + // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, + // an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the + // result: the decision may continue the attempt, and one response type keeps that unambiguous for + // every generated client. When the returned state is `completed`, the client reads the result with + // GetMyAssessmentResult. + // + // Allowed in `ready_to_finalize`, where every required part is done, and in + // `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server + // decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: + // + // - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and + // completes the attempt. It never offers an additional practice. + // - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection + // completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the + // demo policy) on the first finalize, while time and sessions remain, completes nothing: the server + // appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers + // 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no + // new attempt. The next finalize, after its verdict, decides with the added evidence; a probability + // still below confirmation gives `not_confirmed`. An attempt offers at most one additional + // practice. + // - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the + // current evidence. A retry of the first finalize with a new key cannot decline by accident: it + // carries the version from before the offer and answers 412. + // + // A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the + // same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers + // 200 with that attempt even with a new key or an older `expected_version`; the result is computed + // once. When `expires_at` passes or the session limit is reached, the server finalizes + // `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also + // answers 200 with the `completed` attempt. + // + // An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one + // that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list + // what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A + // stale `expected_version` answers 412 version_conflict, the repository status for a stale version. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), + // the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), + // the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under + // the key; 400 and 412 are not. + // + // POST /api/v1/me/assessment-attempts/{attempt_id}/finalize + FinalizeMyAssessmentAttempt(ctx context.Context, req *AssessmentFinalization, params FinalizeMyAssessmentAttemptParams) (FinalizeMyAssessmentAttemptRes, error) // GetConsentText implements GetConsentText operation. // // Public operation without a session. Returns the current text of a consent that is given before an @@ -71,6 +156,71 @@ type Handler interface { // // GET /api/v1/healthz GetHealthz(ctx context.Context) (*HealthResponse, error) + // GetMyAssessmentAttempt implements GetMyAssessmentAttempt operation. + // + // Requires the session cookie of a candidate account. Returns the attempt with its state, fixed + // versions, time and session limits, progress, the item to answer now, and the practices. A reload, a + // retried request, or a new session returns the same item instance with the same text and option + // order; a lost connection never creates a new attempt. The response never says whether an earlier + // answer was correct and never contains answer keys, item scores, family or variant identifiers, + // seeds, hidden checks, or anti-cheat signals. + // + // Reading an active attempt counts as activity: after the previous session ended it starts the next + // session, and when that would exceed the session limit it starts none and the attempt becomes + // `expired`. Before it answers, the server commits any transition that is due, with a new version: + // past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is + // declined and the attempt becomes `completed`, and the other active states become `expired`; a + // practice still `pending` is graded first. The client polls this operation while a practice is + // `pending`. Reading a terminal attempt changes nothing. + // + // The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 + // not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account + // answers 403 forbidden; no operation gives an employer the answers or the attempt history. + // + // GET /api/v1/me/assessment-attempts/{attempt_id} + GetMyAssessmentAttempt(ctx context.Context, params GetMyAssessmentAttemptParams) (GetMyAssessmentAttemptRes, error) + // GetMyAssessmentAvailability implements GetMyAssessmentAvailability operation. + // + // Requires the session cookie of a candidate account; the candidate comes from the session. For each + // specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every + // grade whether an attempt can start now, in which mode, and with which limits: the time limit, the + // session limit, the item limit, and whether a code practice is required. The client shows them before + // the start, together with the method and the signals that are collected, and resumes an active + // attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt. + // + // `insufficient_bank` is the state of a category whose bank is not published or has too few families + // that this candidate has not seen; the server limits attempts instead of repeating families. + // `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with + // that date and offer support. Specializations and their retry intervals are independent. Attempts + // that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations + // and never cause a `cooldown`. + // + // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account + // answers 403 forbidden. + // + // GET /api/v1/me/assessment-availability + GetMyAssessmentAvailability(ctx context.Context) (GetMyAssessmentAvailabilityRes, error) + // GetMyAssessmentResult implements GetMyAssessmentResult operation. + // + // Requires the session cookie of a candidate account. Returns the immutable result of a terminal + // attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and + // algorithm versions, the decision, the previously confirmed grade, the calibration status and + // limitations of the method, the uncertainty where the method computes it, the practice verdicts, the + // weak domains, the working time as a separate label, and the next steps that the server allows. A + // later policy, bank, or algorithm version never changes it. + // + // Fields that the method does not compute are null and never zero: a `demo_basic` result has null + // `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, + // seeds, hidden checks, or anti-cheat signals. + // + // An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active + // and has no result yet. The server first commits any due transition, so an attempt past its limits is + // read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown + // identifier. An employer account answers 403 forbidden; employers see only the current category + // through a separate projection, never this result or the attempt history. + // + // GET /api/v1/me/assessment-attempts/{attempt_id}/result + GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error) // GetMyQuestionnaire implements GetMyQuestionnaire operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -234,6 +384,63 @@ type Handler interface { // // PUT /api/v1/me/questionnaire SaveMyQuestionnaire(ctx context.Context, req *CandidateQuestionnaireUpdate) (SaveMyQuestionnaireRes, error) + // SubmitMyAssessmentAnswer implements SubmitMyAssessmentAnswer operation. + // + // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, + // an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the + // format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or + // `practice`. It never carries a score, a duration, or a correctness flag; the server records the + // times itself and scores the answer with the key of the fixed item instance. Time never enters the + // ability estimate or the grade decision. + // + // The response is the attempt with the next item to answer. It never says whether the answer was + // correct. Items are answered in order and each answer is final. + // + // Practice: an answer with format `practice` submits the solution of the main or the additional + // practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the + // response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. + // Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or + // seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or + // memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure + // could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so + // hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the + // public examples are unlimited apart from the sandbox rate limit and never show hidden group results; + // they are planned as a separate operation. + // + // Repeats and conflicts, per item: + // + // - A retry with the same Idempotency-Key and body within 24 hours replays the stored response. + // - Sending the answer already stored for the item again, even with a new key or an older + // `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. + // Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence + // for `element_ids`, numeric equality for `number`, identical text without normalization for `text` + // and `config`, and the same language with identical source for a practice. + // - A different answer for an item that already has one answers 409 state_conflict when + // `expected_version` is current; with a stale version the version check comes first and answers + // 412. + // - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A + // submission with the same or a different solution, with the current `expected_version`, queues it + // again and advances the version. + // + // Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the + // server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is + // the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is + // kept for commands that the attempt state does not allow at the current version. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), + // the attempt (404 not_found for an unknown attempt or one of another candidate; the server first + // commits any due transition such as expiry, and the request counts as activity for the session + // limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is + // `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is + // not current, the item has a different answer, or the practice verdict is pending or finished), then + // the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). + // Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and + // replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any + // check. + // + // POST /api/v1/me/assessment-attempts/{attempt_id}/answers + SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error) // NewError creates *ProblemStatusCode from error returned by handler. // // Used for common default response. diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 87e8122..49605af 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -43,6 +43,97 @@ func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerifica return r, ht.ErrNotImplemented } +// CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the +// questionnaire and a target grade, and the task language. The server picks the mode from the +// published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the +// time and session limits, and the item variants in one transaction; the client never sends a mode, a +// seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test +// starts and adds no points. An adaptive retest starts from the previous ability estimate of the +// specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the +// measurement over. +// +// A specialization has at most one active attempt. A new attempt cannot start while one is active, +// during a retry or promotion interval or past the attempt limit of the policy, or when the bank is +// insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. +// GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a +// failure, including the first test, a lower grade can be tested at once. An attempt that ends as +// `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the +// same-grade retry interval; one that ends as `insufficient_bank` or with the reason +// `sandbox_unavailable` counts toward neither. +// +// The limits are server-side: `expires_at` and `sessions` come from the policy version, the client +// clock never extends them, and after them the attempt accepts no command. Within them the attempt is +// also bounded by the item limit of the policy. +// +// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 +// state_conflict response and creates nothing, so a lost response never creates a second attempt. A +// different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a +// corrected retry is evaluated again. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 +// idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` +// for a specialization that is not in the questionnaire or `/task_language` for a language that the +// bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with +// Retry-After before any of them; it is not stored. +// +// POST /api/v1/me/assessment-attempts +func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req *AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (r CreateMyAssessmentAttemptRes, _ error) { + return r, ht.ErrNotImplemented +} + +// FinalizeMyAssessmentAttempt implements FinalizeMyAssessmentAttempt operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the +// result: the decision may continue the attempt, and one response type keeps that unambiguous for +// every generated client. When the returned state is `completed`, the client reads the result with +// GetMyAssessmentResult. +// +// Allowed in `ready_to_finalize`, where every required part is done, and in +// `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server +// decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: +// +// - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and +// completes the attempt. It never offers an additional practice. +// - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection +// completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the +// demo policy) on the first finalize, while time and sessions remain, completes nothing: the server +// appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers +// 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no +// new attempt. The next finalize, after its verdict, decides with the added evidence; a probability +// still below confirmation gives `not_confirmed`. An attempt offers at most one additional +// practice. +// - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the +// current evidence. A retry of the first finalize with a new key cannot decline by accident: it +// carries the version from before the offer and answers 412. +// +// A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the +// same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers +// 200 with that attempt even with a new key or an older `expected_version`; the result is computed +// once. When `expires_at` passes or the session limit is reached, the server finalizes +// `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also +// answers 200 with the `completed` attempt. +// +// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one +// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list +// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A +// stale `expected_version` answers 412 version_conflict, the repository status for a stale version. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), +// the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), +// the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under +// the key; 400 and 412 are not. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/finalize +func (UnimplementedHandler) FinalizeMyAssessmentAttempt(ctx context.Context, req *AssessmentFinalization, params FinalizeMyAssessmentAttemptParams) (r FinalizeMyAssessmentAttemptRes, _ error) { + return r, ht.ErrNotImplemented +} + // GetConsentText implements GetConsentText operation. // // Public operation without a session. Returns the current text of a consent that is given before an @@ -91,6 +182,80 @@ func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse, return r, ht.ErrNotImplemented } +// GetMyAssessmentAttempt implements GetMyAssessmentAttempt operation. +// +// Requires the session cookie of a candidate account. Returns the attempt with its state, fixed +// versions, time and session limits, progress, the item to answer now, and the practices. A reload, a +// retried request, or a new session returns the same item instance with the same text and option +// order; a lost connection never creates a new attempt. The response never says whether an earlier +// answer was correct and never contains answer keys, item scores, family or variant identifiers, +// seeds, hidden checks, or anti-cheat signals. +// +// Reading an active attempt counts as activity: after the previous session ended it starts the next +// session, and when that would exceed the session limit it starts none and the attempt becomes +// `expired`. Before it answers, the server commits any transition that is due, with a new version: +// past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is +// declined and the attempt becomes `completed`, and the other active states become `expired`; a +// practice still `pending` is graded first. The client polls this operation while a practice is +// `pending`. Reading a terminal attempt changes nothing. +// +// The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 +// not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account +// answers 403 forbidden; no operation gives an employer the answers or the attempt history. +// +// GET /api/v1/me/assessment-attempts/{attempt_id} +func (UnimplementedHandler) GetMyAssessmentAttempt(ctx context.Context, params GetMyAssessmentAttemptParams) (r GetMyAssessmentAttemptRes, _ error) { + return r, ht.ErrNotImplemented +} + +// GetMyAssessmentAvailability implements GetMyAssessmentAvailability operation. +// +// Requires the session cookie of a candidate account; the candidate comes from the session. For each +// specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every +// grade whether an attempt can start now, in which mode, and with which limits: the time limit, the +// session limit, the item limit, and whether a code practice is required. The client shows them before +// the start, together with the method and the signals that are collected, and resumes an active +// attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt. +// +// `insufficient_bank` is the state of a category whose bank is not published or has too few families +// that this candidate has not seen; the server limits attempts instead of repeating families. +// `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with +// that date and offer support. Specializations and their retry intervals are independent. Attempts +// that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations +// and never cause a `cooldown`. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. +// +// GET /api/v1/me/assessment-availability +func (UnimplementedHandler) GetMyAssessmentAvailability(ctx context.Context) (r GetMyAssessmentAvailabilityRes, _ error) { + return r, ht.ErrNotImplemented +} + +// GetMyAssessmentResult implements GetMyAssessmentResult operation. +// +// Requires the session cookie of a candidate account. Returns the immutable result of a terminal +// attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and +// algorithm versions, the decision, the previously confirmed grade, the calibration status and +// limitations of the method, the uncertainty where the method computes it, the practice verdicts, the +// weak domains, the working time as a separate label, and the next steps that the server allows. A +// later policy, bank, or algorithm version never changes it. +// +// Fields that the method does not compute are null and never zero: a `demo_basic` result has null +// `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, +// seeds, hidden checks, or anti-cheat signals. +// +// An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active +// and has no result yet. The server first commits any due transition, so an attempt past its limits is +// read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown +// identifier. An employer account answers 403 forbidden; employers see only the current category +// through a separate projection, never this result or the attempt history. +// +// GET /api/v1/me/assessment-attempts/{attempt_id}/result +func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (r GetMyAssessmentResultRes, _ error) { + return r, ht.ErrNotImplemented +} + // GetMyQuestionnaire implements GetMyQuestionnaire operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -275,6 +440,66 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid return r, ht.ErrNotImplemented } +// SubmitMyAssessmentAnswer implements SubmitMyAssessmentAnswer operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the +// format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or +// `practice`. It never carries a score, a duration, or a correctness flag; the server records the +// times itself and scores the answer with the key of the fixed item instance. Time never enters the +// ability estimate or the grade decision. +// +// The response is the attempt with the next item to answer. It never says whether the answer was +// correct. Items are answered in order and each answer is final. +// +// Practice: an answer with format `practice` submits the solution of the main or the additional +// practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the +// response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. +// Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or +// seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or +// memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure +// could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so +// hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the +// public examples are unlimited apart from the sandbox rate limit and never show hidden group results; +// they are planned as a separate operation. +// +// Repeats and conflicts, per item: +// +// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response. +// - Sending the answer already stored for the item again, even with a new key or an older +// `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. +// Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence +// for `element_ids`, numeric equality for `number`, identical text without normalization for `text` +// and `config`, and the same language with identical source for a practice. +// - A different answer for an item that already has one answers 409 state_conflict when +// `expected_version` is current; with a stale version the version check comes first and answers +// 412. +// - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A +// submission with the same or a different solution, with the current `expected_version`, queues it +// again and advances the version. +// +// Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the +// server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is +// the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is +// kept for commands that the attempt state does not allow at the current version. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), +// the attempt (404 not_found for an unknown attempt or one of another candidate; the server first +// commits any due transition such as expiry, and the request counts as activity for the session +// limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is +// `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is +// not current, the item has a different answer, or the practice verdict is pending or finished), then +// the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). +// Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and +// replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any +// check. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/answers +func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (r SubmitMyAssessmentAnswerRes, _ error) { + return r, ht.ErrNotImplemented +} + // NewError creates *ProblemStatusCode from error returned by handler. // // Used for common default response. diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index ba744da..43cda93 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -99,6 +99,1974 @@ func (s AccountScenario) Validate() error { } } +func (s AssessmentAnswer) Validate() error { + switch s.Type { + case ChoiceAnswerAssessmentAnswer: + if err := s.ChoiceAnswer.Validate(); err != nil { + return err + } + return nil + case NumberAnswerAssessmentAnswer: + if err := s.NumberAnswer.Validate(); err != nil { + return err + } + return nil + case StringAnswerAssessmentAnswer: + if err := s.StringAnswer.Validate(); err != nil { + return err + } + return nil + case OrderAnswerAssessmentAnswer: + if err := s.OrderAnswer.Validate(); err != nil { + return err + } + return nil + case FindErrorAnswerAssessmentAnswer: + if err := s.FindErrorAnswer.Validate(); err != nil { + return err + } + return nil + case ConfigurationAnswerAssessmentAnswer: + if err := s.ConfigurationAnswer.Validate(); err != nil { + return err + } + return nil + case PracticeAnswerAssessmentAnswer: + if err := s.PracticeAnswer.Validate(); err != nil { + return err + } + return nil + default: + return errors.Errorf("invalid type %q", s.Type) + } +} + +func (s *AssessmentAnswerSubmission) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if err := s.Answer.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "answer", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentAttempt) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.TargetGrade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "target_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TaskLanguage.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "task_language", + Error: err, + }) + } + if err := func() error { + if err := s.Mode.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "mode", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if err := s.Versions.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "versions", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Sessions.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "sessions", + Error: err, + }) + } + if err := func() error { + if err := s.Progress.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "progress", + Error: err, + }) + } + if err := func() error { + if value, ok := s.CurrentItem.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "current_item", + Error: err, + }) + } + if err := func() error { + if s.Practices == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 5, + MaxLengthSet: true, + }).ValidateLength(len(s.Practices)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Practices { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "practices", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentAttemptCreate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.TargetGrade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "target_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TaskLanguage.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "task_language", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentAttemptHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentAttemptState) Validate() error { + switch s { + case "in_progress": + return nil + case "practice_pending": + return nil + case "additional_practice_pending": + return nil + case "ready_to_finalize": + return nil + case "completed": + return nil + case "expired": + return nil + case "insufficient_bank": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentAttemptVersion) Validate() error { + alias := (int64)(s) + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(alias)); err != nil { + return errors.Wrap(err, "int") + } + return nil +} + +func (s *AssessmentAvailability) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Specializations == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2, + MaxLengthSet: true, + }).ValidateLength(len(s.Specializations)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Specializations { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specializations", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentAvailabilityHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentDurations) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.ItemsSeconds)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "items_seconds", + Error: err, + }) + } + if err := func() error { + if value, ok := s.PracticeSeconds.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "practice_seconds", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentFinalization) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentGap) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z0-9_]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Domain)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "domain", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentGradeAvailability) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Grade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "grade", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Mode.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "mode", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TimeLimitSeconds.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "time_limit_seconds", + Error: err, + }) + } + if err := func() error { + if value, ok := s.MaxSessions.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 10, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_sessions", + Error: err, + }) + } + if err := func() error { + if value, ok := s.MaxItems.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 100, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_items", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentGradeAvailabilityStatus) Validate() error { + switch s { + case "available": + return nil + case "active_attempt": + return nil + case "cooldown": + return nil + case "insufficient_bank": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentInterval) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Float{}).Validate(float64(s.Low)); err != nil { + return errors.Wrap(err, "float") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "low", + Error: err, + }) + } + if err := func() error { + if err := (validate.Float{}).Validate(float64(s.High)); err != nil { + return errors.Wrap(err, "float") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "high", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentItem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 100, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Sequence)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "sequence", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 20000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Prompt)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "prompt", + Error: err, + }) + } + if err := func() error { + if err := s.Content.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "content", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentLimitation) Validate() error { + switch s { + case "uncalibrated_thresholds": + return nil + case "demo_bank": + return nil + case "practice_not_included": + return nil + case "unproctored": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentMode) Validate() error { + switch s { + case "demo_basic": + return nil + case "adaptive": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentNextAction) Validate() error { + switch s { + case "retake_same_grade": + return nil + case "take_lower_grade": + return nil + case "accept_lower_grade": + return nil + case "take_higher_grade": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentNextStep) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Action.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "action", + Error: err, + }) + } + if err := func() error { + if err := s.Grade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "grade", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentNotDeterminedReason) Validate() error { + switch s { + case "expired": + return nil + case "practice_incomplete": + return nil + case "insufficient_bank": + return nil + case "sandbox_unavailable": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentOption) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 2000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Text)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentOptionId) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 32, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s AssessmentOutcome) Validate() error { + switch s { + case "confirmed": + return nil + case "not_confirmed": + return nil + case "not_determined": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentPractice) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Verdict.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "verdict", + Error: err, + }) + } + if err := func() error { + if value, ok := s.FailureReason.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "failure_reason", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentPracticeResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Verdict.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "verdict", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentProgress) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 100, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.AnsweredItems)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "answered_items", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 100, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MaxItems)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_items", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.TargetGrade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "target_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TaskLanguage.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "task_language", + Error: err, + }) + } + if err := func() error { + if err := s.Mode.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "mode", + Error: err, + }) + } + if err := func() error { + if err := s.Versions.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "versions", + Error: err, + }) + } + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if value, ok := s.NotDeterminedReason.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "not_determined_reason", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ConfirmedGrade.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "confirmed_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.PreviousConfirmedGrade.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "previous_confirmed_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Strength.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "strength", + Error: err, + }) + } + if err := func() error { + if err := s.CalibrationStatus.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "calibration_status", + Error: err, + }) + } + if err := func() error { + if s.Limitations == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.Limitations)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Limitations); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Limitations { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "limitations", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Uncertainty.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "uncertainty", + Error: err, + }) + } + if err := func() error { + if value, ok := s.BasicScore.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "basic_score", + Error: err, + }) + } + if err := func() error { + if s.Practices == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 5, + MaxLengthSet: true, + }).ValidateLength(len(s.Practices)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Practices { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "practices", + Error: err, + }) + } + if err := func() error { + if s.Gaps == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Gaps)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Gaps { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "gaps", + Error: err, + }) + } + if err := func() error { + if err := s.Durations.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "durations", + Error: err, + }) + } + if err := func() error { + if s.NextSteps == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 5, + MaxLengthSet: true, + }).ValidateLength(len(s.NextSteps)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.NextSteps { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "next_steps", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentResultHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentSessions) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 10, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Used)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "used", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 10, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Max)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 60, + MaxSet: true, + Max: 86400, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.IdleTimeoutSeconds)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "idle_timeout_seconds", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentSpecializationAvailability) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ConfirmedGrade.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "confirmed_grade", + Error: err, + }) + } + if err := func() error { + if s.Grades == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.Grades)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Grades { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "grades", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentStrength) Validate() error { + switch s { + case "high": + return nil + case "medium": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentUncertainty) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Float{}).Validate(float64(s.Theta)); err != nil { + return errors.Wrap(err, "float") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "theta", + Error: err, + }) + } + if err := func() error { + if err := (validate.Float{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: nil, + Pattern: nil, + }).Validate(float64(s.StandardError)); err != nil { + return errors.Wrap(err, "float") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "standard_error", + Error: err, + }) + } + if err := func() error { + if err := s.Interval95.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "interval_95", + Error: err, + }) + } + if err := func() error { + if err := (validate.Float{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 1, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: nil, + Pattern: nil, + }).Validate(float64(s.PGrade)); err != nil { + return errors.Wrap(err, "float") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "p_grade", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentVersionLabel) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *AssessmentVersions) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.PolicyVersion)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "policy_version", + Error: err, + }) + } + if err := func() error { + if err := s.BankVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "bank_version", + Error: err, + }) + } + if err := func() error { + if err := s.AlgorithmVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "algorithm_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *BasicScore) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Points)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "points", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MaxPoints)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_points", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.PassPoints)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "pass_points", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s CacheControlNoStore) Validate() error { switch s { case "no-store": @@ -108,6 +2076,17 @@ func (s CacheControlNoStore) Validate() error { } } +func (s CalibrationStatus) Validate() error { + switch s { + case "uncalibrated": + return nil + case "calibrated": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *CandidateExperience) Validate() error { if s == nil { return validate.ErrNilPointer @@ -528,6 +2507,355 @@ func (s *CatalogSpecialization) Validate() error { return nil } +func (s *ChoiceAnswer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if s.OptionIds == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.OptionIds)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.OptionIds); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.OptionIds { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "option_ids", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ChoiceAnswerFormat) Validate() error { + switch s { + case "choice": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ChoiceItemContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if s.Options == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 2, + MinLengthSet: true, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.Options)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Options { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "options", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ChoiceItemContentFormat) Validate() error { + switch s { + case "choice": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *CodeLine) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 500, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Number)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "number", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Text)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ConfigurationAnswer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 20000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Config)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "config", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ConfigurationAnswerFormat) Validate() error { + switch s { + case "configuration": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ConfigurationItemContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 32, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z0-9_+-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Syntax)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "syntax", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 20000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.InitialConfig)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "initial_config", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 20000, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MaxLength)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_length", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ConfigurationItemContentFormat) Validate() error { + switch s { + case "configuration": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *ConfirmEmailBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -630,6 +2958,46 @@ func (s ConsentTextVersion) Validate() error { return nil } +func (s *CreateMyAssessmentAttemptBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentAttemptConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentAttemptForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentAttemptUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentAttemptUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s CsrfToken) Validate() error { alias := (string)(s) if err := (validate.String{ @@ -787,6 +3155,262 @@ func (s EmailVerificationResultEmailVerified) Validate() error { } } +func (s *FinalizeMyAssessmentAttemptBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *FinalizeMyAssessmentAttemptConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *FinalizeMyAssessmentAttemptForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *FinalizeMyAssessmentAttemptNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *FinalizeMyAssessmentAttemptPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *FinalizeMyAssessmentAttemptUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *FinalizeMyAssessmentAttemptUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *FindErrorAnswer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if s.LineNumbers == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.LineNumbers)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.LineNumbers); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.LineNumbers { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 500, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(elem)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "line_numbers", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s FindErrorAnswerFormat) Validate() error { + switch s { + case "find_error": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *FindErrorItemContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Syntax.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 32, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z0-9_+-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "syntax", + Error: err, + }) + } + if err := func() error { + if s.Lines == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 500, + MaxLengthSet: true, + }).ValidateLength(len(s.Lines)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Lines { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "lines", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 10, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MaxSelections)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_selections", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s FindErrorItemContentFormat) Validate() error { + switch s { + case "find_error": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *GetCurrentSessionOKHeaders) Validate() error { if s == nil { return validate.ErrNilPointer @@ -821,6 +3445,78 @@ func (s *GetCurrentSessionOKHeaders) Validate() error { return nil } +func (s *GetMyAssessmentAttemptForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentAttemptNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentAttemptUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentAvailabilityForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentAvailabilityUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentResultConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentResultForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentResultNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentResultUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetMyQuestionnaireForbidden) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -916,6 +3612,48 @@ func (s IdentityRequestAcceptedStatus) Validate() error { } } +func (s ItemContent) Validate() error { + switch s.Type { + case ChoiceItemContentItemContent: + if err := s.ChoiceItemContent.Validate(); err != nil { + return err + } + return nil + case NumberItemContentItemContent: + if err := s.NumberItemContent.Validate(); err != nil { + return err + } + return nil + case StringItemContentItemContent: + if err := s.StringItemContent.Validate(); err != nil { + return err + } + return nil + case OrderItemContentItemContent: + if err := s.OrderItemContent.Validate(); err != nil { + return err + } + return nil + case FindErrorItemContentItemContent: + if err := s.FindErrorItemContent.Validate(); err != nil { + return err + } + return nil + case ConfigurationItemContentItemContent: + if err := s.ConfigurationItemContent.Validate(); err != nil { + return err + } + return nil + case PracticeItemContentItemContent: + if err := s.PracticeItemContent.Validate(); err != nil { + return err + } + return nil + default: + return errors.Errorf("invalid type %q", s.Type) + } +} + func (s *LoginBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -1049,6 +3787,111 @@ func (s NewPassword) Validate() error { return nil } +func (s *NumberAnswer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if err := (validate.Float{}).Validate(float64(s.Number)); err != nil { + return errors.Wrap(err, "float") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "number", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s NumberAnswerFormat) Validate() error { + switch s { + case "number": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *NumberItemContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Unit.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 32, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "unit", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s NumberItemContentFormat) Validate() error { + switch s { + case "number": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s OnboardingStep) Validate() error { switch s { case "candidate_consents": @@ -1068,6 +3911,145 @@ func (s OnboardingStep) Validate() error { } } +func (s *OrderAnswer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if s.ElementIds == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 2, + MinLengthSet: true, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.ElementIds)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.ElementIds); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.ElementIds { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "element_ids", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s OrderAnswerFormat) Validate() error { + switch s { + case "order": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *OrderItemContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if s.Elements == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 2, + MinLengthSet: true, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Elements)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Elements { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "elements", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s OrderItemContentFormat) Validate() error { + switch s { + case "order": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *PersonalDataConsentAcceptance) Validate() error { if s == nil { return validate.ErrNilPointer @@ -1111,6 +4093,425 @@ func (s PersonalDataConsentAcceptanceAccepted) Validate() error { } } +func (s *PracticeAnswer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Language.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "language", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 65536, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.SourceCode)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source_code", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s PracticeAnswerFormat) Validate() error { + switch s { + case "practice": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *PracticeExample) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Input)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "input", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.ExpectedOutput)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_output", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s PracticeFailureReason) Validate() error { + switch s { + case "sandbox_busy": + return nil + case "sandbox_error": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *PracticeGroupResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 3, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Group)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "group", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *PracticeItemContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if s.Languages == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2, + MaxLengthSet: true, + }).ValidateLength(len(s.Languages)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Languages); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Languages { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "languages", + Error: err, + }) + } + if err := func() error { + if s.PublicExamples == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.PublicExamples)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.PublicExamples { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "public_examples", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 65536, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MaxSourceLength)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_source_length", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s PracticeItemContentFormat) Validate() error { + switch s { + case "practice": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s PracticeKind) Validate() error { + switch s { + case "main": + return nil + case "additional": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s PracticeStatus) Validate() error { + switch s { + case "not_started": + return nil + case "pending": + return nil + case "finished": + return nil + case "failed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *PracticeVerdict) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 3, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Score)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "score", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 3, + MaxSet: true, + Max: 3, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MaxScore)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_score", + Error: err, + }) + } + if err := func() error { + if s.Groups == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 3, + MinLengthSet: true, + MaxLength: 3, + MaxLengthSet: true, + }).ValidateLength(len(s.Groups)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Groups { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "groups", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *Problem) Validate() error { if s == nil { return validate.ErrNilPointer @@ -2056,6 +5457,170 @@ func (s StackTag) Validate() error { return nil } +func (s *StringAnswer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 500, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Text)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s StringAnswerFormat) Validate() error { + switch s { + case "string": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *StringItemContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 500, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MaxLength)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_length", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s StringItemContentFormat) Validate() error { + switch s { + case "string": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SubmitMyAssessmentAnswerBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentAnswerConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentAnswerForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentAnswerNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentAnswerPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentAnswerUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentAnswerUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s TaskLanguage) Validate() error { switch s { case "python": diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index 29a8f9f..9bb7c55 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -564,6 +564,198 @@ func TestCatalogAndQuestionnaireAccessBeforeImplementation(t *testing.T) { } } +// Assessment request fixtures shared by the assessment tests. +const ( + assessmentAttemptsPath = "/api/v1/me/assessment-attempts" + assessmentAttemptPath = assessmentAttemptsPath + "/01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b" + assessmentAnswersPath = assessmentAttemptPath + "/answers" + assessmentFinalizePath = assessmentAttemptPath + "/finalize" + assessmentResultPath = assessmentAttemptPath + "/result" + assessmentItemID = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01" + validAttemptCreate = `{"specialization":"backend","target_grade":"junior","task_language":"go"}` +) + +// assessmentAnswerBody returns a SubmitMyAssessmentAnswer body for version 1 +// of the attempt with the given answer. +func assessmentAnswerBody(answer string) string { + return `{"expected_version":1,"item_id":"` + assessmentItemID + `","answer":` + answer + `}` +} + +// The schema alone must accept every answer format of FR05 and reject what a +// candidate may never send: a score, a seed, a mode, a format mixed with the +// fields of another format, or a missing version or Idempotency-Key. Security +// accepts the session here, so the request reaches validation; a valid request +// then answers 501 until the assessment is implemented. +func TestAssessmentSchemaValidationPrecedesImplementation(t *testing.T) { + session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken} + command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey} + for _, test := range []struct { + name string + request identityRequest + location api.ProblemFieldLocation + pointer string + code string + }{ + { + name: "availability", + request: identityRequest{method: http.MethodGet, path: "/api/v1/me/assessment-availability", headers: session}, + }, + { + name: "create", + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: command}, + }, + { + name: "create without a task language choice", + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: `{"specialization":"network_engineer","target_grade":"middle","task_language":null}`, headers: command}, + }, + { + // The server picks the mode from the published bank. + name: "create with a mode chosen by the client", + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: strings.Replace(validAttemptCreate, `}`, `,"mode":"demo_basic"}`, 1), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "create for a grade outside the MVP scale", + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: strings.Replace(validAttemptCreate, `"junior"`, `"lead"`, 1), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/target_grade", code: "invalid", + }, + { + name: "create without an Idempotency-Key", + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: session}, + location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required", + }, + { + name: "resume", + request: identityRequest{method: http.MethodGet, path: assessmentAttemptPath, headers: session}, + }, + { + name: "resume with an identifier that is not a UUID", + request: identityRequest{method: http.MethodGet, path: assessmentAttemptsPath + "/1", headers: session}, + location: api.ProblemFieldLocationPath, pointer: "/attempt_id", code: "invalid", + }, + { + name: "choice answer", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","option_ids":["x9"]}`), headers: command}, + }, + { + name: "number answer", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"number","number":254}`), headers: command}, + }, + { + name: "string answer", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"string","text":"Retry-After"}`), headers: command}, + }, + { + name: "order answer", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"order","element_ids":["b1","a7","d3"]}`), headers: command}, + }, + { + name: "find-error answer", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"find_error","line_numbers":[5]}`), headers: command}, + }, + { + name: "configuration answer", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"configuration","config":"interface Gi0/1"}`), headers: command}, + }, + { + name: "practice answer", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"practice","language":"python","source_code":"print(1)"}`), headers: command}, + }, + { + // The server scores the answer with the key of the item instance. + name: "answer with a score set by the candidate", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: strings.Replace(assessmentAnswerBody(`{"format":"choice","option_ids":["x9"]}`), `{"expected_version"`, `{"score":1,"expected_version"`, 1), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "practice answer with a seed", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"practice","language":"python","source_code":"print(1)","seed":42}`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "format with the fields of another format", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","number":254}`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "unknown answer format", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"essay","text":"..."}`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/answer/format", code: "invalid", + }, + { + name: "choice answer without an option", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","option_ids":[]}`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/answer/option_ids", code: "invalid", + }, + { + name: "answer without an expected version", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: `{"item_id":"` + assessmentItemID + `","answer":{"format":"number","number":1}}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required", + }, + { + name: "answer without an Idempotency-Key", + request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"number","number":1}`), headers: session}, + location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required", + }, + { + name: "finalize", + request: identityRequest{method: http.MethodPost, path: assessmentFinalizePath, body: `{"expected_version":17}`, headers: command}, + }, + { + name: "finalize with version zero", + request: identityRequest{method: http.MethodPost, path: assessmentFinalizePath, body: `{"expected_version":0}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid", + }, + { + name: "result", + request: identityRequest{method: http.MethodGet, path: assessmentResultPath, headers: session}, + }, + } { + t.Run(test.name, func(t *testing.T) { + logger := slog.New(slog.DiscardHandler) + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + response := serveIdentityRequest(t, router, test.request) + + if test.code == "" { + requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) + return + } + body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed) + want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code} + for _, field := range body.Errors { + if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code { + return + } + } + t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want) + }) + } +} + +// Every assessment operation requires a candidate session; DenyAllSecurity +// grants none, with or without a cookie and a CSRF token. +func TestAssessmentAccessBeforeImplementation(t *testing.T) { + command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey} + for _, test := range []identityRequest{ + {method: http.MethodGet, path: "/api/v1/me/assessment-availability"}, + {method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: command}, + {method: http.MethodGet, path: assessmentAttemptPath}, + {method: http.MethodGet, path: assessmentAttemptPath, headers: map[string]string{"Cookie": testSessionCookie}}, + {method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"number","number":1}`), headers: command}, + {method: http.MethodPost, path: assessmentFinalizePath, body: `{"expected_version":1}`, headers: command}, + {method: http.MethodGet, path: assessmentResultPath}, + } { + t.Run(test.method+" "+test.path, func(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated) + }) + } +} + func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) { var logs bytes.Buffer logger := slog.New(slog.NewJSONHandler(&logs, nil)) diff --git a/frontend/src/shared/api/assessment-contract.test.ts b/frontend/src/shared/api/assessment-contract.test.ts new file mode 100644 index 0000000..16ab4c2 --- /dev/null +++ b/frontend/src/shared/api/assessment-contract.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; +import { submitMyAssessmentAnswer } from "./endpoints/assessment/assessment"; +import { + AssessmentAnswerSubmission, + AssessmentItem, + ItemContent, + SubmitMyAssessmentAnswerBody, +} from "./schemas"; + +// These tests pin the generated assessment contract that the FSD adapters +// consume. They fail when regeneration drops an answer format or adds a field +// that would carry a score, a key, or a seed between the client and the server. + +const itemId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01"; + +const answers = { + choice: { format: "choice", option_ids: ["x9"] }, + number: { format: "number", number: 254 }, + string: { format: "string", text: "Retry-After" }, + order: { format: "order", element_ids: ["a7", "b1", "c2", "d3"] }, + find_error: { format: "find_error", line_numbers: [5] }, + configuration: { format: "configuration", config: "interface Gi0/1" }, + practice: { format: "practice", language: "python", source_code: "print(1)" }, +} as const; + +const bodySchemas = [ + ["AssessmentAnswerSubmission", AssessmentAnswerSubmission], + ["SubmitMyAssessmentAnswerBody", SubmitMyAssessmentAnswerBody], +] as const; + +describe.each(bodySchemas)("generated %s", (_name, schema) => { + it.each(Object.entries(answers))("accepts a %s answer", (format, answer) => { + const parsed = schema.parse({ expected_version: 1, item_id: itemId, answer }); + + expect(parsed.answer.format).toBe(format); + }); + + it("rejects an unknown answer format", () => { + const result = schema.safeParse({ + expected_version: 1, + item_id: itemId, + answer: { format: "essay", text: "..." }, + }); + + expect(result.success).toBe(false); + }); + + it("rejects version 0, which no attempt has", () => { + const result = schema.safeParse({ + expected_version: 0, + item_id: itemId, + answer: answers.choice, + }); + + expect(result.success).toBe(false); + expect(result.error?.issues).toEqual([expect.objectContaining({ path: ["expected_version"] })]); + }); + + it("never carries a client score or seed in the parsed body", () => { + const parsed = schema.parse({ + expected_version: 1, + item_id: itemId, + score: 1, + answer: { ...answers.practice, seed: 42 }, + }); + + // Generated Zod strips unknown keys; the server rejects them with 400. + expect(parsed).not.toHaveProperty("score"); + expect(parsed.answer).not.toHaveProperty("seed"); + }); +}); + +it("parses a practice item without hidden checks", () => { + const parsed = AssessmentItem.parse({ + id: itemId, + sequence: 15, + prompt: "Реализуйте функцию merge_intervals.", + content: { + format: "practice", + languages: ["python"], + max_source_length: 20000, + public_examples: [{ input: "[[1,3],[2,6]]", expected_output: "[[1,6]]" }], + hidden_tests: [{ input: "secret" }], + }, + }); + + expect(parsed.content.format).toBe("practice"); + expect(parsed.content).not.toHaveProperty("hidden_tests"); +}); + +// Every key of every variant of a union. +type KeysOf = T extends unknown ? keyof T : never; +type ForbiddenKey = + | "score" + | "points" + | "seed" + | "key" + | "answer_key" + | "correct" + | "is_correct" + | "correct_option_ids" + | "hidden_tests" + | "family_id"; + +it("exposes answer and item DTOs without scores, keys, seeds, or correctness", () => { + expectTypeOf, ForbiddenKey>>().toEqualTypeOf(); + expectTypeOf< + Extract, ForbiddenKey> + >().toEqualTypeOf(); + expectTypeOf, ForbiddenKey>>().toEqualTypeOf(); + expectTypeOf, ForbiddenKey>>().toEqualTypeOf(); + expectTypeOf(submitMyAssessmentAnswer).parameter(1).toEqualTypeOf(); +}); diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts new file mode 100644 index 0000000..d7de5a2 --- /dev/null +++ b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts @@ -0,0 +1,230 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + faker +} from '@faker-js/faker'; + +import { + HttpResponse, + http +} from 'msw'; +import type { + RequestHandlerOptions +} from 'msw'; + +import { + AssessmentAttemptState, + AssessmentGradeAvailabilityStatus, + AssessmentLimitation, + AssessmentMode, + AssessmentNextAction, + AssessmentNotDeterminedReason, + AssessmentOutcome, + AssessmentStrength, + CalibrationStatus, + GradeCode, + PracticeFailureReason, + PracticeKind, + PracticeStatus, + SpecializationCode, + TaskLanguage +} from '../../schemas'; +import type { + AssessmentAttempt, + AssessmentAvailability, + AssessmentItem, + AssessmentResult, + AssessmentSessions, + AssessmentUncertainty, + BasicScore, + ChoiceItemContent, + ConfigurationItemContent, + FindErrorItemContent, + NumberItemContent, + OrderItemContent, + PracticeItemContent, + PracticeVerdict, + StringItemContent +} from '../../schemas'; + + +export const getGetMyAssessmentAvailabilityResponseMock = (overrideResponse: Partial> = {}): AssessmentAvailability => ({specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), active_attempt_id: faker.helpers.arrayElement([faker.string.uuid(), null]), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({grade: faker.helpers.arrayElement(Object.values(GradeCode)), status: faker.helpers.arrayElement(Object.values(AssessmentGradeAvailabilityStatus)), mode: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(AssessmentMode)),null,]), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), time_limit_seconds: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), max_sessions: faker.helpers.arrayElement([faker.number.int({min: 1, max: 10}), null]), max_items: faker.helpers.arrayElement([faker.number.int({min: 1, max: 100}), null]), practice_required: faker.helpers.arrayElement([faker.datatype.boolean(), null])}))})), ...overrideResponse}) + +export const getCreateMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponseNumberItemContentMock = (overrideResponse: Partial = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponseStringItemContentMock = (overrideResponse: Partial = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseChoiceItemContentMock()},{...getCreateMyAssessmentAttemptResponseNumberItemContentMock()},{...getCreateMyAssessmentAttemptResponseStringItemContentMock()},{...getCreateMyAssessmentAttemptResponseOrderItemContentMock()},{...getCreateMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getCreateMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getCreateMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse}) + +export const getGetMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponseNumberItemContentMock = (overrideResponse: Partial = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponseStringItemContentMock = (overrideResponse: Partial = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseChoiceItemContentMock()},{...getGetMyAssessmentAttemptResponseNumberItemContentMock()},{...getGetMyAssessmentAttemptResponseStringItemContentMock()},{...getGetMyAssessmentAttemptResponseOrderItemContentMock()},{...getGetMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getGetMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getGetMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse}) + +export const getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponseNumberItemContentMock = (overrideResponse: Partial = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponseStringItemContentMock = (overrideResponse: Partial = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseChoiceItemContentMock()},{...getSubmitMyAssessmentAnswerResponseNumberItemContentMock()},{...getSubmitMyAssessmentAnswerResponseStringItemContentMock()},{...getSubmitMyAssessmentAnswerResponseOrderItemContentMock()},{...getSubmitMyAssessmentAnswerResponseFindErrorItemContentMock()},{...getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock()},{...getSubmitMyAssessmentAnswerResponsePracticeItemContentMock()},])}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse}) + +export const getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponseNumberItemContentMock = (overrideResponse: Partial = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponseStringItemContentMock = (overrideResponse: Partial = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseChoiceItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseNumberItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseStringItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseOrderItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse}) + +export const getGetMyAssessmentResultResponseAssessmentUncertaintyMock = (overrideResponse: Partial = {}): AssessmentUncertainty => ({...{theta: faker.number.float({fractionDigits: 2}), standard_error: faker.number.float({min: 0, fractionDigits: 2}), interval_95: {low: faker.number.float({fractionDigits: 2}), high: faker.number.float({fractionDigits: 2})}, p_grade: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, ...overrideResponse}); + +export const getGetMyAssessmentResultResponseBasicScoreMock = (overrideResponse: Partial = {}): BasicScore => ({...{points: faker.number.int({min: 0}), max_points: faker.number.int({min: 1}), pass_points: faker.number.int({min: 1})}, ...overrideResponse}); + +export const getGetMyAssessmentResultResponseMock = (overrideResponse: Partial> = {}): AssessmentResult => ({attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, outcome: faker.helpers.arrayElement(Object.values(AssessmentOutcome)), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(AssessmentNotDeterminedReason)),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(AssessmentStrength)),null,]), calibration_status: faker.helpers.arrayElement(Object.values(CalibrationStatus)), limitations: faker.helpers.arrayElements(Object.values(AssessmentLimitation)), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: faker.helpers.fromRegExp("^[a-z0-9_]+$"), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(Object.values(AssessmentNextAction)), grade: faker.helpers.arrayElement(Object.values(GradeCode)), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + + +export const getGetMyAssessmentAvailabilityMockHandler = (overrideResponse?: AssessmentAvailability | ((info: Parameters[1]>[0]) => Promise | AssessmentAvailability), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/assessment-availability', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMyAssessmentAvailabilityResponseMock(), + { status: 200 + }) + }, options) +} + +export const getCreateMyAssessmentAttemptMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters[1]>[0]) => Promise | AssessmentAttempt), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/assessment-attempts', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getCreateMyAssessmentAttemptResponseMock(), + { status: 201 + }) + }, options) +} + +export const getGetMyAssessmentAttemptMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters[1]>[0]) => Promise | AssessmentAttempt), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/assessment-attempts/:attemptId', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMyAssessmentAttemptResponseMock(), + { status: 200 + }) + }, options) +} + +export const getSubmitMyAssessmentAnswerMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters[1]>[0]) => Promise | AssessmentAttempt), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/assessment-attempts/:attemptId/answers', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getSubmitMyAssessmentAnswerResponseMock(), + { status: 200 + }) + }, options) +} + +export const getFinalizeMyAssessmentAttemptMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters[1]>[0]) => Promise | AssessmentAttempt), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/assessment-attempts/:attemptId/finalize', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getFinalizeMyAssessmentAttemptResponseMock(), + { status: 200 + }) + }, options) +} + +export const getGetMyAssessmentResultMockHandler = (overrideResponse?: AssessmentResult | ((info: Parameters[1]>[0]) => Promise | AssessmentResult), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/assessment-attempts/:attemptId/result', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMyAssessmentResultResponseMock(), + { status: 200 + }) + }, options) +} +export const getAssessmentMock = () => [ + getGetMyAssessmentAvailabilityMockHandler(), + getCreateMyAssessmentAttemptMockHandler(), + getGetMyAssessmentAttemptMockHandler(), + getSubmitMyAssessmentAnswerMockHandler(), + getFinalizeMyAssessmentAttemptMockHandler(), + getGetMyAssessmentResultMockHandler() +] diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.ts b/frontend/src/shared/api/endpoints/assessment/assessment.ts new file mode 100644 index 0000000..4b66970 --- /dev/null +++ b/frontend/src/shared/api/endpoints/assessment/assessment.ts @@ -0,0 +1,678 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + AssessmentAnswerSubmission, + AssessmentAttempt, + AssessmentAttemptCreate, + AssessmentAvailability, + AssessmentFinalization, + AssessmentResult, + CreateMyAssessmentAttemptHeaders, + FinalizeMyAssessmentAttemptHeaders, + Problem, + SubmitMyAssessmentAnswerHeaders +} from '../../schemas'; + +import { apiRequest } from '../../client'; +import type { ErrorType } from '../../client'; + + +type SecondParameter unknown> = Parameters[1]; + + + +const withQueryKey = (query: T, queryKey: K): T & { queryKey: K } => { + const result = { queryKey } as T & { queryKey: K }; + for (const key of Object.keys(query)) { + // The explicit queryKey always wins, matching the previous + // `{ ...query, queryKey }` spread where it was set last. + if (key === 'queryKey') continue; + Object.defineProperty(result, key, { + enumerable: true, + configurable: true, + get: () => (query as Record)[key], + }); + } + return result; +}; + +export const getGetMyAssessmentAvailabilityUrl = () => { + + + + + return `/api/v1/me/assessment-availability` +} + +/** + * Requires the session cookie of a candidate account; the candidate comes from the session. For each specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every grade whether an attempt can start now, in which mode, and with which limits: the time limit, the session limit, the item limit, and whether a code practice is required. The client shows them before the start, together with the method and the signals that are collected, and resumes an active attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt. + * + * `insufficient_bank` is the state of a category whose bank is not published or has too few families that this candidate has not seen; the server limits attempts instead of repeating families. `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with that date and offer support. Specializations and their retry intervals are independent. Attempts that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations and never cause a `cooldown`. + * + * A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + * @summary Read which assessment attempts the current candidate can start. + */ +export const getMyAssessmentAvailability = async ( options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyAssessmentAvailabilityUrl(), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyAssessmentAvailabilityQueryKey = () => { + return [ + `/api/v1/me/assessment-availability` + ] as const; + } + + +export const getGetMyAssessmentAvailabilityQueryOptions = >, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentAvailabilityQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyAssessmentAvailability({ signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyAssessmentAvailabilityQueryResult = NonNullable>> +export type GetMyAssessmentAvailabilityQueryError = ErrorType + + +export function useGetMyAssessmentAvailability>, TError = ErrorType>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentAvailability>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentAvailability>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read which assessment attempts the current candidate can start. + */ + +export function useGetMyAssessmentAvailability>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyAssessmentAvailabilityQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getCreateMyAssessmentAttemptUrl = () => { + + + + + return `/api/v1/me/assessment-attempts` +} + +/** + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the questionnaire and a target grade, and the task language. The server picks the mode from the published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the time and session limits, and the item variants in one transaction; the client never sends a mode, a seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. + * + * A specialization has at most one active attempt. A new attempt cannot start while one is active, during a retry or promotion interval or past the attempt limit of the policy, or when the bank is insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a failure, including the first test, a lower grade can be tested at once. An attempt that ends as `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the same-grade retry interval; one that ends as `insufficient_bank` or with the reason `sandbox_unavailable` counts toward neither. + * + * The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no command. Within them the attempt is also bounded by the item limit of the policy. + * + * Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 state_conflict response and creates nothing, so a lost response never creates a second attempt. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` for a specialization that is not in the questionnaire or `/task_language` for a language that the bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with Retry-After before any of them; it is not stored. + * @summary Start an assessment attempt for a category of the current candidate. + */ +export const createMyAssessmentAttempt = async (assessmentAttemptCreate: AssessmentAttemptCreate, + headers: CreateMyAssessmentAttemptHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getCreateMyAssessmentAttemptUrl(), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(assessmentAttemptCreate) + } +);} + + + + + +export const getCreateMyAssessmentAttemptMutationKey = () => ['createMyAssessmentAttempt'] as const; + +export const getCreateMyAssessmentAttemptMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,CreateMyAssessmentAttemptMutationVariables, TContext> => { + +const mutationKey = getCreateMyAssessmentAttemptMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, CreateMyAssessmentAttemptMutationVariables> = (props) => { + const {data,headers} = props ?? {}; + + return createMyAssessmentAttempt(data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type CreateMyAssessmentAttemptMutationResult = NonNullable>> + export type CreateMyAssessmentAttemptMutationBody = AssessmentAttemptCreate + export type CreateMyAssessmentAttemptMutationError = ErrorType + export type CreateMyAssessmentAttemptMutationVariables = {data: AssessmentAttemptCreate;headers: CreateMyAssessmentAttemptHeaders} + + /** + * @summary Start an assessment attempt for a category of the current candidate. + */ +export const useCreateMyAssessmentAttempt = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + CreateMyAssessmentAttemptMutationVariables, + TContext + > => { + return useMutation(getCreateMyAssessmentAttemptMutationOptions(options), queryClient); + } + export const getGetMyAssessmentAttemptUrl = (attemptId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}` +} + +/** + * Requires the session cookie of a candidate account. Returns the attempt with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + * + * Reading an active attempt counts as activity: after the previous session ended it starts the next session, and when that would exceed the session limit it starts none and the attempt becomes `expired`. Before it answers, the server commits any transition that is due, with a new version: past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is declined and the attempt becomes `completed`, and the other active states become `expired`; a practice still `pending` is graded first. The client polls this operation while a practice is `pending`. Reading a terminal attempt changes nothing. + * + * The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers or the attempt history. + * @summary Read or resume an assessment attempt of the current candidate. + */ +export const getMyAssessmentAttempt = async (attemptId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyAssessmentAttemptUrl(attemptId), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyAssessmentAttemptQueryKey = (attemptId: string,) => { + return [ + `/api/v1/me/assessment-attempts/${attemptId}` + ] as const; + } + + +export const getGetMyAssessmentAttemptQueryOptions = >, TError = ErrorType>(attemptId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentAttemptQueryKey(attemptId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyAssessmentAttempt(attemptId, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: attemptId !== null && attemptId !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyAssessmentAttemptQueryResult = NonNullable>> +export type GetMyAssessmentAttemptQueryError = ErrorType + + +export function useGetMyAssessmentAttempt>, TError = ErrorType>( + attemptId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentAttempt>, TError = ErrorType>( + attemptId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentAttempt>, TError = ErrorType>( + attemptId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read or resume an assessment attempt of the current candidate. + */ + +export function useGetMyAssessmentAttempt>, TError = ErrorType>( + attemptId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyAssessmentAttemptQueryOptions(attemptId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getSubmitMyAssessmentAnswerUrl = (attemptId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/answers` +} + +/** + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision. + * + * The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. + * + * Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation. + * + * Repeats and conflicts, per item: + * - A retry with the same Idempotency-Key and body within 24 hours replays the stored response. + * - Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. + * - A different answer for an item that already has one answers 409 state_conflict when `expected_version` is current; with a stale version the version check comes first and answers 412. + * - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A submission with the same or a different solution, with the current `expected_version`, queues it again and advances the version. + * + * Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is kept for commands that the attempt state does not allow at the current version. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; the server first commits any due transition such as expiry, and the request counts as activity for the session limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. + * @summary Answer the current item or submit a practice of an assessment attempt. + */ +export const submitMyAssessmentAnswer = async (attemptId: string, + assessmentAnswerSubmission: AssessmentAnswerSubmission, + headers: SubmitMyAssessmentAnswerHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getSubmitMyAssessmentAnswerUrl(attemptId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(assessmentAnswerSubmission) + } +);} + + + + + +export const getSubmitMyAssessmentAnswerMutationKey = () => ['submitMyAssessmentAnswer'] as const; + +export const getSubmitMyAssessmentAnswerMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SubmitMyAssessmentAnswerMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,SubmitMyAssessmentAnswerMutationVariables, TContext> => { + +const mutationKey = getSubmitMyAssessmentAnswerMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, SubmitMyAssessmentAnswerMutationVariables> = (props) => { + const {attemptId,data,headers} = props ?? {}; + + return submitMyAssessmentAnswer(attemptId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type SubmitMyAssessmentAnswerMutationResult = NonNullable>> + export type SubmitMyAssessmentAnswerMutationBody = AssessmentAnswerSubmission + export type SubmitMyAssessmentAnswerMutationError = ErrorType + export type SubmitMyAssessmentAnswerMutationVariables = {attemptId: string;data: AssessmentAnswerSubmission;headers: SubmitMyAssessmentAnswerHeaders} + + /** + * @summary Answer the current item or submit a practice of an assessment attempt. + */ +export const useSubmitMyAssessmentAnswer = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SubmitMyAssessmentAnswerMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + SubmitMyAssessmentAnswerMutationVariables, + TContext + > => { + return useMutation(getSubmitMyAssessmentAnswerMutationOptions(options), queryClient); + } + export const getFinalizeMyAssessmentAttemptUrl = (attemptId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/finalize` +} + +/** + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the result: the decision may continue the attempt, and one response type keeps that unambiguous for every generated client. When the returned state is `completed`, the client reads the result with GetMyAssessmentResult. + * + * Allowed in `ready_to_finalize`, where every required part is done, and in `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: + * - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and completes the attempt. It never offers an additional practice. + * - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the demo policy) on the first finalize, while time and sessions remain, completes nothing: the server appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no new attempt. The next finalize, after its verdict, decides with the added evidence; a probability still below confirmation gives `not_confirmed`. An attempt offers at most one additional practice. + * - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the current evidence. A retry of the first finalize with a new key cannot decline by accident: it carries the version from before the offer and answers 412. + * + * A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, the server finalizes `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also answers 200 with the `completed` attempt. + * + * An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. + * @summary Ask for the grade decision of an assessment attempt. + */ +export const finalizeMyAssessmentAttempt = async (attemptId: string, + assessmentFinalization: AssessmentFinalization, + headers: FinalizeMyAssessmentAttemptHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getFinalizeMyAssessmentAttemptUrl(attemptId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(assessmentFinalization) + } +);} + + + + + +export const getFinalizeMyAssessmentAttemptMutationKey = () => ['finalizeMyAssessmentAttempt'] as const; + +export const getFinalizeMyAssessmentAttemptMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext> => { + +const mutationKey = getFinalizeMyAssessmentAttemptMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, FinalizeMyAssessmentAttemptMutationVariables> = (props) => { + const {attemptId,data,headers} = props ?? {}; + + return finalizeMyAssessmentAttempt(attemptId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type FinalizeMyAssessmentAttemptMutationResult = NonNullable>> + export type FinalizeMyAssessmentAttemptMutationBody = AssessmentFinalization + export type FinalizeMyAssessmentAttemptMutationError = ErrorType + export type FinalizeMyAssessmentAttemptMutationVariables = {attemptId: string;data: AssessmentFinalization;headers: FinalizeMyAssessmentAttemptHeaders} + + /** + * @summary Ask for the grade decision of an assessment attempt. + */ +export const useFinalizeMyAssessmentAttempt = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + FinalizeMyAssessmentAttemptMutationVariables, + TContext + > => { + return useMutation(getFinalizeMyAssessmentAttemptMutationOptions(options), queryClient); + } + export const getGetMyAssessmentResultUrl = (attemptId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/result` +} + +/** + * Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and algorithm versions, the decision, the previously confirmed grade, the calibration status and limitations of the method, the uncertainty where the method computes it, the practice verdicts, the weak domains, the working time as a separate label, and the next steps that the server allows. A later policy, bank, or algorithm version never changes it. + * + * Fields that the method does not compute are null and never zero: a `demo_basic` result has null `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. + * + * An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. The server first commits any due transition, so an attempt past its limits is read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. + * @summary Read the result of an assessment attempt of the current candidate. + */ +export const getMyAssessmentResult = async (attemptId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyAssessmentResultUrl(attemptId), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyAssessmentResultQueryKey = (attemptId: string,) => { + return [ + `/api/v1/me/assessment-attempts/${attemptId}/result` + ] as const; + } + + +export const getGetMyAssessmentResultQueryOptions = >, TError = ErrorType>(attemptId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentResultQueryKey(attemptId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyAssessmentResult(attemptId, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: attemptId !== null && attemptId !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyAssessmentResultQueryResult = NonNullable>> +export type GetMyAssessmentResultQueryError = ErrorType + + +export function useGetMyAssessmentResult>, TError = ErrorType>( + attemptId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentResult>, TError = ErrorType>( + attemptId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentResult>, TError = ErrorType>( + attemptId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the result of an assessment attempt of the current candidate. + */ + +export function useGetMyAssessmentResult>, TError = ErrorType>( + attemptId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyAssessmentResultQueryOptions(attemptId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + diff --git a/frontend/src/shared/api/endpoints/index.msw.ts b/frontend/src/shared/api/endpoints/index.msw.ts index 1ea9c04..a596a37 100644 --- a/frontend/src/shared/api/endpoints/index.msw.ts +++ b/frontend/src/shared/api/endpoints/index.msw.ts @@ -1,3 +1,4 @@ +export { getAssessmentMock } from './assessment/assessment.msw' export { getCandidateMock } from './candidate/candidate.msw' export { getCatalogMock } from './catalog/catalog.msw' export { getHealthMock } from './health/health.msw' diff --git a/frontend/src/shared/api/endpoints/index.ts b/frontend/src/shared/api/endpoints/index.ts index f8ece84..c890676 100644 --- a/frontend/src/shared/api/endpoints/index.ts +++ b/frontend/src/shared/api/endpoints/index.ts @@ -1,3 +1,4 @@ +export * from './assessment/assessment'; export * from './candidate/candidate'; export * from './catalog/catalog'; export * from './health/health'; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAnswer.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAnswer.zod.ts new file mode 100644 index 0000000..34d58d6 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAnswer.zod.ts @@ -0,0 +1,58 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentAnswerOneOptionIdsItemMax = 32; + + +export const assessmentAnswerOneOptionIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAnswerOneOptionIdsMax = 10; + +export const assessmentAnswerThreeTextMax = 500; + +export const assessmentAnswerFourElementIdsItemMax = 32; + + +export const assessmentAnswerFourElementIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAnswerFourElementIdsMin = 2; +export const assessmentAnswerFourElementIdsMax = 20; + +export const assessmentAnswerFiveLineNumbersItemMax = 500; + +export const assessmentAnswerFiveLineNumbersMax = 10; + +export const assessmentAnswerSixConfigMax = 20000; + +export const assessmentAnswerSevenSourceCodeMax = 65536; + + +export const AssessmentAnswer = zod.union([zod.object({ + "format": zod.enum(['choice']), + "option_ids": zod.array(zod.string().min(1).max(assessmentAnswerOneOptionIdsItemMax).regex(assessmentAnswerOneOptionIdsItemRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.')).min(1).max(assessmentAnswerOneOptionIdsMax) +}).describe('Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.'),zod.object({ + "format": zod.enum(['number']), + "number": zod.number() +}).describe('Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer.'),zod.object({ + "format": zod.enum(['string']), + "text": zod.string().min(1).max(assessmentAnswerThreeTextMax) +}).describe('String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison.'),zod.object({ + "format": zod.enum(['order']), + "element_ids": zod.array(zod.string().min(1).max(assessmentAnswerFourElementIdsItemMax).regex(assessmentAnswerFourElementIdsItemRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.')).min(assessmentAnswerFourElementIdsMin).max(assessmentAnswerFourElementIdsMax) +}).describe('Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical.'),zod.object({ + "format": zod.enum(['find_error']), + "line_numbers": zod.array(zod.int().min(1).max(assessmentAnswerFiveLineNumbersItemMax)).min(1).max(assessmentAnswerFiveLineNumbersMax) +}).describe('Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order.'),zod.object({ + "format": zod.enum(['configuration']), + "config": zod.string().min(1).max(assessmentAnswerSixConfigMax) +}).describe('Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks.'),zod.object({ + "format": zod.enum(['practice']), + "language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('One of the `languages` of the practice item, or null when the item offers none.'), + "source_code": zod.string().min(1).max(assessmentAnswerSevenSourceCodeMax) +}).describe('Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem.')]).describe('Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.') + +export type AssessmentAnswer = zod.input; +export type AssessmentAnswerOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAnswerSubmission.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAnswerSubmission.zod.ts new file mode 100644 index 0000000..59210d1 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAnswerSubmission.zod.ts @@ -0,0 +1,63 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentAnswerSubmissionAnswerOneOptionIdsItemMax = 32; + + +export const assessmentAnswerSubmissionAnswerOneOptionIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAnswerSubmissionAnswerOneOptionIdsMax = 10; + +export const assessmentAnswerSubmissionAnswerThreeTextMax = 500; + +export const assessmentAnswerSubmissionAnswerFourElementIdsItemMax = 32; + + +export const assessmentAnswerSubmissionAnswerFourElementIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAnswerSubmissionAnswerFourElementIdsMin = 2; +export const assessmentAnswerSubmissionAnswerFourElementIdsMax = 20; + +export const assessmentAnswerSubmissionAnswerFiveLineNumbersItemMax = 500; + +export const assessmentAnswerSubmissionAnswerFiveLineNumbersMax = 10; + +export const assessmentAnswerSubmissionAnswerSixConfigMax = 20000; + +export const assessmentAnswerSubmissionAnswerSevenSourceCodeMax = 65536; + + +export const AssessmentAnswerSubmission = zod.object({ + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "answer": zod.union([zod.object({ + "format": zod.enum(['choice']), + "option_ids": zod.array(zod.string().min(1).max(assessmentAnswerSubmissionAnswerOneOptionIdsItemMax).regex(assessmentAnswerSubmissionAnswerOneOptionIdsItemRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.')).min(1).max(assessmentAnswerSubmissionAnswerOneOptionIdsMax) +}).describe('Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.'),zod.object({ + "format": zod.enum(['number']), + "number": zod.number() +}).describe('Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer.'),zod.object({ + "format": zod.enum(['string']), + "text": zod.string().min(1).max(assessmentAnswerSubmissionAnswerThreeTextMax) +}).describe('String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison.'),zod.object({ + "format": zod.enum(['order']), + "element_ids": zod.array(zod.string().min(1).max(assessmentAnswerSubmissionAnswerFourElementIdsItemMax).regex(assessmentAnswerSubmissionAnswerFourElementIdsItemRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.')).min(assessmentAnswerSubmissionAnswerFourElementIdsMin).max(assessmentAnswerSubmissionAnswerFourElementIdsMax) +}).describe('Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical.'),zod.object({ + "format": zod.enum(['find_error']), + "line_numbers": zod.array(zod.int().min(1).max(assessmentAnswerSubmissionAnswerFiveLineNumbersItemMax)).min(1).max(assessmentAnswerSubmissionAnswerFiveLineNumbersMax) +}).describe('Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order.'),zod.object({ + "format": zod.enum(['configuration']), + "config": zod.string().min(1).max(assessmentAnswerSubmissionAnswerSixConfigMax) +}).describe('Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks.'),zod.object({ + "format": zod.enum(['practice']), + "language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('One of the `languages` of the practice item, or null when the item offers none.'), + "source_code": zod.string().min(1).max(assessmentAnswerSubmissionAnswerSevenSourceCodeMax) +}).describe('Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem.')]).describe('Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.') +}).describe('Answer to one item of the attempt. Unknown fields are rejected, so a request cannot send a score, a duration, or a correctness flag.') + +export type AssessmentAnswerSubmission = zod.input; +export type AssessmentAnswerSubmissionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts new file mode 100644 index 0000000..55dfd88 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts @@ -0,0 +1,190 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const assessmentAttemptVersionsBankVersionMax = 64; + + +export const assessmentAttemptVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptVersionsAlgorithmVersionMax = 64; + + +export const assessmentAttemptVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptSessionsOneUsedMax = 10; + +export const assessmentAttemptSessionsOneMaxMax = 10; + +export const assessmentAttemptSessionsOneIdleTimeoutSecondsMin = 60; +export const assessmentAttemptSessionsOneIdleTimeoutSecondsMax = 86400; + +export const assessmentAttemptProgressAnsweredItemsMin = 0; +export const assessmentAttemptProgressAnsweredItemsMax = 100; + +export const assessmentAttemptProgressMaxItemsMax = 100; + +export const assessmentAttemptCurrentItemOneSequenceMax = 100; + +export const assessmentAttemptCurrentItemOnePromptMax = 20000; + +export const assessmentAttemptCurrentItemOneContentOneOptionsItemIdMax = 32; + + +export const assessmentAttemptCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptCurrentItemOneContentOneOptionsItemTextMax = 2000; + +export const assessmentAttemptCurrentItemOneContentOneOptionsMin = 2; +export const assessmentAttemptCurrentItemOneContentOneOptionsMax = 10; + +export const assessmentAttemptCurrentItemOneContentTwoUnitMax = 32; + +export const assessmentAttemptCurrentItemOneContentThreeMaxLengthMax = 500; + +export const assessmentAttemptCurrentItemOneContentFourElementsItemIdMax = 32; + + +export const assessmentAttemptCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptCurrentItemOneContentFourElementsItemTextMax = 2000; + +export const assessmentAttemptCurrentItemOneContentFourElementsMin = 2; +export const assessmentAttemptCurrentItemOneContentFourElementsMax = 20; + +export const assessmentAttemptCurrentItemOneContentFiveSyntaxMax = 32; + + +export const assessmentAttemptCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptCurrentItemOneContentFiveLinesItemNumberMax = 500; + +export const assessmentAttemptCurrentItemOneContentFiveLinesItemTextMax = 1000; + +export const assessmentAttemptCurrentItemOneContentFiveLinesMax = 500; + +export const assessmentAttemptCurrentItemOneContentFiveMaxSelectionsMax = 10; + +export const assessmentAttemptCurrentItemOneContentSixSyntaxMax = 32; + + +export const assessmentAttemptCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptCurrentItemOneContentSixInitialConfigMax = 20000; + +export const assessmentAttemptCurrentItemOneContentSixMaxLengthMax = 20000; + +export const assessmentAttemptCurrentItemOneContentSevenLanguagesMax = 2; + +export const assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000; + +export const assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000; + +export const assessmentAttemptCurrentItemOneContentSevenPublicExamplesMax = 10; + +export const assessmentAttemptCurrentItemOneContentSevenMaxSourceLengthMax = 65536; + +export const assessmentAttemptPracticesItemVerdictOneScoreMin = 0; +export const assessmentAttemptPracticesItemVerdictOneScoreMax = 3; + +export const assessmentAttemptPracticesItemVerdictOneMaxScoreMin = 3; +export const assessmentAttemptPracticesItemVerdictOneMaxScoreMax = 3; + +export const assessmentAttemptPracticesItemVerdictOneGroupsItemGroupMax = 3; + +export const assessmentAttemptPracticesItemVerdictOneGroupsMin = 3; +export const assessmentAttemptPracticesItemVerdictOneGroupsMax = 3; + +export const assessmentAttemptPracticesMax = 5; + + +export const AssessmentAttempt = zod.object({ + "id": zod.uuid().describe('Attempt identifier.'), + "version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when the bank offers no choice.'), + "mode": zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'), + "state": zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.'), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentAttemptVersionsBankVersionMax).regex(assessmentAttemptVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentAttemptVersionsAlgorithmVersionMax).regex(assessmentAttemptVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "started_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "sessions": zod.union([zod.object({ + "used": zod.int().min(1).max(assessmentAttemptSessionsOneUsedMax).describe('Sessions started so far, including the current one.'), + "max": zod.int().min(1).max(assessmentAttemptSessionsOneMaxMax), + "idle_timeout_seconds": zod.int().min(assessmentAttemptSessionsOneIdleTimeoutSecondsMin).max(assessmentAttemptSessionsOneIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nA session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session.'),zod.null()]).describe('Session limit of the attempt, or null when its policy version defines none.'), + "finished_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time the attempt reached a terminal state, or null while it is active.'), + "progress": zod.object({ + "answered_items": zod.int().min(assessmentAttemptProgressAnsweredItemsMin).max(assessmentAttemptProgressAnsweredItemsMax), + "max_items": zod.int().min(1).max(assessmentAttemptProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') +}).describe('Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`.'), + "current_item": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "sequence": zod.int().min(1).max(assessmentAttemptCurrentItemOneSequenceMax).describe('Position of the item in the attempt, from 1.'), + "prompt": zod.string().min(1).max(assessmentAttemptCurrentItemOnePromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), + "content": zod.union([zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentOneOptionsItemIdMax).regex(assessmentAttemptCurrentItemOneContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptCurrentItemOneContentOneOptionsMin).max(assessmentAttemptCurrentItemOneContentOneOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.'),zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentFourElementsItemIdMax).regex(assessmentAttemptCurrentItemOneContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptCurrentItemOneContentFourElementsMin).max(assessmentAttemptCurrentItemOneContentFourElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentFiveSyntaxMax).regex(assessmentAttemptCurrentItemOneContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentFiveLinesItemNumberMax), + "text": zod.string().max(assessmentAttemptCurrentItemOneContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentAttemptCurrentItemOneContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentSixSyntaxMax).regex(assessmentAttemptCurrentItemOneContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(assessmentAttemptCurrentItemOneContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentAttemptCurrentItemOneContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptCurrentItemOneContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "status": zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.'), + "submitted_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the latest submission, or null before the first one.'), + "verdict": zod.union([zod.object({ + "score": zod.int().min(assessmentAttemptPracticesItemVerdictOneScoreMin).max(assessmentAttemptPracticesItemVerdictOneScoreMax), + "max_score": zod.int().min(assessmentAttemptPracticesItemVerdictOneMaxScoreMin).max(assessmentAttemptPracticesItemVerdictOneMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentAttemptPracticesItemVerdictOneGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentAttemptPracticesItemVerdictOneGroupsMin).max(assessmentAttemptPracticesItemVerdictOneGroupsMax) +}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.'),zod.null()]).describe('The verdict when `status` is `finished`, otherwise null.'), + "failure_reason": zod.union([zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.'),zod.null()]).describe('The reason when `status` is `failed`, otherwise null.') +}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentAttemptPracticesMax).describe('Practices in the order they were assigned: the `main` practice first, then an `additional` practice once finalize offers it. Empty only for a demo_basic attempt while code practice is disabled until the sandbox isolation is verified; its result then lists the `practice_not_included` limitation. A list rather than one field leaves room for more practices without a breaking change.') +}).describe('Assessment attempt of the current candidate for one category, a specialization and a target grade. It shows the state, the fixed versions, the server deadline `expires_at` from the policy version, which the client clock never extends, the session limit, the progress, the item to answer now, and the practices. It never contains answer keys, the correctness of submitted answers, scores of single items, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.') + +export type AssessmentAttempt = zod.input; +export type AssessmentAttemptOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptCreate.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptCreate.zod.ts new file mode 100644 index 0000000..38c1765 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptCreate.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentAttemptCreate = zod.object({ + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first.') +}).describe('Category to assess: a specialization and the target grade, with the task language. The candidate comes from the session. The mode and versions are chosen by the server; unknown fields such as `mode`, `seed`, or `score` are rejected.') + +export type AssessmentAttemptCreate = zod.input; +export type AssessmentAttemptCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptState.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptState.zod.ts new file mode 100644 index 0000000..d91cf8f --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptState.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentAttemptState = zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.') + +export type AssessmentAttemptState = zod.input; +export type AssessmentAttemptStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptVersion.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptVersion.zod.ts new file mode 100644 index 0000000..dde9454 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptVersion.zod.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const AssessmentAttemptVersion = zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') + +export type AssessmentAttemptVersion = zod.input; +export type AssessmentAttemptVersionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts new file mode 100644 index 0000000..f38b708 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts @@ -0,0 +1,38 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentAvailabilitySpecializationsItemGradesItemMaxSessionsMax = 10; + +export const assessmentAvailabilitySpecializationsItemGradesItemMaxItemsMax = 100; + +export const assessmentAvailabilitySpecializationsItemGradesMax = 10; + +export const assessmentAvailabilitySpecializationsMax = 2; + + +export const AssessmentAvailability = zod.object({ + "specializations": zod.array(zod.object({ + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Currently confirmed grade of the specialization, or null.'), + "active_attempt_id": zod.uuid().nullable().describe('Identifier of the active attempt of the specialization, or null.'), + "grades": zod.array(zod.object({ + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "status": zod.enum(['available', 'active_attempt', 'cooldown', 'insufficient_bank']).describe('Whether an attempt for the grade can start now.\n\n- available: CreateMyAssessmentAttempt can start it.\n- active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`.\n- cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it.\n- insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families.'), + "mode": zod.union([zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'),zod.null()]).describe('Mode that an attempt would use, or null when the status is `insufficient_bank`.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the status is `cooldown`, the first time the attempt can start; otherwise null.'), + "time_limit_seconds": zod.int().min(1).nullable().describe('Time from the start to `expires_at`.'), + "max_sessions": zod.int().min(1).max(assessmentAvailabilitySpecializationsItemGradesItemMaxSessionsMax).nullable().describe('Session limit within the time limit.'), + "max_items": zod.int().min(1).max(assessmentAvailabilitySpecializationsItemGradesItemMaxItemsMax).nullable().describe('Item limit, as in `AssessmentProgress.max_items`.'), + "practice_required": zod.boolean().nullable().describe('Whether the attempt would include a main code practice.') +}).describe('Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit.')).max(assessmentAvailabilitySpecializationsItemGradesMax).describe('Every grade of the scale in ascending order.') +}).describe('Assessment state of one questionnaire specialization. Specializations are assessed independently, with independent retry intervals.')).max(assessmentAvailabilitySpecializationsMax).describe('Questionnaire specializations in questionnaire order.') +}).describe('Assessment availability for the specializations of the current candidate\'s questionnaire, derived at the time of the request.') + +export type AssessmentAvailability = zod.input; +export type AssessmentAvailabilityOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentDurations.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentDurations.zod.ts new file mode 100644 index 0000000..fc66a29 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentDurations.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentDurationsItemsSecondsMin = 0; + +export const assessmentDurationsPracticeSecondsMin = 0; + + +export const AssessmentDurations = zod.object({ + "items_seconds": zod.int().min(assessmentDurationsItemsSecondsMin), + "practice_seconds": zod.int().min(assessmentDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') +}).describe('Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.') + +export type AssessmentDurations = zod.input; +export type AssessmentDurationsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentFinalization.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentFinalization.zod.ts new file mode 100644 index 0000000..2e6dffa --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentFinalization.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const AssessmentFinalization = zod.object({ + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') +}).describe('Command to finalize the attempt.') + +export type AssessmentFinalization = zod.input; +export type AssessmentFinalizationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentGap.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentGap.zod.ts new file mode 100644 index 0000000..7f71f71 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentGap.zod.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentGapDomainMax = 64; + + +export const assessmentGapDomainRegExp = new RegExp('^[a-z0-9_]+$'); +export const assessmentGapTitleMax = 200; + + +export const AssessmentGap = zod.object({ + "domain": zod.string().min(1).max(assessmentGapDomainMax).regex(assessmentGapDomainRegExp).describe('Stable domain code of the bank blueprint.'), + "title": zod.string().min(1).max(assessmentGapTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Domain of the specialization where the evidence was weak.') + +export type AssessmentGap = zod.input; +export type AssessmentGapOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailability.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailability.zod.ts new file mode 100644 index 0000000..5804112 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailability.zod.ts @@ -0,0 +1,27 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentGradeAvailabilityMaxSessionsMax = 10; + +export const assessmentGradeAvailabilityMaxItemsMax = 100; + + +export const AssessmentGradeAvailability = zod.object({ + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "status": zod.enum(['available', 'active_attempt', 'cooldown', 'insufficient_bank']).describe('Whether an attempt for the grade can start now.\n\n- available: CreateMyAssessmentAttempt can start it.\n- active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`.\n- cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it.\n- insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families.'), + "mode": zod.union([zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'),zod.null()]).describe('Mode that an attempt would use, or null when the status is `insufficient_bank`.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the status is `cooldown`, the first time the attempt can start; otherwise null.'), + "time_limit_seconds": zod.int().min(1).nullable().describe('Time from the start to `expires_at`.'), + "max_sessions": zod.int().min(1).max(assessmentGradeAvailabilityMaxSessionsMax).nullable().describe('Session limit within the time limit.'), + "max_items": zod.int().min(1).max(assessmentGradeAvailabilityMaxItemsMax).nullable().describe('Item limit, as in `AssessmentProgress.max_items`.'), + "practice_required": zod.boolean().nullable().describe('Whether the attempt would include a main code practice.') +}).describe('Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit.') + +export type AssessmentGradeAvailability = zod.input; +export type AssessmentGradeAvailabilityOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailabilityStatus.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailabilityStatus.zod.ts new file mode 100644 index 0000000..7893419 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailabilityStatus.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentGradeAvailabilityStatus = zod.enum(['available', 'active_attempt', 'cooldown', 'insufficient_bank']).describe('Whether an attempt for the grade can start now.\n\n- available: CreateMyAssessmentAttempt can start it.\n- active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`.\n- cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it.\n- insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families.') + +export type AssessmentGradeAvailabilityStatus = zod.input; +export type AssessmentGradeAvailabilityStatusOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentInterval.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentInterval.zod.ts new file mode 100644 index 0000000..d466fa5 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentInterval.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentInterval = zod.object({ + "low": zod.number(), + "high": zod.number() +}).describe('Interval on the ability scale.') + +export type AssessmentInterval = zod.input; +export type AssessmentIntervalOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentItem.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentItem.zod.ts new file mode 100644 index 0000000..274e5ad --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentItem.zod.ts @@ -0,0 +1,114 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentItemSequenceMax = 100; + +export const assessmentItemPromptMax = 20000; + +export const assessmentItemContentOneOptionsItemIdMax = 32; + + +export const assessmentItemContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentItemContentOneOptionsItemTextMax = 2000; + +export const assessmentItemContentOneOptionsMin = 2; +export const assessmentItemContentOneOptionsMax = 10; + +export const assessmentItemContentTwoUnitMax = 32; + +export const assessmentItemContentThreeMaxLengthMax = 500; + +export const assessmentItemContentFourElementsItemIdMax = 32; + + +export const assessmentItemContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentItemContentFourElementsItemTextMax = 2000; + +export const assessmentItemContentFourElementsMin = 2; +export const assessmentItemContentFourElementsMax = 20; + +export const assessmentItemContentFiveSyntaxMax = 32; + + +export const assessmentItemContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentItemContentFiveLinesItemNumberMax = 500; + +export const assessmentItemContentFiveLinesItemTextMax = 1000; + +export const assessmentItemContentFiveLinesMax = 500; + +export const assessmentItemContentFiveMaxSelectionsMax = 10; + +export const assessmentItemContentSixSyntaxMax = 32; + + +export const assessmentItemContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentItemContentSixInitialConfigMax = 20000; + +export const assessmentItemContentSixMaxLengthMax = 20000; + +export const assessmentItemContentSevenLanguagesMax = 2; + +export const assessmentItemContentSevenPublicExamplesItemInputMax = 10000; + +export const assessmentItemContentSevenPublicExamplesItemExpectedOutputMax = 10000; + +export const assessmentItemContentSevenPublicExamplesMax = 10; + +export const assessmentItemContentSevenMaxSourceLengthMax = 65536; + + +export const AssessmentItem = zod.object({ + "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "sequence": zod.int().min(1).max(assessmentItemSequenceMax).describe('Position of the item in the attempt, from 1.'), + "prompt": zod.string().min(1).max(assessmentItemPromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), + "content": zod.union([zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentItemContentOneOptionsItemIdMax).regex(assessmentItemContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentItemContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentItemContentOneOptionsMin).max(assessmentItemContentOneOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(assessmentItemContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.'),zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(assessmentItemContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentItemContentFourElementsItemIdMax).regex(assessmentItemContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentItemContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentItemContentFourElementsMin).max(assessmentItemContentFourElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(assessmentItemContentFiveSyntaxMax).regex(assessmentItemContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(assessmentItemContentFiveLinesItemNumberMax), + "text": zod.string().max(assessmentItemContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentItemContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(assessmentItemContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(assessmentItemContentSixSyntaxMax).regex(assessmentItemContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(assessmentItemContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(assessmentItemContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentItemContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(assessmentItemContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(assessmentItemContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentItemContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(assessmentItemContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.') + +export type AssessmentItem = zod.input; +export type AssessmentItemOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentItemId.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentItemId.zod.ts new file mode 100644 index 0000000..589597c --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentItemId.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentItemId = zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.') + +export type AssessmentItemId = zod.input; +export type AssessmentItemIdOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLimitation.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLimitation.zod.ts new file mode 100644 index 0000000..dab5b2b --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLimitation.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentLimitation = zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\n\nAdding a value is a contract change.') + +export type AssessmentLimitation = zod.input; +export type AssessmentLimitationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentMode.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentMode.zod.ts new file mode 100644 index 0000000..ed4b459 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentMode.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentMode = zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.') + +export type AssessmentMode = zod.input; +export type AssessmentModeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentNextAction.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentNextAction.zod.ts new file mode 100644 index 0000000..5a83af9 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentNextAction.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentNextAction = zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.') + +export type AssessmentNextAction = zod.input; +export type AssessmentNextActionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentNextStep.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentNextStep.zod.ts new file mode 100644 index 0000000..868287c --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentNextStep.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentNextStep = zod.object({ + "action": zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('First time the step is allowed, or null when it is allowed now.') +}).describe('Step that the server allows after this result, computed when it was decided.') + +export type AssessmentNextStep = zod.input; +export type AssessmentNextStepOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentNotDeterminedReason.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentNotDeterminedReason.zod.ts new file mode 100644 index 0000000..826b618 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentNotDeterminedReason.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentNotDeterminedReason = zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision, and whether it counts against the retry rules.\n\n- expired: the time or session limit passed before the candidate finished the item part. It is the candidate\'s attempt: it counts toward the attempt limit and starts the same-grade retry interval.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`.\n- insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval.') + +export type AssessmentNotDeterminedReason = zod.input; +export type AssessmentNotDeterminedReasonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentOption.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentOption.zod.ts new file mode 100644 index 0000000..138249a --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentOption.zod.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentOptionIdMax = 32; + + +export const assessmentOptionIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentOptionTextMax = 2000; + + +export const AssessmentOption = zod.object({ + "id": zod.string().min(1).max(assessmentOptionIdMax).regex(assessmentOptionIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentOptionTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.') + +export type AssessmentOption = zod.input; +export type AssessmentOptionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentOptionId.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentOptionId.zod.ts new file mode 100644 index 0000000..6d6ac12 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentOptionId.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentOptionIdMax = 32; + + +export const AssessmentOptionIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const AssessmentOptionId = zod.string().min(1).max(AssessmentOptionIdMax).regex(AssessmentOptionIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.') + +export type AssessmentOptionId = zod.input; +export type AssessmentOptionIdOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentOutcome.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentOutcome.zod.ts new file mode 100644 index 0000000..6c79724 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentOutcome.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentOutcome = zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.') + +export type AssessmentOutcome = zod.input; +export type AssessmentOutcomeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentPractice.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentPractice.zod.ts new file mode 100644 index 0000000..7d46954 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentPractice.zod.ts @@ -0,0 +1,38 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentPracticeVerdictOneScoreMin = 0; +export const assessmentPracticeVerdictOneScoreMax = 3; + +export const assessmentPracticeVerdictOneMaxScoreMin = 3; +export const assessmentPracticeVerdictOneMaxScoreMax = 3; + +export const assessmentPracticeVerdictOneGroupsItemGroupMax = 3; + +export const assessmentPracticeVerdictOneGroupsMin = 3; +export const assessmentPracticeVerdictOneGroupsMax = 3; + + +export const AssessmentPractice = zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "status": zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.'), + "submitted_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the latest submission, or null before the first one.'), + "verdict": zod.union([zod.object({ + "score": zod.int().min(assessmentPracticeVerdictOneScoreMin).max(assessmentPracticeVerdictOneScoreMax), + "max_score": zod.int().min(assessmentPracticeVerdictOneMaxScoreMin).max(assessmentPracticeVerdictOneMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentPracticeVerdictOneGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentPracticeVerdictOneGroupsMin).max(assessmentPracticeVerdictOneGroupsMax) +}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.'),zod.null()]).describe('The verdict when `status` is `finished`, otherwise null.'), + "failure_reason": zod.union([zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.'),zod.null()]).describe('The reason when `status` is `failed`, otherwise null.') +}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.') + +export type AssessmentPractice = zod.input; +export type AssessmentPracticeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentPracticeResult.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentPracticeResult.zod.ts new file mode 100644 index 0000000..eefc467 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentPracticeResult.zod.ts @@ -0,0 +1,34 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentPracticeResultVerdictScoreMin = 0; +export const assessmentPracticeResultVerdictScoreMax = 3; + +export const assessmentPracticeResultVerdictMaxScoreMin = 3; +export const assessmentPracticeResultVerdictMaxScoreMax = 3; + +export const assessmentPracticeResultVerdictGroupsItemGroupMax = 3; + +export const assessmentPracticeResultVerdictGroupsMin = 3; +export const assessmentPracticeResultVerdictGroupsMax = 3; + + +export const AssessmentPracticeResult = zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "verdict": zod.object({ + "score": zod.int().min(assessmentPracticeResultVerdictScoreMin).max(assessmentPracticeResultVerdictScoreMax), + "max_score": zod.int().min(assessmentPracticeResultVerdictMaxScoreMin).max(assessmentPracticeResultVerdictMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentPracticeResultVerdictGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentPracticeResultVerdictGroupsMin).max(assessmentPracticeResultVerdictGroupsMax) +}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.') +}).describe('Verdict of one practice of the attempt.') + +export type AssessmentPracticeResult = zod.input; +export type AssessmentPracticeResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentProgress.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentProgress.zod.ts new file mode 100644 index 0000000..8108d99 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentProgress.zod.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentProgressAnsweredItemsMin = 0; +export const assessmentProgressAnsweredItemsMax = 100; + +export const assessmentProgressMaxItemsMax = 100; + + +export const AssessmentProgress = zod.object({ + "answered_items": zod.int().min(assessmentProgressAnsweredItemsMin).max(assessmentProgressAnsweredItemsMax), + "max_items": zod.int().min(1).max(assessmentProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') +}).describe('Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`.') + +export type AssessmentProgress = zod.input; +export type AssessmentProgressOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentResult.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentResult.zod.ts new file mode 100644 index 0000000..814f27f --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentResult.zod.ts @@ -0,0 +1,117 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentResultVersionsBankVersionMax = 64; + + +export const assessmentResultVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentResultVersionsAlgorithmVersionMax = 64; + + +export const assessmentResultVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentResultLimitationsMax = 10; + +export const assessmentResultUncertaintyOneStandardErrorMin = 0; + +export const assessmentResultUncertaintyOnePGradeMin = 0; +export const assessmentResultUncertaintyOnePGradeMax = 1; + +export const assessmentResultBasicScoreOnePointsMin = 0; + + + +export const assessmentResultPracticesItemVerdictScoreMin = 0; +export const assessmentResultPracticesItemVerdictScoreMax = 3; + +export const assessmentResultPracticesItemVerdictMaxScoreMin = 3; +export const assessmentResultPracticesItemVerdictMaxScoreMax = 3; + +export const assessmentResultPracticesItemVerdictGroupsItemGroupMax = 3; + +export const assessmentResultPracticesItemVerdictGroupsMin = 3; +export const assessmentResultPracticesItemVerdictGroupsMax = 3; + +export const assessmentResultPracticesMax = 5; + +export const assessmentResultGapsItemDomainMax = 64; + + +export const assessmentResultGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$'); +export const assessmentResultGapsItemTitleMax = 200; + +export const assessmentResultGapsMax = 20; + +export const assessmentResultDurationsItemsSecondsMin = 0; + +export const assessmentResultDurationsPracticeSecondsMin = 0; + +export const assessmentResultNextStepsMax = 5; + + +export const AssessmentResult = zod.object({ + "attempt_id": zod.uuid(), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]), + "mode": zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentResultVersionsBankVersionMax).regex(assessmentResultVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentResultVersionsAlgorithmVersionMax).regex(assessmentResultVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'), + "not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision, and whether it counts against the retry rules.\n\n- expired: the time or session limit passed before the candidate finished the item part. It is the candidate\'s attempt: it counts toward the attempt limit and starts the same-grade retry interval.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`.\n- insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'), + "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'), + "previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'), + "strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'), + "calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'), + "limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\n\nAdding a value is a contract change.')).max(assessmentResultLimitationsMax), + "uncertainty": zod.union([zod.object({ + "theta": zod.number(), + "standard_error": zod.number().min(assessmentResultUncertaintyOneStandardErrorMin), + "interval_95": zod.object({ + "low": zod.number(), + "high": zod.number() +}).describe('Interval on the ability scale.'), + "p_grade": zod.number().min(assessmentResultUncertaintyOnePGradeMin).max(assessmentResultUncertaintyOnePGradeMax).describe('Probability of reaching the threshold of the target grade.') +}).describe('Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.'),zod.null()]).describe('Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision.'), + "basic_score": zod.union([zod.object({ + "points": zod.int().min(assessmentResultBasicScoreOnePointsMin), + "max_points": zod.int().min(1), + "pass_points": zod.int().min(1) +}).describe('Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass mark comes from that policy version and never from the handler.'),zod.null()]).describe('Raw score of a demo_basic attempt with a decision, otherwise null.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "verdict": zod.object({ + "score": zod.int().min(assessmentResultPracticesItemVerdictScoreMin).max(assessmentResultPracticesItemVerdictScoreMax), + "max_score": zod.int().min(assessmentResultPracticesItemVerdictMaxScoreMin).max(assessmentResultPracticesItemVerdictMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentResultPracticesItemVerdictGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentResultPracticesItemVerdictGroupsMin).max(assessmentResultPracticesItemVerdictGroupsMax) +}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.') +}).describe('Verdict of one practice of the attempt.')).max(assessmentResultPracticesMax).describe('Verdicts of the practices that have one, main first.'), + "gaps": zod.array(zod.object({ + "domain": zod.string().min(1).max(assessmentResultGapsItemDomainMax).regex(assessmentResultGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'), + "title": zod.string().min(1).max(assessmentResultGapsItemTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentResultGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'), + "durations": zod.object({ + "items_seconds": zod.int().min(assessmentResultDurationsItemsSecondsMin), + "practice_seconds": zod.int().min(assessmentResultDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') +}).describe('Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.'), + "next_steps": zod.array(zod.object({ + "action": zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('First time the step is allowed, or null when it is allowed now.') +}).describe('Step that the server allows after this result, computed when it was decided.')).max(assessmentResultNextStepsMax), + "decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Immutable result of a terminal attempt, visible only to its candidate. It records the method, the versions, the decision, its uncertainty, and its limitations; a later policy, bank, or algorithm version never changes it. It never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. Fields that the method does not compute are null, never zero: demo_basic has null `uncertainty` and `strength`, and adaptive has null `basic_score`.') + +export type AssessmentResult = zod.input; +export type AssessmentResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentSessions.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentSessions.zod.ts new file mode 100644 index 0000000..ac3b059 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentSessions.zod.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentSessionsUsedMax = 10; + +export const assessmentSessionsMaxMax = 10; + +export const assessmentSessionsIdleTimeoutSecondsMin = 60; +export const assessmentSessionsIdleTimeoutSecondsMax = 86400; + + +export const AssessmentSessions = zod.object({ + "used": zod.int().min(1).max(assessmentSessionsUsedMax).describe('Sessions started so far, including the current one.'), + "max": zod.int().min(1).max(assessmentSessionsMaxMax), + "idle_timeout_seconds": zod.int().min(assessmentSessionsIdleTimeoutSecondsMin).max(assessmentSessionsIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nA session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session.') + +export type AssessmentSessions = zod.input; +export type AssessmentSessionsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts new file mode 100644 index 0000000..c70bced --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts @@ -0,0 +1,34 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentSpecializationAvailabilityGradesItemMaxSessionsMax = 10; + +export const assessmentSpecializationAvailabilityGradesItemMaxItemsMax = 100; + +export const assessmentSpecializationAvailabilityGradesMax = 10; + + +export const AssessmentSpecializationAvailability = zod.object({ + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Currently confirmed grade of the specialization, or null.'), + "active_attempt_id": zod.uuid().nullable().describe('Identifier of the active attempt of the specialization, or null.'), + "grades": zod.array(zod.object({ + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "status": zod.enum(['available', 'active_attempt', 'cooldown', 'insufficient_bank']).describe('Whether an attempt for the grade can start now.\n\n- available: CreateMyAssessmentAttempt can start it.\n- active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`.\n- cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it.\n- insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families.'), + "mode": zod.union([zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'),zod.null()]).describe('Mode that an attempt would use, or null when the status is `insufficient_bank`.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the status is `cooldown`, the first time the attempt can start; otherwise null.'), + "time_limit_seconds": zod.int().min(1).nullable().describe('Time from the start to `expires_at`.'), + "max_sessions": zod.int().min(1).max(assessmentSpecializationAvailabilityGradesItemMaxSessionsMax).nullable().describe('Session limit within the time limit.'), + "max_items": zod.int().min(1).max(assessmentSpecializationAvailabilityGradesItemMaxItemsMax).nullable().describe('Item limit, as in `AssessmentProgress.max_items`.'), + "practice_required": zod.boolean().nullable().describe('Whether the attempt would include a main code practice.') +}).describe('Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit.')).max(assessmentSpecializationAvailabilityGradesMax).describe('Every grade of the scale in ascending order.') +}).describe('Assessment state of one questionnaire specialization. Specializations are assessed independently, with independent retry intervals.') + +export type AssessmentSpecializationAvailability = zod.input; +export type AssessmentSpecializationAvailabilityOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentStrength.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentStrength.zod.ts new file mode 100644 index 0000000..eef704e --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentStrength.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentStrength = zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.') + +export type AssessmentStrength = zod.input; +export type AssessmentStrengthOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentUncertainty.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentUncertainty.zod.ts new file mode 100644 index 0000000..c91c753 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentUncertainty.zod.ts @@ -0,0 +1,26 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentUncertaintyStandardErrorMin = 0; + +export const assessmentUncertaintyPGradeMin = 0; +export const assessmentUncertaintyPGradeMax = 1; + + +export const AssessmentUncertainty = zod.object({ + "theta": zod.number(), + "standard_error": zod.number().min(assessmentUncertaintyStandardErrorMin), + "interval_95": zod.object({ + "low": zod.number(), + "high": zod.number() +}).describe('Interval on the ability scale.'), + "p_grade": zod.number().min(assessmentUncertaintyPGradeMin).max(assessmentUncertaintyPGradeMax).describe('Probability of reaching the threshold of the target grade.') +}).describe('Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.') + +export type AssessmentUncertainty = zod.input; +export type AssessmentUncertaintyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentVersionLabel.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentVersionLabel.zod.ts new file mode 100644 index 0000000..79f5bad --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentVersionLabel.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentVersionLabelMax = 64; + + +export const AssessmentVersionLabelRegExp = new RegExp('^[A-Za-z0-9._-]+$'); + +export const AssessmentVersionLabel = zod.string().min(1).max(AssessmentVersionLabelMax).regex(AssessmentVersionLabelRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') + +export type AssessmentVersionLabel = zod.input; +export type AssessmentVersionLabelOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentVersions.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentVersions.zod.ts new file mode 100644 index 0000000..c05943e --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentVersions.zod.ts @@ -0,0 +1,26 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentVersionsBankVersionMax = 64; + + +export const assessmentVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentVersionsAlgorithmVersionMax = 64; + + +export const assessmentVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); + +export const AssessmentVersions = zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentVersionsBankVersionMax).regex(assessmentVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentVersionsAlgorithmVersionMax).regex(assessmentVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.') + +export type AssessmentVersions = zod.input; +export type AssessmentVersionsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/basicScore.zod.ts b/frontend/src/shared/api/schemas/assessment/basicScore.zod.ts new file mode 100644 index 0000000..00a977e --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/basicScore.zod.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const basicScorePointsMin = 0; + + + + +export const BasicScore = zod.object({ + "points": zod.int().min(basicScorePointsMin), + "max_points": zod.int().min(1), + "pass_points": zod.int().min(1) +}).describe('Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass mark comes from that policy version and never from the handler.') + +export type BasicScore = zod.input; +export type BasicScoreOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/calibrationStatus.zod.ts b/frontend/src/shared/api/schemas/assessment/calibrationStatus.zod.ts new file mode 100644 index 0000000..151db41 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/calibrationStatus.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const CalibrationStatus = zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.') + +export type CalibrationStatus = zod.input; +export type CalibrationStatusOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/choiceAnswer.zod.ts b/frontend/src/shared/api/schemas/assessment/choiceAnswer.zod.ts new file mode 100644 index 0000000..65aaf1d --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/choiceAnswer.zod.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const choiceAnswerOptionIdsItemMax = 32; + + +export const choiceAnswerOptionIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const choiceAnswerOptionIdsMax = 10; + + +export const ChoiceAnswer = zod.object({ + "format": zod.enum(['choice']), + "option_ids": zod.array(zod.string().min(1).max(choiceAnswerOptionIdsItemMax).regex(choiceAnswerOptionIdsItemRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.')).min(1).max(choiceAnswerOptionIdsMax) +}).describe('Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.') + +export type ChoiceAnswer = zod.input; +export type ChoiceAnswerOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/choiceItemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/choiceItemContent.zod.ts new file mode 100644 index 0000000..0c1029c --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/choiceItemContent.zod.ts @@ -0,0 +1,29 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const choiceItemContentOptionsItemIdMax = 32; + + +export const choiceItemContentOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const choiceItemContentOptionsItemTextMax = 2000; + +export const choiceItemContentOptionsMin = 2; +export const choiceItemContentOptionsMax = 10; + + +export const ChoiceItemContent = zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(choiceItemContentOptionsItemIdMax).regex(choiceItemContentOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(choiceItemContentOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(choiceItemContentOptionsMin).max(choiceItemContentOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.') + +export type ChoiceItemContent = zod.input; +export type ChoiceItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/codeLine.zod.ts b/frontend/src/shared/api/schemas/assessment/codeLine.zod.ts new file mode 100644 index 0000000..99b1419 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/codeLine.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const codeLineNumberMax = 500; + +export const codeLineTextMax = 1000; + + +export const CodeLine = zod.object({ + "number": zod.int().min(1).max(codeLineNumberMax), + "text": zod.string().max(codeLineTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.') + +export type CodeLine = zod.input; +export type CodeLineOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/configurationAnswer.zod.ts b/frontend/src/shared/api/schemas/assessment/configurationAnswer.zod.ts new file mode 100644 index 0000000..38bbb9c --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/configurationAnswer.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const configurationAnswerConfigMax = 20000; + + +export const ConfigurationAnswer = zod.object({ + "format": zod.enum(['configuration']), + "config": zod.string().min(1).max(configurationAnswerConfigMax) +}).describe('Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks.') + +export type ConfigurationAnswer = zod.input; +export type ConfigurationAnswerOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/configurationItemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/configurationItemContent.zod.ts new file mode 100644 index 0000000..85e4a74 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/configurationItemContent.zod.ts @@ -0,0 +1,26 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const configurationItemContentSyntaxMax = 32; + + +export const configurationItemContentSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const configurationItemContentInitialConfigMax = 20000; + +export const configurationItemContentMaxLengthMax = 20000; + + +export const ConfigurationItemContent = zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(configurationItemContentSyntaxMax).regex(configurationItemContentSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(configurationItemContentInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(configurationItemContentMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.') + +export type ConfigurationItemContent = zod.input; +export type ConfigurationItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptBody.zod.ts b/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptBody.zod.ts new file mode 100644 index 0000000..0cdaf0d --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptBody.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const CreateMyAssessmentAttemptBody = zod.object({ + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first.') +}).describe('Category to assess: a specialization and the target grade, with the task language. The candidate comes from the session. The mode and versions are chosen by the server; unknown fields such as `mode`, `seed`, or `score` are rejected.') + +export type CreateMyAssessmentAttemptBody = zod.input; +export type CreateMyAssessmentAttemptBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptHeaders.zod.ts b/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptHeaders.zod.ts new file mode 100644 index 0000000..6b1c7e8 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptHeaders.zod.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const createMyAssessmentAttemptHeadersIdempotencyKeyMax = 255; + + +export const createMyAssessmentAttemptHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const CreateMyAssessmentAttemptHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(createMyAssessmentAttemptHeadersIdempotencyKeyMax).regex(createMyAssessmentAttemptHeadersIdempotencyKeyRegExp) +}) + +export type CreateMyAssessmentAttemptHeaders = zod.input; +export type CreateMyAssessmentAttemptHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptBody.zod.ts b/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptBody.zod.ts new file mode 100644 index 0000000..9c1c945 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptBody.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const FinalizeMyAssessmentAttemptBody = zod.object({ + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') +}).describe('Command to finalize the attempt.') + +export type FinalizeMyAssessmentAttemptBody = zod.input; +export type FinalizeMyAssessmentAttemptBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptHeaders.zod.ts b/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptHeaders.zod.ts new file mode 100644 index 0000000..60d51be --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptHeaders.zod.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const finalizeMyAssessmentAttemptHeadersIdempotencyKeyMax = 255; + + +export const finalizeMyAssessmentAttemptHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const FinalizeMyAssessmentAttemptHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(finalizeMyAssessmentAttemptHeadersIdempotencyKeyMax).regex(finalizeMyAssessmentAttemptHeadersIdempotencyKeyRegExp) +}) + +export type FinalizeMyAssessmentAttemptHeaders = zod.input; +export type FinalizeMyAssessmentAttemptHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/findErrorAnswer.zod.ts b/frontend/src/shared/api/schemas/assessment/findErrorAnswer.zod.ts new file mode 100644 index 0000000..49cd26d --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/findErrorAnswer.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const findErrorAnswerLineNumbersItemMax = 500; + +export const findErrorAnswerLineNumbersMax = 10; + + +export const FindErrorAnswer = zod.object({ + "format": zod.enum(['find_error']), + "line_numbers": zod.array(zod.int().min(1).max(findErrorAnswerLineNumbersItemMax)).min(1).max(findErrorAnswerLineNumbersMax) +}).describe('Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order.') + +export type FindErrorAnswer = zod.input; +export type FindErrorAnswerOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/findErrorItemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/findErrorItemContent.zod.ts new file mode 100644 index 0000000..898d8bf --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/findErrorItemContent.zod.ts @@ -0,0 +1,33 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const findErrorItemContentSyntaxMax = 32; + + +export const findErrorItemContentSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const findErrorItemContentLinesItemNumberMax = 500; + +export const findErrorItemContentLinesItemTextMax = 1000; + +export const findErrorItemContentLinesMax = 500; + +export const findErrorItemContentMaxSelectionsMax = 10; + + +export const FindErrorItemContent = zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(findErrorItemContentSyntaxMax).regex(findErrorItemContentSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(findErrorItemContentLinesItemNumberMax), + "text": zod.string().max(findErrorItemContentLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(findErrorItemContentLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(findErrorItemContentMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.') + +export type FindErrorItemContent = zod.input; +export type FindErrorItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/index.ts b/frontend/src/shared/api/schemas/assessment/index.ts new file mode 100644 index 0000000..fb4c33d --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/index.ts @@ -0,0 +1,70 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ + +export * from './assessmentAnswer.zod'; +export * from './assessmentAnswerSubmission.zod'; +export * from './assessmentAttempt.zod'; +export * from './assessmentAttemptCreate.zod'; +export * from './assessmentAttemptState.zod'; +export * from './assessmentAttemptVersion.zod'; +export * from './assessmentAvailability.zod'; +export * from './assessmentDurations.zod'; +export * from './assessmentFinalization.zod'; +export * from './assessmentGap.zod'; +export * from './assessmentGradeAvailability.zod'; +export * from './assessmentGradeAvailabilityStatus.zod'; +export * from './assessmentInterval.zod'; +export * from './assessmentItem.zod'; +export * from './assessmentItemId.zod'; +export * from './assessmentLimitation.zod'; +export * from './assessmentMode.zod'; +export * from './assessmentNextAction.zod'; +export * from './assessmentNextStep.zod'; +export * from './assessmentNotDeterminedReason.zod'; +export * from './assessmentOption.zod'; +export * from './assessmentOptionId.zod'; +export * from './assessmentOutcome.zod'; +export * from './assessmentPractice.zod'; +export * from './assessmentPracticeResult.zod'; +export * from './assessmentProgress.zod'; +export * from './assessmentResult.zod'; +export * from './assessmentSessions.zod'; +export * from './assessmentSpecializationAvailability.zod'; +export * from './assessmentStrength.zod'; +export * from './assessmentUncertainty.zod'; +export * from './assessmentVersionLabel.zod'; +export * from './assessmentVersions.zod'; +export * from './basicScore.zod'; +export * from './calibrationStatus.zod'; +export * from './choiceAnswer.zod'; +export * from './choiceItemContent.zod'; +export * from './codeLine.zod'; +export * from './configurationAnswer.zod'; +export * from './configurationItemContent.zod'; +export * from './createMyAssessmentAttemptBody.zod'; +export * from './createMyAssessmentAttemptHeaders.zod'; +export * from './finalizeMyAssessmentAttemptBody.zod'; +export * from './finalizeMyAssessmentAttemptHeaders.zod'; +export * from './findErrorAnswer.zod'; +export * from './findErrorItemContent.zod'; +export * from './itemContent.zod'; +export * from './numberAnswer.zod'; +export * from './numberItemContent.zod'; +export * from './orderAnswer.zod'; +export * from './orderItemContent.zod'; +export * from './practiceAnswer.zod'; +export * from './practiceExample.zod'; +export * from './practiceFailureReason.zod'; +export * from './practiceGroupResult.zod'; +export * from './practiceItemContent.zod'; +export * from './practiceKind.zod'; +export * from './practiceStatus.zod'; +export * from './practiceVerdict.zod'; +export * from './stringAnswer.zod'; +export * from './stringItemContent.zod'; +export * from './submitMyAssessmentAnswerBody.zod'; +export * from './submitMyAssessmentAnswerHeaders.zod'; diff --git a/frontend/src/shared/api/schemas/assessment/itemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/itemContent.zod.ts new file mode 100644 index 0000000..4224998 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/itemContent.zod.ts @@ -0,0 +1,105 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const itemContentOneOptionsItemIdMax = 32; + + +export const itemContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const itemContentOneOptionsItemTextMax = 2000; + +export const itemContentOneOptionsMin = 2; +export const itemContentOneOptionsMax = 10; + +export const itemContentTwoUnitMax = 32; + +export const itemContentThreeMaxLengthMax = 500; + +export const itemContentFourElementsItemIdMax = 32; + + +export const itemContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const itemContentFourElementsItemTextMax = 2000; + +export const itemContentFourElementsMin = 2; +export const itemContentFourElementsMax = 20; + +export const itemContentFiveSyntaxMax = 32; + + +export const itemContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const itemContentFiveLinesItemNumberMax = 500; + +export const itemContentFiveLinesItemTextMax = 1000; + +export const itemContentFiveLinesMax = 500; + +export const itemContentFiveMaxSelectionsMax = 10; + +export const itemContentSixSyntaxMax = 32; + + +export const itemContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const itemContentSixInitialConfigMax = 20000; + +export const itemContentSixMaxLengthMax = 20000; + +export const itemContentSevenLanguagesMax = 2; + +export const itemContentSevenPublicExamplesItemInputMax = 10000; + +export const itemContentSevenPublicExamplesItemExpectedOutputMax = 10000; + +export const itemContentSevenPublicExamplesMax = 10; + +export const itemContentSevenMaxSourceLengthMax = 65536; + + +export const ItemContent = zod.union([zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(itemContentOneOptionsItemIdMax).regex(itemContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(itemContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(itemContentOneOptionsMin).max(itemContentOneOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(itemContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.'),zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(itemContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(itemContentFourElementsItemIdMax).regex(itemContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(itemContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(itemContentFourElementsMin).max(itemContentFourElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(itemContentFiveSyntaxMax).regex(itemContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(itemContentFiveLinesItemNumberMax), + "text": zod.string().max(itemContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(itemContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(itemContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(itemContentSixSyntaxMax).regex(itemContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(itemContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(itemContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(itemContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(itemContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(itemContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(itemContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(itemContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') + +export type ItemContent = zod.input; +export type ItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/numberAnswer.zod.ts b/frontend/src/shared/api/schemas/assessment/numberAnswer.zod.ts new file mode 100644 index 0000000..7a5dbb1 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/numberAnswer.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const NumberAnswer = zod.object({ + "format": zod.enum(['number']), + "number": zod.number() +}).describe('Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer.') + +export type NumberAnswer = zod.input; +export type NumberAnswerOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/numberItemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/numberItemContent.zod.ts new file mode 100644 index 0000000..e1034b0 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/numberItemContent.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const numberItemContentUnitMax = 32; + + +export const NumberItemContent = zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(numberItemContentUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.') + +export type NumberItemContent = zod.input; +export type NumberItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/orderAnswer.zod.ts b/frontend/src/shared/api/schemas/assessment/orderAnswer.zod.ts new file mode 100644 index 0000000..51c7e21 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/orderAnswer.zod.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const orderAnswerElementIdsItemMax = 32; + + +export const orderAnswerElementIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const orderAnswerElementIdsMin = 2; +export const orderAnswerElementIdsMax = 20; + + +export const OrderAnswer = zod.object({ + "format": zod.enum(['order']), + "element_ids": zod.array(zod.string().min(1).max(orderAnswerElementIdsItemMax).regex(orderAnswerElementIdsItemRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.')).min(orderAnswerElementIdsMin).max(orderAnswerElementIdsMax) +}).describe('Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical.') + +export type OrderAnswer = zod.input; +export type OrderAnswerOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/orderItemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/orderItemContent.zod.ts new file mode 100644 index 0000000..23f7891 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/orderItemContent.zod.ts @@ -0,0 +1,28 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const orderItemContentElementsItemIdMax = 32; + + +export const orderItemContentElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const orderItemContentElementsItemTextMax = 2000; + +export const orderItemContentElementsMin = 2; +export const orderItemContentElementsMax = 20; + + +export const OrderItemContent = zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(orderItemContentElementsItemIdMax).regex(orderItemContentElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(orderItemContentElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(orderItemContentElementsMin).max(orderItemContentElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.') + +export type OrderItemContent = zod.input; +export type OrderItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceAnswer.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceAnswer.zod.ts new file mode 100644 index 0000000..1699c03 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceAnswer.zod.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const practiceAnswerSourceCodeMax = 65536; + + +export const PracticeAnswer = zod.object({ + "format": zod.enum(['practice']), + "language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('One of the `languages` of the practice item, or null when the item offers none.'), + "source_code": zod.string().min(1).max(practiceAnswerSourceCodeMax) +}).describe('Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem.') + +export type PracticeAnswer = zod.input; +export type PracticeAnswerOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceExample.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceExample.zod.ts new file mode 100644 index 0000000..769ac39 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceExample.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const practiceExampleInputMax = 10000; + +export const practiceExampleExpectedOutputMax = 10000; + + +export const PracticeExample = zod.object({ + "input": zod.string().max(practiceExampleInputMax), + "expected_output": zod.string().max(practiceExampleExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.') + +export type PracticeExample = zod.input; +export type PracticeExampleOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceFailureReason.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceFailureReason.zod.ts new file mode 100644 index 0000000..1f09187 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceFailureReason.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const PracticeFailureReason = zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.') + +export type PracticeFailureReason = zod.input; +export type PracticeFailureReasonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceGroupResult.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceGroupResult.zod.ts new file mode 100644 index 0000000..0ae58c4 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceGroupResult.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const practiceGroupResultGroupMax = 3; + + +export const PracticeGroupResult = zod.object({ + "group": zod.int().min(1).max(practiceGroupResultGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.') + +export type PracticeGroupResult = zod.input; +export type PracticeGroupResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceItemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceItemContent.zod.ts new file mode 100644 index 0000000..e65fa24 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceItemContent.zod.ts @@ -0,0 +1,31 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const practiceItemContentLanguagesMax = 2; + +export const practiceItemContentPublicExamplesItemInputMax = 10000; + +export const practiceItemContentPublicExamplesItemExpectedOutputMax = 10000; + +export const practiceItemContentPublicExamplesMax = 10; + +export const practiceItemContentMaxSourceLengthMax = 65536; + + +export const PracticeItemContent = zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(practiceItemContentLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(practiceItemContentPublicExamplesItemInputMax), + "expected_output": zod.string().max(practiceItemContentPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(practiceItemContentPublicExamplesMax), + "max_source_length": zod.int().min(1).max(practiceItemContentMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.') + +export type PracticeItemContent = zod.input; +export type PracticeItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceKind.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceKind.zod.ts new file mode 100644 index 0000000..571a048 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceKind.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const PracticeKind = zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.') + +export type PracticeKind = zod.input; +export type PracticeKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceStatus.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceStatus.zod.ts new file mode 100644 index 0000000..8a170ad --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceStatus.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const PracticeStatus = zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.') + +export type PracticeStatus = zod.input; +export type PracticeStatusOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceVerdict.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceVerdict.zod.ts new file mode 100644 index 0000000..749d21e --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceVerdict.zod.ts @@ -0,0 +1,31 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const practiceVerdictScoreMin = 0; +export const practiceVerdictScoreMax = 3; + +export const practiceVerdictMaxScoreMin = 3; +export const practiceVerdictMaxScoreMax = 3; + +export const practiceVerdictGroupsItemGroupMax = 3; + +export const practiceVerdictGroupsMin = 3; +export const practiceVerdictGroupsMax = 3; + + +export const PracticeVerdict = zod.object({ + "score": zod.int().min(practiceVerdictScoreMin).max(practiceVerdictScoreMax), + "max_score": zod.int().min(practiceVerdictMaxScoreMin).max(practiceVerdictMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(practiceVerdictGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(practiceVerdictGroupsMin).max(practiceVerdictGroupsMax) +}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.') + +export type PracticeVerdict = zod.input; +export type PracticeVerdictOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/stringAnswer.zod.ts b/frontend/src/shared/api/schemas/assessment/stringAnswer.zod.ts new file mode 100644 index 0000000..695cc92 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/stringAnswer.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const stringAnswerTextMax = 500; + + +export const StringAnswer = zod.object({ + "format": zod.enum(['string']), + "text": zod.string().min(1).max(stringAnswerTextMax) +}).describe('String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison.') + +export type StringAnswer = zod.input; +export type StringAnswerOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/stringItemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/stringItemContent.zod.ts new file mode 100644 index 0000000..3ff695c --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/stringItemContent.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const stringItemContentMaxLengthMax = 500; + + +export const StringItemContent = zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(stringItemContentMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.') + +export type StringItemContent = zod.input; +export type StringItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerBody.zod.ts b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerBody.zod.ts new file mode 100644 index 0000000..d9ff93d --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerBody.zod.ts @@ -0,0 +1,63 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const submitMyAssessmentAnswerBodyAnswerOneOptionIdsItemMax = 32; + + +export const submitMyAssessmentAnswerBodyAnswerOneOptionIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const submitMyAssessmentAnswerBodyAnswerOneOptionIdsMax = 10; + +export const submitMyAssessmentAnswerBodyAnswerThreeTextMax = 500; + +export const submitMyAssessmentAnswerBodyAnswerFourElementIdsItemMax = 32; + + +export const submitMyAssessmentAnswerBodyAnswerFourElementIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const submitMyAssessmentAnswerBodyAnswerFourElementIdsMin = 2; +export const submitMyAssessmentAnswerBodyAnswerFourElementIdsMax = 20; + +export const submitMyAssessmentAnswerBodyAnswerFiveLineNumbersItemMax = 500; + +export const submitMyAssessmentAnswerBodyAnswerFiveLineNumbersMax = 10; + +export const submitMyAssessmentAnswerBodyAnswerSixConfigMax = 20000; + +export const submitMyAssessmentAnswerBodyAnswerSevenSourceCodeMax = 65536; + + +export const SubmitMyAssessmentAnswerBody = zod.object({ + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "answer": zod.union([zod.object({ + "format": zod.enum(['choice']), + "option_ids": zod.array(zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerOneOptionIdsItemMax).regex(submitMyAssessmentAnswerBodyAnswerOneOptionIdsItemRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.')).min(1).max(submitMyAssessmentAnswerBodyAnswerOneOptionIdsMax) +}).describe('Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.'),zod.object({ + "format": zod.enum(['number']), + "number": zod.number() +}).describe('Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer.'),zod.object({ + "format": zod.enum(['string']), + "text": zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerThreeTextMax) +}).describe('String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison.'),zod.object({ + "format": zod.enum(['order']), + "element_ids": zod.array(zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerFourElementIdsItemMax).regex(submitMyAssessmentAnswerBodyAnswerFourElementIdsItemRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.')).min(submitMyAssessmentAnswerBodyAnswerFourElementIdsMin).max(submitMyAssessmentAnswerBodyAnswerFourElementIdsMax) +}).describe('Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical.'),zod.object({ + "format": zod.enum(['find_error']), + "line_numbers": zod.array(zod.int().min(1).max(submitMyAssessmentAnswerBodyAnswerFiveLineNumbersItemMax)).min(1).max(submitMyAssessmentAnswerBodyAnswerFiveLineNumbersMax) +}).describe('Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order.'),zod.object({ + "format": zod.enum(['configuration']), + "config": zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerSixConfigMax) +}).describe('Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks.'),zod.object({ + "format": zod.enum(['practice']), + "language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('One of the `languages` of the practice item, or null when the item offers none.'), + "source_code": zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerSevenSourceCodeMax) +}).describe('Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem.')]).describe('Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.') +}).describe('Answer to one item of the attempt. Unknown fields are rejected, so a request cannot send a score, a duration, or a correctness flag.') + +export type SubmitMyAssessmentAnswerBody = zod.input; +export type SubmitMyAssessmentAnswerBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerHeaders.zod.ts b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerHeaders.zod.ts new file mode 100644 index 0000000..bf0482f --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerHeaders.zod.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const submitMyAssessmentAnswerHeadersIdempotencyKeyMax = 255; + + +export const submitMyAssessmentAnswerHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const SubmitMyAssessmentAnswerHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(submitMyAssessmentAnswerHeadersIdempotencyKeyMax).regex(submitMyAssessmentAnswerHeadersIdempotencyKeyRegExp) +}) + +export type SubmitMyAssessmentAnswerHeaders = zod.input; +export type SubmitMyAssessmentAnswerHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index 66d397c..4211c22 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -14,6 +14,7 @@ export * from './problemFieldLocation.zod'; export * from './specializationCode.zod'; export * from './taskLanguage.zod'; export * from './timestamp.zod'; +export * from './assessment'; export * from './candidate'; export * from './catalog'; export * from './health';