From 51770eea6c00308f3e838e4a7df41f4b5917a149 Mon Sep 17 00:00:00 2001 From: shira Date: Sun, 11 Oct 2026 14:58:04 +0300 Subject: [PATCH] feat(practice): store code submissions and practice states apart from attempts --- api/README.en.md | 3 + api/README.md | 3 + api/core/components/responses.yml | 21 + api/core/components/schemas.yml | 173 +++ .../components/schemas/practice_schemas.yml | 189 +++ api/core/openapi.bundle.yml | 331 +++++ api/core/openapi.yml | 20 + ...didate_assessment_attempt_practice_run.yml | 64 + ...idate_assessment_attempt_practice_runs.yml | 76 + ...create_assessment_practice_submissions.sql | 209 +++ backend/db/queries/assessment_practice.sql | 159 ++ .../assessment_practice_http_test.go | 479 ++++++ .../integration_test/organizations_test.go | 1 + backend/integration_test/policy_test.go | 2 +- .../primary/http/api/oas_handlers_gen.go | 475 ++++++ .../primary/http/api/oas_interfaces_gen.go | 8 + .../adapter/primary/http/api/oas_json_gen.go | 1284 +++++++++++++++++ .../primary/http/api/oas_operations_gen.go | 2 + .../primary/http/api/oas_parameters_gen.go | 270 ++++ .../http/api/oas_request_decoders_gen.go | 79 + .../http/api/oas_response_encoders_gen.go | 211 +++ .../primary/http/api/oas_router_gen.go | 280 +++- .../primary/http/api/oas_schemas_gen.go | 608 ++++++++ .../primary/http/api/oas_security_gen.go | 3 + .../primary/http/api/oas_server_gen.go | 46 + .../primary/http/api/oas_unimplemented_gen.go | 52 + .../primary/http/api/oas_validators_gen.go | 626 ++++++++ .../internal/adapter/primary/http/v1/api.go | 6 + .../adapter/primary/http/v1/practice.go | 210 +++ .../secondary/postgres/assessment_practice.go | 285 ++++ .../postgres/sqlc/assessment_practice.sql.go | 377 +++++ .../adapter/secondary/postgres/sqlc/models.go | 37 + .../secondary/postgres/sqlc/querier.go | 24 + backend/internal/bootstrap/identity.go | 2 + backend/internal/bootstrap/practice.go | 49 + backend/internal/bootstrap/wire.go | 1 + backend/internal/bootstrap/wire_gen.go | 136 +- .../internal/domain/assessment_practice.go | 568 ++++++++ .../port/outbound/assessment_practice.go | 84 ++ backend/internal/port/outbound/transaction.go | 1 + backend/internal/usecase/practice/request.go | 103 ++ .../internal/usecase/practice/request_test.go | 72 + backend/internal/usecase/practice/service.go | 509 +++++++ docs/en/ARCHITECTURE.md | 17 +- docs/en/TESTING.md | 12 + docs/ru/ARCHITECTURE.md | 17 +- docs/ru/TESTING.md | 12 + .../endpoints/assessment/assessment.msw.ts | 36 + .../api/endpoints/assessment/assessment.ts | 216 ++- .../createMyAssessmentPracticeRunBody.zod.ts | 29 + ...reateMyAssessmentPracticeRunHeaders.zod.ts | 19 + .../shared/api/schemas/assessment/index.ts | 10 + .../api/schemas/assessment/practiceRun.zod.ts | 44 + .../assessment/practiceRunCreate.zod.ts | 29 + .../assessment/practiceRunOutcome.zod.ts | 12 + .../assessment/practiceRunResult.zod.ts | 36 + .../assessment/practiceRunState.zod.ts | 12 + .../schemas/assessment/practiceRunTest.zod.ts | 20 + .../assessment/practiceRunTestResult.zod.ts | 28 + .../assessment/practiceRunTestSource.zod.ts | 12 + scripts/test_assessment_contract.py | 20 + 61 files changed, 8584 insertions(+), 135 deletions(-) create mode 100644 api/core/components/schemas/practice_schemas.yml create mode 100644 api/core/routes/candidate_assessment_attempt_practice_run.yml create mode 100644 api/core/routes/candidate_assessment_attempt_practice_runs.yml create mode 100644 backend/db/migrations/00052_create_assessment_practice_submissions.sql create mode 100644 backend/db/queries/assessment_practice.sql create mode 100644 backend/integration_test/assessment_practice_http_test.go create mode 100644 backend/internal/adapter/primary/http/v1/practice.go create mode 100644 backend/internal/adapter/secondary/postgres/assessment_practice.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/assessment_practice.sql.go create mode 100644 backend/internal/bootstrap/practice.go create mode 100644 backend/internal/domain/assessment_practice.go create mode 100644 backend/internal/port/outbound/assessment_practice.go create mode 100644 backend/internal/usecase/practice/request.go create mode 100644 backend/internal/usecase/practice/request_test.go create mode 100644 backend/internal/usecase/practice/service.go create mode 100644 frontend/src/shared/api/schemas/assessment/createMyAssessmentPracticeRunBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/createMyAssessmentPracticeRunHeaders.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/practiceRun.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/practiceRunCreate.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/practiceRunOutcome.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/practiceRunResult.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/practiceRunState.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/practiceRunTest.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/practiceRunTestResult.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/practiceRunTestSource.zod.ts diff --git a/api/README.en.md b/api/README.en.md index e435642..fa6f324 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -267,6 +267,8 @@ The `assessment` tag covers the assessment attempts of the current candidate (PR | `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}/sessions` | `StartMyAssessmentAttemptSession` | 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}/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}/practice-runs` | `CreateMyAssessmentPracticeRun` | session and CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 503 `service_unavailable` | +| `GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}` | `GetMyAssessmentPracticeRun` | session | 200 `PracticeRun`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | | `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (another page holds it, or the attempt has no work session) | | `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 | | `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 | @@ -320,6 +322,7 @@ Items and answers: - One open window. A real attempt allows one open page at a time. The page generates a random identifier when it loads and sends it as `X-Attempt-Client` (16 to 64 characters of `A-Za-z0-9_-`) to `HoldMyAssessmentWorkSession`, which holds the work session for 120 seconds and asks the page to renew every 15 seconds, and to `ReleaseMyAssessmentWorkSession` when it closes. `StartMyAssessmentAttemptSession` and `SubmitMyAssessmentAnswer` take the same header as an optional parameter; while another page holds the session, a request from a different page or from none answers 409 `state_conflict` and changes nothing, and that refusal is not stored under the Idempotency-Key. An attempt that nobody holds, a released hold, and a hold that stopped renewing admit every page. It is a one-page-at-a-time rule, not a security boundary, and it is separate from `sessions` (`used`, `max`, `idle_timeout_seconds`), which count sequential work sessions. The server keeps only keyed digests of the page identifier and of the User-Agent bound to the attempt. No new problem code is added, so the page reads 409 on these operations as "open in another window". - 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. +- Debug runs (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) run a solution against the public examples and up to ten tests of the candidate while the practice is the current item. They never run, list, or score a hidden check, and change neither the practice state, the verdict, nor the attempt version. A run is queued and read by its own identifier; a repeat with the same Idempotency-Key and body returns the stored run. Without a configured sandbox the operation answers 503 `service_unavailable` and stores nothing. - 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. diff --git a/api/README.md b/api/README.md index d2b8d4c..4d8dd13 100644 --- a/api/README.md +++ b/api/README.md @@ -267,6 +267,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro | `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}/sessions` | `StartMyAssessmentAttemptSession` | сессия и 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}/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}/practice-runs` | `CreateMyAssessmentPracticeRun` | сессия и CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 503 `service_unavailable` | +| `GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}` | `GetMyAssessmentPracticeRun` | сессия | 200 `PracticeRun`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | | `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (сеанс занят другой страницей или у попытки нет рабочего сеанса) | | `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 | | `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 | @@ -320,6 +322,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Одно открытое окно. Реальная попытка допускает одну открытую страницу за раз. Страница при загрузке создает случайный идентификатор и отправляет его как `X-Attempt-Client` (от 16 до 64 символов `A-Za-z0-9_-`) в `HoldMyAssessmentWorkSession`, который занимает рабочий сеанс на 120 секунд и просит страницу продлевать его раз в 15 секунд, и в `ReleaseMyAssessmentWorkSession` при закрытии. `StartMyAssessmentAttemptSession` и `SubmitMyAssessmentAnswer` принимают тот же заголовок как необязательный параметр; пока сеанс занят другой страницей, запрос от другой страницы или без заголовка получает 409 `state_conflict` и ничего не меняет, а этот отказ не сохраняется под Idempotency-Key. Попытка, которую никто не держит, освобожденное занятие и переставшее продлеваться пускают любую страницу. Это правило "одна страница за раз", а не граница безопасности, и оно отделено от `sessions` (`used`, `max`, `idle_timeout_seconds`), которые считают последовательные рабочие сеансы. Сервер хранит только ключевые отпечатки идентификатора страницы и User-Agent, привязанные к попытке. Новый код ошибки не добавлялся, поэтому страница читает 409 на этих операциях как "открыто в другом окне". - Ответ (`AssessmentAnswer`) имеет те же семь форматов и несет только ответ. Неизвестные поля вроде `score`, `duration` или `seed` дают 400. Сервер сам записывает время и оценивает ответ по ключу экземпляра задания; время не входит в решение о грейде. Ответы API никогда не сообщают, был ли ответ правильным. - Решение практики исполняется в песочнице асинхронно на трех группах скрытых проверок; клиент опрашивает попытку, пока оно `pending`. Вердикт показывает только балл 0-3 и прохождение каждой группы. Любой исход, вызванный самим решением (ошибка компиляции или выполнения, лимит времени или памяти), - это `finished` с непройденными группами. `failed` (`sandbox_busy` или `sandbox_error`) означает только, что инфраструктура не смогла исполнить решение; он ничего не расходует. Так `failed` не становится оракулом для скрытых проверок и не дает бесконечных повторов. После `finished` другое решение не принимается. +- Отладочные прогоны (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) исполняют решение на публичных примерах и до десяти тестах кандидата, пока практика - текущий элемент. Они никогда не запускают, не показывают и не оценивают скрытые проверки и не меняют ни состояние практики, ни вердикт, ни версию попытки. Прогон ставится в очередь и читается по своему идентификатору; повтор с тем же Idempotency-Key и телом возвращает сохраненный прогон. Без настроенной песочницы операция отвечает 503 `service_unavailable` и ничего не сохраняет. - Если к истечению лимита последняя отправка все еще `failed`, результат - `not_determined` с причиной `sandbox_unavailable`. Неотправленная практика дает `practice_incomplete`. - Попытка бывает без практики только в `demo_basic`, пока кодовая практика выключена до проверки изоляции песочницы; результат тогда содержит ограничение `practice_not_included`. diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index aa67346..0296803 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -140,6 +140,27 @@ NotImplemented: examples: not_implemented: $ref: ./examples.yml#/NotImplemented +ServiceUnavailable: + description: >- + The service cannot serve the request now; code service_unavailable. + Retry-After is sent when a retry after that wait can succeed, for example + when a queue is full, and omitted when a retry cannot help soon, for + example when the feature is not enabled on this server. + headers: + Retry-After: + $ref: ./headers.yml#/RetryAfter + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + service_unavailable: + summary: A queue is full. + value: + type: urn:lincodex:problem:service_unavailable + title: Service unavailable + status: 503 + code: service_unavailable Problem: description: >- Any error response. The body is a Problem whose `status` equals the HTTP diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index d6c7faf..f524b7c 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -6837,6 +6837,179 @@ MyOrganizationList: $ref: '#/MyOrganization' page: $ref: '#/PageInfo' +PracticeRunTest: + type: object + description: 'One test of the candidate for a debug run: an input and the output the candidate expects. It is compared with the checker of the task.' + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 +PracticeRunCreate: + type: object + description: Debug run of a practice solution against the public examples of the task and up to ten tests of the candidate. It never runs a hidden check and never changes the practice state, the verdict, or the attempt version. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + - language + - source_code + properties: + item_id: + $ref: '#/AssessmentItemId' + 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 + tests: + type: array + maxItems: 10 + description: Tests of the candidate, run after the public examples. + items: + $ref: '#/PracticeRunTest' +PracticeRunState: + type: string + description: 'State of a debug run. + + + - queued: the run waits in the sandbox queue. + + - running: the sandbox runs it. + + - finished: `result` holds the outcome of the public examples and the tests of the candidate. + + - failed: the sandbox infrastructure could not run it, independently of the solution; `failure_reason` is `sandbox_error`. Start a new run. + + + Adding a value is a contract change.' + enum: + - queued + - running + - finished + - failed +PracticeRunOutcome: + type: string + description: Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error +PracticeRunTestSource: + type: string + description: 'Where a test of a debug run comes from: a public example of the task or a test of the candidate.' + enum: + - example + - candidate +PracticeRunTestResult: + type: object + description: Outcome of one evaluated test. The tests of a source stop at the first failed one, so later tests of that source are not listed. + additionalProperties: false + required: + - source + - index + - outcome + - time_ms + - memory_kb + - diagnostic + properties: + source: + $ref: '#/PracticeRunTestSource' + index: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Position of the test in its source, from 1. + outcome: + $ref: '#/PracticeRunOutcome' + time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + diagnostic: + description: Truncated error output of a failed test, or null. + oneOf: + - type: string + maxLength: 2048 + - type: 'null' +PracticeRunResult: + type: object + description: Result of a debug run on the public examples and the tests of the candidate. It never contains a hidden check, its outcome, or the score. + additionalProperties: false + required: + - outcome + - compile_diagnostic + - tests + properties: + outcome: + $ref: '#/PracticeRunOutcome' + compile_diagnostic: + description: The compiler message when `outcome` is `compile_error`, otherwise null. + oneOf: + - type: string + maxLength: 4096 + - type: 'null' + tests: + type: array + maxItems: 20 + items: + $ref: '#/PracticeRunTestResult' +PracticeRun: + type: object + description: Debug run of a practice solution. It shows only the public examples and the tests of the candidate; hidden checks are never run, listed, or scored by a debug run. + additionalProperties: false + required: + - id + - item_id + - state + - created_at + - finished_at + - failure_reason + - result + properties: + id: + type: string + format: uuid + description: Identifier of the run. + item_id: + $ref: '#/AssessmentItemId' + state: + $ref: '#/PracticeRunState' + created_at: + $ref: '#/Timestamp' + finished_at: + description: Time the run reached `finished` or `failed`, or null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + failure_reason: + description: '`sandbox_error` when `state` is `failed`, otherwise null.' + oneOf: + - $ref: '#/PracticeFailureReason' + - type: 'null' + result: + description: The result when `state` is `finished`, otherwise null. + oneOf: + - $ref: '#/PracticeRunResult' + - type: 'null' PublicationVersion: type: integer format: int64 diff --git a/api/core/components/schemas/practice_schemas.yml b/api/core/components/schemas/practice_schemas.yml new file mode 100644 index 0000000..10fb7bf --- /dev/null +++ b/api/core/components/schemas/practice_schemas.yml @@ -0,0 +1,189 @@ +schemas: + PracticeRunTest: + type: object + description: >- + One test of the candidate for a debug run: an input and the output the + candidate expects. It is compared with the checker of the task. + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 + PracticeRunCreate: + type: object + description: >- + Debug run of a practice solution against the public examples of the task + and up to ten tests of the candidate. It never runs a hidden check and + never changes the practice state, the verdict, or the attempt version. + Unknown fields are rejected. + additionalProperties: false + required: + - item_id + - language + - source_code + properties: + item_id: + $ref: "./assessment_schemas.yml#/schemas/AssessmentItemId" + 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 + tests: + type: array + maxItems: 10 + description: Tests of the candidate, run after the public examples. + items: + $ref: "#/schemas/PracticeRunTest" + PracticeRunState: + type: string + description: |- + State of a debug run. + + - queued: the run waits in the sandbox queue. + - running: the sandbox runs it. + - finished: `result` holds the outcome of the public examples and the tests of the candidate. + - failed: the sandbox infrastructure could not run it, independently of the solution; `failure_reason` is `sandbox_error`. Start a new run. + + Adding a value is a contract change. + enum: + - queued + - running + - finished + - failed + PracticeRunOutcome: + type: string + description: >- + Outcome of a run or one of its tests. Every outcome caused by the + solution, such as a compilation error, a crash, or a limit, is a + finished run with this outcome; an infrastructure failure is a failed + run instead. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + PracticeRunTestSource: + type: string + description: >- + Where a test of a debug run comes from: a public example of the task or + a test of the candidate. + enum: + - example + - candidate + PracticeRunTestResult: + type: object + description: >- + Outcome of one evaluated test. The tests of a source stop at the first + failed one, so later tests of that source are not listed. + additionalProperties: false + required: + - source + - index + - outcome + - time_ms + - memory_kb + - diagnostic + properties: + source: + $ref: "#/schemas/PracticeRunTestSource" + index: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Position of the test in its source, from 1. + outcome: + $ref: "#/schemas/PracticeRunOutcome" + time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + diagnostic: + description: Truncated error output of a failed test, or null. + oneOf: + - type: string + maxLength: 2048 + - type: "null" + PracticeRunResult: + type: object + description: >- + Result of a debug run on the public examples and the tests of the + candidate. It never contains a hidden check, its outcome, or the score. + additionalProperties: false + required: + - outcome + - compile_diagnostic + - tests + properties: + outcome: + $ref: "#/schemas/PracticeRunOutcome" + compile_diagnostic: + description: The compiler message when `outcome` is `compile_error`, otherwise null. + oneOf: + - type: string + maxLength: 4096 + - type: "null" + tests: + type: array + maxItems: 20 + items: + $ref: "#/schemas/PracticeRunTestResult" + PracticeRun: + type: object + description: >- + Debug run of a practice solution. It shows only the public examples and + the tests of the candidate; hidden checks are never run, listed, or + scored by a debug run. + additionalProperties: false + required: + - id + - item_id + - state + - created_at + - finished_at + - failure_reason + - result + properties: + id: + type: string + format: uuid + description: Identifier of the run. + item_id: + $ref: "./assessment_schemas.yml#/schemas/AssessmentItemId" + state: + $ref: "#/schemas/PracticeRunState" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + finished_at: + description: Time the run reached `finished` or `failed`, or null. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + failure_reason: + description: "`sandbox_error` when `state` is `failed`, otherwise null." + oneOf: + - $ref: "./assessment_schemas.yml#/schemas/PracticeFailureReason" + - type: "null" + result: + description: The result when `state` is `finished`, otherwise null. + oneOf: + - $ref: "#/schemas/PracticeRunResult" + - type: "null" diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 16efb0a..5471f7c 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -1281,6 +1281,151 @@ paths: $ref: '#/components/responses/TooManyRequests' default: $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/practice-runs: + post: + operationId: CreateMyAssessmentPracticeRun + summary: Start a debug run of a practice solution. + 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 practice item of the attempt and carries the language, the source, and up to ten tests of the candidate. + + A debug run executes the solution in the isolated sandbox against the public examples of the task and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes neither the practice state, the verdict, nor the attempt version; the graded solution is submitted with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed asynchronously: the response is 202 with the run `queued`, and the client polls GetMyAssessmentPracticeRun. The source is never echoed. + + The practice must be the current item: the attempt is in `practice_pending` for the main practice or `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the server answers 409 state_conflict. + + Availability. When code practice is not enabled on this server, the server answers 503 service_unavailable and stores nothing. + + Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), then the solution against the item (400 with a pointer such as `/language` or `/source_code`). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PracticeRunCreate' + examples: + run: + summary: A Python solution with one test of the candidate. + value: + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + language: python + source_code: | + print(sum(map(int, input().split()))) + tests: + - input: | + 2 3 + expected_output: | + 5 + responses: + '202': + description: The run is queued, or this request was already accepted and the stored run is returned. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/PracticeRun' + examples: + queued: + summary: A queued run. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a70 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + state: queued + created_at: '2026-10-05T09:30:00Z' + finished_at: null + failure_reason: null + result: null + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/StateConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}: + get: + operationId: GetMyAssessmentPracticeRun + summary: Read a debug run of a practice solution. + description: |- + Requires the session cookie of a candidate account. Returns the state of a debug run started with CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source. This GET is read-only. + + A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is not readable here. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - name: run_id + in: path + required: true + description: Identifier of a debug run of this attempt. + schema: + type: string + format: uuid + responses: + '200': + description: The run. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/PracticeRun' + examples: + finished: + summary: A finished run whose test of the candidate failed. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a70 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + state: finished + created_at: '2026-10-05T09:30:00Z' + finished_at: '2026-10-05T09:30:04Z' + failure_reason: null + result: + outcome: wrong_answer + compile_diagnostic: null + tests: + - source: example + index: 1 + outcome: accepted + time_ms: 21 + memory_kb: 9216 + diagnostic: null + - source: candidate + index: 1 + outcome: wrong_answer + time_ms: 20 + memory_kb: 9180 + diagnostic: null + '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}/finalize: post: operationId: FinalizeMyAssessmentAttempt @@ -5714,6 +5859,175 @@ components: oneOf: - $ref: '#/components/schemas/PracticeFailureReason' - type: 'null' + PracticeRunTest: + type: object + description: 'One test of the candidate for a debug run: an input and the output the candidate expects. It is compared with the checker of the task.' + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 + PracticeRunCreate: + type: object + description: Debug run of a practice solution against the public examples of the task and up to ten tests of the candidate. It never runs a hidden check and never changes the practice state, the verdict, or the attempt version. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + - language + - source_code + properties: + item_id: + $ref: '#/components/schemas/AssessmentItemId' + 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 + tests: + type: array + maxItems: 10 + description: Tests of the candidate, run after the public examples. + items: + $ref: '#/components/schemas/PracticeRunTest' + PracticeRunState: + type: string + description: |- + State of a debug run. + + - queued: the run waits in the sandbox queue. + - running: the sandbox runs it. + - finished: `result` holds the outcome of the public examples and the tests of the candidate. + - failed: the sandbox infrastructure could not run it, independently of the solution; `failure_reason` is `sandbox_error`. Start a new run. + + Adding a value is a contract change. + enum: + - queued + - running + - finished + - failed + PracticeRunOutcome: + type: string + description: Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + PracticeRunTestSource: + type: string + description: 'Where a test of a debug run comes from: a public example of the task or a test of the candidate.' + enum: + - example + - candidate + PracticeRunTestResult: + type: object + description: Outcome of one evaluated test. The tests of a source stop at the first failed one, so later tests of that source are not listed. + additionalProperties: false + required: + - source + - index + - outcome + - time_ms + - memory_kb + - diagnostic + properties: + source: + $ref: '#/components/schemas/PracticeRunTestSource' + index: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Position of the test in its source, from 1. + outcome: + $ref: '#/components/schemas/PracticeRunOutcome' + time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + diagnostic: + description: Truncated error output of a failed test, or null. + oneOf: + - type: string + maxLength: 2048 + - type: 'null' + PracticeRunResult: + type: object + description: Result of a debug run on the public examples and the tests of the candidate. It never contains a hidden check, its outcome, or the score. + additionalProperties: false + required: + - outcome + - compile_diagnostic + - tests + properties: + outcome: + $ref: '#/components/schemas/PracticeRunOutcome' + compile_diagnostic: + description: The compiler message when `outcome` is `compile_error`, otherwise null. + oneOf: + - type: string + maxLength: 4096 + - type: 'null' + tests: + type: array + maxItems: 20 + items: + $ref: '#/components/schemas/PracticeRunTestResult' + PracticeRun: + type: object + description: Debug run of a practice solution. It shows only the public examples and the tests of the candidate; hidden checks are never run, listed, or scored by a debug run. + additionalProperties: false + required: + - id + - item_id + - state + - created_at + - finished_at + - failure_reason + - result + properties: + id: + type: string + format: uuid + description: Identifier of the run. + item_id: + $ref: '#/components/schemas/AssessmentItemId' + state: + $ref: '#/components/schemas/PracticeRunState' + created_at: + $ref: '#/components/schemas/Timestamp' + finished_at: + description: Time the run reached `finished` or `failed`, or null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + failure_reason: + description: '`sandbox_error` when `state` is `failed`, otherwise null.' + oneOf: + - $ref: '#/components/schemas/PracticeFailureReason' + - type: 'null' + result: + description: The result when `state` is `finished`, otherwise null. + oneOf: + - $ref: '#/components/schemas/PracticeRunResult' + - type: 'null' AssessmentAttempt: description: Candidate view of a real assessment, a corrective real assessment, or a demo_express training run. The variants keep training output separate from qualification attempts. oneOf: @@ -12407,6 +12721,23 @@ components: $ref: '#/components/examples/VerificationCodeInvalid' validation_failed: $ref: '#/components/examples/VerificationCodeMalformed' + ServiceUnavailable: + description: The service cannot serve the request now; code service_unavailable. Retry-After is sent when a retry after that wait can succeed, for example when a queue is full, and omitted when a retry cannot help soon, for example when the feature is not enabled on this server. + headers: + Retry-After: + $ref: '#/components/headers/RetryAfter' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + service_unavailable: + summary: A queue is full. + value: + type: urn:lincodex:problem:service_unavailable + title: Service unavailable + status: 503 + code: service_unavailable securitySchemes: sessionCookie: type: apiKey diff --git a/api/core/openapi.yml b/api/core/openapi.yml index cb70d29..871f084 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -139,6 +139,10 @@ paths: $ref: ./routes/candidate_assessment_attempt_work_session.yml /api/v1/me/assessment-attempts/{attempt_id}/answers: $ref: ./routes/candidate_assessment_attempt_answers.yml + /api/v1/me/assessment-attempts/{attempt_id}/practice-runs: + $ref: ./routes/candidate_assessment_attempt_practice_runs.yml + /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}: + $ref: ./routes/candidate_assessment_attempt_practice_run.yml /api/v1/me/assessment-attempts/{attempt_id}/finalize: $ref: ./routes/candidate_assessment_attempt_finalize.yml /api/v1/me/assessment-attempts/{attempt_id}/result: @@ -463,6 +467,22 @@ components: $ref: ./components/schemas.yml#/PracticeVerdict AssessmentPractice: $ref: ./components/schemas.yml#/AssessmentPractice + PracticeRunTest: + $ref: ./components/schemas.yml#/PracticeRunTest + PracticeRunCreate: + $ref: ./components/schemas.yml#/PracticeRunCreate + PracticeRunState: + $ref: ./components/schemas.yml#/PracticeRunState + PracticeRunOutcome: + $ref: ./components/schemas.yml#/PracticeRunOutcome + PracticeRunTestSource: + $ref: ./components/schemas.yml#/PracticeRunTestSource + PracticeRunTestResult: + $ref: ./components/schemas.yml#/PracticeRunTestResult + PracticeRunResult: + $ref: ./components/schemas.yml#/PracticeRunResult + PracticeRun: + $ref: ./components/schemas.yml#/PracticeRun AssessmentAttempt: $ref: ./components/schemas.yml#/AssessmentAttempt ChoiceAnswer: diff --git a/api/core/routes/candidate_assessment_attempt_practice_run.yml b/api/core/routes/candidate_assessment_attempt_practice_run.yml new file mode 100644 index 0000000..7a0ee9e --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_practice_run.yml @@ -0,0 +1,64 @@ +get: + operationId: GetMyAssessmentPracticeRun + summary: Read a debug run of a practice solution. + description: |- + Requires the session cookie of a candidate account. Returns the state of a debug run started with CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source. This GET is read-only. + + A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is not readable here. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - name: run_id + in: path + required: true + description: Identifier of a debug run of this attempt. + schema: + type: string + format: uuid + responses: + "200": + description: The run. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PracticeRun + examples: + finished: + summary: A finished run whose test of the candidate failed. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a70 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + state: finished + created_at: "2026-10-05T09:30:00Z" + finished_at: "2026-10-05T09:30:04Z" + failure_reason: null + result: + outcome: wrong_answer + compile_diagnostic: null + tests: + - source: example + index: 1 + outcome: accepted + time_ms: 21 + memory_kb: 9216 + diagnostic: null + - source: candidate + index: 1 + outcome: wrong_answer + time_ms: 20 + memory_kb: 9180 + diagnostic: null + "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_practice_runs.yml b/api/core/routes/candidate_assessment_attempt_practice_runs.yml new file mode 100644 index 0000000..bf637b4 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_practice_runs.yml @@ -0,0 +1,76 @@ +post: + operationId: CreateMyAssessmentPracticeRun + summary: Start a debug run of a practice solution. + 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 practice item of the attempt and carries the language, the source, and up to ten tests of the candidate. + + A debug run executes the solution in the isolated sandbox against the public examples of the task and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes neither the practice state, the verdict, nor the attempt version; the graded solution is submitted with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed asynchronously: the response is 202 with the run `queued`, and the client polls GetMyAssessmentPracticeRun. The source is never echoed. + + The practice must be the current item: the attempt is in `practice_pending` for the main practice or `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the server answers 409 state_conflict. + + Availability. When code practice is not enabled on this server, the server answers 503 service_unavailable and stores nothing. + + Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), then the solution against the item (400 with a pointer such as `/language` or `/source_code`). + 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#/PracticeRunCreate + examples: + run: + summary: A Python solution with one test of the candidate. + value: + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + language: python + source_code: "print(sum(map(int, input().split())))\n" + tests: + - input: "2 3\n" + expected_output: "5\n" + responses: + "202": + description: The run is queued, or this request was already accepted and the stored run is returned. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PracticeRun + examples: + queued: + summary: A queued run. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a70 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + state: queued + created_at: "2026-10-05T09:30:00Z" + finished_at: null + failure_reason: null + result: null + "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#/StateConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "503": + $ref: ../components/responses.yml#/ServiceUnavailable + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/db/migrations/00052_create_assessment_practice_submissions.sql b/backend/db/migrations/00052_create_assessment_practice_submissions.sql new file mode 100644 index 0000000..a9ab62d --- /dev/null +++ b/backend/db/migrations/00052_create_assessment_practice_submissions.sql @@ -0,0 +1,209 @@ +-- +goose Up +-- Code practice keeps its own records next to the attempt and its result: +-- the practice items of an attempt with their private task content and +-- state, the submissions of candidate code, and one execution job per +-- submission. None of these rows is part of the attempt snapshot, the +-- idempotent attempt responses, or the result. +-- +-- A submission and its execution job are inserted in one transaction, so a +-- job exists exactly when its submission committed; the practice queue +-- worker picks the job later. The job table is that transactional queue: a +-- separate event is not needed because nothing outside PostgreSQL has to +-- learn about the submission before the worker runs it. + +-- One practice item of an attempt: the main practice or the additional one. +-- The ID is the item ID the candidate sees and the attempt item of the run +-- key. task is the private task content (languages, limits, checker, public +-- examples, and the hidden test groups); it never leaves the backend except +-- in a request to the code runner. +CREATE TABLE assessment_practices ( + id uuid NOT NULL, + attempt_id uuid NOT NULL, + user_id uuid NOT NULL, + kind text NOT NULL, + task jsonb NOT NULL, + -- not_started: nothing submitted; pending: the latest final submission + -- waits for its verdict; finished: it has one; failed: the sandbox + -- infrastructure could not run it, and the practice can be submitted + -- again. + status text NOT NULL, + failure_reason text, + -- Time of the latest final submission, or NULL before the first one. + submitted_at timestamptz, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT assessment_practices_pkey PRIMARY KEY (id), + CONSTRAINT assessment_practices_id_owner_key UNIQUE (id, user_id), + CONSTRAINT assessment_practices_attempt_kind_key UNIQUE (attempt_id, kind), + CONSTRAINT assessment_practices_attempt_owner_fk FOREIGN KEY (attempt_id, user_id) + REFERENCES assessment_attempts (id, user_id) ON DELETE CASCADE, + CONSTRAINT assessment_practices_kind CHECK (kind IN ('main', 'additional')), + CONSTRAINT assessment_practices_task_object CHECK ( + jsonb_typeof(task) = 'object' AND octet_length(task::text) <= 8388608 + ), + CONSTRAINT assessment_practices_status CHECK ( + status IN ('not_started', 'pending', 'finished', 'failed') + ), + CONSTRAINT assessment_practices_failure CHECK ( + (status = 'failed') = (failure_reason IS NOT NULL) + AND (failure_reason IS NULL OR failure_reason IN ('sandbox_busy', 'sandbox_error')) + ), + CONSTRAINT assessment_practices_submitted CHECK ( + (status = 'not_started') = (submitted_at IS NULL) + ), + CONSTRAINT assessment_practices_timestamps CHECK ( + created_at <= updated_at + AND (submitted_at IS NULL OR submitted_at >= created_at) + ) +); + +-- The identity, owner, kind, and task content of a practice never change; +-- only its state moves. +-- +goose StatementBegin +CREATE FUNCTION assessment_practice_immutable_task() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.id <> OLD.id OR NEW.attempt_id <> OLD.attempt_id OR NEW.user_id <> OLD.user_id OR + NEW.kind <> OLD.kind OR NEW.task <> OLD.task OR NEW.created_at <> OLD.created_at OR + NEW.updated_at < OLD.updated_at THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_practice_task_immutable', + MESSAGE = 'assessment practice identity and task are immutable'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_practice_immutable_task +BEFORE UPDATE ON assessment_practices +FOR EACH ROW EXECUTE FUNCTION assessment_practice_immutable_task(); + +-- One submission of candidate code. public is a debug run against the +-- public examples and the candidate's own tests; final is the solution that +-- the hidden groups grade. The request part of a row is immutable: once +-- stored, the source of a submission can never be replaced, and the result +-- is written once. +-- +-- idempotency_scope is the keyed digest of the operation, the +-- Idempotency-Key, and the account; it does not reveal the key. The generic +-- idempotency record of the same scope, written in the same transaction, +-- holds the request fingerprint and decides a replay for 24 hours; this +-- column only finds the submission that a replay returns. +CREATE TABLE assessment_practice_submissions ( + id uuid NOT NULL, + practice_id uuid NOT NULL, + user_id uuid NOT NULL, + mode text NOT NULL, + language text NOT NULL, + source text NOT NULL, + source_sha256 bytea NOT NULL, + -- The candidate's own tests of a public run, or NULL. + custom_tests jsonb, + idempotency_scope bytea NOT NULL, + -- The validated run result, written once by the queue worker. + result jsonb, + result_at timestamptz, + created_at timestamptz NOT NULL, + CONSTRAINT assessment_practice_submissions_pkey PRIMARY KEY (id), + CONSTRAINT assessment_practice_submissions_practice_owner_fk FOREIGN KEY (practice_id, user_id) + REFERENCES assessment_practices (id, user_id) ON DELETE CASCADE, + CONSTRAINT assessment_practice_submissions_mode CHECK (mode IN ('public', 'final')), + CONSTRAINT assessment_practice_submissions_language CHECK (language IN ('go', 'python')), + CONSTRAINT assessment_practice_submissions_source CHECK ( + char_length(source) >= 1 AND octet_length(source) <= 65536 + ), + CONSTRAINT assessment_practice_submissions_digests CHECK ( + octet_length(source_sha256) = 32 + AND octet_length(idempotency_scope) = 32 + ), + CONSTRAINT assessment_practice_submissions_custom_tests CHECK ( + custom_tests IS NULL OR ( + mode = 'public' + AND jsonb_typeof(custom_tests) = 'array' + AND octet_length(custom_tests::text) <= 262144 + ) + ), + CONSTRAINT assessment_practice_submissions_result CHECK ( + (result IS NULL) = (result_at IS NULL) + AND (result IS NULL OR (jsonb_typeof(result) = 'object' AND octet_length(result::text) <= 1048576)) + AND (result_at IS NULL OR result_at >= created_at) + ) +); + +CREATE INDEX assessment_practice_submissions_practice_idx +ON assessment_practice_submissions (practice_id, mode, created_at, id); + +-- Serves the replay of a submission by its idempotency scope. +CREATE INDEX assessment_practice_submissions_scope_idx +ON assessment_practice_submissions (user_id, idempotency_scope, created_at); + +-- A submission is immutable except for its one-time result. Rows are removed +-- only by the cascade of an account, attempt, or practice deletion. +-- +goose StatementBegin +CREATE FUNCTION assessment_practice_submission_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_practice_submission_delete_forbidden', + MESSAGE = 'assessment practice submissions are removed only by cascade'; + END IF; + IF (to_jsonb(NEW) - 'result' - 'result_at') IS DISTINCT FROM (to_jsonb(OLD) - 'result' - 'result_at') OR + OLD.result IS NOT NULL OR NEW.result IS NULL THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_practice_submission_immutable', + MESSAGE = 'assessment practice submissions are immutable and get one result'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_practice_submission_guard +BEFORE UPDATE OR DELETE ON assessment_practice_submissions +FOR EACH ROW EXECUTE FUNCTION assessment_practice_submission_guard(); + +-- The execution job of a submission. mode is copied from the submission so +-- the worker can run final submissions before debug runs without a join. +CREATE TABLE assessment_practice_jobs ( + submission_id uuid NOT NULL, + mode text NOT NULL, + -- queued: waits for the worker; running: the worker holds it; finished: + -- the result is stored; failed: the infrastructure gave up on it, which + -- is never a verdict on the code. + state text NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + finished_at timestamptz, + CONSTRAINT assessment_practice_jobs_pkey PRIMARY KEY (submission_id), + CONSTRAINT assessment_practice_jobs_submission_fk FOREIGN KEY (submission_id) + REFERENCES assessment_practice_submissions (id) ON DELETE CASCADE, + CONSTRAINT assessment_practice_jobs_mode CHECK (mode IN ('public', 'final')), + CONSTRAINT assessment_practice_jobs_state CHECK ( + state IN ('queued', 'running', 'finished', 'failed') + ), + CONSTRAINT assessment_practice_jobs_finished CHECK ( + (state IN ('finished', 'failed')) = (finished_at IS NOT NULL) + AND created_at <= updated_at + AND (finished_at IS NULL OR finished_at >= created_at) + ) +); + +-- Serves the scan of unfinished jobs, which stays small while finished rows +-- accumulate. +CREATE INDEX assessment_practice_jobs_active_idx +ON assessment_practice_jobs (created_at, submission_id) +WHERE state IN ('queued', 'running'); + +-- +goose Down +DROP TABLE assessment_practice_jobs; +DROP TRIGGER assessment_practice_submission_guard ON assessment_practice_submissions; +DROP FUNCTION assessment_practice_submission_guard(); +DROP TABLE assessment_practice_submissions; +DROP TRIGGER assessment_practice_immutable_task ON assessment_practices; +DROP FUNCTION assessment_practice_immutable_task(); +DROP TABLE assessment_practices; diff --git a/backend/db/queries/assessment_practice.sql b/backend/db/queries/assessment_practice.sql new file mode 100644 index 0000000..4257d98 --- /dev/null +++ b/backend/db/queries/assessment_practice.sql @@ -0,0 +1,159 @@ +-- Lock order of a practice command: the idempotency record, the attempt in +-- share mode, then the practice row. The attempt flows lock the attempt +-- first as well, so a practice command never waits for them in the opposite +-- order. + +-- Locks the owner's attempt in share mode, so its state cannot change while +-- a practice command decides on it, and reads the database time after the +-- lock. +-- name: LockAssessmentAttemptForPractice :one +SELECT + attempt.state, + attempt.expires_at, + clock_timestamp()::timestamptz AS database_time +FROM assessment_attempts AS attempt +WHERE + attempt.id = sqlc.arg(attempt_id) + AND attempt.user_id = sqlc.arg(user_id) +FOR SHARE; + +-- Locks one practice of the owner's attempt for a state change. +-- name: LockAssessmentPractice :one +SELECT + practice.id, + practice.attempt_id, + practice.user_id, + practice.kind, + practice.task, + practice.status, + practice.failure_reason, + practice.submitted_at, + practice.created_at +FROM assessment_practices AS practice +WHERE + practice.id = sqlc.arg(id) + AND practice.attempt_id = sqlc.arg(attempt_id) + AND practice.user_id = sqlc.arg(user_id) +FOR UPDATE; + +-- name: InsertAssessmentPractice :exec +INSERT INTO assessment_practices ( + id, + attempt_id, + user_id, + kind, + task, + status, + failure_reason, + submitted_at, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(attempt_id), + sqlc.arg(user_id), + sqlc.arg(kind), + sqlc.arg(task), + 'not_started', + NULL, + NULL, + sqlc.arg(created_at), + sqlc.arg(created_at) +); + +-- name: UpdateAssessmentPracticeState :execrows +UPDATE assessment_practices +SET + status = sqlc.arg(status), + failure_reason = sqlc.narg(failure_reason), + submitted_at = sqlc.narg(submitted_at), + updated_at = greatest(updated_at, sqlc.arg(updated_at)::timestamptz) +WHERE id = sqlc.arg(id); + +-- Finds the latest submission of the owner under an idempotency scope, which +-- a replay returns. +-- name: FindAssessmentPracticeSubmissionByScope :one +SELECT + submission.id, + submission.practice_id, + submission.mode +FROM assessment_practice_submissions AS submission +WHERE + submission.user_id = sqlc.arg(user_id) + AND submission.idempotency_scope = sqlc.arg(idempotency_scope) +ORDER BY submission.created_at DESC, submission.id DESC +LIMIT 1; + +-- The latest final submission of a practice: the solution the practice +-- state describes. +-- name: GetLatestFinalPracticeSubmission :one +SELECT + submission.id, + submission.language, + submission.source_sha256 +FROM assessment_practice_submissions AS submission +WHERE + submission.practice_id = sqlc.arg(practice_id) + AND submission.mode = 'final' +ORDER BY submission.created_at DESC, submission.id DESC +LIMIT 1; + +-- name: InsertAssessmentPracticeSubmission :exec +INSERT INTO assessment_practice_submissions ( + id, + practice_id, + user_id, + mode, + language, + source, + source_sha256, + custom_tests, + idempotency_scope, + created_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(practice_id), + sqlc.arg(user_id), + sqlc.arg(mode), + sqlc.arg(language), + sqlc.arg(source), + sqlc.arg(source_sha256), + sqlc.narg(custom_tests), + sqlc.arg(idempotency_scope), + sqlc.arg(created_at) +); + +-- Queues the execution job of a submission in the transaction that stores +-- the submission. +-- name: InsertAssessmentPracticeJob :exec +INSERT INTO assessment_practice_jobs ( + submission_id, + mode, + state, + created_at, + updated_at +) VALUES ( + sqlc.arg(submission_id), + sqlc.arg(mode), + 'queued', + sqlc.arg(created_at), + sqlc.arg(created_at) +); + +-- Reads a debug run of the owner's attempt with the state of its job. +-- name: GetAssessmentPracticeRun :one +SELECT + submission.id, + submission.practice_id, + submission.created_at, + submission.result, + job.state, + job.finished_at +FROM assessment_practice_submissions AS submission +INNER JOIN assessment_practices AS practice ON submission.practice_id = practice.id +INNER JOIN assessment_practice_jobs AS job ON submission.id = job.submission_id +WHERE + submission.id = sqlc.arg(id) + AND submission.user_id = sqlc.arg(user_id) + AND submission.mode = 'public' + AND practice.attempt_id = sqlc.arg(attempt_id); diff --git a/backend/integration_test/assessment_practice_http_test.go b/backend/integration_test/assessment_practice_http_test.go new file mode 100644 index 0000000..7ba3a20 --- /dev/null +++ b/backend/integration_test/assessment_practice_http_test.go @@ -0,0 +1,479 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + v1 "lincodex/backend/internal/adapter/primary/http/v1" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/practice" +) + +const ( + assessmentPracticeTimeout = 6 * time.Minute + // practiceHiddenMarker is part of every hidden test text, so a response + // that leaks hidden content is found by a substring search. + practiceHiddenMarker = "hidden-secret" + practiceSource = "print(sum(map(int, input().split())))\n" +) + +func TestAssessmentPracticeSubmissionStorage(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentPracticeTimeout) + defer cancel() + harness := newPracticeHarness(ctx, t, env, func(parts assessmentHarnessParts) (*practice.Service, error) { + return practice.NewService(parts.transactor, parts.keyring, parts.clock.Now, true) + }) + owner := newPracticeCandidate(ctx, t, harness, "practice-owner", 10) + other := newPracticeCandidate(ctx, t, harness, "practice-other", 20) + + t.Run("debug run is stored with its job and shows no hidden content", func(t *testing.T) { + body := practiceRunBody(t, owner.practiceID, "python", practiceSource, []domain.PracticeTest{{Input: "4 5\n", ExpectedOutput: "9\n"}}) + created := practiceRunRequest(t, harness, owner, body, "run-first") + if created.Code != http.StatusAccepted { + t.Fatalf("create run = %d %s", created.Code, created.Body.String()) + } + if created.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("run Cache-Control = %q, want no-store", created.Header().Get("Cache-Control")) + } + run := decodePracticeRun(t, created) + if run.ItemID != owner.practiceID || run.State != "queued" || run.Result != nil || run.FailureReason != nil || run.FinishedAt != nil { + t.Fatalf("created run = %+v, want a queued run of the practice", run) + } + assertPracticeResponseIsPublic(t, created) + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1) + + replay := practiceRunRequest(t, harness, owner, body, "run-first") + if replay.Code != http.StatusAccepted || decodePracticeRun(t, replay).ID != run.ID { + t.Fatalf("same-key replay = %d %s, want the stored run %s", replay.Code, replay.Body.String(), run.ID) + } + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1) + + changed := practiceRunBody(t, owner.practiceID, "python", practiceSource+"# changed\n", nil) + requireSessionProblem(t, practiceRunRequest(t, harness, owner, changed, "run-first"), http.StatusUnprocessableEntity, "idempotency_key_reused") + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1) + + read := practiceRunRead(t, harness, owner, owner.attemptID, run.ID) + if read.Code != http.StatusOK || decodePracticeRun(t, read).ID != run.ID { + t.Fatalf("read run = %d %s", read.Code, read.Body.String()) + } + requireSessionProblem(t, practiceRunRead(t, harness, other, owner.attemptID, run.ID), http.StatusNotFound, "not_found") + requireSessionProblem(t, practiceRunRead(t, harness, owner, owner.attemptID, uuid.New()), http.StatusNotFound, "not_found") + requireSessionProblem(t, practiceRunRead(t, harness, owner, other.attemptID, run.ID), http.StatusNotFound, "not_found") + }) + + t.Run("refusals store nothing", func(t *testing.T) { + foreign := practiceRunBody(t, owner.practiceID, "python", practiceSource, nil) + requireSessionProblem(t, practiceRunRequest(t, harness, other, foreign, "run-foreign"), http.StatusNotFound, "not_found") + closed := practiceRunBody(t, owner.additionalID, "python", practiceSource, nil) + requireSessionProblem(t, practiceRunRequest(t, harness, owner, closed, "run-closed"), http.StatusConflict, "state_conflict") + tooLong := practiceRunBody(t, owner.practiceID, "python", strings.Repeat("x", 1001), nil) + requireSessionProblem(t, practiceRunRequest(t, harness, owner, tooLong, "run-too-long"), http.StatusBadRequest, "validation_failed") + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1) + assertPracticeRows(t, ctx, harness.pool, owner.additionalID, "public", 0) + }) + + t.Run("a stored result is shown without hidden groups", func(t *testing.T) { + body := practiceRunBody(t, owner.practiceID, "go", "package main\nfunc main() {}\n", nil) + created := practiceRunRequest(t, harness, owner, body, "run-with-result") + if created.Code != http.StatusAccepted { + t.Fatalf("create run = %d %s", created.Code, created.Body.String()) + } + run := decodePracticeRun(t, created) + // A result that holds a hidden group, which a debug run never gets, + // proves that the presentation drops it. + storePracticeResult(t, ctx, harness.pool, run.ID, domain.PracticeRunResult{ + Outcome: domain.PracticeOutcomeWrongAnswer, DurationMs: 42, + Groups: []domain.PracticeGroupOutcome{ + {ID: practice.PublicGroupID, Outcome: domain.PracticeOutcomeWrongAnswer, PassedTests: 1, TotalTests: 2, Tests: []domain.PracticeTestOutcome{ + {ID: "1", Outcome: domain.PracticeOutcomeAccepted, TimeMs: 3, MemoryKB: 900}, + {ID: "2", Outcome: domain.PracticeOutcomeWrongAnswer, TimeMs: 4, MemoryKB: 901}, + }}, + {ID: "hidden-1", Hidden: true, Outcome: domain.PracticeOutcomeAccepted, PassedTests: 1, TotalTests: 1}, + }, + }) + read := practiceRunRead(t, harness, owner, owner.attemptID, run.ID) + finished := decodePracticeRun(t, read) + if read.Code != http.StatusOK || finished.State != "finished" || finished.Result == nil || len(finished.Result.Tests) != 2 { + t.Fatalf("finished run = %d %s", read.Code, read.Body.String()) + } + for _, test := range finished.Result.Tests { + if test.Source != "example" { + t.Fatalf("finished run lists a test from %q", test.Source) + } + } + assertPracticeResponseIsPublic(t, read) + }) + + t.Run("final source is stored once and never replaced", func(t *testing.T) { + service := harness.service + command := practice.FinalCommand{ + ActorID: owner.userID, AttemptID: domain.AssessmentAttemptID(owner.attemptID), PracticeID: owner.practiceID, + IdempotencyKey: "final-first", Language: languagePointer(domain.TaskLanguagePython), Source: practiceSource, + } + first, err := service.SubmitFinal(ctx, command) + if err != nil || first.Replayed || first.Unchanged || first.Practice.Status != domain.AssessmentPracticePending || + first.Practice.SubmittedAt == nil || first.Practice.ItemID != owner.practiceID { + t.Fatalf("first final submission = %+v, error %v", first, err) + } + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "final", 1) + + replay, err := service.SubmitFinal(ctx, command) + if err != nil || !replay.Replayed || replay.Practice.Status != domain.AssessmentPracticePending { + t.Fatalf("final replay = %+v, error %v", replay, err) + } + repeat := command + repeat.IdempotencyKey = "final-same-source" + same, err := service.SubmitFinal(ctx, repeat) + if err != nil || !same.Unchanged { + t.Fatalf("same final solution under a new key = %+v, error %v", same, err) + } + other := command + other.IdempotencyKey = "final-other-source" + other.Source = practiceSource + "# another solution\n" + if _, err := service.SubmitFinal(ctx, other); !errors.Is(err, practice.ErrStateConflict) { + t.Fatalf("another final solution error = %v, want state conflict", err) + } + reused := command + reused.Source = other.Source + if _, err := service.SubmitFinal(ctx, reused); !errors.Is(err, practice.ErrKeyReused) { + t.Fatalf("final key reused error = %v, want key reused", err) + } + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "final", 1) + assertFinalSourceIsImmutable(t, ctx, harness.pool, owner.practiceID) + + // A practice that failed in the sandbox accepts a solution again; the + // first one stays stored as it was. + if _, err := harness.pool.Exec(ctx, `UPDATE assessment_practices + SET status = 'failed', failure_reason = 'sandbox_error' WHERE id = $1`, owner.practiceID); err != nil { + t.Fatalf("mark practice failed: %v", err) + } + retry := other + retry.IdempotencyKey = "final-after-failure" + again, err := service.SubmitFinal(ctx, retry) + if err != nil || again.Practice.Status != domain.AssessmentPracticePending || again.Practice.FailureReason != "" { + t.Fatalf("final submission after a sandbox failure = %+v, error %v", again, err) + } + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "final", 2) + }) + + t.Run("disabled runner stores nothing", func(t *testing.T) { + disabled, err := practice.NewService(postgresadapter.NewTransactor(harness.pool), harness.keyring, time.Now, false) + if err != nil { + t.Fatalf("NewService() error = %v", err) + } + _, err = disabled.SubmitRun(ctx, practice.RunCommand{ + ActorID: other.userID, AttemptID: domain.AssessmentAttemptID(other.attemptID), PracticeID: other.practiceID, + IdempotencyKey: "disabled-run", Source: practiceSource, Language: languagePointer(domain.TaskLanguagePython), + }) + if !errors.Is(err, practice.ErrUnavailable) { + t.Fatalf("run with a disabled runner error = %v, want unavailable", err) + } + assertPracticeRows(t, ctx, harness.pool, other.practiceID, "public", 0) + }) + + assertEverySubmissionHasOneJob(t, ctx, harness.pool) +} + +// practiceHarness is the attempt router with the practice operations. +type practiceHarness struct { + *assessmentAttemptHTTPHarness + service *practice.Service + passwordHash domain.PasswordHash +} + +// newPracticeHarness builds the router on an isolated, migrated database with +// the reviewed fixture bank, and the practice service that build returns. +func newPracticeHarness( + ctx context.Context, + t *testing.T, + env *testEnvironment, + build func(assessmentHarnessParts) (*practice.Service, error), +) *practiceHarness { + t.Helper() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + var service *practice.Service + attemptHarness := newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, &isolatedEnv, assessment.AssessmentCategoryDecisionSettings{}, func(parts assessmentHarnessParts) []v1.HandlerOption { + built, err := build(parts) + if err != nil { + t.Fatalf("build practice service: %v", err) + } + service = built + return []v1.HandlerOption{v1.WithPractice(v1.NewPracticeHandler(built))} + }) + seedAssessmentAttemptHTTPBank(ctx, t, attemptHarness.pool) + passwordHash, err := attemptHarness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + return &practiceHarness{assessmentAttemptHTTPHarness: attemptHarness, service: service, passwordHash: passwordHash} +} + +// practiceCandidate is a candidate whose real attempt is at its main practice. +type practiceCandidate struct { + userID uuid.UUID + cookie string + csrf string + remoteAddr string + attemptID uuid.UUID + // practiceID is the main practice, the current item of the attempt. + practiceID uuid.UUID + // additionalID is the additional practice, which is not open while the + // attempt is at the main one. + additionalID uuid.UUID +} + +// newPracticeCandidate registers a candidate, starts a real attempt, moves it +// to practice_pending, and assigns its two practices. hostIndex keeps the +// client addresses of candidates apart. +func newPracticeCandidate(ctx context.Context, t *testing.T, harness *practiceHarness, name string, hostIndex int) practiceCandidate { + t.Helper() + address := func(port int) string { return fmt.Sprintf("192.0.2.%d:%d", hostIndex, port) } + user := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, name+"@example.test", harness.passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", user.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, user.Email.Address(), address(1)) + if response := assessmentAttemptQuestionnaireRequest(t, harness.assessmentAttemptHTTPHarness, cookie.Value, csrf, address(2)); response.Code != http.StatusOK { + t.Fatalf("save questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness.assessmentAttemptHTTPHarness, cookie, csrf, address(3)) + created := assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, name+"-attempt", address(4)) + if created.Code != http.StatusCreated { + t.Fatalf("create attempt = %d %s", created.Code, created.Body.String()) + } + attemptID := assessmentAttemptIDOf(t, created) + // No flow serves practice items yet, so the fixture moves the attempt to + // its main practice the way the item part will end. + if _, err := harness.pool.Exec(ctx, `UPDATE assessment_attempts + SET state = 'practice_pending', version = version + 1, updated_at = greatest(updated_at, clock_timestamp()) + WHERE id = $1`, attemptID); err != nil { + t.Fatalf("move attempt to its practice: %v", err) + } + candidate := practiceCandidate{ + userID: user.ID, cookie: cookie.Value, csrf: csrf, remoteAddr: address(5), attemptID: attemptID, + practiceID: createPractice(ctx, t, harness.pool, user.ID, attemptID, domain.AssessmentPracticeMain), + } + candidate.additionalID = createPractice(ctx, t, harness.pool, user.ID, attemptID, domain.AssessmentPracticeAdditional) + return candidate +} + +func createPractice( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + userID, attemptID uuid.UUID, + kind domain.AssessmentPracticeKind, +) uuid.UUID { + t.Helper() + id, err := uuid.NewV7() + if err != nil { + t.Fatalf("generate practice ID: %v", err) + } + transactor := postgresadapter.NewTransactor(pool) + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.AssessmentPractices().Create(ctx, domain.AssessmentPractice{ + ID: id, AttemptID: domain.AssessmentAttemptID(attemptID), UserID: userID, Kind: kind, Task: practiceTestTask(), + Status: domain.AssessmentPracticeNotStarted, CreatedAt: time.Now().UTC().Truncate(time.Microsecond), + }) + }) + if err != nil { + t.Fatalf("create %s practice: %v", kind, err) + } + return id +} + +// practiceTestTask is a synthetic task whose hidden texts carry +// practiceHiddenMarker. +func practiceTestTask() domain.PracticeTask { + hidden := make([]domain.PracticeTestGroup, 0, domain.PracticeHiddenGroups) + for group := 1; group <= domain.PracticeHiddenGroups; group++ { + hidden = append(hidden, domain.PracticeTestGroup{Tests: []domain.PracticeTest{{ + Input: fmt.Sprintf("%s-input-%d\n", practiceHiddenMarker, group), + ExpectedOutput: fmt.Sprintf("%s-output-%d\n", practiceHiddenMarker, group), + }}}) + } + return domain.PracticeTask{ + Languages: []domain.TaskLanguageCode{domain.TaskLanguagePython, domain.TaskLanguageGo}, + MaxSourceLength: 1000, TimeLimitMs: 1000, MemoryLimitMB: 64, OutputLimitKB: 64, + Checker: domain.PracticeChecker{Kind: domain.PracticeCheckerTokens}, + PublicTests: []domain.PracticeTest{{Input: "1 2\n", ExpectedOutput: "3\n"}, {Input: "2 2\n", ExpectedOutput: "4\n"}}, + HiddenGroups: hidden, + } +} + +func practiceRunBody(t *testing.T, itemID uuid.UUID, language, source string, tests []domain.PracticeTest) string { + t.Helper() + body := map[string]any{"item_id": itemID, "language": language, "source_code": source} + if tests != nil { + body["tests"] = tests + } + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal practice run body: %v", err) + } + return string(encoded) +} + +func practiceRunRequest(t *testing.T, harness *practiceHarness, candidate practiceCandidate, body, key string) *httptest.ResponseRecorder { + t.Helper() + return assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+candidate.attemptID.String()+"/practice-runs", body, + sessionHTTPTestOrigin, candidate.cookie, candidate.csrf, key, candidate.remoteAddr) +} + +func practiceRunRead(t *testing.T, harness *practiceHarness, candidate practiceCandidate, attemptID, runID uuid.UUID) *httptest.ResponseRecorder { + t.Helper() + return assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, http.MethodGet, + "/api/v1/me/assessment-attempts/"+attemptID.String()+"/practice-runs/"+runID.String(), "", + "", candidate.cookie, "", "", candidate.remoteAddr) +} + +type practiceRunResponse struct { + ID uuid.UUID `json:"id"` + ItemID uuid.UUID `json:"item_id"` + State string `json:"state"` + FinishedAt *time.Time `json:"finished_at"` + FailureReason *string `json:"failure_reason"` + Result *struct { + Outcome string `json:"outcome"` + Tests []struct { + Source string `json:"source"` + Index int `json:"index"` + Outcome string `json:"outcome"` + } `json:"tests"` + } `json:"result"` +} + +func decodePracticeRun(t *testing.T, response *httptest.ResponseRecorder) practiceRunResponse { + t.Helper() + var run practiceRunResponse + if err := json.Unmarshal(response.Body.Bytes(), &run); err != nil || run.ID == uuid.Nil { + t.Fatalf("practice run response %d %s: %v", response.Code, response.Body.String(), err) + } + return run +} + +// assertPracticeResponseIsPublic checks that a run response holds only the +// fields of the contract and nothing of the hidden groups or the source. +func assertPracticeResponseIsPublic(t *testing.T, response *httptest.ResponseRecorder) { + t.Helper() + text := response.Body.String() + for _, secret := range []string{practiceHiddenMarker, "hidden-1", "hidden", "print(sum", "expected_output", "input"} { + if strings.Contains(text, secret) { + t.Fatalf("practice run response exposes %q: %s", secret, text) + } + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(response.Body.Bytes(), &fields); err != nil { + t.Fatalf("decode practice run fields: %v", err) + } + allowed := map[string]bool{"id": true, "item_id": true, "state": true, "created_at": true, "finished_at": true, "failure_reason": true, "result": true} + for name := range fields { + if !allowed[name] { + t.Fatalf("practice run response has field %q", name) + } + } +} + +func assertPracticeRows(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, mode string, want int) { + t.Helper() + var submissions, jobs int + if err := pool.QueryRow(ctx, `SELECT count(*), count(job.submission_id) + FROM assessment_practice_submissions AS submission + LEFT JOIN assessment_practice_jobs AS job ON job.submission_id = submission.id + WHERE submission.practice_id = $1 AND submission.mode = $2`, practiceID, mode).Scan(&submissions, &jobs); err != nil { + t.Fatalf("count practice rows: %v", err) + } + if submissions != want || jobs != want { + t.Fatalf("%s submissions = %d with %d jobs, want %d of each", mode, submissions, jobs, want) + } +} + +func assertEverySubmissionHasOneJob(t *testing.T, ctx context.Context, pool *pgxpool.Pool) { + t.Helper() + var orphans int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions AS submission + WHERE NOT EXISTS (SELECT 1 FROM assessment_practice_jobs AS job WHERE job.submission_id = submission.id)`).Scan(&orphans); err != nil { + t.Fatalf("count submissions without a job: %v", err) + } + if orphans != 0 { + t.Fatalf("%d submissions have no execution job", orphans) + } +} + +// assertFinalSourceIsImmutable proves that the database refuses to replace or +// delete a stored final solution, and accepts its result only once. +func assertFinalSourceIsImmutable(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID) { + t.Helper() + var submissionID uuid.UUID + if err := pool.QueryRow(ctx, `SELECT id FROM assessment_practice_submissions WHERE practice_id = $1 AND mode = 'final'`, + practiceID).Scan(&submissionID); err != nil { + t.Fatalf("read final submission: %v", err) + } + statements := map[string]string{ + `UPDATE assessment_practice_submissions SET source = 'print(42)' WHERE id = $1`: "assessment_practice_submission_immutable", + `UPDATE assessment_practice_submissions SET language = 'go' WHERE id = $1`: "assessment_practice_submission_immutable", + `DELETE FROM assessment_practice_submissions WHERE id = $1`: "assessment_practice_submission_delete_forbidden", + } + for statement, constraint := range statements { + _, err := pool.Exec(ctx, statement, submissionID) + requireConstraintViolation(t, err, constraint) + } + setResult := `UPDATE assessment_practice_submissions + SET result = '{"outcome":"accepted","groups":[],"duration_ms":1}', result_at = created_at WHERE id = $1` + if _, err := pool.Exec(ctx, setResult, submissionID); err != nil { + t.Fatalf("store the first result: %v", err) + } + _, err := pool.Exec(ctx, setResult, submissionID) + requireConstraintViolation(t, err, "assessment_practice_submission_immutable") +} + +func requireConstraintViolation(t *testing.T, err error, constraint string) { + t.Helper() + var databaseError *pgconn.PgError + if !errors.As(err, &databaseError) || databaseError.ConstraintName != constraint { + t.Fatalf("statement error = %v, want a violation of %s", err, constraint) + } +} + +func storePracticeResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool, submissionID uuid.UUID, result domain.PracticeRunResult) { + t.Helper() + encoded, err := json.Marshal(result) + if err != nil { + t.Fatalf("marshal practice result: %v", err) + } + if _, err := pool.Exec(ctx, `UPDATE assessment_practice_submissions SET result = $2, result_at = created_at WHERE id = $1`, + submissionID, encoded); err != nil { + t.Fatalf("store practice result: %v", err) + } + if _, err := pool.Exec(ctx, `UPDATE assessment_practice_jobs + SET state = 'finished', finished_at = greatest(created_at, clock_timestamp()), updated_at = greatest(updated_at, clock_timestamp()) + WHERE submission_id = $1`, submissionID); err != nil { + t.Fatalf("finish practice job: %v", err) + } +} + +func languagePointer(language domain.TaskLanguageCode) *domain.TaskLanguageCode { + return &language +} diff --git a/backend/integration_test/organizations_test.go b/backend/integration_test/organizations_test.go index 5dff964..39e4a7b 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -59,6 +59,7 @@ var ( {"candidate_assessment_categories"}, {"assessment_attempt_results"}, {"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"}, {"assessment_answer_observations"}, {"assessment_attempt_origin_marks"}, {"assessment_attempt_reviews"}, + {"assessment_practice_jobs"}, {"assessment_practice_submissions"}, {"assessment_practices"}, {"assessment_attempt_work_leases"}, {"assessment_attempt_items"}, {"assessment_attempts"}, {"assessment_attempt_idempotency_outcomes"}, } supportCaseTables = []pgx.Identifier{ diff --git a/backend/integration_test/policy_test.go b/backend/integration_test/policy_test.go index 2bfdf5e..75fe79c 100644 --- a/backend/integration_test/policy_test.go +++ b/backend/integration_test/policy_test.go @@ -247,7 +247,7 @@ func TestPolicyVersions(t *testing.T) { {name: "truncate", sql: `TRUNCATE policy_versions, company_invitation_quota_usage, company_card_view_quota_usage, assessment_training_bank_bindings, assessment_training_bank_binding_families, assessment_attempts, assessment_attempt_items, - assessment_attempt_work_leases, + assessment_attempt_work_leases, assessment_practice_jobs, assessment_practice_submissions, assessment_practices, support_cases, support_case_events, assessment_signal_idempotency_outcomes, assessment_signal_events, assessment_signal_batches, assessment_attempt_results, assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks, 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 c17b9be..19e7916 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -1482,6 +1482,270 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca } } +// handleCreateMyAssessmentPracticeRunRequest handles CreateMyAssessmentPracticeRun 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 practice item of the attempt and +// carries the language, the source, and up to ten tests of the candidate. +// +// A debug run executes the solution in the isolated sandbox against the public examples of the task +// and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes +// neither the practice state, the verdict, nor the attempt version; the graded solution is submitted +// with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed +// asynchronously: the response is 202 with the run `queued`, and the client polls +// GetMyAssessmentPracticeRun. The source is never echoed. +// +// The practice must be the current item: the attempt is in `practice_pending` for the main practice or +// `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the +// server answers 409 state_conflict. +// +// Availability. When code practice is not enabled on this server, the server answers 503 +// service_unavailable and stores nothing. +// +// Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in +// its current state with 202, without starting another run. A different body with the same key answers +// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are +// evaluated again. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, +// replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of +// another candidate), the state (409), then the solution against the item (400 with a pointer such as +// `/language` or `/source_code`). +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs +func (s *Server) handleCreateMyAssessmentPracticeRunRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CreateMyAssessmentPracticeRun"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/practice-runs"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateMyAssessmentPracticeRunOperation, + 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: CreateMyAssessmentPracticeRunOperation, + ID: "CreateMyAssessmentPracticeRun", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, CreateMyAssessmentPracticeRunOperation, 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, CreateMyAssessmentPracticeRunOperation, 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 := decodeCreateMyAssessmentPracticeRunParams(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.decodeCreateMyAssessmentPracticeRunRequest(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 CreateMyAssessmentPracticeRunRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CreateMyAssessmentPracticeRunOperation, + OperationSummary: "Start a debug run of a practice solution.", + OperationID: "CreateMyAssessmentPracticeRun", + 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 = *PracticeRunCreate + Params = CreateMyAssessmentPracticeRunParams + Response = CreateMyAssessmentPracticeRunRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackCreateMyAssessmentPracticeRunParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.CreateMyAssessmentPracticeRun(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.CreateMyAssessmentPracticeRun(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 := encodeCreateMyAssessmentPracticeRunResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleCreateMySupportCaseRequest handles CreateMySupportCase operation. // // Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and @@ -4265,6 +4529,217 @@ func (s *Server) handleGetMyAssessmentAvailabilityRequest(args [0]string, argsEs } } +// handleGetMyAssessmentPracticeRunRequest handles GetMyAssessmentPracticeRun operation. +// +// Requires the session cookie of a candidate account. Returns the state of a debug run started with +// CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of +// the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source. +// This GET is read-only. +// +// A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer +// 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is +// not readable here. +// +// GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id} +func (s *Server) handleGetMyAssessmentPracticeRunRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyAssessmentPracticeRun"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_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(), GetMyAssessmentPracticeRunOperation, + 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: GetMyAssessmentPracticeRunOperation, + ID: "GetMyAssessmentPracticeRun", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentPracticeRunOperation, 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 := decodeGetMyAssessmentPracticeRunParams(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 GetMyAssessmentPracticeRunRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyAssessmentPracticeRunOperation, + OperationSummary: "Read a debug run of a practice solution.", + OperationID: "GetMyAssessmentPracticeRun", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "attempt_id", + In: "path", + }: params.AttemptID, + { + Name: "run_id", + In: "path", + }: params.RunID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetMyAssessmentPracticeRunParams + Response = GetMyAssessmentPracticeRunRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetMyAssessmentPracticeRunParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyAssessmentPracticeRun(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetMyAssessmentPracticeRun(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 := encodeGetMyAssessmentPracticeRunResponse(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 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 cb13cc2..5e8e678 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -25,6 +25,10 @@ type CreateMyAssessmentAttemptRes interface { createMyAssessmentAttemptRes() } +type CreateMyAssessmentPracticeRunRes interface { + createMyAssessmentPracticeRunRes() +} + type CreateMySupportCaseRes interface { createMySupportCaseRes() } @@ -69,6 +73,10 @@ type GetMyAssessmentAvailabilityRes interface { getMyAssessmentAvailabilityRes() } +type GetMyAssessmentPracticeRunRes interface { + getMyAssessmentPracticeRunRes() +} + type GetMyAssessmentResultRes interface { getMyAssessmentResultRes() } 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 596de49..481d73c 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -18763,6 +18763,234 @@ func (s *CreateMyAssessmentAttemptUnprocessableEntity) UnmarshalJSON(data []byte return s.Decode(d) } +// Encode encodes CreateMyAssessmentPracticeRunBadRequest as json. +func (s *CreateMyAssessmentPracticeRunBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentPracticeRunBadRequest from json. +func (s *CreateMyAssessmentPracticeRunBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentPracticeRunBadRequest 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 = CreateMyAssessmentPracticeRunBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentPracticeRunBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentPracticeRunBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentPracticeRunConflict as json. +func (s *CreateMyAssessmentPracticeRunConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentPracticeRunConflict from json. +func (s *CreateMyAssessmentPracticeRunConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentPracticeRunConflict 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 = CreateMyAssessmentPracticeRunConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentPracticeRunConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentPracticeRunConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentPracticeRunForbidden as json. +func (s *CreateMyAssessmentPracticeRunForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentPracticeRunForbidden from json. +func (s *CreateMyAssessmentPracticeRunForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentPracticeRunForbidden 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 = CreateMyAssessmentPracticeRunForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentPracticeRunForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentPracticeRunForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentPracticeRunNotFound as json. +func (s *CreateMyAssessmentPracticeRunNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentPracticeRunNotFound from json. +func (s *CreateMyAssessmentPracticeRunNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentPracticeRunNotFound 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 = CreateMyAssessmentPracticeRunNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentPracticeRunNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentPracticeRunNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentPracticeRunUnauthorized as json. +func (s *CreateMyAssessmentPracticeRunUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentPracticeRunUnauthorized from json. +func (s *CreateMyAssessmentPracticeRunUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentPracticeRunUnauthorized 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 = CreateMyAssessmentPracticeRunUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentPracticeRunUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentPracticeRunUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentPracticeRunUnprocessableEntity as json. +func (s *CreateMyAssessmentPracticeRunUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentPracticeRunUnprocessableEntity from json. +func (s *CreateMyAssessmentPracticeRunUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentPracticeRunUnprocessableEntity 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 = CreateMyAssessmentPracticeRunUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentPracticeRunUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentPracticeRunUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CreateMySupportCaseBadRequest as json. func (s *CreateMySupportCaseBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -22264,6 +22492,120 @@ func (s *GetMyAssessmentAvailabilityUnauthorized) UnmarshalJSON(data []byte) err return s.Decode(d) } +// Encode encodes GetMyAssessmentPracticeRunForbidden as json. +func (s *GetMyAssessmentPracticeRunForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentPracticeRunForbidden from json. +func (s *GetMyAssessmentPracticeRunForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentPracticeRunForbidden 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 = GetMyAssessmentPracticeRunForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentPracticeRunForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentPracticeRunForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentPracticeRunNotFound as json. +func (s *GetMyAssessmentPracticeRunNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentPracticeRunNotFound from json. +func (s *GetMyAssessmentPracticeRunNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentPracticeRunNotFound 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 = GetMyAssessmentPracticeRunNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentPracticeRunNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentPracticeRunNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentPracticeRunUnauthorized as json. +func (s *GetMyAssessmentPracticeRunUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentPracticeRunUnauthorized from json. +func (s *GetMyAssessmentPracticeRunUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentPracticeRunUnauthorized 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 = GetMyAssessmentPracticeRunUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentPracticeRunUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentPracticeRunUnauthorized) 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) @@ -41700,6 +42042,50 @@ func (s *NilPracticeFailureReason) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes PracticeRunResult as json. +func (o NilPracticeRunResult) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes PracticeRunResult from json. +func (o *NilPracticeRunResult) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilPracticeRunResult to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v PracticeRunResult + 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 NilPracticeRunResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilPracticeRunResult) 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 { @@ -49634,6 +50020,904 @@ func (s *PracticeKind) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *PracticeRun) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeRun) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("item_id") + s.ItemID.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("created_at") + s.CreatedAt.Encode(e) + } + { + e.FieldStart("finished_at") + s.FinishedAt.Encode(e) + } + { + e.FieldStart("failure_reason") + s.FailureReason.Encode(e) + } + { + e.FieldStart("result") + s.Result.Encode(e) + } +} + +var jsonFieldsNameOfPracticeRun = [7]string{ + 0: "id", + 1: "item_id", + 2: "state", + 3: "created_at", + 4: "finished_at", + 5: "failure_reason", + 6: "result", +} + +// Decode decodes PracticeRun from json. +func (s *PracticeRun) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeRun 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 { + 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 "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 "state": + requiredBitSet[0] |= 1 << 2 + 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 "created_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.CreatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"created_at\"") + } + case "finished_at": + requiredBitSet[0] |= 1 << 4 + 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 "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\"") + } + case "result": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.Result.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"result\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PracticeRun") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 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(jsonFieldsNameOfPracticeRun) { + name = jsonFieldsNameOfPracticeRun[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 *PracticeRun) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeRun) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PracticeRunCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeRunCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("item_id") + s.ItemID.Encode(e) + } + { + e.FieldStart("language") + s.Language.Encode(e) + } + { + e.FieldStart("source_code") + e.Str(s.SourceCode) + } + { + if s.Tests != nil { + e.FieldStart("tests") + e.ArrStart() + for _, elem := range s.Tests { + elem.Encode(e) + } + e.ArrEnd() + } + } +} + +var jsonFieldsNameOfPracticeRunCreate = [4]string{ + 0: "item_id", + 1: "language", + 2: "source_code", + 3: "tests", +} + +// Decode decodes PracticeRunCreate from json. +func (s *PracticeRunCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeRunCreate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "item_id": + requiredBitSet[0] |= 1 << 0 + 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 "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\"") + } + case "tests": + if err := func() error { + s.Tests = make([]PracticeRunTest, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem PracticeRunTest + if err := elem.Decode(d); err != nil { + return err + } + s.Tests = append(s.Tests, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tests\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PracticeRunCreate") + } + // 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(jsonFieldsNameOfPracticeRunCreate) { + name = jsonFieldsNameOfPracticeRunCreate[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 *PracticeRunCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeRunCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeRunOutcome as json. +func (s PracticeRunOutcome) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PracticeRunOutcome from json. +func (s *PracticeRunOutcome) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeRunOutcome to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PracticeRunOutcome(v) { + case PracticeRunOutcomeAccepted: + *s = PracticeRunOutcomeAccepted + case PracticeRunOutcomeWrongAnswer: + *s = PracticeRunOutcomeWrongAnswer + case PracticeRunOutcomeCompileError: + *s = PracticeRunOutcomeCompileError + case PracticeRunOutcomeTimeLimitExceeded: + *s = PracticeRunOutcomeTimeLimitExceeded + case PracticeRunOutcomeMemoryLimitExceeded: + *s = PracticeRunOutcomeMemoryLimitExceeded + case PracticeRunOutcomeOutputLimitExceeded: + *s = PracticeRunOutcomeOutputLimitExceeded + case PracticeRunOutcomeRuntimeError: + *s = PracticeRunOutcomeRuntimeError + default: + *s = PracticeRunOutcome(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PracticeRunOutcome) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeRunOutcome) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PracticeRunResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeRunResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("compile_diagnostic") + s.CompileDiagnostic.Encode(e) + } + { + e.FieldStart("tests") + e.ArrStart() + for _, elem := range s.Tests { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfPracticeRunResult = [3]string{ + 0: "outcome", + 1: "compile_diagnostic", + 2: "tests", +} + +// Decode decodes PracticeRunResult from json. +func (s *PracticeRunResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeRunResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "outcome": + requiredBitSet[0] |= 1 << 0 + 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 "compile_diagnostic": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.CompileDiagnostic.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"compile_diagnostic\"") + } + case "tests": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.Tests = make([]PracticeRunTestResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem PracticeRunTestResult + if err := elem.Decode(d); err != nil { + return err + } + s.Tests = append(s.Tests, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tests\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PracticeRunResult") + } + // 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(jsonFieldsNameOfPracticeRunResult) { + name = jsonFieldsNameOfPracticeRunResult[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 *PracticeRunResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeRunResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeRunState as json. +func (s PracticeRunState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PracticeRunState from json. +func (s *PracticeRunState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeRunState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PracticeRunState(v) { + case PracticeRunStateQueued: + *s = PracticeRunStateQueued + case PracticeRunStateRunning: + *s = PracticeRunStateRunning + case PracticeRunStateFinished: + *s = PracticeRunStateFinished + case PracticeRunStateFailed: + *s = PracticeRunStateFailed + default: + *s = PracticeRunState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PracticeRunState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeRunState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PracticeRunTest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeRunTest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("input") + e.Str(s.Input) + } + { + e.FieldStart("expected_output") + e.Str(s.ExpectedOutput) + } +} + +var jsonFieldsNameOfPracticeRunTest = [2]string{ + 0: "input", + 1: "expected_output", +} + +// Decode decodes PracticeRunTest from json. +func (s *PracticeRunTest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeRunTest 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 PracticeRunTest") + } + // 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(jsonFieldsNameOfPracticeRunTest) { + name = jsonFieldsNameOfPracticeRunTest[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 *PracticeRunTest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeRunTest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PracticeRunTestResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PracticeRunTestResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("source") + s.Source.Encode(e) + } + { + e.FieldStart("index") + e.Int32(s.Index) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("time_ms") + e.Int64(s.TimeMs) + } + { + e.FieldStart("memory_kb") + e.Int64(s.MemoryKB) + } + { + e.FieldStart("diagnostic") + s.Diagnostic.Encode(e) + } +} + +var jsonFieldsNameOfPracticeRunTestResult = [6]string{ + 0: "source", + 1: "index", + 2: "outcome", + 3: "time_ms", + 4: "memory_kb", + 5: "diagnostic", +} + +// Decode decodes PracticeRunTestResult from json. +func (s *PracticeRunTestResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeRunTestResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "source": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + case "index": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.Index = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"index\"") + } + case "outcome": + requiredBitSet[0] |= 1 << 2 + 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 "time_ms": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int64() + s.TimeMs = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"time_ms\"") + } + case "memory_kb": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + v, err := d.Int64() + s.MemoryKB = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"memory_kb\"") + } + case "diagnostic": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Diagnostic.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"diagnostic\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PracticeRunTestResult") + } + // 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(jsonFieldsNameOfPracticeRunTestResult) { + name = jsonFieldsNameOfPracticeRunTestResult[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 *PracticeRunTestResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeRunTestResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PracticeRunTestSource as json. +func (s PracticeRunTestSource) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PracticeRunTestSource from json. +func (s *PracticeRunTestSource) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PracticeRunTestSource to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PracticeRunTestSource(v) { + case PracticeRunTestSourceExample: + *s = PracticeRunTestSourceExample + case PracticeRunTestSourceCandidate: + *s = PracticeRunTestSourceCandidate + default: + *s = PracticeRunTestSource(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PracticeRunTestSource) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PracticeRunTestSource) 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)) 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 56cc407..61ab725 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -12,6 +12,7 @@ const ( ConfirmEmailOperation OperationName = "ConfirmEmail" ConfirmEmailByCodeOperation OperationName = "ConfirmEmailByCode" CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt" + CreateMyAssessmentPracticeRunOperation OperationName = "CreateMyAssessmentPracticeRun" CreateMySupportCaseOperation OperationName = "CreateMySupportCase" CreateOrganizationOperation OperationName = "CreateOrganization" CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation" @@ -24,6 +25,7 @@ const ( GetHealthzOperation OperationName = "GetHealthz" GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt" GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability" + GetMyAssessmentPracticeRunOperation OperationName = "GetMyAssessmentPracticeRun" GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult" GetMyAssessmentSignalNoticeOperation OperationName = "GetMyAssessmentSignalNotice" GetMyCardPreviewOperation OperationName = "GetMyCardPreview" 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 38d9126..bc0f880 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -593,6 +593,155 @@ func decodeCreateMyAssessmentAttemptParams(args [0]string, argsEscaped bool, r * return params, nil } +// CreateMyAssessmentPracticeRunParams is parameters of CreateMyAssessmentPracticeRun operation. +type CreateMyAssessmentPracticeRunParams 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 unpackCreateMyAssessmentPracticeRunParams(packed middleware.Parameters) (params CreateMyAssessmentPracticeRunParams) { + { + 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 decodeCreateMyAssessmentPracticeRunParams(args [1]string, argsEscaped bool, r *http.Request) (params CreateMyAssessmentPracticeRunParams, _ 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 +} + // CreateMySupportCaseParams is parameters of CreateMySupportCase operation. type CreateMySupportCaseParams struct { // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value @@ -1523,6 +1672,127 @@ func decodeGetMyAssessmentAttemptParams(args [1]string, argsEscaped bool, r *htt return params, nil } +// GetMyAssessmentPracticeRunParams is parameters of GetMyAssessmentPracticeRun operation. +type GetMyAssessmentPracticeRunParams 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 + // Identifier of a debug run of this attempt. + RunID uuid.UUID +} + +func unpackGetMyAssessmentPracticeRunParams(packed middleware.Parameters) (params GetMyAssessmentPracticeRunParams) { + { + key := middleware.ParameterKey{ + Name: "attempt_id", + In: "path", + } + params.AttemptID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "run_id", + In: "path", + } + params.RunID = packed[key].(uuid.UUID) + } + return params +} + +func decodeGetMyAssessmentPracticeRunParams(args [2]string, argsEscaped bool, r *http.Request) (params GetMyAssessmentPracticeRunParams, _ 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, + } + } + // Decode path: run_id. + if err := func() error { + param := args[1] + if argsEscaped { + unescaped, err := url.PathUnescape(args[1]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "run_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.RunID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "run_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 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 068bbf5..85596ad 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 @@ -488,6 +488,85 @@ func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) ( } } +func (s *Server) decodeCreateMyAssessmentPracticeRunRequest(r *http.Request) ( + req *PracticeRunCreate, + 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 PracticeRunCreate + 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) decodeCreateMySupportCaseRequest(r *http.Request) ( req SupportCaseCreate, rawBody []byte, 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 7740de6..dd9c097 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 @@ -676,6 +676,146 @@ func encodeCreateMyAssessmentAttemptResponse(response CreateMyAssessmentAttemptR } } +func encodeCreateMyAssessmentPracticeRunResponse(response CreateMyAssessmentPracticeRunRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *PracticeRunHeaders: + 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(202) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateMyAssessmentPracticeRunBadRequest: + 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 *CreateMyAssessmentPracticeRunUnauthorized: + 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 *CreateMyAssessmentPracticeRunForbidden: + 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 *CreateMyAssessmentPracticeRunNotFound: + 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 *CreateMyAssessmentPracticeRunConflict: + 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 *CreateMyAssessmentPracticeRunUnprocessableEntity: + 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 *ServiceUnavailableHeaders: + 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(503) + span.SetStatus(codes.Error, http.StatusText(503)) + + 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 encodeCreateMySupportCaseResponse(response CreateMySupportCaseRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *SupportCaseHeaders: @@ -1758,6 +1898,77 @@ func encodeGetMyAssessmentAvailabilityResponse(response GetMyAssessmentAvailabil } } +func encodeGetMyAssessmentPracticeRunResponse(response GetMyAssessmentPracticeRunRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *PracticeRunHeaders: + 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 *GetMyAssessmentPracticeRunUnauthorized: + 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 *GetMyAssessmentPracticeRunForbidden: + 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 *GetMyAssessmentPracticeRunNotFound: + 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 encodeGetMyAssessmentResultResponse(response GetMyAssessmentResultRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *AssessmentResultHeaders: 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 ee96598..6b2ec06 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,7 +11,7 @@ import ( ) var ( - rn86AllowedHeaders = map[string]string{ + rn89AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn9AllowedHeaders = map[string]string{ @@ -20,44 +20,47 @@ var ( rn10AllowedHeaders = map[string]string{ "POST": "Content-Type,Origin", } - rn81AllowedHeaders = map[string]string{ + rn84AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn71AllowedHeaders = map[string]string{ + rn74AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn28AllowedHeaders = map[string]string{ + rn30AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } - rn83AllowedHeaders = map[string]string{ + rn86AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } rn12AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn97AllowedHeaders = map[string]string{ + rn100AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token", } - rn23AllowedHeaders = map[string]string{ + rn25AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn96AllowedHeaders = map[string]string{ + rn15AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn99AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token", } - rn80AllowedHeaders = map[string]string{ + rn83AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn58AllowedHeaders = map[string]string{ + rn61AllowedHeaders = map[string]string{ "DELETE": "X-Attempt-Client,X-Csrf-Token", "PUT": "X-Attempt-Client,X-Csrf-Token", } rn5AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn88AllowedHeaders = map[string]string{ + rn91AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } - rn54AllowedHeaders = map[string]string{ + rn57AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "Content-Type,X-Csrf-Token", } @@ -67,68 +70,68 @@ var ( rn7AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn20AllowedHeaders = map[string]string{ + rn23AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn98AllowedHeaders = map[string]string{ + rn101AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn74AllowedHeaders = map[string]string{ + rn77AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn57AllowedHeaders = map[string]string{ + rn60AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "X-Csrf-Token", } - rn93AllowedHeaders = map[string]string{ + rn96AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn94AllowedHeaders = map[string]string{ + rn97AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn39AllowedHeaders = map[string]string{ + rn42AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn84AllowedHeaders = map[string]string{ + rn87AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn40AllowedHeaders = map[string]string{ + rn43AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn13AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn14AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } rn16AllowedHeaders = map[string]string{ - "PATCH": "Content-Type,X-Csrf-Token", + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn17AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn47AllowedHeaders = map[string]string{ + rn19AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn79AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn91AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn99AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn89AllowedHeaders = map[string]string{ - "POST": "Content-Type,X-Csrf-Token", - } - rn19AllowedHeaders = map[string]string{ + rn20AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn50AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn77AllowedHeaders = map[string]string{ + rn82AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn94AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn102AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn92AllowedHeaders = map[string]string{ + "POST": "Content-Type,X-Csrf-Token", + } + rn22AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn53AllowedHeaders = map[string]string{ + "PATCH": "Content-Type,X-Csrf-Token", + } + rn80AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } ) @@ -285,7 +288,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn86AllowedHeaders, + allowedHeaders: rn89AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -388,7 +391,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn81AllowedHeaders, + allowedHeaders: rn84AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -412,7 +415,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn71AllowedHeaders, + allowedHeaders: rn74AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -439,7 +442,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,GET", - allowedHeaders: rn28AllowedHeaders, + allowedHeaders: rn30AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -492,7 +495,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn83AllowedHeaders, + allowedHeaders: rn86AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -614,7 +617,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn97AllowedHeaders, + allowedHeaders: rn100AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -641,7 +644,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn23AllowedHeaders, + allowedHeaders: rn25AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -650,6 +653,71 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + case 'p': // Prefix: "practice-runs" + + if l := len("practice-runs"); len(elem) >= l && elem[0:l] == "practice-runs" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "POST": + s.handleCreateMyAssessmentPracticeRunRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn15AllowedHeaders, + 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: "run_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[1] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyAssessmentPracticeRunRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + case 'r': // Prefix: "result" if l := len("result"); len(elem) >= l && elem[0:l] == "result" { @@ -707,7 +775,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn96AllowedHeaders, + allowedHeaders: rn99AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -734,7 +802,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn80AllowedHeaders, + allowedHeaders: rn83AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -767,7 +835,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn58AllowedHeaders, + allowedHeaders: rn61AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -976,7 +1044,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE", - allowedHeaders: rn88AllowedHeaders, + allowedHeaders: rn91AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1010,7 +1078,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn54AllowedHeaders, + allowedHeaders: rn57AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1191,7 +1259,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn20AllowedHeaders, + allowedHeaders: rn23AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1218,7 +1286,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn98AllowedHeaders, + allowedHeaders: rn101AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1296,7 +1364,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn74AllowedHeaders, + allowedHeaders: rn77AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1474,7 +1542,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn57AllowedHeaders, + allowedHeaders: rn60AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1565,7 +1633,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn93AllowedHeaders, + allowedHeaders: rn96AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1592,7 +1660,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn94AllowedHeaders, + allowedHeaders: rn97AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1622,7 +1690,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn39AllowedHeaders, + allowedHeaders: rn42AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1647,7 +1715,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn84AllowedHeaders, + allowedHeaders: rn87AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1678,7 +1746,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn40AllowedHeaders, + allowedHeaders: rn43AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1704,7 +1772,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn13AllowedHeaders, + allowedHeaders: rn16AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1768,7 +1836,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn14AllowedHeaders, + allowedHeaders: rn17AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1807,7 +1875,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn16AllowedHeaders, + allowedHeaders: rn19AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -1915,7 +1983,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn17AllowedHeaders, + allowedHeaders: rn20AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1956,7 +2024,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn47AllowedHeaders, + allowedHeaders: rn50AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -2036,7 +2104,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn79AllowedHeaders, + allowedHeaders: rn82AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2064,7 +2132,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn91AllowedHeaders, + allowedHeaders: rn94AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2094,7 +2162,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn99AllowedHeaders, + allowedHeaders: rn102AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2127,7 +2195,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn89AllowedHeaders, + allowedHeaders: rn92AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2169,7 +2237,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn19AllowedHeaders, + allowedHeaders: rn22AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2211,7 +2279,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn50AllowedHeaders, + allowedHeaders: rn53AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -2288,7 +2356,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn77AllowedHeaders, + allowedHeaders: rn80AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -2899,6 +2967,66 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } + case 'p': // Prefix: "practice-runs" + + if l := len("practice-runs"); len(elem) >= l && elem[0:l] == "practice-runs" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "POST": + r.name = CreateMyAssessmentPracticeRunOperation + r.summary = "Start a debug run of a practice solution." + r.operationID = "CreateMyAssessmentPracticeRun" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/practice-runs" + 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 + } + + // Param: "run_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[1] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyAssessmentPracticeRunOperation + r.summary = "Read a debug run of a practice solution." + r.operationID = "GetMyAssessmentPracticeRun" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + } + case 'r': // Prefix: "result" if l := len("result"); len(elem) >= l && elem[0:l] == "result" { 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 4c8310a..5af0d7b 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -9746,6 +9746,30 @@ type CreateMyAssessmentAttemptUnprocessableEntity Problem func (*CreateMyAssessmentAttemptUnprocessableEntity) createMyAssessmentAttemptRes() {} +type CreateMyAssessmentPracticeRunBadRequest Problem + +func (*CreateMyAssessmentPracticeRunBadRequest) createMyAssessmentPracticeRunRes() {} + +type CreateMyAssessmentPracticeRunConflict Problem + +func (*CreateMyAssessmentPracticeRunConflict) createMyAssessmentPracticeRunRes() {} + +type CreateMyAssessmentPracticeRunForbidden Problem + +func (*CreateMyAssessmentPracticeRunForbidden) createMyAssessmentPracticeRunRes() {} + +type CreateMyAssessmentPracticeRunNotFound Problem + +func (*CreateMyAssessmentPracticeRunNotFound) createMyAssessmentPracticeRunRes() {} + +type CreateMyAssessmentPracticeRunUnauthorized Problem + +func (*CreateMyAssessmentPracticeRunUnauthorized) createMyAssessmentPracticeRunRes() {} + +type CreateMyAssessmentPracticeRunUnprocessableEntity Problem + +func (*CreateMyAssessmentPracticeRunUnprocessableEntity) createMyAssessmentPracticeRunRes() {} + type CreateMySupportCaseBadRequest Problem func (*CreateMySupportCaseBadRequest) createMySupportCaseRes() {} @@ -10991,6 +11015,18 @@ type GetMyAssessmentAvailabilityUnauthorized Problem func (*GetMyAssessmentAvailabilityUnauthorized) getMyAssessmentAvailabilityRes() {} +type GetMyAssessmentPracticeRunForbidden Problem + +func (*GetMyAssessmentPracticeRunForbidden) getMyAssessmentPracticeRunRes() {} + +type GetMyAssessmentPracticeRunNotFound Problem + +func (*GetMyAssessmentPracticeRunNotFound) getMyAssessmentPracticeRunRes() {} + +type GetMyAssessmentPracticeRunUnauthorized Problem + +func (*GetMyAssessmentPracticeRunUnauthorized) getMyAssessmentPracticeRunRes() {} + type GetMyAssessmentResultConflict Problem func (*GetMyAssessmentResultConflict) getMyAssessmentResultRes() {} @@ -19952,6 +19988,51 @@ func (o NilPracticeFailureReason) Or(d PracticeFailureReason) PracticeFailureRea return d } +// NewNilPracticeRunResult returns new NilPracticeRunResult with value set to v. +func NewNilPracticeRunResult(v PracticeRunResult) NilPracticeRunResult { + return NilPracticeRunResult{ + Value: v, + } +} + +// NilPracticeRunResult is nullable PracticeRunResult. +type NilPracticeRunResult struct { + Value PracticeRunResult + Null bool +} + +// SetTo sets value to v. +func (o *NilPracticeRunResult) SetTo(v PracticeRunResult) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilPracticeRunResult) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilPracticeRunResult) SetToNull() { + o.Null = true + var v PracticeRunResult + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilPracticeRunResult) Get() (v PracticeRunResult, 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 NilPracticeRunResult) Or(d PracticeRunResult) PracticeRunResult { + 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{ @@ -25883,6 +25964,505 @@ func (s *PracticeKind) UnmarshalText(data []byte) error { } } +// Debug run of a practice solution. It shows only the public examples and the tests of the candidate; +// hidden checks are never run, listed, or scored by a debug run. +// Ref: #/components/schemas/PracticeRun +type PracticeRun struct { + // Identifier of the run. + ID uuid.UUID `json:"id"` + ItemID AssessmentItemId `json:"item_id"` + State PracticeRunState `json:"state"` + CreatedAt Timestamp `json:"created_at"` + // Time the run reached `finished` or `failed`, or null. + FinishedAt NilTimestamp `json:"finished_at"` + // `sandbox_error` when `state` is `failed`, otherwise null. + FailureReason NilPracticeFailureReason `json:"failure_reason"` + // The result when `state` is `finished`, otherwise null. + Result NilPracticeRunResult `json:"result"` +} + +// GetID returns the value of ID. +func (s *PracticeRun) GetID() uuid.UUID { + return s.ID +} + +// GetItemID returns the value of ItemID. +func (s *PracticeRun) GetItemID() AssessmentItemId { + return s.ItemID +} + +// GetState returns the value of State. +func (s *PracticeRun) GetState() PracticeRunState { + return s.State +} + +// GetCreatedAt returns the value of CreatedAt. +func (s *PracticeRun) GetCreatedAt() Timestamp { + return s.CreatedAt +} + +// GetFinishedAt returns the value of FinishedAt. +func (s *PracticeRun) GetFinishedAt() NilTimestamp { + return s.FinishedAt +} + +// GetFailureReason returns the value of FailureReason. +func (s *PracticeRun) GetFailureReason() NilPracticeFailureReason { + return s.FailureReason +} + +// GetResult returns the value of Result. +func (s *PracticeRun) GetResult() NilPracticeRunResult { + return s.Result +} + +// SetID sets the value of ID. +func (s *PracticeRun) SetID(val uuid.UUID) { + s.ID = val +} + +// SetItemID sets the value of ItemID. +func (s *PracticeRun) SetItemID(val AssessmentItemId) { + s.ItemID = val +} + +// SetState sets the value of State. +func (s *PracticeRun) SetState(val PracticeRunState) { + s.State = val +} + +// SetCreatedAt sets the value of CreatedAt. +func (s *PracticeRun) SetCreatedAt(val Timestamp) { + s.CreatedAt = val +} + +// SetFinishedAt sets the value of FinishedAt. +func (s *PracticeRun) SetFinishedAt(val NilTimestamp) { + s.FinishedAt = val +} + +// SetFailureReason sets the value of FailureReason. +func (s *PracticeRun) SetFailureReason(val NilPracticeFailureReason) { + s.FailureReason = val +} + +// SetResult sets the value of Result. +func (s *PracticeRun) SetResult(val NilPracticeRunResult) { + s.Result = val +} + +// Debug run of a practice solution against the public examples of the task and up to ten tests of the +// candidate. It never runs a hidden check and never changes the practice state, the verdict, or the +// attempt version. Unknown fields are rejected. +// Ref: #/components/schemas/PracticeRunCreate +type PracticeRunCreate struct { + ItemID AssessmentItemId `json:"item_id"` + // One of the `languages` of the practice item, or null when the item offers none. + Language NilTaskLanguage `json:"language"` + SourceCode string `json:"source_code"` + // Tests of the candidate, run after the public examples. + Tests []PracticeRunTest `json:"tests"` +} + +// GetItemID returns the value of ItemID. +func (s *PracticeRunCreate) GetItemID() AssessmentItemId { + return s.ItemID +} + +// GetLanguage returns the value of Language. +func (s *PracticeRunCreate) GetLanguage() NilTaskLanguage { + return s.Language +} + +// GetSourceCode returns the value of SourceCode. +func (s *PracticeRunCreate) GetSourceCode() string { + return s.SourceCode +} + +// GetTests returns the value of Tests. +func (s *PracticeRunCreate) GetTests() []PracticeRunTest { + return s.Tests +} + +// SetItemID sets the value of ItemID. +func (s *PracticeRunCreate) SetItemID(val AssessmentItemId) { + s.ItemID = val +} + +// SetLanguage sets the value of Language. +func (s *PracticeRunCreate) SetLanguage(val NilTaskLanguage) { + s.Language = val +} + +// SetSourceCode sets the value of SourceCode. +func (s *PracticeRunCreate) SetSourceCode(val string) { + s.SourceCode = val +} + +// SetTests sets the value of Tests. +func (s *PracticeRunCreate) SetTests(val []PracticeRunTest) { + s.Tests = val +} + +// PracticeRunHeaders wraps PracticeRun with response headers. +type PracticeRunHeaders struct { + CacheControl CacheControlNoStore + Response PracticeRun +} + +// GetCacheControl returns the value of CacheControl. +func (s *PracticeRunHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *PracticeRunHeaders) GetResponse() PracticeRun { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *PracticeRunHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *PracticeRunHeaders) SetResponse(val PracticeRun) { + s.Response = val +} + +func (*PracticeRunHeaders) createMyAssessmentPracticeRunRes() {} +func (*PracticeRunHeaders) getMyAssessmentPracticeRunRes() {} + +// Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation +// error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a +// failed run instead. +// Ref: #/components/schemas/PracticeRunOutcome +type PracticeRunOutcome string + +const ( + PracticeRunOutcomeAccepted PracticeRunOutcome = "accepted" + PracticeRunOutcomeWrongAnswer PracticeRunOutcome = "wrong_answer" + PracticeRunOutcomeCompileError PracticeRunOutcome = "compile_error" + PracticeRunOutcomeTimeLimitExceeded PracticeRunOutcome = "time_limit_exceeded" + PracticeRunOutcomeMemoryLimitExceeded PracticeRunOutcome = "memory_limit_exceeded" + PracticeRunOutcomeOutputLimitExceeded PracticeRunOutcome = "output_limit_exceeded" + PracticeRunOutcomeRuntimeError PracticeRunOutcome = "runtime_error" +) + +// AllValues returns all PracticeRunOutcome values. +func (PracticeRunOutcome) AllValues() []PracticeRunOutcome { + return []PracticeRunOutcome{ + PracticeRunOutcomeAccepted, + PracticeRunOutcomeWrongAnswer, + PracticeRunOutcomeCompileError, + PracticeRunOutcomeTimeLimitExceeded, + PracticeRunOutcomeMemoryLimitExceeded, + PracticeRunOutcomeOutputLimitExceeded, + PracticeRunOutcomeRuntimeError, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PracticeRunOutcome) MarshalText() ([]byte, error) { + switch s { + case PracticeRunOutcomeAccepted: + return []byte(s), nil + case PracticeRunOutcomeWrongAnswer: + return []byte(s), nil + case PracticeRunOutcomeCompileError: + return []byte(s), nil + case PracticeRunOutcomeTimeLimitExceeded: + return []byte(s), nil + case PracticeRunOutcomeMemoryLimitExceeded: + return []byte(s), nil + case PracticeRunOutcomeOutputLimitExceeded: + return []byte(s), nil + case PracticeRunOutcomeRuntimeError: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PracticeRunOutcome) UnmarshalText(data []byte) error { + switch PracticeRunOutcome(data) { + case PracticeRunOutcomeAccepted: + *s = PracticeRunOutcomeAccepted + return nil + case PracticeRunOutcomeWrongAnswer: + *s = PracticeRunOutcomeWrongAnswer + return nil + case PracticeRunOutcomeCompileError: + *s = PracticeRunOutcomeCompileError + return nil + case PracticeRunOutcomeTimeLimitExceeded: + *s = PracticeRunOutcomeTimeLimitExceeded + return nil + case PracticeRunOutcomeMemoryLimitExceeded: + *s = PracticeRunOutcomeMemoryLimitExceeded + return nil + case PracticeRunOutcomeOutputLimitExceeded: + *s = PracticeRunOutcomeOutputLimitExceeded + return nil + case PracticeRunOutcomeRuntimeError: + *s = PracticeRunOutcomeRuntimeError + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Result of a debug run on the public examples and the tests of the candidate. It never contains a +// hidden check, its outcome, or the score. +// Ref: #/components/schemas/PracticeRunResult +type PracticeRunResult struct { + Outcome PracticeRunOutcome `json:"outcome"` + // The compiler message when `outcome` is `compile_error`, otherwise null. + CompileDiagnostic NilString `json:"compile_diagnostic"` + Tests []PracticeRunTestResult `json:"tests"` +} + +// GetOutcome returns the value of Outcome. +func (s *PracticeRunResult) GetOutcome() PracticeRunOutcome { + return s.Outcome +} + +// GetCompileDiagnostic returns the value of CompileDiagnostic. +func (s *PracticeRunResult) GetCompileDiagnostic() NilString { + return s.CompileDiagnostic +} + +// GetTests returns the value of Tests. +func (s *PracticeRunResult) GetTests() []PracticeRunTestResult { + return s.Tests +} + +// SetOutcome sets the value of Outcome. +func (s *PracticeRunResult) SetOutcome(val PracticeRunOutcome) { + s.Outcome = val +} + +// SetCompileDiagnostic sets the value of CompileDiagnostic. +func (s *PracticeRunResult) SetCompileDiagnostic(val NilString) { + s.CompileDiagnostic = val +} + +// SetTests sets the value of Tests. +func (s *PracticeRunResult) SetTests(val []PracticeRunTestResult) { + s.Tests = val +} + +// State of a debug run. +// +// - queued: the run waits in the sandbox queue. +// - running: the sandbox runs it. +// - finished: `result` holds the outcome of the public examples and the tests of the candidate. +// - failed: the sandbox infrastructure could not run it, independently of the solution; +// `failure_reason` is `sandbox_error`. Start a new run. +// +// Adding a value is a contract change. +// Ref: #/components/schemas/PracticeRunState +type PracticeRunState string + +const ( + PracticeRunStateQueued PracticeRunState = "queued" + PracticeRunStateRunning PracticeRunState = "running" + PracticeRunStateFinished PracticeRunState = "finished" + PracticeRunStateFailed PracticeRunState = "failed" +) + +// AllValues returns all PracticeRunState values. +func (PracticeRunState) AllValues() []PracticeRunState { + return []PracticeRunState{ + PracticeRunStateQueued, + PracticeRunStateRunning, + PracticeRunStateFinished, + PracticeRunStateFailed, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PracticeRunState) MarshalText() ([]byte, error) { + switch s { + case PracticeRunStateQueued: + return []byte(s), nil + case PracticeRunStateRunning: + return []byte(s), nil + case PracticeRunStateFinished: + return []byte(s), nil + case PracticeRunStateFailed: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PracticeRunState) UnmarshalText(data []byte) error { + switch PracticeRunState(data) { + case PracticeRunStateQueued: + *s = PracticeRunStateQueued + return nil + case PracticeRunStateRunning: + *s = PracticeRunStateRunning + return nil + case PracticeRunStateFinished: + *s = PracticeRunStateFinished + return nil + case PracticeRunStateFailed: + *s = PracticeRunStateFailed + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One test of the candidate for a debug run: an input and the output the candidate expects. It is +// compared with the checker of the task. +// Ref: #/components/schemas/PracticeRunTest +type PracticeRunTest struct { + Input string `json:"input"` + ExpectedOutput string `json:"expected_output"` +} + +// GetInput returns the value of Input. +func (s *PracticeRunTest) GetInput() string { + return s.Input +} + +// GetExpectedOutput returns the value of ExpectedOutput. +func (s *PracticeRunTest) GetExpectedOutput() string { + return s.ExpectedOutput +} + +// SetInput sets the value of Input. +func (s *PracticeRunTest) SetInput(val string) { + s.Input = val +} + +// SetExpectedOutput sets the value of ExpectedOutput. +func (s *PracticeRunTest) SetExpectedOutput(val string) { + s.ExpectedOutput = val +} + +// Outcome of one evaluated test. The tests of a source stop at the first failed one, so later tests of +// that source are not listed. +// Ref: #/components/schemas/PracticeRunTestResult +type PracticeRunTestResult struct { + Source PracticeRunTestSource `json:"source"` + // Position of the test in its source, from 1. + Index int32 `json:"index"` + Outcome PracticeRunOutcome `json:"outcome"` + TimeMs int64 `json:"time_ms"` + MemoryKB int64 `json:"memory_kb"` + // Truncated error output of a failed test, or null. + Diagnostic NilString `json:"diagnostic"` +} + +// GetSource returns the value of Source. +func (s *PracticeRunTestResult) GetSource() PracticeRunTestSource { + return s.Source +} + +// GetIndex returns the value of Index. +func (s *PracticeRunTestResult) GetIndex() int32 { + return s.Index +} + +// GetOutcome returns the value of Outcome. +func (s *PracticeRunTestResult) GetOutcome() PracticeRunOutcome { + return s.Outcome +} + +// GetTimeMs returns the value of TimeMs. +func (s *PracticeRunTestResult) GetTimeMs() int64 { + return s.TimeMs +} + +// GetMemoryKB returns the value of MemoryKB. +func (s *PracticeRunTestResult) GetMemoryKB() int64 { + return s.MemoryKB +} + +// GetDiagnostic returns the value of Diagnostic. +func (s *PracticeRunTestResult) GetDiagnostic() NilString { + return s.Diagnostic +} + +// SetSource sets the value of Source. +func (s *PracticeRunTestResult) SetSource(val PracticeRunTestSource) { + s.Source = val +} + +// SetIndex sets the value of Index. +func (s *PracticeRunTestResult) SetIndex(val int32) { + s.Index = val +} + +// SetOutcome sets the value of Outcome. +func (s *PracticeRunTestResult) SetOutcome(val PracticeRunOutcome) { + s.Outcome = val +} + +// SetTimeMs sets the value of TimeMs. +func (s *PracticeRunTestResult) SetTimeMs(val int64) { + s.TimeMs = val +} + +// SetMemoryKB sets the value of MemoryKB. +func (s *PracticeRunTestResult) SetMemoryKB(val int64) { + s.MemoryKB = val +} + +// SetDiagnostic sets the value of Diagnostic. +func (s *PracticeRunTestResult) SetDiagnostic(val NilString) { + s.Diagnostic = val +} + +// Where a test of a debug run comes from: a public example of the task or a test of the candidate. +// Ref: #/components/schemas/PracticeRunTestSource +type PracticeRunTestSource string + +const ( + PracticeRunTestSourceExample PracticeRunTestSource = "example" + PracticeRunTestSourceCandidate PracticeRunTestSource = "candidate" +) + +// AllValues returns all PracticeRunTestSource values. +func (PracticeRunTestSource) AllValues() []PracticeRunTestSource { + return []PracticeRunTestSource{ + PracticeRunTestSourceExample, + PracticeRunTestSourceCandidate, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PracticeRunTestSource) MarshalText() ([]byte, error) { + switch s { + case PracticeRunTestSourceExample: + return []byte(s), nil + case PracticeRunTestSourceCandidate: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PracticeRunTestSource) UnmarshalText(data []byte) error { + switch PracticeRunTestSource(data) { + case PracticeRunTestSourceExample: + *s = PracticeRunTestSourceExample + return nil + case PracticeRunTestSourceCandidate: + *s = PracticeRunTestSourceCandidate + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // State of a practice. // // - not_started: no solution was submitted yet. @@ -29631,6 +30211,34 @@ type SendOrganizationInvitationUnprocessableEntity Problem func (*SendOrganizationInvitationUnprocessableEntity) sendOrganizationInvitationRes() {} +// ServiceUnavailableHeaders wraps Problem with response headers. +type ServiceUnavailableHeaders struct { + RetryAfter OptInt32 + Response Problem +} + +// GetRetryAfter returns the value of RetryAfter. +func (s *ServiceUnavailableHeaders) GetRetryAfter() OptInt32 { + return s.RetryAfter +} + +// GetResponse returns the value of Response. +func (s *ServiceUnavailableHeaders) GetResponse() Problem { + return s.Response +} + +// SetRetryAfter sets the value of RetryAfter. +func (s *ServiceUnavailableHeaders) SetRetryAfter(val OptInt32) { + s.RetryAfter = val +} + +// SetResponse sets the value of Response. +func (s *ServiceUnavailableHeaders) SetResponse(val Problem) { + s.Response = val +} + +func (*ServiceUnavailableHeaders) createMyAssessmentPracticeRunRes() {} + // Current session as the client may see it: the account and the CSRF token. The session identifier // itself travels only in the HttpOnly session cookie and never appears in a body. // Ref: #/components/schemas/Session 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 882d8b6..51b1004 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -60,6 +60,7 @@ var operationRolesSessionCookie = map[string][]string{ AcknowledgeMyAssessmentSignalNoticeOperation: []string{}, CancelMyInvitationOperation: []string{}, CreateMyAssessmentAttemptOperation: []string{}, + CreateMyAssessmentPracticeRunOperation: []string{}, CreateMySupportCaseOperation: []string{}, CreateOrganizationOperation: []string{}, CreateOrganizationInvitationOperation: []string{}, @@ -70,6 +71,7 @@ var operationRolesSessionCookie = map[string][]string{ GetCurrentSessionOperation: []string{}, GetMyAssessmentAttemptOperation: []string{}, GetMyAssessmentAvailabilityOperation: []string{}, + GetMyAssessmentPracticeRunOperation: []string{}, GetMyAssessmentResultOperation: []string{}, GetMyAssessmentSignalNoticeOperation: []string{}, GetMyCardPreviewOperation: []string{}, @@ -154,6 +156,7 @@ var operationRolesSessionCsrf = map[string][]string{ AcknowledgeMyAssessmentSignalNoticeOperation: []string{}, CancelMyInvitationOperation: []string{}, CreateMyAssessmentAttemptOperation: []string{}, + CreateMyAssessmentPracticeRunOperation: []string{}, CreateMySupportCaseOperation: []string{}, CreateOrganizationOperation: []string{}, CreateOrganizationInvitationOperation: []string{}, 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 04eb4d9..f592bb0 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -230,6 +230,39 @@ type Handler interface { // // POST /api/v1/me/assessment-attempts CreateMyAssessmentAttempt(ctx context.Context, req AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (CreateMyAssessmentAttemptRes, error) + // CreateMyAssessmentPracticeRun implements CreateMyAssessmentPracticeRun 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 practice item of the attempt and + // carries the language, the source, and up to ten tests of the candidate. + // + // A debug run executes the solution in the isolated sandbox against the public examples of the task + // and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes + // neither the practice state, the verdict, nor the attempt version; the graded solution is submitted + // with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed + // asynchronously: the response is 202 with the run `queued`, and the client polls + // GetMyAssessmentPracticeRun. The source is never echoed. + // + // The practice must be the current item: the attempt is in `practice_pending` for the main practice or + // `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the + // server answers 409 state_conflict. + // + // Availability. When code practice is not enabled on this server, the server answers 503 + // service_unavailable and stores nothing. + // + // Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in + // its current state with 202, without starting another run. A different body with the same key answers + // 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are + // evaluated again. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, + // replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of + // another candidate), the state (409), then the solution against the item (400 with a pointer such as + // `/language` or `/source_code`). + // + // POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs + CreateMyAssessmentPracticeRun(ctx context.Context, req *PracticeRunCreate, params CreateMyAssessmentPracticeRunParams) (CreateMyAssessmentPracticeRunRes, error) // CreateMySupportCase implements CreateMySupportCase operation. // // Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and @@ -627,6 +660,19 @@ type Handler interface { // // GET /api/v1/me/assessment-availability GetMyAssessmentAvailability(ctx context.Context) (GetMyAssessmentAvailabilityRes, error) + // GetMyAssessmentPracticeRun implements GetMyAssessmentPracticeRun operation. + // + // Requires the session cookie of a candidate account. Returns the state of a debug run started with + // CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of + // the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source. + // This GET is read-only. + // + // A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer + // 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is + // not readable here. + // + // GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id} + GetMyAssessmentPracticeRun(ctx context.Context, params GetMyAssessmentPracticeRunParams) (GetMyAssessmentPracticeRunRes, error) // GetMyAssessmentResult implements GetMyAssessmentResult operation. // // Requires the session cookie of a candidate account. Returns the immutable result of a terminal 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 a366cfb..d7e46c8 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -253,6 +253,42 @@ func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req A return r, ht.ErrNotImplemented } +// CreateMyAssessmentPracticeRun implements CreateMyAssessmentPracticeRun 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 practice item of the attempt and +// carries the language, the source, and up to ten tests of the candidate. +// +// A debug run executes the solution in the isolated sandbox against the public examples of the task +// and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes +// neither the practice state, the verdict, nor the attempt version; the graded solution is submitted +// with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed +// asynchronously: the response is 202 with the run `queued`, and the client polls +// GetMyAssessmentPracticeRun. The source is never echoed. +// +// The practice must be the current item: the attempt is in `practice_pending` for the main practice or +// `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the +// server answers 409 state_conflict. +// +// Availability. When code practice is not enabled on this server, the server answers 503 +// service_unavailable and stores nothing. +// +// Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in +// its current state with 202, without starting another run. A different body with the same key answers +// 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are +// evaluated again. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, +// replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of +// another candidate), the state (409), then the solution against the item (400 with a pointer such as +// `/language` or `/source_code`). +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs +func (UnimplementedHandler) CreateMyAssessmentPracticeRun(ctx context.Context, req *PracticeRunCreate, params CreateMyAssessmentPracticeRunParams) (r CreateMyAssessmentPracticeRunRes, _ error) { + return r, ht.ErrNotImplemented +} + // CreateMySupportCase implements CreateMySupportCase operation. // // Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and @@ -686,6 +722,22 @@ func (UnimplementedHandler) GetMyAssessmentAvailability(ctx context.Context) (r return r, ht.ErrNotImplemented } +// GetMyAssessmentPracticeRun implements GetMyAssessmentPracticeRun operation. +// +// Requires the session cookie of a candidate account. Returns the state of a debug run started with +// CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of +// the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source. +// This GET is read-only. +// +// A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer +// 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is +// not readable here. +// +// GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id} +func (UnimplementedHandler) GetMyAssessmentPracticeRun(ctx context.Context, params GetMyAssessmentPracticeRunParams) (r GetMyAssessmentPracticeRunRes, _ error) { + return r, ht.ErrNotImplemented +} + // GetMyAssessmentResult implements GetMyAssessmentResult operation. // // Requires the session cookie of a candidate account. Returns the immutable result of a terminal 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 356f8d9..200a0e8 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -8873,6 +8873,54 @@ func (s *CreateMyAssessmentAttemptUnprocessableEntity) Validate() error { return nil } +func (s *CreateMyAssessmentPracticeRunBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentPracticeRunConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentPracticeRunForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentPracticeRunNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentPracticeRunUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentPracticeRunUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *CreateMySupportCaseBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -10072,6 +10120,30 @@ func (s *GetMyAssessmentAvailabilityUnauthorized) Validate() error { return nil } +func (s *GetMyAssessmentPracticeRunForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentPracticeRunNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentPracticeRunUnauthorized) 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 { @@ -19468,6 +19540,509 @@ func (s PracticeKind) Validate() error { } } +func (s *PracticeRun) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + 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 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 err := func() error { + if value, ok := s.Result.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: "result", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *PracticeRunCreate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + 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 err := func() error { + if s.Tests == nil { + return nil // optional + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.Tests)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Tests { + 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: "tests", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *PracticeRunHeaders) 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 PracticeRunOutcome) Validate() error { + switch s { + case "accepted": + return nil + case "wrong_answer": + return nil + case "compile_error": + return nil + case "time_limit_exceeded": + return nil + case "memory_limit_exceeded": + return nil + case "output_limit_exceeded": + return nil + case "runtime_error": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *PracticeRunResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + 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.CompileDiagnostic.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 4096, + 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: "compile_diagnostic", + Error: err, + }) + } + if err := func() error { + if s.Tests == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Tests)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Tests { + 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: "tests", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s PracticeRunState) Validate() error { + switch s { + case "queued": + return nil + case "running": + return nil + case "finished": + return nil + case "failed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *PracticeRunTest) 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 *PracticeRunTestResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Source.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + 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.Index)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "index", + 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 err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TimeMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "time_ms", + Error: err, + }) + } + 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.MemoryKB)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "memory_kb", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Diagnostic.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2048, + 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: "diagnostic", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s PracticeRunTestSource) Validate() error { + switch s { + case "example": + return nil + case "candidate": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s PracticeStatus) Validate() error { switch s { case "not_started": @@ -23633,6 +24208,57 @@ func (s *SendOrganizationInvitationUnprocessableEntity) Validate() error { return nil } +func (s *ServiceUnavailableHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if value, ok := s.RetryAfter.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 86400, + 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: "RetryAfter", + 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 *Session) Validate() error { if s == nil { return validate.ErrNilPointer diff --git a/backend/internal/adapter/primary/http/v1/api.go b/backend/internal/adapter/primary/http/v1/api.go index 15b98ec..560a5ba 100644 --- a/backend/internal/adapter/primary/http/v1/api.go +++ b/backend/internal/adapter/primary/http/v1/api.go @@ -29,6 +29,7 @@ type Handler struct { support *SupportHandler assessment *AssessmentHandler assessmentSignals *AssessmentSignalHandler + practice *PracticeHandler privacy *PrivacyHandler evidence *EvidenceHandler matches *MatchHandler @@ -96,6 +97,11 @@ func WithAssessmentSignals(signals *AssessmentSignalHandler) HandlerOption { return func(handler *Handler) { handler.assessmentSignals = signals } } +// WithPractice serves the debug runs of code practices. +func WithPractice(practice *PracticeHandler) HandlerOption { + return func(handler *Handler) { handler.practice = practice } +} + // WithPrivacy serves current publication and candidate-card visibility operations. func WithPrivacy(privacy *PrivacyHandler) HandlerOption { return func(handler *Handler) { handler.privacy = privacy } diff --git a/backend/internal/adapter/primary/http/v1/practice.go b/backend/internal/adapter/primary/http/v1/practice.go new file mode 100644 index 0000000..50be5ef --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/practice.go @@ -0,0 +1,210 @@ +package v1 + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/practice" +) + +// PracticeOperations serves the debug runs of code practices. +type PracticeOperations interface { + SubmitRun(ctx context.Context, command practice.RunCommand) (practice.RunResult, error) + GetRun(ctx context.Context, actorID uuid.UUID, attemptID domain.AssessmentAttemptID, runID uuid.UUID) (domain.PracticeRunView, error) +} + +// PracticeHandler binds the practice usecases to the v1 API. +type PracticeHandler struct { + operations PracticeOperations +} + +func NewPracticeHandler(operations PracticeOperations) *PracticeHandler { + if operations == nil { + panic("v1.NewPracticeHandler - operations must not be nil") + } + return &PracticeHandler{operations: operations} +} + +func (handler *Handler) CreateMyAssessmentPracticeRun( + ctx context.Context, + request *api.PracticeRunCreate, + params api.CreateMyAssessmentPracticeRunParams, +) (api.CreateMyAssessmentPracticeRunRes, error) { + if handler.practice == nil { + return handler.UnimplementedHandler.CreateMyAssessmentPracticeRun(ctx, request, params) + } + return handler.practice.CreateMyAssessmentPracticeRun(ctx, request, params) +} + +func (handler *Handler) GetMyAssessmentPracticeRun( + ctx context.Context, + params api.GetMyAssessmentPracticeRunParams, +) (api.GetMyAssessmentPracticeRunRes, error) { + if handler.practice == nil { + return handler.UnimplementedHandler.GetMyAssessmentPracticeRun(ctx, params) + } + return handler.practice.GetMyAssessmentPracticeRun(ctx, params) +} + +func (handler *PracticeHandler) CreateMyAssessmentPracticeRun( + ctx context.Context, + request *api.PracticeRunCreate, + params api.CreateMyAssessmentPracticeRunParams, +) (api.CreateMyAssessmentPracticeRunRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.CreateMyAssessmentPracticeRunUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if request == nil { + return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil + } + command := practice.RunCommand{ + ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID), + PracticeID: uuid.UUID(request.ItemID), IdempotencyKey: params.IdempotencyKey, Source: request.SourceCode, + Tests: make([]domain.PracticeTest, 0, len(request.Tests)), + } + if !request.Language.Null { + language := domain.TaskLanguageCode(request.Language.Value) + command.Language = &language + } + for _, test := range request.Tests { + command.Tests = append(command.Tests, domain.PracticeTest{Input: test.Input, ExpectedOutput: test.ExpectedOutput}) + } + result, err := handler.operations.SubmitRun(ctx, command) + if err != nil { + return practiceRunFailure(ctx, err) + } + response, err := practiceRunResponse(result.Run) + if err != nil { + return nil, fmt.Errorf("PracticeHandler.CreateMyAssessmentPracticeRun - map run: %w", err) + } + return &api.PracticeRunHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil +} + +func (handler *PracticeHandler) GetMyAssessmentPracticeRun( + ctx context.Context, + params api.GetMyAssessmentPracticeRunParams, +) (api.GetMyAssessmentPracticeRunRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.GetMyAssessmentPracticeRunUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + run, err := handler.operations.GetRun(ctx, principal.UserID, domain.AssessmentAttemptID(params.AttemptID), params.RunID) + switch { + case errors.Is(err, practice.ErrForbidden): + return (*api.GetMyAssessmentPracticeRunForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, practice.ErrNotFound): + return (*api.GetMyAssessmentPracticeRunNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case err != nil: + return nil, err + } + response, err := practiceRunResponse(run) + if err != nil { + return nil, fmt.Errorf("PracticeHandler.GetMyAssessmentPracticeRun - map run: %w", err) + } + return &api.PracticeRunHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil +} + +func practiceRunFailure(ctx context.Context, err error) (api.CreateMyAssessmentPracticeRunRes, error) { + var fieldError *practice.FieldError + switch { + case errors.As(err, &fieldError): + return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "/"+fieldError.Field).Response), nil + case errors.Is(err, practice.ErrInvalidKey): + return (*api.CreateMyAssessmentPracticeRunBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil + case errors.Is(err, practice.ErrForbidden): + return (*api.CreateMyAssessmentPracticeRunForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, practice.ErrUnavailable): + unavailable := problem.New(ctx, api.ProblemCodeServiceUnavailable) + return &api.ServiceUnavailableHeaders{Response: unavailable.Response}, nil + case errors.Is(err, practice.ErrKeyReused): + return (*api.CreateMyAssessmentPracticeRunUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil + case errors.Is(err, practice.ErrNotFound): + return (*api.CreateMyAssessmentPracticeRunNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case errors.Is(err, practice.ErrStateConflict): + return (*api.CreateMyAssessmentPracticeRunConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil + default: + return nil, err + } +} + +// practiceRunResponse maps a run to its public form. It reads only the public +// groups of the result, so a hidden group could never reach the response +// even if one were stored with a debug run. +func practiceRunResponse(run domain.PracticeRunView) (api.PracticeRun, error) { + response := api.PracticeRun{ + ID: run.ID, ItemID: api.AssessmentItemId(run.PracticeID), CreatedAt: api.Timestamp(run.CreatedAt.UTC()), + FinishedAt: api.NilTimestamp{Null: true}, FailureReason: api.NilPracticeFailureReason{Null: true}, + Result: api.NilPracticeRunResult{Null: true}, + } + switch run.State { + case domain.PracticeJobQueued: + response.State = api.PracticeRunStateQueued + case domain.PracticeJobRunning: + response.State = api.PracticeRunStateRunning + case domain.PracticeJobFinished: + response.State = api.PracticeRunStateFinished + case domain.PracticeJobFailed: + response.State = api.PracticeRunStateFailed + response.FailureReason = api.NewNilPracticeFailureReason(api.PracticeFailureReasonSandboxError) + default: + return api.PracticeRun{}, errors.New("v1.practiceRunResponse - run state is unknown") + } + if run.FinishedAt != nil { + response.FinishedAt = api.NewNilTimestamp(api.Timestamp(run.FinishedAt.UTC())) + } + if run.State == domain.PracticeJobFinished && run.Result != nil { + result, err := practiceRunResultResponse(run.Result.Public()) + if err != nil { + return api.PracticeRun{}, err + } + response.Result = api.NewNilPracticeRunResult(result) + } + return response, nil +} + +func practiceRunResultResponse(result domain.PracticeRunResult) (api.PracticeRunResult, error) { + response := api.PracticeRunResult{ + Outcome: api.PracticeRunOutcome(result.Outcome), CompileDiagnostic: api.NilString{Null: true}, + Tests: []api.PracticeRunTestResult{}, + } + if result.CompileDiagnostic != "" { + response.CompileDiagnostic = api.NewNilString(result.CompileDiagnostic) + } + for _, group := range result.Groups { + var source api.PracticeRunTestSource + switch { + case group.Hidden: + continue + case group.ID == practice.PublicGroupID: + source = api.PracticeRunTestSourceExample + case group.ID == practice.CustomGroupID: + source = api.PracticeRunTestSourceCandidate + default: + return api.PracticeRunResult{}, errors.New("v1.practiceRunResultResponse - group is unknown") + } + for _, test := range group.Tests { + index, err := strconv.ParseInt(test.ID, 10, 32) + if err != nil || index < 1 { + return api.PracticeRunResult{}, errors.New("v1.practiceRunResultResponse - test index is invalid") + } + item := api.PracticeRunTestResult{ + Source: source, Index: int32(index), Outcome: api.PracticeRunOutcome(test.Outcome), + TimeMs: test.TimeMs, MemoryKB: test.MemoryKB, Diagnostic: api.NilString{Null: true}, + } + if diagnostic := strings.TrimSpace(test.Diagnostic); diagnostic != "" { + item.Diagnostic = api.NewNilString(test.Diagnostic) + } + response.Tests = append(response.Tests, item) + } + } + return response, nil +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_practice.go b/backend/internal/adapter/secondary/postgres/assessment_practice.go new file mode 100644 index 0000000..f4a9ccf --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_practice.go @@ -0,0 +1,285 @@ +package postgres + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var _ outbound.AssessmentPracticeRepositories = (*UnitOfWork)(nil) + +func (unit *UnitOfWork) AssessmentPractices() outbound.AssessmentPracticeRepository { + return assessmentPracticeRepository{queries: unit.queries} +} + +type assessmentPracticeRepository struct { + queries *sqlc.Queries +} + +func (repository assessmentPracticeRepository) Create(ctx context.Context, practice domain.AssessmentPractice) error { + const location = "assessmentPracticeRepository.Create" + if practice.Status != domain.AssessmentPracticeNotStarted { + return fmt.Errorf("%s - a new practice must not be started: %w", location, domain.ErrInvalidAssessmentPractice) + } + if err := practice.Validate(); err != nil { + return fmt.Errorf("%s - validate practice: %w", location, err) + } + task, err := json.Marshal(practice.Task) + if err != nil { + return fmt.Errorf("%s - encode task: %w", location, domain.ErrInvalidAssessmentPractice) + } + if err := repository.queries.InsertAssessmentPractice(ctx, sqlc.InsertAssessmentPracticeParams{ + ID: pgUUID(practice.ID), AttemptID: pgUUID(practice.AttemptID.UUID()), UserID: pgUUID(practice.UserID), + Kind: string(practice.Kind), Task: task, CreatedAt: pgTime(practice.CreatedAt), + }); err != nil { + return fmt.Errorf("%s - insert practice: %w", location, mapAssessmentError(err)) + } + return nil +} + +func (repository assessmentPracticeRepository) LockAttempt( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, +) (outbound.PracticeAttemptLock, error) { + const location = "assessmentPracticeRepository.LockAttempt" + row, err := repository.queries.LockAssessmentAttemptForPractice(ctx, sqlc.LockAssessmentAttemptForPracticeParams{ + AttemptID: pgUUID(attemptID.UUID()), UserID: pgUUID(userID), + }) + if isNoRows(err) { + return outbound.PracticeAttemptLock{}, fmt.Errorf("%s - lock attempt: %w", location, outbound.ErrAssessmentAttemptNotFound) + } + if err != nil { + return outbound.PracticeAttemptLock{}, fmt.Errorf("%s - lock attempt: %w", location, mapAssessmentError(err)) + } + if !row.ExpiresAt.Valid || !row.DatabaseTime.Valid { + return outbound.PracticeAttemptLock{}, errors.New(location + " - attempt deadline or database time is missing") + } + return outbound.PracticeAttemptLock{ + State: domain.AssessmentAttemptState(row.State), + ExpiresAt: row.ExpiresAt.Time.UTC(), + DatabaseTime: row.DatabaseTime.Time.UTC().Truncate(time.Microsecond), + }, nil +} + +func (repository assessmentPracticeRepository) LockPractice( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, + practiceID uuid.UUID, +) (domain.AssessmentPractice, error) { + const location = "assessmentPracticeRepository.LockPractice" + row, err := repository.queries.LockAssessmentPractice(ctx, sqlc.LockAssessmentPracticeParams{ + ID: pgUUID(practiceID), AttemptID: pgUUID(attemptID.UUID()), UserID: pgUUID(userID), + }) + if isNoRows(err) { + return domain.AssessmentPractice{}, fmt.Errorf("%s - lock practice: %w", location, outbound.ErrAssessmentPracticeNotFound) + } + if err != nil { + return domain.AssessmentPractice{}, fmt.Errorf("%s - lock practice: %w", location, mapAssessmentError(err)) + } + practice, err := restorePractice(practiceRow{ + ID: row.ID, AttemptID: row.AttemptID, UserID: row.UserID, Kind: row.Kind, Task: row.Task, Status: row.Status, + FailureReason: row.FailureReason, SubmittedAt: row.SubmittedAt, CreatedAt: row.CreatedAt, + }) + if err != nil { + return domain.AssessmentPractice{}, fmt.Errorf("%s - restore practice: %w", location, err) + } + return practice, nil +} + +func (repository assessmentPracticeRepository) SaveState(ctx context.Context, practice domain.AssessmentPractice, updatedAt time.Time) error { + const location = "assessmentPracticeRepository.SaveState" + if err := practice.Validate(); err != nil { + return fmt.Errorf("%s - validate practice: %w", location, err) + } + if updatedAt.IsZero() { + return errors.New(location + " - update time is required") + } + submittedAt := pgtype.Timestamptz{} + if !practice.SubmittedAt.IsZero() { + submittedAt = pgTime(practice.SubmittedAt) + } + updated, err := repository.queries.UpdateAssessmentPracticeState(ctx, sqlc.UpdateAssessmentPracticeStateParams{ + ID: pgUUID(practice.ID), Status: string(practice.Status), FailureReason: pgOptionalText(string(practice.FailureReason)), + SubmittedAt: submittedAt, UpdatedAt: pgTime(updatedAt), + }) + if err != nil { + return fmt.Errorf("%s - update practice: %w", location, mapAssessmentError(err)) + } + if updated != 1 { + return fmt.Errorf("%s - update practice: %w", location, outbound.ErrAssessmentPracticeNotFound) + } + return nil +} + +func (repository assessmentPracticeRepository) FindByScope( + ctx context.Context, + userID uuid.UUID, + scope [outbound.IdempotencyDigestSize]byte, +) (outbound.PracticeSubmissionReplay, bool, error) { + const location = "assessmentPracticeRepository.FindByScope" + row, err := repository.queries.FindAssessmentPracticeSubmissionByScope(ctx, sqlc.FindAssessmentPracticeSubmissionByScopeParams{ + UserID: pgUUID(userID), IdempotencyScope: scope[:], + }) + if isNoRows(err) { + return outbound.PracticeSubmissionReplay{}, false, nil + } + if err != nil { + return outbound.PracticeSubmissionReplay{}, false, fmt.Errorf("%s - find submission: %w", location, mapAssessmentError(err)) + } + if !row.ID.Valid || !row.PracticeID.Valid || !domain.PracticeSubmissionMode(row.Mode).IsKnown() { + return outbound.PracticeSubmissionReplay{}, false, fmt.Errorf("%s - stored submission is incomplete: %w", location, domain.ErrInvalidAssessmentPractice) + } + return outbound.PracticeSubmissionReplay{ + ID: row.ID.Bytes, PracticeID: row.PracticeID.Bytes, Mode: domain.PracticeSubmissionMode(row.Mode), + }, true, nil +} + +func (repository assessmentPracticeRepository) LatestFinal(ctx context.Context, practiceID uuid.UUID) (outbound.PracticeFinalSolution, bool, error) { + const location = "assessmentPracticeRepository.LatestFinal" + row, err := repository.queries.GetLatestFinalPracticeSubmission(ctx, pgUUID(practiceID)) + if isNoRows(err) { + return outbound.PracticeFinalSolution{}, false, nil + } + if err != nil { + return outbound.PracticeFinalSolution{}, false, fmt.Errorf("%s - read latest final submission: %w", location, mapAssessmentError(err)) + } + solution := outbound.PracticeFinalSolution{SubmissionID: row.ID.Bytes, Language: domain.TaskLanguageCode(row.Language)} + if !row.ID.Valid || !solution.Language.IsKnown() || len(row.SourceSha256) != len(solution.SourceDigest) { + return outbound.PracticeFinalSolution{}, false, fmt.Errorf("%s - stored submission is incomplete: %w", location, domain.ErrInvalidAssessmentPractice) + } + copy(solution.SourceDigest[:], row.SourceSha256) + return solution, true, nil +} + +func (repository assessmentPracticeRepository) Submit( + ctx context.Context, + submission domain.PracticeSubmission, + scope [outbound.IdempotencyDigestSize]byte, +) error { + const location = "assessmentPracticeRepository.Submit" + if submission.ID == uuid.Nil || submission.PracticeID == uuid.Nil || submission.UserID == uuid.Nil || + !submission.Mode.IsKnown() || !submission.Language.IsKnown() || submission.CreatedAt.IsZero() { + return fmt.Errorf("%s - submission is incomplete: %w", location, domain.ErrInvalidAssessmentPractice) + } + var customTests []byte + if len(submission.CustomTests) > 0 { + encoded, err := json.Marshal(submission.CustomTests) + if err != nil { + return fmt.Errorf("%s - encode custom tests: %w", location, domain.ErrInvalidAssessmentPractice) + } + customTests = encoded + } + digest := domain.DigestPracticeSource(submission.Source) + if err := repository.queries.InsertAssessmentPracticeSubmission(ctx, sqlc.InsertAssessmentPracticeSubmissionParams{ + ID: pgUUID(submission.ID), PracticeID: pgUUID(submission.PracticeID), UserID: pgUUID(submission.UserID), + Mode: string(submission.Mode), Language: string(submission.Language), Source: submission.Source, + SourceSha256: digest[:], CustomTests: customTests, IdempotencyScope: scope[:], CreatedAt: pgTime(submission.CreatedAt), + }); err != nil { + return fmt.Errorf("%s - insert submission: %w", location, mapAssessmentError(err)) + } + if err := repository.queries.InsertAssessmentPracticeJob(ctx, sqlc.InsertAssessmentPracticeJobParams{ + SubmissionID: pgUUID(submission.ID), Mode: string(submission.Mode), CreatedAt: pgTime(submission.CreatedAt), + }); err != nil { + return fmt.Errorf("%s - queue job: %w", location, mapAssessmentError(err)) + } + return nil +} + +func (repository assessmentPracticeRepository) GetRun( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, + runID uuid.UUID, +) (domain.PracticeRunView, error) { + const location = "assessmentPracticeRepository.GetRun" + row, err := repository.queries.GetAssessmentPracticeRun(ctx, sqlc.GetAssessmentPracticeRunParams{ + ID: pgUUID(runID), UserID: pgUUID(userID), AttemptID: pgUUID(attemptID.UUID()), + }) + if isNoRows(err) { + return domain.PracticeRunView{}, fmt.Errorf("%s - read run: %w", location, outbound.ErrPracticeRunNotFound) + } + if err != nil { + return domain.PracticeRunView{}, fmt.Errorf("%s - read run: %w", location, mapAssessmentError(err)) + } + view := domain.PracticeRunView{ + ID: row.ID.Bytes, PracticeID: row.PracticeID.Bytes, State: domain.PracticeJobState(row.State), + CreatedAt: row.CreatedAt.Time.UTC(), + } + if !row.ID.Valid || !row.PracticeID.Valid || !row.CreatedAt.Valid || !view.State.IsKnown() { + return domain.PracticeRunView{}, fmt.Errorf("%s - stored run is incomplete: %w", location, domain.ErrInvalidAssessmentPractice) + } + if row.FinishedAt.Valid { + finishedAt := row.FinishedAt.Time.UTC() + view.FinishedAt = &finishedAt + } + if len(row.Result) > 0 { + result, err := decodePracticeRunResult(row.Result) + if err != nil { + return domain.PracticeRunView{}, fmt.Errorf("%s - restore result: %w", location, err) + } + public := result.Public() + view.Result = &public + } + return view, nil +} + +// practiceRow is the stored form of a practice that several queries read. +type practiceRow struct { + ID pgtype.UUID + AttemptID pgtype.UUID + UserID pgtype.UUID + Kind string + Task []byte + Status string + FailureReason pgtype.Text + SubmittedAt pgtype.Timestamptz + CreatedAt pgtype.Timestamptz +} + +func restorePractice(row practiceRow) (domain.AssessmentPractice, error) { + const location = "postgres.restorePractice" + if !row.ID.Valid || !row.AttemptID.Valid || !row.UserID.Valid || !row.CreatedAt.Valid { + return domain.AssessmentPractice{}, fmt.Errorf("%s - stored practice is incomplete: %w", location, domain.ErrInvalidAssessmentPractice) + } + var task domain.PracticeTask + if err := json.Unmarshal(row.Task, &task); err != nil { + return domain.AssessmentPractice{}, fmt.Errorf("%s - decode task: %w", location, domain.ErrInvalidAssessmentPractice) + } + practice := domain.AssessmentPractice{ + ID: row.ID.Bytes, AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes), UserID: row.UserID.Bytes, + Kind: domain.AssessmentPracticeKind(row.Kind), Task: task, Status: domain.AssessmentPracticeStatus(row.Status), + CreatedAt: row.CreatedAt.Time.UTC(), + } + if row.FailureReason.Valid { + practice.FailureReason = domain.AssessmentPracticeFailureReason(row.FailureReason.String) + } + if row.SubmittedAt.Valid { + practice.SubmittedAt = row.SubmittedAt.Time.UTC() + } + if err := practice.Validate(); err != nil { + return domain.AssessmentPractice{}, fmt.Errorf("%s - validate practice: %w", location, err) + } + return practice, nil +} + +func decodePracticeRunResult(encoded []byte) (domain.PracticeRunResult, error) { + var result domain.PracticeRunResult + if err := json.Unmarshal(encoded, &result); err != nil { + return domain.PracticeRunResult{}, fmt.Errorf("postgres.decodePracticeRunResult - decode result: %w", domain.ErrInvalidAssessmentPractice) + } + if err := result.Validate(); err != nil { + return domain.PracticeRunResult{}, fmt.Errorf("postgres.decodePracticeRunResult - validate result: %w", err) + } + return result, nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice.sql.go new file mode 100644 index 0000000..bf6399f --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_practice.sql.go @@ -0,0 +1,377 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: assessment_practice.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const findAssessmentPracticeSubmissionByScope = `-- name: FindAssessmentPracticeSubmissionByScope :one +SELECT + submission.id, + submission.practice_id, + submission.mode +FROM assessment_practice_submissions AS submission +WHERE + submission.user_id = $1 + AND submission.idempotency_scope = $2 +ORDER BY submission.created_at DESC, submission.id DESC +LIMIT 1 +` + +type FindAssessmentPracticeSubmissionByScopeParams struct { + UserID pgtype.UUID + IdempotencyScope []byte +} + +type FindAssessmentPracticeSubmissionByScopeRow struct { + ID pgtype.UUID + PracticeID pgtype.UUID + Mode string +} + +// Finds the latest submission of the owner under an idempotency scope, which +// a replay returns. +func (q *Queries) FindAssessmentPracticeSubmissionByScope(ctx context.Context, arg FindAssessmentPracticeSubmissionByScopeParams) (FindAssessmentPracticeSubmissionByScopeRow, error) { + row := q.db.QueryRow(ctx, findAssessmentPracticeSubmissionByScope, arg.UserID, arg.IdempotencyScope) + var i FindAssessmentPracticeSubmissionByScopeRow + err := row.Scan(&i.ID, &i.PracticeID, &i.Mode) + return i, err +} + +const getAssessmentPracticeRun = `-- name: GetAssessmentPracticeRun :one +SELECT + submission.id, + submission.practice_id, + submission.created_at, + submission.result, + job.state, + job.finished_at +FROM assessment_practice_submissions AS submission +INNER JOIN assessment_practices AS practice ON submission.practice_id = practice.id +INNER JOIN assessment_practice_jobs AS job ON submission.id = job.submission_id +WHERE + submission.id = $1 + AND submission.user_id = $2 + AND submission.mode = 'public' + AND practice.attempt_id = $3 +` + +type GetAssessmentPracticeRunParams struct { + ID pgtype.UUID + UserID pgtype.UUID + AttemptID pgtype.UUID +} + +type GetAssessmentPracticeRunRow struct { + ID pgtype.UUID + PracticeID pgtype.UUID + CreatedAt pgtype.Timestamptz + Result []byte + State string + FinishedAt pgtype.Timestamptz +} + +// Reads a debug run of the owner's attempt with the state of its job. +func (q *Queries) GetAssessmentPracticeRun(ctx context.Context, arg GetAssessmentPracticeRunParams) (GetAssessmentPracticeRunRow, error) { + row := q.db.QueryRow(ctx, getAssessmentPracticeRun, arg.ID, arg.UserID, arg.AttemptID) + var i GetAssessmentPracticeRunRow + err := row.Scan( + &i.ID, + &i.PracticeID, + &i.CreatedAt, + &i.Result, + &i.State, + &i.FinishedAt, + ) + return i, err +} + +const getLatestFinalPracticeSubmission = `-- name: GetLatestFinalPracticeSubmission :one +SELECT + submission.id, + submission.language, + submission.source_sha256 +FROM assessment_practice_submissions AS submission +WHERE + submission.practice_id = $1 + AND submission.mode = 'final' +ORDER BY submission.created_at DESC, submission.id DESC +LIMIT 1 +` + +type GetLatestFinalPracticeSubmissionRow struct { + ID pgtype.UUID + Language string + SourceSha256 []byte +} + +// The latest final submission of a practice: the solution the practice +// state describes. +func (q *Queries) GetLatestFinalPracticeSubmission(ctx context.Context, practiceID pgtype.UUID) (GetLatestFinalPracticeSubmissionRow, error) { + row := q.db.QueryRow(ctx, getLatestFinalPracticeSubmission, practiceID) + var i GetLatestFinalPracticeSubmissionRow + err := row.Scan(&i.ID, &i.Language, &i.SourceSha256) + return i, err +} + +const insertAssessmentPractice = `-- name: InsertAssessmentPractice :exec +INSERT INTO assessment_practices ( + id, + attempt_id, + user_id, + kind, + task, + status, + failure_reason, + submitted_at, + created_at, + updated_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + 'not_started', + NULL, + NULL, + $6, + $6 +) +` + +type InsertAssessmentPracticeParams struct { + ID pgtype.UUID + AttemptID pgtype.UUID + UserID pgtype.UUID + Kind string + Task []byte + CreatedAt pgtype.Timestamptz +} + +func (q *Queries) InsertAssessmentPractice(ctx context.Context, arg InsertAssessmentPracticeParams) error { + _, err := q.db.Exec(ctx, insertAssessmentPractice, + arg.ID, + arg.AttemptID, + arg.UserID, + arg.Kind, + arg.Task, + arg.CreatedAt, + ) + return err +} + +const insertAssessmentPracticeJob = `-- name: InsertAssessmentPracticeJob :exec +INSERT INTO assessment_practice_jobs ( + submission_id, + mode, + state, + created_at, + updated_at +) VALUES ( + $1, + $2, + 'queued', + $3, + $3 +) +` + +type InsertAssessmentPracticeJobParams struct { + SubmissionID pgtype.UUID + Mode string + CreatedAt pgtype.Timestamptz +} + +// Queues the execution job of a submission in the transaction that stores +// the submission. +func (q *Queries) InsertAssessmentPracticeJob(ctx context.Context, arg InsertAssessmentPracticeJobParams) error { + _, err := q.db.Exec(ctx, insertAssessmentPracticeJob, arg.SubmissionID, arg.Mode, arg.CreatedAt) + return err +} + +const insertAssessmentPracticeSubmission = `-- name: InsertAssessmentPracticeSubmission :exec +INSERT INTO assessment_practice_submissions ( + id, + practice_id, + user_id, + mode, + language, + source, + source_sha256, + custom_tests, + idempotency_scope, + created_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + $9, + $10 +) +` + +type InsertAssessmentPracticeSubmissionParams struct { + ID pgtype.UUID + PracticeID pgtype.UUID + UserID pgtype.UUID + Mode string + Language string + Source string + SourceSha256 []byte + CustomTests []byte + IdempotencyScope []byte + CreatedAt pgtype.Timestamptz +} + +func (q *Queries) InsertAssessmentPracticeSubmission(ctx context.Context, arg InsertAssessmentPracticeSubmissionParams) error { + _, err := q.db.Exec(ctx, insertAssessmentPracticeSubmission, + arg.ID, + arg.PracticeID, + arg.UserID, + arg.Mode, + arg.Language, + arg.Source, + arg.SourceSha256, + arg.CustomTests, + arg.IdempotencyScope, + arg.CreatedAt, + ) + return err +} + +const lockAssessmentAttemptForPractice = `-- name: LockAssessmentAttemptForPractice :one + +SELECT + attempt.state, + attempt.expires_at, + clock_timestamp()::timestamptz AS database_time +FROM assessment_attempts AS attempt +WHERE + attempt.id = $1 + AND attempt.user_id = $2 +FOR SHARE +` + +type LockAssessmentAttemptForPracticeParams struct { + AttemptID pgtype.UUID + UserID pgtype.UUID +} + +type LockAssessmentAttemptForPracticeRow struct { + State string + ExpiresAt pgtype.Timestamptz + DatabaseTime pgtype.Timestamptz +} + +// Lock order of a practice command: the idempotency record, the attempt in +// share mode, then the practice row. The attempt flows lock the attempt +// first as well, so a practice command never waits for them in the opposite +// order. +// Locks the owner's attempt in share mode, so its state cannot change while +// a practice command decides on it, and reads the database time after the +// lock. +func (q *Queries) LockAssessmentAttemptForPractice(ctx context.Context, arg LockAssessmentAttemptForPracticeParams) (LockAssessmentAttemptForPracticeRow, error) { + row := q.db.QueryRow(ctx, lockAssessmentAttemptForPractice, arg.AttemptID, arg.UserID) + var i LockAssessmentAttemptForPracticeRow + err := row.Scan(&i.State, &i.ExpiresAt, &i.DatabaseTime) + return i, err +} + +const lockAssessmentPractice = `-- name: LockAssessmentPractice :one +SELECT + practice.id, + practice.attempt_id, + practice.user_id, + practice.kind, + practice.task, + practice.status, + practice.failure_reason, + practice.submitted_at, + practice.created_at +FROM assessment_practices AS practice +WHERE + practice.id = $1 + AND practice.attempt_id = $2 + AND practice.user_id = $3 +FOR UPDATE +` + +type LockAssessmentPracticeParams struct { + ID pgtype.UUID + AttemptID pgtype.UUID + UserID pgtype.UUID +} + +type LockAssessmentPracticeRow struct { + ID pgtype.UUID + AttemptID pgtype.UUID + UserID pgtype.UUID + Kind string + Task []byte + Status string + FailureReason pgtype.Text + SubmittedAt pgtype.Timestamptz + CreatedAt pgtype.Timestamptz +} + +// Locks one practice of the owner's attempt for a state change. +func (q *Queries) LockAssessmentPractice(ctx context.Context, arg LockAssessmentPracticeParams) (LockAssessmentPracticeRow, error) { + row := q.db.QueryRow(ctx, lockAssessmentPractice, arg.ID, arg.AttemptID, arg.UserID) + var i LockAssessmentPracticeRow + err := row.Scan( + &i.ID, + &i.AttemptID, + &i.UserID, + &i.Kind, + &i.Task, + &i.Status, + &i.FailureReason, + &i.SubmittedAt, + &i.CreatedAt, + ) + return i, err +} + +const updateAssessmentPracticeState = `-- name: UpdateAssessmentPracticeState :execrows +UPDATE assessment_practices +SET + status = $1, + failure_reason = $2, + submitted_at = $3, + updated_at = greatest(updated_at, $4::timestamptz) +WHERE id = $5 +` + +type UpdateAssessmentPracticeStateParams struct { + Status string + FailureReason pgtype.Text + SubmittedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + ID pgtype.UUID +} + +func (q *Queries) UpdateAssessmentPracticeState(ctx context.Context, arg UpdateAssessmentPracticeStateParams) (int64, error) { + result, err := q.db.Exec(ctx, updateAssessmentPracticeState, + arg.Status, + arg.FailureReason, + arg.SubmittedAt, + arg.UpdatedAt, + arg.ID, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 21045fa..c29a09b 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -229,6 +229,43 @@ type AssessmentLeakTrace struct { EvidenceBits int32 } +type AssessmentPractice struct { + ID pgtype.UUID + AttemptID pgtype.UUID + UserID pgtype.UUID + Kind string + Task []byte + Status string + FailureReason pgtype.Text + SubmittedAt pgtype.Timestamptz + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + +type AssessmentPracticeJob struct { + SubmissionID pgtype.UUID + Mode string + State string + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + FinishedAt pgtype.Timestamptz +} + +type AssessmentPracticeSubmission struct { + ID pgtype.UUID + PracticeID pgtype.UUID + UserID pgtype.UUID + Mode string + Language string + Source string + SourceSha256 []byte + CustomTests []byte + IdempotencyScope []byte + Result []byte + ResultAt pgtype.Timestamptz + CreatedAt pgtype.Timestamptz +} + type AssessmentReviewRead struct { ID pgtype.UUID AttemptID pgtype.UUID diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index c9c7a41..12e2b97 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -277,6 +277,9 @@ type Querier interface { // NULL retry_at. due_at keeps the deadline. The same guard as the // completion applies. FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error) + // Finds the latest submission of the owner under an idempotency scope, which + // a replay returns. + FindAssessmentPracticeSubmissionByScope(ctx context.Context, arg FindAssessmentPracticeSubmissionByScopeParams) (FindAssessmentPracticeSubmissionByScopeRow, error) // The unmarked statements of real attempts whose text, with runs of white space // collapsed, contains the fragment. The fragment is matched literally: position // is not a pattern. The scan reads the stored variant of every item, which is @@ -314,6 +317,8 @@ type Querier interface { GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error) GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error) GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error) + // Reads a debug run of the owner's attempt with the state of its job. + GetAssessmentPracticeRun(ctx context.Context, arg GetAssessmentPracticeRunParams) (GetAssessmentPracticeRunRow, error) // The attempt a review job works on: real attempts only. GetAssessmentReviewSubject(ctx context.Context, attemptID pgtype.UUID) (pgtype.UUID, error) // Counts eligible root attempts in a policy window and computes the instant @@ -390,6 +395,9 @@ type Querier interface { // for the account's own view of its mail. It selects no address and no // content. The recipient index narrows the scan to the account's rows. GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeliveryStatusParams) (GetLatestDeliveryStatusRow, error) + // The latest final submission of a practice: the solution the practice + // state describes. + GetLatestFinalPracticeSubmission(ctx context.Context, practiceID pgtype.UUID) (GetLatestFinalPracticeSubmissionRow, error) // The pending credentials of the newest token of a registration, for a // resend, which issues its token with the same credentials. GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error) @@ -487,6 +495,11 @@ type Querier interface { InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error) InsertAssessmentLeakTrace(ctx context.Context, arg InsertAssessmentLeakTraceParams) error InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error + InsertAssessmentPractice(ctx context.Context, arg InsertAssessmentPracticeParams) error + // Queues the execution job of a submission in the transaction that stores + // the submission. + InsertAssessmentPracticeJob(ctx context.Context, arg InsertAssessmentPracticeJobParams) error + InsertAssessmentPracticeSubmission(ctx context.Context, arg InsertAssessmentPracticeSubmissionParams) error InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error // The attempt row is already locked by the caller. Store a parent before its // bounded child events, in the same transaction as the immutable receipt. @@ -829,6 +842,14 @@ type Querier interface { LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error) // Locks one owner-scoped attempt while a session command performs its CAS. LockAssessmentAttemptForCandidate(ctx context.Context, arg LockAssessmentAttemptForCandidateParams) (AssessmentAttempt, error) + // Lock order of a practice command: the idempotency record, the attempt in + // share mode, then the practice row. The attempt flows lock the attempt + // first as well, so a practice command never waits for them in the opposite + // order. + // Locks the owner's attempt in share mode, so its state cannot change while + // a practice command decides on it, and reads the database time after the + // lock. + LockAssessmentAttemptForPractice(ctx context.Context, arg LockAssessmentAttemptForPracticeParams) (LockAssessmentAttemptForPracticeRow, error) // Serializes root quota checks for one candidate before taking its optional // specialization or training lock. All callers acquire these locks in order. LockAssessmentAttemptScope(ctx context.Context, arg LockAssessmentAttemptScopeParams) error @@ -836,6 +857,8 @@ type Querier interface { // published or open the category, until the transaction ends. The key is // namespaced, so it cannot collide with another use of advisory locks. LockAssessmentCategory(ctx context.Context, category string) error + // Locks one practice of the owner's attempt for a state change. + LockAssessmentPractice(ctx context.Context, arg LockAssessmentPracticeParams) (LockAssessmentPracticeRow, error) // Serializes the evaluations of one review. A job takes these locks for every // attempt it will write, in ascending attempt order, before it reads any fact, // so what it reads is what the previous writer committed. @@ -1220,6 +1243,7 @@ type Querier interface { // Applies an answer, expiry, or finalization transition after the attempt row // is locked. Session limits and all immutable pins remain unchanged. UpdateAssessmentAttemptTransition(ctx context.Context, arg UpdateAssessmentAttemptTransitionParams) (AssessmentAttempt, error) + UpdateAssessmentPracticeState(ctx context.Context, arg UpdateAssessmentPracticeStateParams) (int64, error) // Replaces the publication over the version the caller read and advances the // version in the same statement. No row returns for a stale version, which // the caller answers as a version conflict. The update time never moves back, diff --git a/backend/internal/bootstrap/identity.go b/backend/internal/bootstrap/identity.go index 5770310..8f0e049 100644 --- a/backend/internal/bootstrap/identity.go +++ b/backend/internal/bootstrap/identity.go @@ -45,6 +45,7 @@ func newAPIHandler( supportHandler *v1.SupportHandler, assessmentHandler *v1.AssessmentHandler, assessmentSignalHandler *v1.AssessmentSignalHandler, + practiceHandler *v1.PracticeHandler, privacyHandler *v1.PrivacyHandler, evidenceHandler *v1.EvidenceHandler, notificationHandler *v1.NotificationHandler, @@ -62,6 +63,7 @@ func newAPIHandler( v1.WithSupport(supportHandler), v1.WithAssessment(assessmentHandler), v1.WithAssessmentSignals(assessmentSignalHandler), + v1.WithPractice(practiceHandler), v1.WithPrivacy(privacyHandler), v1.WithEvidence(evidenceHandler), v1.WithNotifications(notificationHandler), diff --git a/backend/internal/bootstrap/practice.go b/backend/internal/bootstrap/practice.go new file mode 100644 index 0000000..06caa52 --- /dev/null +++ b/backend/internal/bootstrap/practice.go @@ -0,0 +1,49 @@ +package bootstrap + +import ( + "context" + "errors" + "fmt" + "log/slog" + "time" + + "lincodex/backend/config" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/practice" +) + +// practicePoolMaxConns covers concurrent debug run requests; each holds one +// short transaction. +const practicePoolMaxConns = 4 + +// newPracticeHandler builds the debug run operations of code practice and the +// PostgreSQL pool they own. Nothing connects here. It returns no handler when +// DATABASE_URL is unset, and the operations then answer 501. Without a code +// runner (CODE_RUNNER_URL unset) the operations answer 503 and store nothing. +// The application clock is time.Now. +func newPracticeHandler( + ctx context.Context, + settings config.Config, + logger *slog.Logger, + keyring *identity.Keyring, +) (*v1.PracticeHandler, func(), error) { + if settings.DatabaseURL == "" { + logger.Warn("code practice operations are not served because DATABASE_URL is not set") + return nil, func() {}, nil + } + if keyring == nil { + return nil, nil, errors.New("bootstrap.newPracticeHandler - identity keyring must be set") + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, practicePoolMaxConns) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newPracticeHandler - create pool: %w", err) + } + service, err := practice.NewService(postgres.NewTransactor(pool), keyring, time.Now, settings.CodeRunner.Enabled()) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newPracticeHandler - create service: %w", err) + } + return v1.NewPracticeHandler(service), pool.Close, nil +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 598fc4b..94ce89e 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -57,6 +57,7 @@ func initialize( newSupportHandler, newAssessmentHandler, newAssessmentSignalHandler, + newPracticeHandler, newPrivacyHandler, newEvidenceHandler, newNotificationHandler, diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index afa64d0..8fa438d 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -184,7 +184,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - privacyHandler, cleanup15, err := newPrivacyHandler(ctx, config2, logger, keyring) + practiceHandler, cleanup15, err := newPracticeHandler(ctx, config2, logger, keyring) if err != nil { cleanup14() cleanup13() @@ -202,7 +202,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - evidenceHandler, cleanup16, err := newEvidenceHandler(ctx, config2, logger, keyring) + privacyHandler, cleanup16, err := newPrivacyHandler(ctx, config2, logger, keyring) if err != nil { cleanup15() cleanup14() @@ -221,7 +221,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - notificationHandler, cleanup17, err := newNotificationHandler(ctx, config2, logger) + evidenceHandler, cleanup17, err := newEvidenceHandler(ctx, config2, logger, keyring) if err != nil { cleanup16() cleanup15() @@ -241,7 +241,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - matchHandler, cleanup18, err := newMatchHandler(ctx, config2, logger, keyring) + notificationHandler, cleanup18, err := newNotificationHandler(ctx, config2, logger) if err != nil { cleanup17() cleanup16() @@ -262,54 +262,32 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, invitationHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler) + matchHandler, cleanup19, err := newMatchHandler(ctx, config2, logger, keyring) + if err != nil { + cleanup18() + cleanup17() + cleanup16() + cleanup15() + cleanup14() + cleanup13() + cleanup12() + cleanup11() + cleanup10() + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, invitationHandler, supportHandler, assessmentHandler, assessmentSignalHandler, practiceHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler) sessionSecurity := newSessionSecurity(identityHandler) v := newTrustedProxies(config2) httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler) - if err != nil { - cleanup18() - cleanup17() - cleanup16() - cleanup15() - cleanup14() - cleanup13() - cleanup12() - cleanup11() - cleanup10() - cleanup9() - cleanup8() - cleanup7() - cleanup6() - cleanup5() - cleanup4() - cleanup3() - cleanup2() - cleanup() - return nil, nil, err - } - relay, cleanup19, err := newOutboxRelay(ctx, config2, logger, metrics) - if err != nil { - cleanup18() - cleanup17() - cleanup16() - cleanup15() - cleanup14() - cleanup13() - cleanup12() - cleanup11() - cleanup10() - cleanup9() - cleanup8() - cleanup7() - cleanup6() - cleanup5() - cleanup4() - cleanup3() - cleanup2() - cleanup() - return nil, nil, err - } - bootstrapEventConsumers, cleanup20, err := newEventConsumers(ctx, config2, logger, metrics) if err != nil { cleanup19() cleanup18() @@ -332,7 +310,30 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - worker, cleanup21, err := newJobWorker(ctx, config2, logger, metrics) + relay, cleanup20, err := newOutboxRelay(ctx, config2, logger, metrics) + if err != nil { + cleanup19() + cleanup18() + cleanup17() + cleanup16() + cleanup15() + cleanup14() + cleanup13() + cleanup12() + cleanup11() + cleanup10() + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + bootstrapEventConsumers, cleanup21, err := newEventConsumers(ctx, config2, logger, metrics) if err != nil { cleanup20() cleanup19() @@ -356,7 +357,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - mailsenderWorker, cleanup22, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) + worker, cleanup22, err := newJobWorker(ctx, config2, logger, metrics) if err != nil { cleanup21() cleanup20() @@ -381,7 +382,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - bootstrapNotificationSendingWorker, cleanup23, err := newNotificationSenderWorker(ctx, config2, logger, metrics, mailSender) + mailsenderWorker, cleanup23, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) if err != nil { cleanup22() cleanup21() @@ -407,7 +408,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - sampler, cleanup24, err := newDeliveryMetrics(ctx, config2, logger, metrics) + bootstrapNotificationSendingWorker, cleanup24, err := newNotificationSenderWorker(ctx, config2, logger, metrics, mailSender) if err != nil { cleanup23() cleanup22() @@ -434,8 +435,37 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } + sampler, cleanup25, err := newDeliveryMetrics(ctx, config2, logger, metrics) + if err != nil { + cleanup24() + cleanup23() + cleanup22() + cleanup21() + cleanup20() + cleanup19() + cleanup18() + cleanup17() + cleanup16() + cleanup15() + cleanup14() + cleanup13() + cleanup12() + cleanup11() + cleanup10() + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, bootstrapNotificationSendingWorker, sampler) return application, func() { + cleanup25() cleanup24() cleanup23() cleanup22() diff --git a/backend/internal/domain/assessment_practice.go b/backend/internal/domain/assessment_practice.go new file mode 100644 index 0000000..1447afa --- /dev/null +++ b/backend/internal/domain/assessment_practice.go @@ -0,0 +1,568 @@ +package domain + +import ( + "crypto/sha256" + "errors" + "fmt" + "log/slog" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +// ErrInvalidAssessmentPractice reports practice content, a submission, or a +// run result that breaks the rules below. +var ErrInvalidAssessmentPractice = errors.New("invalid assessment practice") + +// Bounds of practice content and submissions. The runner contract bounds the +// technical limits and the payload; these are the product bounds of a task. +const ( + // PracticeHiddenGroups is the number of hidden test groups: the verdict + // scores one point for each group that passes. + PracticeHiddenGroups = 3 + // MaxPracticeSourceBytes is the runner bound of a source, which is also + // the largest max_source_length a task may set in characters. + MaxPracticeSourceBytes = 65536 + // MaxPracticePublicTests bounds the public examples of a task, and + // MaxPracticeCustomTests the candidate's own tests of one debug run. + MaxPracticePublicTests = 10 + MaxPracticeCustomTests = 10 + // MaxPracticeHiddenTests bounds the tests of one hidden group, as the + // runner bounds the tests of a group. + MaxPracticeHiddenTests = 50 + // MaxPracticeExampleText bounds the input and the expected output of a + // public example and of a candidate test in characters. + MaxPracticeExampleText = 10000 + // MaxPracticeHiddenText bounds the input and the expected output of a + // hidden test in bytes, as the runner bounds a test text. + MaxPracticeHiddenText = 262144 + // maxPracticeLanguages is the number of task languages. + maxPracticeLanguages = 2 + + redactedPracticeTask = "[redacted practice task]" + redactedPracticeSubmission = "[redacted practice submission]" +) + +// AssessmentPracticeKind is the role of a practice in its attempt. +type AssessmentPracticeKind string + +const ( + AssessmentPracticeMain AssessmentPracticeKind = "main" + AssessmentPracticeAdditional AssessmentPracticeKind = "additional" +) + +func (kind AssessmentPracticeKind) IsKnown() bool { + return kind == AssessmentPracticeMain || kind == AssessmentPracticeAdditional +} + +// AttemptState is the attempt state in which the practice is the current +// item: only then does it accept runs and submissions. +func (kind AssessmentPracticeKind) AttemptState() AssessmentAttemptState { + if kind == AssessmentPracticeAdditional { + return AssessmentAttemptStateAdditionalPracticePending + } + return AssessmentAttemptStatePracticePending +} + +// AssessmentPracticeStatus is the state of a practice as the candidate sees it. +type AssessmentPracticeStatus string + +const ( + AssessmentPracticeNotStarted AssessmentPracticeStatus = "not_started" + AssessmentPracticePending AssessmentPracticeStatus = "pending" + AssessmentPracticeFinished AssessmentPracticeStatus = "finished" + AssessmentPracticeFailed AssessmentPracticeStatus = "failed" +) + +func (status AssessmentPracticeStatus) IsKnown() bool { + switch status { + case AssessmentPracticeNotStarted, AssessmentPracticePending, AssessmentPracticeFinished, AssessmentPracticeFailed: + return true + default: + return false + } +} + +// AcceptsFinalSubmission reports whether a new final solution may be +// submitted: nothing was submitted yet, or the sandbox failed the latest one. +func (status AssessmentPracticeStatus) AcceptsFinalSubmission() bool { + return status == AssessmentPracticeNotStarted || status == AssessmentPracticeFailed +} + +// AssessmentPracticeFailureReason says why the sandbox gave no verdict. It +// never depends on the solution. +type AssessmentPracticeFailureReason string + +const ( + // AssessmentPracticeSandboxBusy: the practice queue was full. + AssessmentPracticeSandboxBusy AssessmentPracticeFailureReason = "sandbox_busy" + // AssessmentPracticeSandboxError: the infrastructure could not run it. + AssessmentPracticeSandboxError AssessmentPracticeFailureReason = "sandbox_error" +) + +func (reason AssessmentPracticeFailureReason) IsKnown() bool { + return reason == AssessmentPracticeSandboxBusy || reason == AssessmentPracticeSandboxError +} + +// PracticeSubmissionMode separates a debug run from the graded solution. +type PracticeSubmissionMode string + +const ( + // PracticeModePublic runs the public examples and the candidate's own + // tests. It never runs or reports a hidden group. + PracticeModePublic PracticeSubmissionMode = "public" + // PracticeModeFinal runs the hidden groups that grade the practice. + PracticeModeFinal PracticeSubmissionMode = "final" +) + +func (mode PracticeSubmissionMode) IsKnown() bool { + return mode == PracticeModePublic || mode == PracticeModeFinal +} + +// PracticeJobState is the state of the execution job of a submission. +type PracticeJobState string + +const ( + PracticeJobQueued PracticeJobState = "queued" + PracticeJobRunning PracticeJobState = "running" + PracticeJobFinished PracticeJobState = "finished" + // PracticeJobFailed means the infrastructure gave up on the job. It is + // never a verdict on the code. + PracticeJobFailed PracticeJobState = "failed" +) + +func (state PracticeJobState) IsKnown() bool { + switch state { + case PracticeJobQueued, PracticeJobRunning, PracticeJobFinished, PracticeJobFailed: + return true + default: + return false + } +} + +// PracticeCheckerKind says how the output of a test is compared. +type PracticeCheckerKind string + +const ( + PracticeCheckerExact PracticeCheckerKind = "exact" + PracticeCheckerTokens PracticeCheckerKind = "tokens" + PracticeCheckerNumbers PracticeCheckerKind = "numbers" + PracticeCheckerCustom PracticeCheckerKind = "custom" +) + +// PracticeTest is one input with the output the checker expects. +type PracticeTest struct { + Input string `json:"input"` + ExpectedOutput string `json:"expected_output"` +} + +// PracticeTestGroup is one hidden group of tests. +type PracticeTestGroup struct { + Tests []PracticeTest `json:"tests"` +} + +// PracticeCheckerProgram is the checker program of a custom checker. +type PracticeCheckerProgram struct { + Language TaskLanguageCode `json:"language"` + Source string `json:"source"` +} + +// PracticeChecker configures the comparison of every group of the task. +type PracticeChecker struct { + Kind PracticeCheckerKind `json:"kind"` + AbsTolerance float64 `json:"abs_tolerance,omitempty"` + RelTolerance float64 `json:"rel_tolerance,omitempty"` + Program *PracticeCheckerProgram `json:"program,omitempty"` +} + +// PracticeTask is the private content of a practice item: what the runner +// needs to run a solution. The hidden groups are task secrets; they never +// reach a candidate, a log, or an error. The statement and the public +// projection of the item belong to the attempt item, not to this record. +// +// String, GoString, Format, and LogValue redact the whole task. +type PracticeTask struct { + // Languages lists the languages a solution may use, one or two. + Languages []TaskLanguageCode `json:"languages"` + // MaxSourceLength bounds the solution in characters. + MaxSourceLength int `json:"max_source_length"` + // TimeLimitMs, MemoryLimitMB, and OutputLimitKB apply to every test. + TimeLimitMs int32 `json:"time_limit_ms"` + MemoryLimitMB int32 `json:"memory_limit_mb"` + OutputLimitKB int32 `json:"output_limit_kb"` + Checker PracticeChecker `json:"checker"` + // PublicTests are the public examples the candidate sees. + PublicTests []PracticeTest `json:"public_tests"` + // HiddenGroups are the PracticeHiddenGroups groups that grade a final + // solution. + HiddenGroups []PracticeTestGroup `json:"hidden_groups"` +} + +func (task PracticeTask) String() string { return redactedPracticeTask } +func (task PracticeTask) GoString() string { return redactedPracticeTask } +func (task PracticeTask) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedPracticeTask) +} +func (task PracticeTask) LogValue() slog.Value { return slog.StringValue(redactedPracticeTask) } + +// Validate checks the product rules of the task. The runner rules (limit +// ranges, checker parameters, the CPU budget, the payload size) are checked +// when a run request is built from it. Errors never quote task content. +func (task PracticeTask) Validate() error { + const location = "PracticeTask.Validate" + if err := validatePracticeLanguages(task.Languages); err != nil { + return err + } + if task.MaxSourceLength < 1 || task.MaxSourceLength > MaxPracticeSourceBytes { + return practiceError(location, "max source length must be between 1 and 65536") + } + if task.TimeLimitMs <= 0 || task.MemoryLimitMB <= 0 || task.OutputLimitKB <= 0 { + return practiceError(location, "limits must be positive") + } + if err := task.Checker.validate(); err != nil { + return err + } + if len(task.PublicTests) < 1 || len(task.PublicTests) > MaxPracticePublicTests { + return practiceError(location, "public tests must have 1 to 10 entries") + } + for _, test := range task.PublicTests { + if err := test.validate(MaxPracticeExampleText, true); err != nil { + return err + } + } + return validatePracticeHiddenGroups(task.HiddenGroups) +} + +func validatePracticeLanguages(languages []TaskLanguageCode) error { + const location = "domain.validatePracticeLanguages" + if len(languages) < 1 || len(languages) > maxPracticeLanguages { + return practiceError(location, "languages must have one or two entries") + } + seen := make(map[TaskLanguageCode]struct{}, len(languages)) + for _, language := range languages { + if _, duplicate := seen[language]; duplicate || !language.IsKnown() { + return practiceError(location, "languages must be distinct known task languages") + } + seen[language] = struct{}{} + } + return nil +} + +func validatePracticeHiddenGroups(groups []PracticeTestGroup) error { + const location = "domain.validatePracticeHiddenGroups" + if len(groups) != PracticeHiddenGroups { + return practiceError(location, "hidden groups must have exactly three entries") + } + for _, group := range groups { + if len(group.Tests) < 1 || len(group.Tests) > MaxPracticeHiddenTests { + return practiceError(location, "a hidden group must have 1 to 50 tests") + } + for _, test := range group.Tests { + if err := test.validate(MaxPracticeHiddenText, false); err != nil { + return err + } + } + } + return nil +} + +// AllowsLanguage reports whether a solution may use the language. +func (task PracticeTask) AllowsLanguage(language TaskLanguageCode) bool { + for _, allowed := range task.Languages { + if allowed == language { + return true + } + } + return false +} + +func (checker PracticeChecker) validate() error { + const location = "PracticeChecker.validate" + switch checker.Kind { + case PracticeCheckerExact, PracticeCheckerTokens, PracticeCheckerNumbers: + if checker.Program != nil { + return practiceError(location, "only a custom checker has a program") + } + case PracticeCheckerCustom: + if checker.Program == nil || !checker.Program.Language.IsKnown() || strings.TrimSpace(checker.Program.Source) == "" { + return practiceError(location, "a custom checker needs a program in a task language") + } + default: + return practiceError(location, "checker kind must be exact, tokens, numbers, or custom") + } + return nil +} + +// validate checks one test. maxLength counts characters when byCharacters +// is set and bytes otherwise. +func (test PracticeTest) validate(maxLength int, byCharacters bool) error { + const location = "PracticeTest.validate" + for _, text := range []string{test.Input, test.ExpectedOutput} { + if !utf8.ValidString(text) || strings.ContainsRune(text, 0) { + return practiceError(location, "test texts must be valid UTF-8 without NUL") + } + length := len(text) + if byCharacters { + length = utf8.RuneCountInString(text) + } + if length > maxLength { + return practiceError(location, "a test text is too long") + } + } + return nil +} + +// ValidatePracticeCustomTests checks the candidate's own tests of a debug run. +func ValidatePracticeCustomTests(tests []PracticeTest) error { + if len(tests) > MaxPracticeCustomTests { + return practiceError("domain.ValidatePracticeCustomTests", "at most 10 custom tests are allowed") + } + for _, test := range tests { + if err := test.validate(MaxPracticeExampleText, true); err != nil { + return err + } + } + return nil +} + +// ValidatePracticeSource checks a solution source against the task bound in +// characters and the runner bound in bytes. +func ValidatePracticeSource(source string, maxLength int) error { + const location = "domain.ValidatePracticeSource" + switch { + case strings.TrimSpace(source) == "": + return practiceError(location, "source must not be blank") + case !utf8.ValidString(source) || strings.ContainsRune(source, 0): + return practiceError(location, "source must be valid UTF-8 without NUL") + case len(source) > MaxPracticeSourceBytes || utf8.RuneCountInString(source) > maxLength: + return practiceError(location, "source is too long") + } + return nil +} + +// AssessmentPractice is one practice item of an attempt with its state. +type AssessmentPractice struct { + ID uuid.UUID + AttemptID AssessmentAttemptID + UserID uuid.UUID + Kind AssessmentPracticeKind + Task PracticeTask + Status AssessmentPracticeStatus + FailureReason AssessmentPracticeFailureReason + // SubmittedAt is the time of the latest final submission; zero before + // the first one. + SubmittedAt time.Time + CreatedAt time.Time +} + +// Validate checks that the practice can be stored or was restored intact. +func (practice AssessmentPractice) Validate() error { + const location = "AssessmentPractice.Validate" + switch { + case practice.ID == uuid.Nil, practice.AttemptID.IsZero(), practice.UserID == uuid.Nil: + return practiceError(location, "practice, attempt, and owner IDs are required") + case !practice.Kind.IsKnown(), !practice.Status.IsKnown(): + return practiceError(location, "kind and status must be known") + case (practice.Status == AssessmentPracticeFailed) != practice.FailureReason.IsKnown(), + practice.Status != AssessmentPracticeFailed && practice.FailureReason != "": + return practiceError(location, "only a failed practice has a failure reason") + case (practice.Status == AssessmentPracticeNotStarted) != practice.SubmittedAt.IsZero(): + return practiceError(location, "only a submitted practice has a submission time") + case practice.CreatedAt.IsZero(): + return practiceError(location, "creation time is required") + } + return practice.Task.Validate() +} + +// View is the candidate's view of the practice state. It holds nothing of +// the task. +func (practice AssessmentPractice) View() AssessmentPracticeView { + view := AssessmentPracticeView{ + Kind: practice.Kind, ItemID: practice.ID, Status: practice.Status, FailureReason: practice.FailureReason, + } + if !practice.SubmittedAt.IsZero() { + submittedAt := practice.SubmittedAt + view.SubmittedAt = &submittedAt + } + return view +} + +// AssessmentPracticeView is the state of a practice that the candidate may +// see: never the task content, the hidden groups, or the source. +type AssessmentPracticeView struct { + Kind AssessmentPracticeKind + ItemID uuid.UUID + Status AssessmentPracticeStatus + SubmittedAt *time.Time + FailureReason AssessmentPracticeFailureReason +} + +// PracticeSourceDigest is the SHA-256 of a source; two final submissions are +// the same solution when their languages and digests are equal. +type PracticeSourceDigest [sha256.Size]byte + +// DigestPracticeSource returns the digest of a source. +func DigestPracticeSource(source string) PracticeSourceDigest { + return sha256.Sum256([]byte(source)) +} + +// PracticeSubmission is one stored submission of candidate code. Its request +// part is immutable. +// +// String, GoString, Format, and LogValue redact the source and the tests, +// which are candidate work. +type PracticeSubmission struct { + ID uuid.UUID + PracticeID uuid.UUID + UserID uuid.UUID + Mode PracticeSubmissionMode + Language TaskLanguageCode + Source string + CustomTests []PracticeTest + CreatedAt time.Time +} + +func (submission PracticeSubmission) String() string { return redactedPracticeSubmission } +func (submission PracticeSubmission) GoString() string { return redactedPracticeSubmission } +func (submission PracticeSubmission) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedPracticeSubmission) +} +func (submission PracticeSubmission) LogValue() slog.Value { + return slog.GroupValue( + slog.String("submission_id", submission.ID.String()), + slog.String("mode", string(submission.Mode)), + slog.String("language", string(submission.Language)), + ) +} + +// Validate checks the submission against the task of its practice. +func (submission PracticeSubmission) Validate(task PracticeTask) error { + const location = "PracticeSubmission.Validate" + switch { + case submission.ID == uuid.Nil, submission.PracticeID == uuid.Nil, submission.UserID == uuid.Nil: + return practiceError(location, "submission, practice, and owner IDs are required") + case !submission.Mode.IsKnown(): + return practiceError(location, "mode must be public or final") + case !task.AllowsLanguage(submission.Language): + return practiceError(location, "language is not offered by the task") + case submission.Mode == PracticeModeFinal && len(submission.CustomTests) > 0: + return practiceError(location, "a final submission has no custom tests") + case submission.CreatedAt.IsZero(): + return practiceError(location, "creation time is required") + } + if err := ValidatePracticeSource(submission.Source, task.MaxSourceLength); err != nil { + return err + } + return ValidatePracticeCustomTests(submission.CustomTests) +} + +// PracticeOutcome is the verdict of a test, a group, a compile step, or a +// run, as the runner reports it. +type PracticeOutcome string + +const ( + PracticeOutcomeAccepted PracticeOutcome = "accepted" + PracticeOutcomeWrongAnswer PracticeOutcome = "wrong_answer" + PracticeOutcomeCompileError PracticeOutcome = "compile_error" + PracticeOutcomeTimeLimitExceeded PracticeOutcome = "time_limit_exceeded" + PracticeOutcomeMemoryLimitExceeded PracticeOutcome = "memory_limit_exceeded" + PracticeOutcomeOutputLimitExceeded PracticeOutcome = "output_limit_exceeded" + PracticeOutcomeRuntimeError PracticeOutcome = "runtime_error" +) + +func (outcome PracticeOutcome) IsKnown() bool { + switch outcome { + case PracticeOutcomeAccepted, PracticeOutcomeWrongAnswer, PracticeOutcomeCompileError, + PracticeOutcomeTimeLimitExceeded, PracticeOutcomeMemoryLimitExceeded, + PracticeOutcomeOutputLimitExceeded, PracticeOutcomeRuntimeError: + return true + default: + return false + } +} + +// PracticeTestOutcome is the result of one evaluated public test. +type PracticeTestOutcome struct { + ID string `json:"id"` + Outcome PracticeOutcome `json:"outcome"` + TimeMs int64 `json:"time_ms"` + MemoryKB int64 `json:"memory_kb"` + Diagnostic string `json:"diagnostic,omitempty"` +} + +// PracticeGroupOutcome is the result of one group. A hidden group keeps only +// its outcome and counts, never its tests. +type PracticeGroupOutcome struct { + ID string `json:"id"` + Hidden bool `json:"hidden"` + Outcome PracticeOutcome `json:"outcome"` + PassedTests int `json:"passed_tests"` + TotalTests int `json:"total_tests"` + Tests []PracticeTestOutcome `json:"tests,omitempty"` +} + +// PracticeRunResult is the stored result of a run. +type PracticeRunResult struct { + Outcome PracticeOutcome `json:"outcome"` + // CompileDiagnostic is the compiler message of a compile error. It can + // quote the source, never test data. + CompileDiagnostic string `json:"compile_diagnostic,omitempty"` + Groups []PracticeGroupOutcome `json:"groups"` + DurationMs int64 `json:"duration_ms"` +} + +// Validate checks that the result can be stored and shown. +func (result PracticeRunResult) Validate() error { + const location = "PracticeRunResult.Validate" + if !result.Outcome.IsKnown() || result.DurationMs < 0 { + return practiceError(location, "outcome must be known and duration not negative") + } + if result.CompileDiagnostic != "" && result.Outcome != PracticeOutcomeCompileError { + return practiceError(location, "only a compile error has a compile diagnostic") + } + for _, group := range result.Groups { + if group.ID == "" || !group.Outcome.IsKnown() || group.PassedTests < 0 || group.PassedTests > group.TotalTests { + return practiceError(location, "group outcome and counts are inconsistent") + } + if group.Hidden && len(group.Tests) > 0 { + return practiceError(location, "a hidden group keeps no test results") + } + for _, test := range group.Tests { + if test.ID == "" || !test.Outcome.IsKnown() { + return practiceError(location, "test outcome is unknown") + } + } + } + return nil +} + +// Public returns the result without hidden groups. Only this projection may +// be shown for a debug run. +func (result PracticeRunResult) Public() PracticeRunResult { + public := result + public.Groups = make([]PracticeGroupOutcome, 0, len(result.Groups)) + for _, group := range result.Groups { + if !group.Hidden { + public.Groups = append(public.Groups, group) + } + } + return public +} + +// PracticeRunView is a debug run as the candidate sees it: its state and the +// public result. A debug run never runs a hidden group, and the view never +// carries one. +type PracticeRunView struct { + ID uuid.UUID + PracticeID uuid.UUID + State PracticeJobState + CreatedAt time.Time + FinishedAt *time.Time + Result *PracticeRunResult +} + +func practiceError(location, reason string) error { + return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidAssessmentPractice) +} diff --git a/backend/internal/port/outbound/assessment_practice.go b/backend/internal/port/outbound/assessment_practice.go new file mode 100644 index 0000000..b4d8be1 --- /dev/null +++ b/backend/internal/port/outbound/assessment_practice.go @@ -0,0 +1,84 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrAssessmentPracticeNotFound reports a practice that is unknown or + // not a practice of the owner's attempt. + ErrAssessmentPracticeNotFound = errors.New("assessment practice not found") + // ErrPracticeRunNotFound reports a debug run that is unknown or not a + // run of the owner's attempt. + ErrPracticeRunNotFound = errors.New("practice run not found") +) + +// PracticeAttemptLock is what a practice command reads about its attempt +// under the share lock. +type PracticeAttemptLock struct { + State domain.AssessmentAttemptState + ExpiresAt time.Time + // DatabaseTime is read after the lock was granted. + DatabaseTime time.Time +} + +// PracticeSubmissionReplay identifies the stored submission that a replayed +// request returns. +type PracticeSubmissionReplay struct { + ID uuid.UUID + PracticeID uuid.UUID + Mode domain.PracticeSubmissionMode +} + +// PracticeFinalSolution identifies the latest final submission of a practice +// without its source. +type PracticeFinalSolution struct { + SubmissionID uuid.UUID + Language domain.TaskLanguageCode + SourceDigest domain.PracticeSourceDigest +} + +// AssessmentPracticeRepositories groups the practice repositories of a unit +// of work. +type AssessmentPracticeRepositories interface { + AssessmentPractices() AssessmentPracticeRepository +} + +// AssessmentPracticeRepository keeps the practice items of attempts, their +// submissions, and the execution jobs of the submissions, separately from the +// attempt snapshot and the result. Every read is scoped by the owner, so an +// identifier of another candidate reads as not found. +type AssessmentPracticeRepository interface { + // Create stores a new practice of an attempt in the not_started state. + // The attempt flow that serves practice items calls it. + Create(ctx context.Context, practice domain.AssessmentPractice) error + // LockAttempt locks the owner's attempt in share mode and reads its + // state, deadline, and the database time. An unknown or foreign attempt + // returns ErrAssessmentAttemptNotFound. + LockAttempt(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (PracticeAttemptLock, error) + // LockPractice locks one practice of the owner's attempt for a state + // change. An unknown or foreign practice returns + // ErrAssessmentPracticeNotFound. + LockPractice(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID, practiceID uuid.UUID) (domain.AssessmentPractice, error) + // SaveState stores the status, failure reason, and submission time of a + // locked practice. + SaveState(ctx context.Context, practice domain.AssessmentPractice, updatedAt time.Time) error + // FindByScope returns the latest submission of the owner stored under + // the idempotency scope, if any. + FindByScope(ctx context.Context, userID uuid.UUID, scope [IdempotencyDigestSize]byte) (PracticeSubmissionReplay, bool, error) + // LatestFinal returns the latest final submission of a practice, if any. + LatestFinal(ctx context.Context, practiceID uuid.UUID) (PracticeFinalSolution, bool, error) + // Submit stores a submission under the idempotency scope and queues its + // execution job in the same transaction. + Submit(ctx context.Context, submission domain.PracticeSubmission, scope [IdempotencyDigestSize]byte) error + // GetRun reads a debug run of the owner's attempt with the state of its + // job. It never returns a final submission; an unknown, foreign, or final + // submission returns ErrPracticeRunNotFound. + GetRun(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID, runID uuid.UUID) (domain.PracticeRunView, error) +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 530b161..a58605c 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -74,6 +74,7 @@ type UnitOfWork interface { AssessmentAttemptRepositories AssessmentSignalRepositories AssessmentSignalNoticeRepositories + AssessmentPracticeRepositories SupportCaseRepositories Policies() PolicyRepository Deliveries() DeliveryRepository diff --git a/backend/internal/usecase/practice/request.go b/backend/internal/usecase/practice/request.go new file mode 100644 index 0000000..68071ed --- /dev/null +++ b/backend/internal/usecase/practice/request.go @@ -0,0 +1,103 @@ +package practice + +import ( + "fmt" + "strconv" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// Group IDs of a run request. They are opaque labels for the runner and the +// stored result; the hidden ones never reach a candidate. +const ( + // PublicGroupID holds the public examples of the task. + PublicGroupID = "public" + // CustomGroupID holds the candidate's own tests of a debug run. + CustomGroupID = "custom" + // hiddenGroupPrefix is followed by the group number, from 1. + hiddenGroupPrefix = "hidden-" +) + +// RunRequest builds the runner request of a submission. A debug run carries +// the public examples and the candidate's own tests, never a hidden group; a +// final submission carries the hidden groups only, which grade it. The key +// binds the run to the practice item, the submission, and the generation, so +// a retry reuses the run and a new generation starts a new one. +func RunRequest(task domain.PracticeTask, submission domain.PracticeSubmission, generation uint32) (outbound.CodeRunRequest, error) { + const location = "practice.RunRequest" + language, err := runnerLanguage(submission.Language) + if err != nil { + return outbound.CodeRunRequest{}, fmt.Errorf("%s - map language: %w", location, err) + } + checker, err := runnerChecker(task.Checker) + if err != nil { + return outbound.CodeRunRequest{}, fmt.Errorf("%s - map checker: %w", location, err) + } + request := outbound.CodeRunRequest{ + Key: outbound.CodeRunKey{AttemptItemID: submission.PracticeID, SubmissionID: submission.ID, Generation: generation}, + Language: language, + Source: submission.Source, + Limits: outbound.CodeRunLimits{ + TimeLimitMs: task.TimeLimitMs, MemoryLimitMB: task.MemoryLimitMB, OutputLimitKB: task.OutputLimitKB, + }, + } + switch submission.Mode { + case domain.PracticeModePublic: + request.Groups = append(request.Groups, runnerGroup(PublicGroupID, outbound.CodeTestPublic, checker, task.PublicTests)) + if len(submission.CustomTests) > 0 { + request.Groups = append(request.Groups, runnerGroup(CustomGroupID, outbound.CodeTestPublic, checker, submission.CustomTests)) + } + case domain.PracticeModeFinal: + for index, group := range task.HiddenGroups { + id := hiddenGroupPrefix + strconv.Itoa(index+1) + request.Groups = append(request.Groups, runnerGroup(id, outbound.CodeTestHidden, checker, group.Tests)) + } + default: + return outbound.CodeRunRequest{}, fmt.Errorf("%s - mode must be public or final: %w", location, domain.ErrInvalidAssessmentPractice) + } + if err := request.Validate(); err != nil { + return outbound.CodeRunRequest{}, fmt.Errorf("%s - validate request: %w", location, err) + } + return request, nil +} + +func runnerGroup( + id string, + visibility outbound.CodeTestVisibility, + checker outbound.CodeChecker, + tests []domain.PracticeTest, +) outbound.CodeTestGroup { + group := outbound.CodeTestGroup{ID: id, Visibility: visibility, Checker: checker, Tests: make([]outbound.CodeTest, 0, len(tests))} + for index, test := range tests { + group.Tests = append(group.Tests, outbound.CodeTest{ + ID: strconv.Itoa(index + 1), Input: test.Input, ExpectedOutput: test.ExpectedOutput, + }) + } + return group +} + +func runnerLanguage(language domain.TaskLanguageCode) (outbound.CodeLanguage, error) { + switch language { + case domain.TaskLanguageGo: + return outbound.CodeLanguageGo, nil + case domain.TaskLanguagePython: + return outbound.CodeLanguagePython3, nil + default: + return "", fmt.Errorf("practice.runnerLanguage - language is unknown: %w", domain.ErrInvalidAssessmentPractice) + } +} + +func runnerChecker(checker domain.PracticeChecker) (outbound.CodeChecker, error) { + mapped := outbound.CodeChecker{ + Kind: outbound.CodeCheckerKind(checker.Kind), AbsTolerance: checker.AbsTolerance, RelTolerance: checker.RelTolerance, + } + if checker.Program != nil { + language, err := runnerLanguage(checker.Program.Language) + if err != nil { + return outbound.CodeChecker{}, fmt.Errorf("practice.runnerChecker - map program language: %w", err) + } + mapped.Program = &outbound.CodeCheckerProgram{Language: language, Source: checker.Program.Source} + } + return mapped, nil +} diff --git a/backend/internal/usecase/practice/request_test.go b/backend/internal/usecase/practice/request_test.go new file mode 100644 index 0000000..426b773 --- /dev/null +++ b/backend/internal/usecase/practice/request_test.go @@ -0,0 +1,72 @@ +package practice + +import ( + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const hiddenMarker = "hidden-secret" + +func TestRunRequestKeepsHiddenGroupsOutOfDebugRuns(t *testing.T) { + task := testTask() + submission := domain.PracticeSubmission{ + ID: uuid.New(), PracticeID: uuid.New(), UserID: uuid.New(), Mode: domain.PracticeModePublic, + Language: domain.TaskLanguagePython, Source: "print(1)\n", CreatedAt: time.Now(), + CustomTests: []domain.PracticeTest{{Input: "1\n", ExpectedOutput: "1\n"}}, + } + request, err := RunRequest(task, submission, 0) + if err != nil { + t.Fatalf("RunRequest(public) error = %v", err) + } + if len(request.Groups) != 2 || request.Groups[0].ID != PublicGroupID || request.Groups[1].ID != CustomGroupID { + t.Fatalf("public groups = %d, want the public and the custom group", len(request.Groups)) + } + for _, group := range request.Groups { + if group.Visibility != outbound.CodeTestPublic { + t.Fatalf("group %s visibility = %s, want public", group.ID, group.Visibility) + } + for _, test := range group.Tests { + if strings.Contains(test.Input+test.ExpectedOutput, hiddenMarker) { + t.Fatalf("a debug run carries hidden test content in group %s", group.ID) + } + } + } + if request.Language != outbound.CodeLanguagePython3 || request.Key.AttemptItemID != submission.PracticeID || + request.Key.SubmissionID != submission.ID { + t.Fatal("request language or key does not match the submission") + } + + submission.Mode, submission.CustomTests = domain.PracticeModeFinal, nil + request, err = RunRequest(task, submission, 3) + if err != nil { + t.Fatalf("RunRequest(final) error = %v", err) + } + if len(request.Groups) != domain.PracticeHiddenGroups || request.Key.Generation != 3 { + t.Fatalf("final groups = %d with generation %d, want three hidden groups and generation 3", len(request.Groups), request.Key.Generation) + } + for index, group := range request.Groups { + if group.Visibility != outbound.CodeTestHidden || group.ID != hiddenGroupPrefix+string(rune('1'+index)) { + t.Fatalf("final group %d = %s %s, want a hidden group", index, group.ID, group.Visibility) + } + } +} + +func testTask() domain.PracticeTask { + hidden := make([]domain.PracticeTestGroup, 0, domain.PracticeHiddenGroups) + for range domain.PracticeHiddenGroups { + hidden = append(hidden, domain.PracticeTestGroup{Tests: []domain.PracticeTest{{Input: hiddenMarker, ExpectedOutput: hiddenMarker}}}) + } + return domain.PracticeTask{ + Languages: []domain.TaskLanguageCode{domain.TaskLanguagePython}, + MaxSourceLength: 100, TimeLimitMs: 1000, MemoryLimitMB: 64, OutputLimitKB: 64, + Checker: domain.PracticeChecker{Kind: domain.PracticeCheckerExact}, + PublicTests: []domain.PracticeTest{{Input: "1\n", ExpectedOutput: "1\n"}}, + HiddenGroups: hidden, + } +} diff --git a/backend/internal/usecase/practice/service.go b/backend/internal/usecase/practice/service.go new file mode 100644 index 0000000..24cf32e --- /dev/null +++ b/backend/internal/usecase/practice/service.go @@ -0,0 +1,509 @@ +// Package practice stores code practice submissions and their execution +// jobs. It keeps practice state apart from the attempt snapshot and the +// result: a submission and its job commit together, and the practice queue +// worker runs the job later. +package practice + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// Idempotency operations. Each scopes its keys separately. +const ( + runOperation = "assessment_practice.run" + finalOperation = "assessment_practice.final" + // maxIdempotencyKeyBytes is the contract bound of Idempotency-Key. + maxIdempotencyKeyBytes = 255 +) + +// Request fields that a FieldError names. The HTTP adapter turns them into +// pointers of its own body. +const ( + FieldLanguage = "language" + FieldSource = "source_code" + FieldTests = "tests" +) + +var ( + // ErrInvalidRequest reports a command that breaks the contract or the + // rules of the task; FieldError names the field. + ErrInvalidRequest = errors.New("invalid practice request") + // ErrInvalidKey reports a malformed Idempotency-Key. + ErrInvalidKey = errors.New("invalid practice idempotency key") + // ErrKeyReused reports an Idempotency-Key used with another request. + ErrKeyReused = errors.New("practice idempotency key reused") + // ErrForbidden reports an account that is not a verified candidate. + ErrForbidden = errors.New("practice is for verified candidates only") + // ErrNotFound reports an attempt, practice, or run that is unknown or + // belongs to another candidate. + ErrNotFound = errors.New("practice not found") + // ErrStateConflict reports a command that the attempt or the practice + // does not accept now: the attempt is not at this practice or past its + // deadline, or the practice already has another solution. + ErrStateConflict = errors.New("practice state conflict") + // ErrUnavailable reports that code practice cannot run now, for example + // because the code runner is disabled. Nothing was stored or graded. + ErrUnavailable = errors.New("code practice unavailable") +) + +// FieldError names the request field that ErrInvalidRequest is about. +type FieldError struct { + Field string +} + +func (fieldError *FieldError) Error() string { + return "invalid practice request field " + fieldError.Field +} + +func (fieldError *FieldError) Unwrap() error { return ErrInvalidRequest } + +// Keyring computes scoped idempotency digests with the server secret. +type Keyring interface { + IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte + Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte +} + +// Service accepts debug runs and final solutions of code practices. +type Service struct { + transactor outbound.Transactor + keyring Keyring + clock func() time.Time + // enabled is false when no code runner is configured: practice then + // answers unavailable and stores nothing. + enabled bool +} + +func NewService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time, enabled bool) (*Service, error) { + if transactor == nil || keyring == nil || clock == nil { + return nil, errors.New("practice.NewService - transactor, keyring, and clock are required") + } + return &Service{transactor: transactor, keyring: keyring, clock: clock, enabled: enabled}, nil +} + +// RunCommand asks for a debug run of a solution against the public examples +// and the candidate's own tests. +type RunCommand struct { + ActorID uuid.UUID + AttemptID domain.AssessmentAttemptID + PracticeID uuid.UUID + IdempotencyKey string + // Language is nil when the task offers one language only. + Language *domain.TaskLanguageCode + Source string + Tests []domain.PracticeTest +} + +// RunResult is the queued or replayed run. +type RunResult struct { + Run domain.PracticeRunView + Replayed bool +} + +// FinalCommand submits the solution that the hidden groups grade. +type FinalCommand struct { + ActorID uuid.UUID + AttemptID domain.AssessmentAttemptID + PracticeID uuid.UUID + IdempotencyKey string + Language *domain.TaskLanguageCode + Source string +} + +// FinalResult is the practice state after the command. +type FinalResult struct { + Practice domain.AssessmentPracticeView + // Replayed reports a repeat of an earlier request with the same key. + Replayed bool + // Unchanged reports that the same solution was already submitted and + // nothing was stored. + Unchanged bool +} + +type canonicalRequest struct { + PracticeID string `json:"item_id"` + Language *string `json:"language"` + Source string `json:"source_code"` + Tests []domain.PracticeTest `json:"tests,omitempty"` +} + +// SubmitRun stores a debug run and queues its job in one transaction. A +// repeat with the same Idempotency-Key and request returns the stored run in +// its current state; refusals are not stored and are evaluated again. +func (service *Service) SubmitRun(ctx context.Context, command RunCommand) (RunResult, error) { + const location = "Service.SubmitRun" + if err := domain.ValidatePracticeCustomTests(command.Tests); err != nil { + return RunResult{}, fmt.Errorf("%s - validate tests: %w", location, &FieldError{Field: FieldTests}) + } + request, err := service.prepare(runOperation, command.ActorID, command.AttemptID, command.PracticeID, command.IdempotencyKey, + canonicalRequest{Language: languageText(command.Language), Source: command.Source, Tests: command.Tests}) + if err != nil { + return RunResult{}, fmt.Errorf("%s - prepare: %w", location, err) + } + var result RunResult + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var transactionErr error + result, transactionErr = service.submitRunInTransaction(ctx, unit, command, request) + return transactionErr + }) + if err != nil { + return RunResult{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} + +func (service *Service) submitRunInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command RunCommand, + request idempotentRequest, +) (RunResult, error) { + const location = "Service.submitRunInTransaction" + if err := requireCandidate(ctx, unit, command.ActorID); err != nil { + return RunResult{}, fmt.Errorf("%s - check account: %w", location, err) + } + if !service.enabled { + return RunResult{}, fmt.Errorf("%s - code runner is disabled: %w", location, ErrUnavailable) + } + replayed, err := reserve(ctx, unit, request) + if err != nil { + return RunResult{}, fmt.Errorf("%s - reserve key: %w", location, err) + } + repository := unit.AssessmentPractices() + if replayed { + stored, found, err := repository.FindByScope(ctx, command.ActorID, request.record.Scope) + if err != nil { + return RunResult{}, fmt.Errorf("%s - find replayed run: %w", location, err) + } + if !found || stored.Mode != domain.PracticeModePublic { + return RunResult{}, fmt.Errorf("%s - replayed key has no run: %w", location, ErrKeyReused) + } + run, err := repository.GetRun(ctx, command.ActorID, command.AttemptID, stored.ID) + if err != nil { + return RunResult{}, fmt.Errorf("%s - read replayed run: %w", location, mapNotFound(err)) + } + return RunResult{Run: run, Replayed: true}, nil + } + practice, now, err := lockOpenPractice(ctx, repository, command.ActorID, command.AttemptID, command.PracticeID) + if err != nil { + return RunResult{}, fmt.Errorf("%s - lock practice: %w", location, err) + } + submission, err := newSubmission(practice, domain.PracticeModePublic, command.ActorID, command.Language, command.Source, command.Tests, now) + if err != nil { + return RunResult{}, fmt.Errorf("%s - build submission: %w", location, err) + } + if err := repository.Submit(ctx, submission, request.record.Scope); err != nil { + return RunResult{}, fmt.Errorf("%s - store run: %w", location, err) + } + return RunResult{Run: domain.PracticeRunView{ + ID: submission.ID, PracticeID: practice.ID, State: domain.PracticeJobQueued, CreatedAt: now, + }}, nil +} + +// SubmitFinal stores the final solution of a practice and queues its job in +// one transaction, and marks the practice pending. The same solution sent +// again stores nothing; a different one is refused while the practice is +// pending or finished, so the source of a graded solution never changes. A +// practice that failed in the sandbox accepts a solution again. +func (service *Service) SubmitFinal(ctx context.Context, command FinalCommand) (FinalResult, error) { + const location = "Service.SubmitFinal" + request, err := service.prepare(finalOperation, command.ActorID, command.AttemptID, command.PracticeID, command.IdempotencyKey, + canonicalRequest{Language: languageText(command.Language), Source: command.Source}) + if err != nil { + return FinalResult{}, fmt.Errorf("%s - prepare: %w", location, err) + } + var result FinalResult + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var transactionErr error + result, transactionErr = service.submitFinalInTransaction(ctx, unit, command, request) + return transactionErr + }) + if err != nil { + return FinalResult{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} + +func (service *Service) submitFinalInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command FinalCommand, + request idempotentRequest, +) (FinalResult, error) { + const location = "Service.submitFinalInTransaction" + if err := requireCandidate(ctx, unit, command.ActorID); err != nil { + return FinalResult{}, fmt.Errorf("%s - check account: %w", location, err) + } + if !service.enabled { + return FinalResult{}, fmt.Errorf("%s - code runner is disabled: %w", location, ErrUnavailable) + } + replayed, err := reserve(ctx, unit, request) + if err != nil { + return FinalResult{}, fmt.Errorf("%s - reserve key: %w", location, err) + } + repository := unit.AssessmentPractices() + if replayed { + if _, err := repository.LockAttempt(ctx, command.ActorID, command.AttemptID); err != nil { + return FinalResult{}, fmt.Errorf("%s - lock attempt of replay: %w", location, mapNotFound(err)) + } + practice, err := repository.LockPractice(ctx, command.ActorID, command.AttemptID, command.PracticeID) + if err != nil { + return FinalResult{}, fmt.Errorf("%s - read practice of replay: %w", location, mapNotFound(err)) + } + return FinalResult{Practice: practice.View(), Replayed: true}, nil + } + practice, now, err := lockOpenPractice(ctx, repository, command.ActorID, command.AttemptID, command.PracticeID) + if err != nil { + return FinalResult{}, fmt.Errorf("%s - lock practice: %w", location, err) + } + submission, err := newSubmission(practice, domain.PracticeModeFinal, command.ActorID, command.Language, command.Source, nil, now) + if err != nil { + return FinalResult{}, fmt.Errorf("%s - build submission: %w", location, err) + } + if !practice.Status.AcceptsFinalSubmission() { + return finalRepeat(ctx, repository, practice, submission) + } + if err := repository.Submit(ctx, submission, request.record.Scope); err != nil { + return FinalResult{}, fmt.Errorf("%s - store final submission: %w", location, err) + } + practice.Status, practice.FailureReason, practice.SubmittedAt = domain.AssessmentPracticePending, "", now + if err := repository.SaveState(ctx, practice, now); err != nil { + return FinalResult{}, fmt.Errorf("%s - mark practice pending: %w", location, err) + } + return FinalResult{Practice: practice.View()}, nil +} + +// finalRepeat answers a final submission to a pending or finished practice: +// the stored solution sent again changes nothing, anything else conflicts. +func finalRepeat( + ctx context.Context, + repository outbound.AssessmentPracticeRepository, + practice domain.AssessmentPractice, + submission domain.PracticeSubmission, +) (FinalResult, error) { + const location = "practice.finalRepeat" + stored, found, err := repository.LatestFinal(ctx, practice.ID) + if err != nil { + return FinalResult{}, fmt.Errorf("%s - read stored solution: %w", location, err) + } + if !found || stored.Language != submission.Language || stored.SourceDigest != domain.DigestPracticeSource(submission.Source) { + return FinalResult{}, fmt.Errorf("%s - practice already has another solution: %w", location, ErrStateConflict) + } + return FinalResult{Practice: practice.View(), Unchanged: true}, nil +} + +// GetRun reads a debug run of the owner's attempt. +func (service *Service) GetRun( + ctx context.Context, + actorID uuid.UUID, + attemptID domain.AssessmentAttemptID, + runID uuid.UUID, +) (domain.PracticeRunView, error) { + const location = "Service.GetRun" + if actorID == uuid.Nil || attemptID.IsZero() || runID == uuid.Nil { + return domain.PracticeRunView{}, fmt.Errorf("%s - candidate, attempt, and run IDs are required: %w", location, ErrNotFound) + } + var run domain.PracticeRunView + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireCandidate(ctx, unit, actorID); err != nil { + return err + } + var readErr error + run, readErr = unit.AssessmentPractices().GetRun(ctx, actorID, attemptID, runID) + return mapNotFound(readErr) + }) + if err != nil { + return domain.PracticeRunView{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return run, nil +} + +type idempotentRequest struct { + record outbound.IdempotencyRecord +} + +// prepare checks what a command needs before any database work and derives +// its idempotency record. +func (service *Service) prepare( + operation string, + actorID uuid.UUID, + attemptID domain.AssessmentAttemptID, + practiceID uuid.UUID, + key string, + body canonicalRequest, +) (idempotentRequest, error) { + const location = "Service.prepare" + if actorID == uuid.Nil || attemptID.IsZero() || practiceID == uuid.Nil { + return idempotentRequest{}, fmt.Errorf("%s - candidate, attempt, and practice IDs are required: %w", location, ErrNotFound) + } + if !validIdempotencyKey(key) { + return idempotentRequest{}, fmt.Errorf("%s - check key: %w", location, ErrInvalidKey) + } + if body.Language != nil && !domain.TaskLanguageCode(*body.Language).IsKnown() { + return idempotentRequest{}, fmt.Errorf("%s - check language: %w", location, &FieldError{Field: FieldLanguage}) + } + body.PracticeID = practiceID.String() + canonical, err := json.Marshal(body) + if err != nil { + return idempotentRequest{}, fmt.Errorf("%s - encode request fingerprint: %w", location, ErrInvalidRequest) + } + now := service.clock().UTC().Truncate(time.Microsecond) + return idempotentRequest{record: outbound.IdempotencyRecord{ + Scope: service.keyring.IdempotencyScope(operation, key, actorID.String()), + Fingerprint: service.keyring.Fingerprint(canonical), + CreatedAt: now, + ExpiresAt: now.Add(outbound.IdempotencyRetention), + }}, nil +} + +// requireCandidate admits a verified candidate account only. +func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error { + const location = "practice.requireCandidate" + user, err := unit.Users().GetByID(ctx, actorID) + if errors.Is(err, outbound.ErrUserNotFound) { + return fmt.Errorf("%s - account is missing: %w", location, ErrForbidden) + } + if err != nil { + return fmt.Errorf("%s - read account: %w", location, err) + } + if !user.EmailVerified() || user.Scenario != domain.ScenarioCandidate { + return fmt.Errorf("%s - require a verified candidate: %w", location, ErrForbidden) + } + return nil +} + +// reserve takes the idempotency record in the transaction and reports a +// replay of the same request. A concurrent request with the same key waits +// for the first transaction. +func reserve(ctx context.Context, unit outbound.UnitOfWork, request idempotentRequest) (bool, error) { + const location = "practice.reserve" + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return false, fmt.Errorf("%s - reserve record: %w", location, err) + } + if created { + return false, nil + } + if stored.Fingerprint != request.record.Fingerprint { + return false, fmt.Errorf("%s - compare request fingerprint: %w", location, ErrKeyReused) + } + return true, nil +} + +// lockOpenPractice locks the attempt and the practice and checks that the +// practice is the current item of a running attempt. It returns the database +// time read under the attempt lock. +func lockOpenPractice( + ctx context.Context, + repository outbound.AssessmentPracticeRepository, + actorID uuid.UUID, + attemptID domain.AssessmentAttemptID, + practiceID uuid.UUID, +) (domain.AssessmentPractice, time.Time, error) { + const location = "practice.lockOpenPractice" + attempt, err := repository.LockAttempt(ctx, actorID, attemptID) + if err != nil { + return domain.AssessmentPractice{}, time.Time{}, fmt.Errorf("%s - lock attempt: %w", location, mapNotFound(err)) + } + practice, err := repository.LockPractice(ctx, actorID, attemptID, practiceID) + if err != nil { + return domain.AssessmentPractice{}, time.Time{}, fmt.Errorf("%s - lock practice: %w", location, mapNotFound(err)) + } + if attempt.State != practice.Kind.AttemptState() || !attempt.DatabaseTime.Before(attempt.ExpiresAt) { + return domain.AssessmentPractice{}, time.Time{}, fmt.Errorf("%s - attempt is not at this practice: %w", location, ErrStateConflict) + } + return practice, attempt.DatabaseTime, nil +} + +// newSubmission builds a submission and checks it against the task and the +// runner contract, so the queue never holds a request the runner refuses. +func newSubmission( + practice domain.AssessmentPractice, + mode domain.PracticeSubmissionMode, + actorID uuid.UUID, + language *domain.TaskLanguageCode, + source string, + tests []domain.PracticeTest, + now time.Time, +) (domain.PracticeSubmission, error) { + const location = "practice.newSubmission" + resolved, err := resolveLanguage(practice.Task, language) + if err != nil { + return domain.PracticeSubmission{}, fmt.Errorf("%s - resolve language: %w", location, err) + } + if err := domain.ValidatePracticeSource(source, practice.Task.MaxSourceLength); err != nil { + return domain.PracticeSubmission{}, fmt.Errorf("%s - validate source: %w", location, &FieldError{Field: FieldSource}) + } + id, err := uuid.NewV7() + if err != nil { + return domain.PracticeSubmission{}, fmt.Errorf("%s - generate submission ID: %w", location, err) + } + submission := domain.PracticeSubmission{ + ID: id, PracticeID: practice.ID, UserID: actorID, Mode: mode, Language: resolved, Source: source, + CustomTests: tests, CreatedAt: now, + } + if err := submission.Validate(practice.Task); err != nil { + return domain.PracticeSubmission{}, fmt.Errorf("%s - validate submission: %w", location, err) + } + // A task the runner would refuse is a content bug, not the candidate's. + if _, err := RunRequest(practice.Task, submission, 0); err != nil { + return domain.PracticeSubmission{}, fmt.Errorf("%s - build run request: %w", location, err) + } + return submission, nil +} + +// resolveLanguage returns the submitted language, or the only language of +// the task when none was sent. +func resolveLanguage(task domain.PracticeTask, language *domain.TaskLanguageCode) (domain.TaskLanguageCode, error) { + switch { + case language == nil && len(task.Languages) == 1: + return task.Languages[0], nil + case language != nil && task.AllowsLanguage(*language): + return *language, nil + default: + return "", &FieldError{Field: FieldLanguage} + } +} + +func languageText(language *domain.TaskLanguageCode) *string { + if language == nil { + return nil + } + text := string(*language) + return &text +} + +func mapNotFound(err error) error { + switch { + case err == nil: + return nil + case errors.Is(err, outbound.ErrAssessmentAttemptNotFound), errors.Is(err, outbound.ErrAssessmentPracticeNotFound), + errors.Is(err, outbound.ErrPracticeRunNotFound): + return fmt.Errorf("practice.mapNotFound - %w: %w", ErrNotFound, err) + default: + return err + } +} + +func validIdempotencyKey(value string) bool { + if len(value) == 0 || len(value) > maxIdempotencyKeyBytes { + return false + } + for index := range len(value) { + character := value[index] + if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' || + character >= '0' && character <= '9' || character == '.' || character == '_' || character == ':' || character == '-' { + continue + } + return false + } + return true +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 123bfd4..48c797e 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -786,13 +786,13 @@ A checker is set per group: `exact`, `tokens`, `numbers` (numeric tokens are equ Outcomes distinguish `accepted`, `wrong_answer`, `compile_error` (for Python, a syntax check with `compile()` before the tests; for Go, compile and link), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (including the process limit), and `infrastructure_failure`. Test time is the CPU time of every process of the test, including interpreter startup; memory is the cgroup peak of the test, including nsjail and file cache charged to the test. -Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; the run queue and the practice usecases that call the backend port (the port and its client are implemented, see below); service metrics; running the A16 suite on the runner VM. +Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; the worker of the run queue that calls the backend port, and scoring (the port, its client, and the stored submissions are implemented, see below); service metrics; running the A16 suite on the runner VM. The A16 hostile-program suite (`make -C runner test-a16`, see [checks](TESTING.md#a16-hostile-program-suite)) is implemented and passes locally. Code practice is enabled only after the suite has passed on the runner VM with the verdict `pass`; any failed case blocks enabling it. #### Backend port and client -Implemented: the outbound `CodeRunner` port (`backend/internal/port/outbound/code_runner.go`), its client over HTTPS (`backend/internal/adapter/secondary/code_runner/`, built on the generated client in `api/`), and the disabled runner (`code_runner/disabled/`). Bootstrap selects the runner from `CODE_RUNNER_URL` (`bootstrap/code_runner.go`): an unset URL selects the disabled runner, a set one the client, and an unusable setting stops startup instead of falling back. Nothing calls the port yet: the practice usecases, the run queue, and scoring are planned. The environment variables are in [DEPLOY.md](DEPLOY.md#code-runner-client). +Implemented: the outbound `CodeRunner` port (`backend/internal/port/outbound/code_runner.go`), its client over HTTPS (`backend/internal/adapter/secondary/code_runner/`, built on the generated client in `api/`), and the disabled runner (`code_runner/disabled/`). Bootstrap selects the runner from `CODE_RUNNER_URL` (`bootstrap/code_runner.go`): an unset URL selects the disabled runner, a set one the client, and an unusable setting stops startup instead of falling back. Nothing calls the port yet: the submissions it will run are stored (see [Practice submissions](#practice-submissions)), and the worker of the run queue and scoring are planned. The environment variables are in [DEPLOY.md](DEPLOY.md#code-runner-client). - What leaves the backend. A request holds the language, the source, the technical limits, and the test groups with their checkers; the checker program of a task family is part of a group. It holds no account, attempt, task, or company identifier and no name or contact. `CodeRunRequest.Validate` checks the runner contract rules (ranges, unique IDs, checker parameters, the CPU budget of 300000 ms, the payload size) before anything is sent. A request prints as `[redacted code run request]` in every format and in logs, because the source is candidate work and the hidden tests are task secrets. - Two calls, no hidden retries. `Submit` is idempotent by run key and reports `running`, `finished`, or `busy`; `Poll` reads the run without sending the payload again. Each makes one runner call and neither retries nor sleeps. `busy` is the runner's 503 `runner_busy`: the runner stored nothing, `RetryAfter` carries its `Retry-After`, and the caller keeps the queue and submits again with the same key. When the runner has lost a run (a restart or the retention time), `Poll` returns `ErrCodeRunNotFound` and the caller submits again. @@ -803,6 +803,19 @@ Implemented: the outbound `CodeRunner` port (`backend/internal/port/outbound/cod What the checks cover: the fixture tests run the client against a local TLS 1.3 stand-in that speaks the `api/runner` protocol (success, every outcome, compile error, runner timeout, busy, 401 and 5xx, malformed and contradictory answers, a stopped service, a foreign CA, TLS 1.2, idempotent retry). They do not prove sandbox isolation or behavior on the production runner VM. The run on a real runner is `make -C backend test-code-runner-live` (see DEPLOY) and has not been performed against the runner VM. +#### Practice submissions + +Implemented: the storage of practice items, their submissions, and the execution jobs, separate from the attempt snapshot and the result. Code: migration `00052_create_assessment_practice_submissions.sql`, the domain `backend/internal/domain/assessment_practice.go`, the port `outbound.AssessmentPracticeRepository` (`port/outbound/assessment_practice.go`), the repository `adapter/secondary/postgres/assessment_practice.go`, the usecase `backend/internal/usecase/practice/`, the handler `adapter/primary/http/v1/practice.go`, and the wiring `bootstrap/practice.go`. + +- Three tables. `assessment_practices` holds one practice item of an attempt, `main` or `additional` (one of each per attempt), with its private task content in `task` (languages, the source length bound, limits, the checker, the public examples, and exactly three hidden groups) and its state: `not_started`, `pending`, `finished`, or `failed` with `sandbox_busy` or `sandbox_error`. Its ID is the item ID the candidate sees and the attempt item of the run key. `assessment_practice_submissions` holds every submission: the mode `public` (a debug run) or `final` (the graded solution), the language, the source with its SHA-256, the candidate's own tests of a debug run, the idempotency scope, and the result, written once. `assessment_practice_jobs` holds the execution job of every submission. Triggers keep the identity and the task of a practice and the request part of a submission immutable: the database refuses to replace the source or the language of a stored submission, to write a second result, and to delete a submission other than by the cascade of its account, attempt, or practice. +- Transactional queue. A submission and its job (`queued`) are inserted in one transaction, so a job exists exactly when its submission committed, and a worker picks it later. The job table is the outbox of the runner: nothing outside PostgreSQL has to learn about a submission before it runs, so no Kafka event is written. +- Debug runs. `CreateMyAssessmentPracticeRun` (`POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs`) stores a `public` submission and answers 202 with the queued run; `GetMyAssessmentPracticeRun` reads it. A debug run carries the public examples and up to ten tests of the candidate and never a hidden group: the request built for the runner has none, and the response maps only the public groups of a stored result. The task content, the hidden tests, and the source never reach a response. A debug run changes neither the practice state nor the attempt version. +- Final solutions. `practice.Service.SubmitFinal` stores a `final` submission with its job and marks the practice `pending`. The stored solution sent again (the same language and source) stores nothing; another solution is refused while the practice is `pending` or `finished`, so the source of a graded solution never changes; a practice that failed in the sandbox accepts a solution again. No HTTP operation calls it yet: `SubmitMyAssessmentAnswer` will, once the attempt flow serves practice items, and then the attempt version advances in the same transaction. +- Gates. A practice accepts commands only while it is the current item: its attempt is in `practice_pending` (main) or `additional_practice_pending` (additional) and before its deadline, read under a share lock of the attempt. The account must be a verified candidate. Every read is scoped by the owner, so an attempt, practice, or run of another candidate reads as not found. Without `CODE_RUNNER_URL` the operations answer 503 and store nothing. +- Idempotency. A command reserves the generic idempotency record of its scope (a keyed digest of the operation, the key, and the account) in its transaction. A repeat with the same body within 24 hours returns the stored run or the current practice state, and another body answers `idempotency_key_reused`. Refusals are not stored and are evaluated again. + +The attempt flow does not serve practice items yet, so no practice exists in production; the assignment (`AssessmentPracticeRepository.Create`) is called by tests only. Retention of stored sources is not defined yet. + ## Matching and explanations Implemented as a deterministic search that never calls ML and reads precomputed vectors (see [Semantic layer and explanations](#semantic-layer-and-explanations)): `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. Visibility has no new query: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 36714c4..3aaff9b 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -642,6 +642,18 @@ On the runner host the suite runs from a bundle: `make -C runner a16-bundle` (`A What the tests do not prove: isolation in the production VM until the suite has passed there; protection against kernel, nsjail, or cgroup vulnerabilities; the absence of side channels (timing, CPU caches); or behavior under load. +## Code practice tests + +`TestAssessmentPracticeSubmissionStorage` in `backend/integration_test/assessment_practice_http_test.go` uses `bootstrap(t, postgresService, redisService)`, an isolated migrated database, the real router, the practice usecase, and the PostgreSQL repository. No flow serves practice items yet, so the test moves a real attempt to `practice_pending` and creates its main and additional practices directly; the synthetic task marks every hidden test text. The sequential cases are: + +- A debug run answers 202 with `Cache-Control: no-store`, is stored with exactly one queued job, and a repeat with the same key and body returns the same run without a new row; the same key with another body answers 422. Another candidate, another attempt, and an unknown run read as 404. +- Refusals store nothing: a practice of another candidate (404), the additional practice while the attempt is at the main one (409), and a source over the bound of the task (400). +- A stored result that also holds a hidden group is shown with the public tests only; the response has only the contract fields and no hidden text, source, or test text. +- A final solution marks the practice `pending` and is stored with one job; a replay returns it, the same solution under a new key stores nothing, another solution conflicts, and a reused key with another body is refused. The database refuses to replace the source or the language of the stored solution, to delete it, and to write a second result. After a sandbox failure the practice accepts another solution, and the first one stays as it was. +- With the runner disabled a run is refused as unavailable and nothing is stored. At the end every stored submission has exactly one job. + +`backend/internal/usecase/practice/request_test.go` checks that the runner request of a debug run holds only the public examples and the candidate's tests, and that of a final solution exactly the three hidden groups. The tests do not run code: the worker of the run queue is planned. + ## Semantic matching tests - ML service (`make -C ml test`, no model, no network): `tests/test_embeddings.py` checks the `POST /v1/embeddings` contract on the deterministic hash encoder: response order, normalization, equal vectors for two equal requests, micro-batches by length, 503 `service_unavailable` before readiness and ready only after the warm-up, 400 for too many texts, a length, and unknown fields, 413 for a body over the limit (with Content-Length and streamed), and no request text in the logs; `tests/test_model_files.py` checks the lock file (only safetensors and configs, a full revision, no code or pickle) and the size and SHA-256 verification. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index bce5c21..df10c79 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -786,13 +786,13 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи Исходы различают `accepted`, `wrong_answer`, `compile_error` (для Python - проверка синтаксиса через `compile()` до тестов, для Go - компиляция и линковка), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (включая лимит процессов) и `infrastructure_failure`. Время теста - CPU всех процессов теста вместе с запуском интерпретатора; память - пик cgroup теста, включая nsjail и файловый кеш, отнесенный к тесту. -Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; очередь прогонов и usecase практики, которые вызывают порт backend (порт и его клиент реализованы, см. ниже); метрики сервиса; прогон набора A16 на VM исполнителя. +Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; обработчик очереди прогонов, который вызывает порт backend, и подсчет баллов (порт, его клиент и хранение отправок реализованы, см. ниже); метрики сервиса; прогон набора A16 на VM исполнителя. Набор враждебных программ A16 (`make -C runner test-a16`, см. [проверки](TESTING.md#набор-враждебных-программ-a16)) реализован и проходит локально. Практика с кодом включается только после того, как набор прошел на VM исполнителя с вердиктом `pass`; любой проваленный случай блокирует включение. #### Порт и клиент в backend -Реализовано: исходящий порт `CodeRunner` (`backend/internal/port/outbound/code_runner.go`), его клиент по HTTPS (`backend/internal/adapter/secondary/code_runner/` поверх generated client в `api/`) и отключенный исполнитель (`code_runner/disabled/`). Bootstrap выбирает исполнителя по `CODE_RUNNER_URL` (`bootstrap/code_runner.go`): незаданный URL выбирает отключенного исполнителя, заданный - клиент, а непригодная настройка останавливает запуск и не откатывается к другому варианту. Порт пока никто не вызывает: usecase практики, очередь прогонов и подсчет баллов запланированы. Переменные окружения описаны в [DEPLOY.md](DEPLOY.md#клиент-исполнителя-кода). +Реализовано: исходящий порт `CodeRunner` (`backend/internal/port/outbound/code_runner.go`), его клиент по HTTPS (`backend/internal/adapter/secondary/code_runner/` поверх generated client в `api/`) и отключенный исполнитель (`code_runner/disabled/`). Bootstrap выбирает исполнителя по `CODE_RUNNER_URL` (`bootstrap/code_runner.go`): незаданный URL выбирает отключенного исполнителя, заданный - клиент, а непригодная настройка останавливает запуск и не откатывается к другому варианту. Порт пока никто не вызывает: отправки, которые он будет запускать, хранятся (см. [Отправки практики](#отправки-практики)), а обработчик очереди прогонов и подсчет баллов запланированы. Переменные окружения описаны в [DEPLOY.md](DEPLOY.md#клиент-исполнителя-кода). - Что уходит из backend. Запрос содержит язык, исходный код, технические лимиты и группы тестов с их checker; программа checker семейства задач входит в группу. В нем нет идентификатора аккаунта, попытки, задачи или компании, имени и контактов. `CodeRunRequest.Validate` проверяет правила контракта исполнителя (диапазоны, уникальные ID, параметры checker, CPU-бюджет 300000 мс, размер запроса) до отправки. Запрос печатается как `[redacted code run request]` в любом формате и в логах, потому что исходный код - работа кандидата, а скрытые тесты - секрет задачи. - Два вызова без скрытых повторов. `Submit` идемпотентен по ключу прогона и сообщает `running`, `finished` или `busy`; `Poll` читает прогон, не отправляя данные снова. Каждый делает один вызов исполнителя и не повторяет и не ждет. `busy` - это 503 `runner_busy` исполнителя: он ничего не сохранил, `RetryAfter` несет его `Retry-After`, а очередь ведет вызывающий и отправляет снова с тем же ключом. Если исполнитель потерял прогон (перезапуск или истекшее хранение), `Poll` возвращает `ErrCodeRunNotFound`, и вызывающий отправляет прогон заново. @@ -803,6 +803,19 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи Что покрывают проверки: тесты с fixture запускают клиент против локальной замены с TLS 1.3, которая говорит по протоколу `api/runner` (успех, каждый исход, ошибка компиляции, таймаут исполнителя, занятость, 401 и 5xx, искаженные и противоречивые ответы, остановленный сервис, чужой CA, TLS 1.2, идемпотентный повтор). Они не доказывают изоляцию песочницы и поведение на производственной VM исполнителя. Прогон на настоящем исполнителе - `make -C backend test-code-runner-live` (см. DEPLOY); против VM исполнителя он не выполнялся. +#### Отправки практики + +Реализовано: хранение элементов практики, их отправок и заданий на выполнение отдельно от снимка попытки и результата. Код: миграция `00052_create_assessment_practice_submissions.sql`, домен `backend/internal/domain/assessment_practice.go`, порт `outbound.AssessmentPracticeRepository` (`port/outbound/assessment_practice.go`), репозиторий `adapter/secondary/postgres/assessment_practice.go`, usecase `backend/internal/usecase/practice/`, обработчик `adapter/primary/http/v1/practice.go` и сборка `bootstrap/practice.go`. + +- Три таблицы. `assessment_practices` хранит один элемент практики попытки, `main` или `additional` (не больше одного каждого вида на попытку), с закрытым содержимым задачи в `task` (языки, предел длины кода, лимиты, checker, публичные примеры и ровно три скрытые группы) и его состояние: `not_started`, `pending`, `finished` или `failed` с `sandbox_busy` или `sandbox_error`. Его ID - это ID элемента, который видит кандидат, и элемент попытки в ключе прогона. `assessment_practice_submissions` хранит каждую отправку: режим `public` (отладочный прогон) или `final` (оцениваемое решение), язык, исходный код с его SHA-256, собственные тесты кандидата для отладочного прогона, область идемпотентности и результат, который записывается один раз. `assessment_practice_jobs` хранит задание на выполнение каждой отправки. Триггеры делают неизменяемыми идентичность и задачу практики и запросную часть отправки: база отказывает в замене исходного кода или языка сохраненной отправки, во второй записи результата и в удалении отправки иначе как каскадом от ее аккаунта, попытки или практики. +- Транзакционная очередь. Отправка и ее задание (`queued`) вставляются в одной транзакции, поэтому задание существует ровно тогда, когда зафиксирована его отправка, а обработчик берет его позже. Таблица заданий служит outbox для исполнителя: никому вне PostgreSQL не нужно узнавать об отправке до ее запуска, поэтому событие в Kafka не пишется. +- Отладочные прогоны. `CreateMyAssessmentPracticeRun` (`POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs`) сохраняет отправку `public` и отвечает 202 с прогоном в очереди; `GetMyAssessmentPracticeRun` читает его. Отладочный прогон несет публичные примеры и до десяти тестов кандидата и никогда не несет скрытую группу: в запросе к исполнителю ее нет, а ответ показывает только публичные группы сохраненного результата. Содержимое задачи, скрытые тесты и исходный код никогда не попадают в ответ. Отладочный прогон не меняет ни состояние практики, ни версию попытки. +- Финальные решения. `practice.Service.SubmitFinal` сохраняет отправку `final` с ее заданием и переводит практику в `pending`. Повтор сохраненного решения (тот же язык и код) ничего не сохраняет; другое решение отклоняется, пока практика в `pending` или `finished`, поэтому код оцениваемого решения никогда не меняется; практика, на которой сломалась песочница, снова принимает решение. HTTP-операция пока его не вызывает: это будет делать `SubmitMyAssessmentAnswer`, когда поток попытки начнет выдавать элементы практики, и тогда версия попытки будет расти в той же транзакции. +- Условия. Практика принимает команды, только пока она текущий элемент: ее попытка в `practice_pending` (main) или `additional_practice_pending` (additional) и срок не прошел; это читается под разделяемой блокировкой попытки. Аккаунт должен быть подтвержденным кандидатом. Каждое чтение ограничено владельцем, поэтому попытка, практика или прогон другого кандидата читаются как отсутствующие. Без `CODE_RUNNER_URL` операции отвечают 503 и ничего не сохраняют. +- Идемпотентность. Команда резервирует общую запись идемпотентности своей области (ключевой дайджест операции, ключа и аккаунта) в своей транзакции. Повтор с тем же телом в течение 24 часов возвращает сохраненный прогон или текущее состояние практики, а другое тело получает `idempotency_key_reused`. Отказы не сохраняются и вычисляются заново. + +Поток попытки пока не выдает элементы практики, поэтому в production практик нет; назначение (`AssessmentPracticeRepository.Create`) вызывают только тесты. Срок хранения исходного кода еще не определен. + ## Подбор и объяснение Реализован как детерминированный поиск, который не вызывает ML, а читает заранее вычисленные векторы (см. [Семантический слой и объяснения](#семантический-слой-и-объяснения)): `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Видимость не получила новых запросов: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 497bc2e..35a2119 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -642,6 +642,18 @@ Vitest работает в Node без DOM, поэтому ограничени Что тесты не доказывают: изоляцию в production VM, пока набор там не прошел; защиту от уязвимостей ядра, nsjail или cgroup; отсутствие побочных каналов (время, кеш процессора) и устойчивость под нагрузкой. +## Тесты практики с кодом + +`TestAssessmentPracticeSubmissionStorage` в `backend/integration_test/assessment_practice_http_test.go` использует `bootstrap(t, postgresService, redisService)`, изолированную базу с миграциями, настоящий роутер, usecase практики и репозиторий PostgreSQL. Поток попытки пока не выдает элементы практики, поэтому тест сам переводит настоящую попытку в `practice_pending` и создает ее основную и дополнительную практики; синтетическая задача помечает текст каждого скрытого теста. Последовательные случаи: + +- Отладочный прогон отвечает 202 с `Cache-Control: no-store` и сохраняется ровно с одним заданием в очереди, а повтор с тем же ключом и телом возвращает тот же прогон без новой строки; тот же ключ с другим телом получает 422. Другой кандидат, другая попытка и неизвестный прогон читаются как 404. +- Отказы ничего не сохраняют: практика другого кандидата (404), дополнительная практика, пока попытка на основной (409), и код длиннее предела задачи (400). +- Сохраненный результат, в котором есть и скрытая группа, показывается только с публичными тестами; в ответе только поля контракта и нет скрытого текста, исходного кода и текстов тестов. +- Финальное решение переводит практику в `pending` и сохраняется с одним заданием; повтор возвращает его, то же решение под новым ключом ничего не сохраняет, другое решение дает конфликт, а ключ с другим телом отклоняется. База отказывает в замене исходного кода или языка сохраненного решения, в его удалении и во второй записи результата. После сбоя песочницы практика принимает другое решение, а первое остается неизменным. +- С отключенным исполнителем прогон отклоняется как недоступный, и ничего не сохраняется. В конце у каждой сохраненной отправки ровно одно задание. + +`backend/internal/usecase/practice/request_test.go` проверяет, что запрос к исполнителю для отладочного прогона содержит только публичные примеры и тесты кандидата, а для финального решения - ровно три скрытые группы. Тесты не запускают код: обработчик очереди прогонов запланирован. + ## Тесты семантического подбора - ML-сервис (`make -C ml test`, без модели и сети): `tests/test_embeddings.py` проверяет контракт `POST /v1/embeddings` на детерминированном хеш-кодировщике: порядок ответа, нормировку, одинаковые векторы двух одинаковых запросов, микропакеты по длине, 503 `service_unavailable` до готовности и ready только после прогрева, 400 на лишние тексты, длину и неизвестные поля, 413 на тело больше лимита (с Content-Length и потоком), отсутствие текстов запроса в логах; `tests/test_model_files.py` проверяет lock-файл (только safetensors и конфиги, полная ревизия, без кода и pickle) и сверку размера и SHA-256. diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts index 6b38bbd..aacd02a 100644 --- a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts +++ b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts @@ -44,6 +44,8 @@ import type { NumberItemContent, OrderItemContent, PracticeItemContent, + PracticeRun, + PracticeRunResult, PracticeVerdict, StringItemContent } from '../../schemas'; @@ -181,6 +183,14 @@ export const getSubmitMyAssessmentAnswerResponseAssessmentExpressAttemptMock = ( export const getSubmitMyAssessmentAnswerResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentQualifiedAttemptMock()},{...getSubmitMyAssessmentAnswerResponseAssessmentCorrectiveAttemptMock()},{...getSubmitMyAssessmentAnswerResponseAssessmentExpressAttemptMock()},])) +export const getCreateMyAssessmentPracticeRunResponsePracticeRunResultMock = (overrideResponse: Partial = {}): PracticeRunResult => ({...{outcome: faker.helpers.arrayElement(['accepted','wrong_answer','compile_error','time_limit_exceeded','memory_limit_exceeded','output_limit_exceeded','runtime_error'] as const), compile_diagnostic: faker.helpers.arrayElement([faker.string.alpha({length: {min: 10, max: 4096}}),null,]), tests: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({source: faker.helpers.arrayElement(['example','candidate'] as const), index: faker.number.int({min: 1, max: 10}), outcome: faker.helpers.arrayElement(['accepted','wrong_answer','compile_error','time_limit_exceeded','memory_limit_exceeded','output_limit_exceeded','runtime_error'] as const), time_ms: faker.number.int({min: 0}), memory_kb: faker.number.int({min: 0}), diagnostic: faker.helpers.arrayElement([faker.string.alpha({length: {min: 10, max: 2048}}),null,])}))}, ...overrideResponse}); + +export const getCreateMyAssessmentPracticeRunResponseMock = (overrideResponse: Partial> = {}): PracticeRun => ({id: faker.string.uuid(), item_id: faker.string.uuid(), state: faker.helpers.arrayElement(['queued','running','finished','failed'] as const), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,]), result: faker.helpers.arrayElement([{...getCreateMyAssessmentPracticeRunResponsePracticeRunResultMock()},null,]), ...overrideResponse}) + +export const getGetMyAssessmentPracticeRunResponsePracticeRunResultMock = (overrideResponse: Partial = {}): PracticeRunResult => ({...{outcome: faker.helpers.arrayElement(['accepted','wrong_answer','compile_error','time_limit_exceeded','memory_limit_exceeded','output_limit_exceeded','runtime_error'] as const), compile_diagnostic: faker.helpers.arrayElement([faker.string.alpha({length: {min: 10, max: 4096}}),null,]), tests: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({source: faker.helpers.arrayElement(['example','candidate'] as const), index: faker.number.int({min: 1, max: 10}), outcome: faker.helpers.arrayElement(['accepted','wrong_answer','compile_error','time_limit_exceeded','memory_limit_exceeded','output_limit_exceeded','runtime_error'] as const), time_ms: faker.number.int({min: 0}), memory_kb: faker.number.int({min: 0}), diagnostic: faker.helpers.arrayElement([faker.string.alpha({length: {min: 10, max: 2048}}),null,])}))}, ...overrideResponse}); + +export const getGetMyAssessmentPracticeRunResponseMock = (overrideResponse: Partial> = {}): PracticeRun => ({id: faker.string.uuid(), item_id: faker.string.uuid(), state: faker.helpers.arrayElement(['queued','running','finished','failed'] as const), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,]), result: faker.helpers.arrayElement([{...getGetMyAssessmentPracticeRunResponsePracticeRunResultMock()},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: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); @@ -352,6 +362,30 @@ export const getSubmitMyAssessmentAnswerMockHandler = (overrideResponse?: Assess }, options) } +export const getCreateMyAssessmentPracticeRunMockHandler = (overrideResponse?: PracticeRun | ((info: Parameters[1]>[0]) => Promise | PracticeRun), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/assessment-attempts/:attemptId/practice-runs', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getCreateMyAssessmentPracticeRunResponseMock(), + { status: 202 + }) + }, options) +} + +export const getGetMyAssessmentPracticeRunMockHandler = (overrideResponse?: PracticeRun | ((info: Parameters[1]>[0]) => Promise | PracticeRun), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/assessment-attempts/:attemptId/practice-runs/:runId', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMyAssessmentPracticeRunResponseMock(), + { 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]) => { @@ -387,6 +421,8 @@ export const getAssessmentMock = () => [ getHoldMyAssessmentWorkSessionMockHandler(), getReleaseMyAssessmentWorkSessionMockHandler(), getSubmitMyAssessmentAnswerMockHandler(), + getCreateMyAssessmentPracticeRunMockHandler(), + getGetMyAssessmentPracticeRunMockHandler(), getFinalizeMyAssessmentAttemptMockHandler(), getGetMyAssessmentResultMockHandler() ] diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.ts b/frontend/src/shared/api/endpoints/assessment/assessment.ts index f2267c0..cc492da 100644 --- a/frontend/src/shared/api/endpoints/assessment/assessment.ts +++ b/frontend/src/shared/api/endpoints/assessment/assessment.ts @@ -39,9 +39,12 @@ import type { AssessmentSignalReceipt, AssessmentWorkSession, CreateMyAssessmentAttemptHeaders, + CreateMyAssessmentPracticeRunHeaders, FinalizeMyAssessmentAttemptHeaders, HoldMyAssessmentWorkSessionHeaders, ListMyAssessmentResultsParams, + PracticeRun, + PracticeRunCreate, Problem, RecordMyAssessmentAttemptSignalsHeaders, ReleaseMyAssessmentWorkSessionHeaders, @@ -1176,7 +1179,218 @@ export const useSubmitMyAssessmentAnswer = , > => { return useMutation(getSubmitMyAssessmentAnswerMutationOptions(options), queryClient); } - export const getFinalizeMyAssessmentAttemptUrl = (attemptId: string,) => { + export const getCreateMyAssessmentPracticeRunUrl = (attemptId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/practice-runs` +} + +/** + * 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 practice item of the attempt and carries the language, the source, and up to ten tests of the candidate. + * + * A debug run executes the solution in the isolated sandbox against the public examples of the task and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes neither the practice state, the verdict, nor the attempt version; the graded solution is submitted with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed asynchronously: the response is 202 with the run `queued`, and the client polls GetMyAssessmentPracticeRun. The source is never echoed. + * + * The practice must be the current item: the attempt is in `practice_pending` for the main practice or `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the server answers 409 state_conflict. + * + * Availability. When code practice is not enabled on this server, the server answers 503 service_unavailable and stores nothing. + * + * Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 503) are not stored under the key and are evaluated again. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), then the solution against the item (400 with a pointer such as `/language` or `/source_code`). + * @summary Start a debug run of a practice solution. + */ +export const createMyAssessmentPracticeRun = async (attemptId: string, + practiceRunCreate: PracticeRunCreate, + headers: CreateMyAssessmentPracticeRunHeaders, 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(getCreateMyAssessmentPracticeRunUrl(attemptId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(practiceRunCreate) + } +);} + + + + + +export const getCreateMyAssessmentPracticeRunMutationKey = () => ['createMyAssessmentPracticeRun'] as const; + +export const getCreateMyAssessmentPracticeRunMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMyAssessmentPracticeRunMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,CreateMyAssessmentPracticeRunMutationVariables, TContext> => { + +const mutationKey = getCreateMyAssessmentPracticeRunMutationKey(); +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>, CreateMyAssessmentPracticeRunMutationVariables> = (props) => { + const {attemptId,data,headers} = props ?? {}; + + return createMyAssessmentPracticeRun(attemptId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type CreateMyAssessmentPracticeRunMutationResult = NonNullable>> + export type CreateMyAssessmentPracticeRunMutationBody = PracticeRunCreate + export type CreateMyAssessmentPracticeRunMutationError = ErrorType + export type CreateMyAssessmentPracticeRunMutationVariables = {attemptId: string;data: PracticeRunCreate;headers: CreateMyAssessmentPracticeRunHeaders} + + /** + * @summary Start a debug run of a practice solution. + */ +export const useCreateMyAssessmentPracticeRun = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMyAssessmentPracticeRunMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + CreateMyAssessmentPracticeRunMutationVariables, + TContext + > => { + return useMutation(getCreateMyAssessmentPracticeRunMutationOptions(options), queryClient); + } + export const getGetMyAssessmentPracticeRunUrl = (attemptId: string, + runId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/practice-runs/${runId}` +} + +/** + * Requires the session cookie of a candidate account. Returns the state of a debug run started with CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source. This GET is read-only. + * + * A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is not readable here. + * @summary Read a debug run of a practice solution. + */ +export const getMyAssessmentPracticeRun = async (attemptId: string, + runId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyAssessmentPracticeRunUrl(attemptId,runId), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyAssessmentPracticeRunQueryKey = (attemptId: string, + runId: string,) => { + return [ + `/api/v1/me/assessment-attempts/${attemptId}/practice-runs/${runId}` + ] as const; + } + + +export const getGetMyAssessmentPracticeRunQueryOptions = >, TError = ErrorType>(attemptId: string, + runId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentPracticeRunQueryKey(attemptId,runId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyAssessmentPracticeRun(attemptId,runId, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: attemptId !== null && attemptId !== undefined && runId !== null && runId !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyAssessmentPracticeRunQueryResult = NonNullable>> +export type GetMyAssessmentPracticeRunQueryError = ErrorType + + +export function useGetMyAssessmentPracticeRun>, TError = ErrorType>( + attemptId: string, + runId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentPracticeRun>, TError = ErrorType>( + attemptId: string, + runId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentPracticeRun>, TError = ErrorType>( + attemptId: string, + runId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read a debug run of a practice solution. + */ + +export function useGetMyAssessmentPracticeRun>, TError = ErrorType>( + attemptId: string, + runId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyAssessmentPracticeRunQueryOptions(attemptId,runId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getFinalizeMyAssessmentAttemptUrl = (attemptId: string,) => { diff --git a/frontend/src/shared/api/schemas/assessment/createMyAssessmentPracticeRunBody.zod.ts b/frontend/src/shared/api/schemas/assessment/createMyAssessmentPracticeRunBody.zod.ts new file mode 100644 index 0000000..f25a472 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/createMyAssessmentPracticeRunBody.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 createMyAssessmentPracticeRunBodySourceCodeMax = 65536; + +export const createMyAssessmentPracticeRunBodyTestsItemInputMax = 10000; + +export const createMyAssessmentPracticeRunBodyTestsItemExpectedOutputMax = 10000; + +export const createMyAssessmentPracticeRunBodyTestsMax = 10; + + +export const CreateMyAssessmentPracticeRunBody = zod.object({ + "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.'), + "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(createMyAssessmentPracticeRunBodySourceCodeMax), + "tests": zod.array(zod.object({ + "input": zod.string().max(createMyAssessmentPracticeRunBodyTestsItemInputMax), + "expected_output": zod.string().max(createMyAssessmentPracticeRunBodyTestsItemExpectedOutputMax) +}).describe('One test of the candidate for a debug run: an input and the output the candidate expects. It is compared with the checker of the task.')).max(createMyAssessmentPracticeRunBodyTestsMax).exactOptional().describe('Tests of the candidate, run after the public examples.') +}).describe('Debug run of a practice solution against the public examples of the task and up to ten tests of the candidate. It never runs a hidden check and never changes the practice state, the verdict, or the attempt version. Unknown fields are rejected.') + +export type CreateMyAssessmentPracticeRunBody = zod.input; +export type CreateMyAssessmentPracticeRunBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/createMyAssessmentPracticeRunHeaders.zod.ts b/frontend/src/shared/api/schemas/assessment/createMyAssessmentPracticeRunHeaders.zod.ts new file mode 100644 index 0000000..01c29ad --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/createMyAssessmentPracticeRunHeaders.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 createMyAssessmentPracticeRunHeadersIdempotencyKeyMax = 255; + + +export const createMyAssessmentPracticeRunHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const CreateMyAssessmentPracticeRunHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(createMyAssessmentPracticeRunHeadersIdempotencyKeyMax).regex(createMyAssessmentPracticeRunHeadersIdempotencyKeyRegExp) +}) + +export type CreateMyAssessmentPracticeRunHeaders = zod.input; +export type CreateMyAssessmentPracticeRunHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/index.ts b/frontend/src/shared/api/schemas/assessment/index.ts index 8a128c9..f8d3cb4 100644 --- a/frontend/src/shared/api/schemas/assessment/index.ts +++ b/frontend/src/shared/api/schemas/assessment/index.ts @@ -78,6 +78,8 @@ export * from './configurationAnswer.zod'; export * from './configurationItemContent.zod'; export * from './createMyAssessmentAttemptBody.zod'; export * from './createMyAssessmentAttemptHeaders.zod'; +export * from './createMyAssessmentPracticeRunBody.zod'; +export * from './createMyAssessmentPracticeRunHeaders.zod'; export * from './finalizeMyAssessmentAttemptBody.zod'; export * from './finalizeMyAssessmentAttemptHeaders.zod'; export * from './findErrorAnswer.zod'; @@ -95,6 +97,14 @@ export * from './practiceFailureReason.zod'; export * from './practiceGroupResult.zod'; export * from './practiceItemContent.zod'; export * from './practiceKind.zod'; +export * from './practiceRun.zod'; +export * from './practiceRunCreate.zod'; +export * from './practiceRunOutcome.zod'; +export * from './practiceRunResult.zod'; +export * from './practiceRunState.zod'; +export * from './practiceRunTest.zod'; +export * from './practiceRunTestResult.zod'; +export * from './practiceRunTestSource.zod'; export * from './practiceStatus.zod'; export * from './practiceVerdict.zod'; export * from './recordMyAssessmentAttemptSignalsBody.zod'; diff --git a/frontend/src/shared/api/schemas/assessment/practiceRun.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceRun.zod.ts new file mode 100644 index 0000000..0fc67b8 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceRun.zod.ts @@ -0,0 +1,44 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const practiceRunResultOneCompileDiagnosticOneMax = 4096; + +export const practiceRunResultOneTestsItemIndexMax = 10; + +export const practiceRunResultOneTestsItemTimeMsMin = 0; + +export const practiceRunResultOneTestsItemMemoryKbMin = 0; + +export const practiceRunResultOneTestsItemDiagnosticOneMax = 2048; + +export const practiceRunResultOneTestsMax = 20; + + +export const PracticeRun = zod.object({ + "id": zod.uuid().describe('Identifier of the run.'), + "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.'), + "state": zod.enum(['queued', 'running', 'finished', 'failed']).describe('State of a debug run.\n\n- queued: the run waits in the sandbox queue.\n- running: the sandbox runs it.\n- finished: `result` holds the outcome of the public examples and the tests of the candidate.\n- failed: the sandbox infrastructure could not run it, independently of the solution; `failure_reason` is `sandbox_error`. Start a new run.\n\nAdding a value is a contract change.'), + "created_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.'), + "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 run reached `finished` or `failed`, or 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('`sandbox_error` when `state` is `failed`, otherwise null.'), + "result": zod.union([zod.object({ + "outcome": zod.enum(['accepted', 'wrong_answer', 'compile_error', 'time_limit_exceeded', 'memory_limit_exceeded', 'output_limit_exceeded', 'runtime_error']).describe('Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead.'), + "compile_diagnostic": zod.union([zod.string().max(practiceRunResultOneCompileDiagnosticOneMax),zod.null()]).describe('The compiler message when `outcome` is `compile_error`, otherwise null.'), + "tests": zod.array(zod.object({ + "source": zod.enum(['example', 'candidate']).describe('Where a test of a debug run comes from: a public example of the task or a test of the candidate.'), + "index": zod.int().min(1).max(practiceRunResultOneTestsItemIndexMax).describe('Position of the test in its source, from 1.'), + "outcome": zod.enum(['accepted', 'wrong_answer', 'compile_error', 'time_limit_exceeded', 'memory_limit_exceeded', 'output_limit_exceeded', 'runtime_error']).describe('Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead.'), + "time_ms": zod.int().min(practiceRunResultOneTestsItemTimeMsMin), + "memory_kb": zod.int().min(practiceRunResultOneTestsItemMemoryKbMin), + "diagnostic": zod.union([zod.string().max(practiceRunResultOneTestsItemDiagnosticOneMax),zod.null()]).describe('Truncated error output of a failed test, or null.') +}).describe('Outcome of one evaluated test. The tests of a source stop at the first failed one, so later tests of that source are not listed.')).max(practiceRunResultOneTestsMax) +}).describe('Result of a debug run on the public examples and the tests of the candidate. It never contains a hidden check, its outcome, or the score.'),zod.null()]).describe('The result when `state` is `finished`, otherwise null.') +}).describe('Debug run of a practice solution. It shows only the public examples and the tests of the candidate; hidden checks are never run, listed, or scored by a debug run.') + +export type PracticeRun = zod.input; +export type PracticeRunOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceRunCreate.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceRunCreate.zod.ts new file mode 100644 index 0000000..3a9dfe2 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceRunCreate.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 practiceRunCreateSourceCodeMax = 65536; + +export const practiceRunCreateTestsItemInputMax = 10000; + +export const practiceRunCreateTestsItemExpectedOutputMax = 10000; + +export const practiceRunCreateTestsMax = 10; + + +export const PracticeRunCreate = zod.object({ + "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.'), + "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(practiceRunCreateSourceCodeMax), + "tests": zod.array(zod.object({ + "input": zod.string().max(practiceRunCreateTestsItemInputMax), + "expected_output": zod.string().max(practiceRunCreateTestsItemExpectedOutputMax) +}).describe('One test of the candidate for a debug run: an input and the output the candidate expects. It is compared with the checker of the task.')).max(practiceRunCreateTestsMax).exactOptional().describe('Tests of the candidate, run after the public examples.') +}).describe('Debug run of a practice solution against the public examples of the task and up to ten tests of the candidate. It never runs a hidden check and never changes the practice state, the verdict, or the attempt version. Unknown fields are rejected.') + +export type PracticeRunCreate = zod.input; +export type PracticeRunCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceRunOutcome.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceRunOutcome.zod.ts new file mode 100644 index 0000000..9e0dcec --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceRunOutcome.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 PracticeRunOutcome = zod.enum(['accepted', 'wrong_answer', 'compile_error', 'time_limit_exceeded', 'memory_limit_exceeded', 'output_limit_exceeded', 'runtime_error']).describe('Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead.') + +export type PracticeRunOutcome = zod.input; +export type PracticeRunOutcomeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceRunResult.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceRunResult.zod.ts new file mode 100644 index 0000000..0c71edd --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceRunResult.zod.ts @@ -0,0 +1,36 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const practiceRunResultCompileDiagnosticOneMax = 4096; + +export const practiceRunResultTestsItemIndexMax = 10; + +export const practiceRunResultTestsItemTimeMsMin = 0; + +export const practiceRunResultTestsItemMemoryKbMin = 0; + +export const practiceRunResultTestsItemDiagnosticOneMax = 2048; + +export const practiceRunResultTestsMax = 20; + + +export const PracticeRunResult = zod.object({ + "outcome": zod.enum(['accepted', 'wrong_answer', 'compile_error', 'time_limit_exceeded', 'memory_limit_exceeded', 'output_limit_exceeded', 'runtime_error']).describe('Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead.'), + "compile_diagnostic": zod.union([zod.string().max(practiceRunResultCompileDiagnosticOneMax),zod.null()]).describe('The compiler message when `outcome` is `compile_error`, otherwise null.'), + "tests": zod.array(zod.object({ + "source": zod.enum(['example', 'candidate']).describe('Where a test of a debug run comes from: a public example of the task or a test of the candidate.'), + "index": zod.int().min(1).max(practiceRunResultTestsItemIndexMax).describe('Position of the test in its source, from 1.'), + "outcome": zod.enum(['accepted', 'wrong_answer', 'compile_error', 'time_limit_exceeded', 'memory_limit_exceeded', 'output_limit_exceeded', 'runtime_error']).describe('Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead.'), + "time_ms": zod.int().min(practiceRunResultTestsItemTimeMsMin), + "memory_kb": zod.int().min(practiceRunResultTestsItemMemoryKbMin), + "diagnostic": zod.union([zod.string().max(practiceRunResultTestsItemDiagnosticOneMax),zod.null()]).describe('Truncated error output of a failed test, or null.') +}).describe('Outcome of one evaluated test. The tests of a source stop at the first failed one, so later tests of that source are not listed.')).max(practiceRunResultTestsMax) +}).describe('Result of a debug run on the public examples and the tests of the candidate. It never contains a hidden check, its outcome, or the score.') + +export type PracticeRunResult = zod.input; +export type PracticeRunResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceRunState.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceRunState.zod.ts new file mode 100644 index 0000000..070fc88 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceRunState.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 PracticeRunState = zod.enum(['queued', 'running', 'finished', 'failed']).describe('State of a debug run.\n\n- queued: the run waits in the sandbox queue.\n- running: the sandbox runs it.\n- finished: `result` holds the outcome of the public examples and the tests of the candidate.\n- failed: the sandbox infrastructure could not run it, independently of the solution; `failure_reason` is `sandbox_error`. Start a new run.\n\nAdding a value is a contract change.') + +export type PracticeRunState = zod.input; +export type PracticeRunStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceRunTest.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceRunTest.zod.ts new file mode 100644 index 0000000..6765cf5 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceRunTest.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 practiceRunTestInputMax = 10000; + +export const practiceRunTestExpectedOutputMax = 10000; + + +export const PracticeRunTest = zod.object({ + "input": zod.string().max(practiceRunTestInputMax), + "expected_output": zod.string().max(practiceRunTestExpectedOutputMax) +}).describe('One test of the candidate for a debug run: an input and the output the candidate expects. It is compared with the checker of the task.') + +export type PracticeRunTest = zod.input; +export type PracticeRunTestOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceRunTestResult.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceRunTestResult.zod.ts new file mode 100644 index 0000000..ec3b4b9 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceRunTestResult.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 practiceRunTestResultIndexMax = 10; + +export const practiceRunTestResultTimeMsMin = 0; + +export const practiceRunTestResultMemoryKbMin = 0; + +export const practiceRunTestResultDiagnosticOneMax = 2048; + + +export const PracticeRunTestResult = zod.object({ + "source": zod.enum(['example', 'candidate']).describe('Where a test of a debug run comes from: a public example of the task or a test of the candidate.'), + "index": zod.int().min(1).max(practiceRunTestResultIndexMax).describe('Position of the test in its source, from 1.'), + "outcome": zod.enum(['accepted', 'wrong_answer', 'compile_error', 'time_limit_exceeded', 'memory_limit_exceeded', 'output_limit_exceeded', 'runtime_error']).describe('Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead.'), + "time_ms": zod.int().min(practiceRunTestResultTimeMsMin), + "memory_kb": zod.int().min(practiceRunTestResultMemoryKbMin), + "diagnostic": zod.union([zod.string().max(practiceRunTestResultDiagnosticOneMax),zod.null()]).describe('Truncated error output of a failed test, or null.') +}).describe('Outcome of one evaluated test. The tests of a source stop at the first failed one, so later tests of that source are not listed.') + +export type PracticeRunTestResult = zod.input; +export type PracticeRunTestResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/practiceRunTestSource.zod.ts b/frontend/src/shared/api/schemas/assessment/practiceRunTestSource.zod.ts new file mode 100644 index 0000000..79ad6dc --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/practiceRunTestSource.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 PracticeRunTestSource = zod.enum(['example', 'candidate']).describe('Where a test of a debug run comes from: a public example of the task or a test of the candidate.') + +export type PracticeRunTestSource = zod.input; +export type PracticeRunTestSourceOutput = zod.output; diff --git a/scripts/test_assessment_contract.py b/scripts/test_assessment_contract.py index f9b4206..d0ac7a0 100644 --- a/scripts/test_assessment_contract.py +++ b/scripts/test_assessment_contract.py @@ -362,6 +362,26 @@ class AssessmentContractTest(unittest.TestCase): self.assertIn("employer", result_description) self.assertIn("404", self.paths["/api/v1/me/assessment-attempts/{attempt_id}"]["get"]["responses"]) + def test_practice_runs_never_name_hidden_checks_or_scores(self) -> None: + forbidden = {"hidden", "hidden_checks", "hidden_groups", "seed", "score", "verdict", "source_code"} + run_schemas = ( + "PracticeRun", + "PracticeRunResult", + "PracticeRunTestResult", + ) + for name in run_schemas: + schema = self.schemas[name] + self.assertFalse(forbidden.intersection(schema.get("properties", {})), name) + self.assertFalse(schema.get("additionalProperties", True), name) + create = self.paths["/api/v1/me/assessment-attempts/{attempt_id}/practice-runs"]["post"] + read = self.paths["/api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}"]["get"] + self.assertEqual(create["operationId"], "CreateMyAssessmentPracticeRun") + self.assertEqual(read["operationId"], "GetMyAssessmentPracticeRun") + for operation, status in ((create, "202"), (read, "200")): + response = operation["responses"][status]["content"]["application/json"]["schema"] + self.assertEqual(referenced_schema_name(response), "PracticeRun") + self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}"]) + def test_signal_operation_is_bounded_private_and_separate_from_results(self) -> None: operation = self.paths[ "/api/v1/me/assessment-attempts/{attempt_id}/signals"