diff --git a/api/Makefile b/api/Makefile index a1f217e..f5ca14c 100644 --- a/api/Makefile +++ b/api/Makefile @@ -16,19 +16,22 @@ install: ## Install pinned OpenAPI tooling npm ci --prefix "$(API_DIR)" --ignore-scripts --no-audit --no-fund .PHONY: bundle -bundle: ## Merge split schemas and create public, ML, and code runner bundles +bundle: ## Merge split schemas and create public, ML, code runner, and lab provisioner bundles "$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/core" "$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/ml" "$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/runner" + "$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/labd" "$(REDOCLY)" bundle "$(API_DIR)/core/openapi.yml" --output "$(API_DIR)/core/openapi.bundle.yml" "$(REDOCLY)" bundle "$(API_DIR)/ml/openapi.yml" --output "$(API_DIR)/ml/openapi.bundle.yml" "$(REDOCLY)" bundle "$(API_DIR)/runner/openapi.yml" --output "$(API_DIR)/runner/openapi.bundle.yml" + "$(REDOCLY)" bundle "$(API_DIR)/labd/openapi.yml" --output "$(API_DIR)/labd/openapi.bundle.yml" .PHONY: lint lint: bundle ## Lint every bundled contract "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/core/openapi.bundle.yml" "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/ml/openapi.bundle.yml" "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/runner/openapi.bundle.yml" + "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/labd/openapi.bundle.yml" .PHONY: check check: lint ## Build and lint every contract bundle and run the contract tests @@ -37,6 +40,7 @@ check: lint ## Build and lint every contract bundle and run the contract tests PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_assessment_contract.py' PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_match_contract.py' PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_runner_contract.py' + PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_lab_contract.py' .PHONY: check-compat check-compat: bundle ## Compare the public contract with API_BASE_REF diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index f524b7c..2dd5318 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -476,6 +476,7 @@ ItemContent: - $ref: '#/FindErrorItemContent' - $ref: '#/ConfigurationItemContent' - $ref: '#/PracticeItemContent' + - $ref: '#/LabItemContent' AssessmentItem: type: object description: 'Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.' @@ -4829,6 +4830,214 @@ InvitationDeclineRequest: oneOf: - $ref: '#/InvitationDeclineComment' - type: 'null' +AssessmentLabNodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: ^[a-z][a-z0-9-]{0,14}$ + description: Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address. +AssessmentLabNodeKind: + type: string + description: 'What the console of a node shows. + + + - mikrotik: a MikroTik router with the RouterOS console. + + - ubuntu: a small Ubuntu server with a Linux login. + + + Adding a value is a contract change.' + enum: + - mikrotik + - ubuntu +AssessmentLabNode: + type: object + description: A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: '#/AssessmentLabNodeName' + kind: + $ref: '#/AssessmentLabNodeKind' +LabItemContent: + type: object + description: 'Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.' + additionalProperties: false + required: + - format + - nodes + - time_limit_seconds + properties: + format: + type: string + enum: + - lab + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the lab in the order of the statement. + items: + $ref: '#/AssessmentLabNode' + time_limit_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline. +LabAnswer: + type: object + description: 'Answer of a lab item: the state of the nodes of the named lab at the moment of submission. The server reads that state with the checker of the task; the body carries no configuration text, score, or correctness flag. Two answers are equal when they name the same lab. It is the answer of SubmitMyAssessmentLab only and is not a member of AssessmentAnswer.' + additionalProperties: false + required: + - format + - lab_id + properties: + format: + type: string + enum: + - lab + lab_id: + type: string + format: uuid + description: The lab of this item that the candidate worked in. +AssessmentLabState: + type: string + description: 'State of a lab of an attempt item. + + + - provisioning: the nodes are being prepared; poll GetMyAssessmentLab. + + - ready: the consoles can be opened until `expires_at`. + + - checking: the answer was accepted; the consoles are closed and the server checks the nodes. + + - submitted: the check finished and the answer is recorded; the lab is deleted. The state never says whether the answer was correct. + + - expired: the lifetime or the attempt deadline ended before a submission; the lab is deleted and the item cannot start another lab. + + - failed: the lab infrastructure failed, independently of the candidate; `failure_reason` is `lab_error`. Nothing was recorded or consumed, and the candidate may start a new lab of the same item while the item is current. + + + Adding a value is a contract change.' + enum: + - provisioning + - ready + - checking + - submitted + - expired + - failed +AssessmentLabFailureReason: + type: string + description: 'Why a lab failed: `lab_error` for an infrastructure failure, such as a node that did not boot or a check that could not reach a node. It never depends on the candidate and is never a failed check.' + enum: + - lab_error +AssessmentLab: + type: object + description: Candidate view of the lab of one attempt item. It contains no node address, MAC address, port, password, key, token, seed, checker state, criteria, score, or infrastructure name. + additionalProperties: false + required: + - id + - item_id + - state + - nodes + - created_at + - ready_at + - expires_at + - finished_at + - failure_reason + properties: + id: + type: string + format: uuid + description: Identifier of the lab. + item_id: + $ref: '#/AssessmentItemId' + state: + $ref: '#/AssessmentLabState' + nodes: + type: array + minItems: 1 + maxItems: 8 + items: + $ref: '#/AssessmentLabNode' + created_at: + $ref: '#/Timestamp' + ready_at: + description: Time the lab became `ready`, or null before. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + expires_at: + description: 'Time the lab ends unless it was submitted before: the earlier of the lifetime of the item and the attempt deadline. It never moves.' + $ref: '#/Timestamp' + finished_at: + description: Time the lab reached `submitted`, `expired`, or `failed`, or null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + failure_reason: + description: '`lab_error` when `state` is `failed`, otherwise null.' + oneOf: + - $ref: '#/AssessmentLabFailureReason' + - type: 'null' +AssessmentLabCreate: + type: object + description: Start the lab of the current lab item. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + properties: + item_id: + $ref: '#/AssessmentItemId' +AssessmentLabConsoleSessionCreate: + type: object + description: Open a console of one node of a ready lab. Unknown fields are rejected. + additionalProperties: false + required: + - node + properties: + node: + $ref: '#/AssessmentLabNodeName' +AssessmentLabConsoleSession: + type: object + description: A console session of one node. The client opens a WebSocket to `websocket_path` on the same origin before `expires_at`; the session cookie and the Origin check authorize the upgrade, so no secret travels in the path, the body, or a query string. A session can be attached once and ends with the lab. + additionalProperties: false + required: + - id + - node + - websocket_path + - expires_at + properties: + id: + type: string + format: uuid + description: Identifier of the console session; it is not a secret. + node: + $ref: '#/AssessmentLabNodeName' + websocket_path: + type: string + maxLength: 128 + pattern: ^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$ + description: Same-origin path of the console WebSocket. + expires_at: + description: Time by which the WebSocket must be opened. + $ref: '#/Timestamp' +AssessmentLabSubmission: + type: object + description: Submit the lab of the current lab item as its answer. Unknown fields are rejected, so a request cannot send a score or a correctness flag. + additionalProperties: false + required: + - expected_version + - answer + properties: + expected_version: + $ref: '#/AssessmentAttemptVersion' + answer: + $ref: '#/LabAnswer' MatchConfirmationStatus: type: string description: Confirmation state for this specialization only. A result for one specialization never changes the state of another specialization. diff --git a/api/core/components/schemas/assessment_schemas.yml b/api/core/components/schemas/assessment_schemas.yml index 80d36a0..4d5030d 100644 --- a/api/core/components/schemas/assessment_schemas.yml +++ b/api/core/components/schemas/assessment_schemas.yml @@ -511,6 +511,7 @@ schemas: - $ref: "#/schemas/FindErrorItemContent" - $ref: "#/schemas/ConfigurationItemContent" - $ref: "#/schemas/PracticeItemContent" + - $ref: "./lab_schemas.yml#/schemas/LabItemContent" AssessmentItem: type: object description: >- diff --git a/api/core/components/schemas/lab_schemas.yml b/api/core/components/schemas/lab_schemas.yml new file mode 100644 index 0000000..28ca48d --- /dev/null +++ b/api/core/components/schemas/lab_schemas.yml @@ -0,0 +1,236 @@ +schemas: + AssessmentLabNodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: "^[a-z][a-z0-9-]{0,14}$" + description: >- + Name of a lab node as the task statement uses it, such as `r1` or + `srv`. It is a label of the task, not a host name or an address. + AssessmentLabNodeKind: + type: string + description: |- + What the console of a node shows. + + - mikrotik: a MikroTik router with the RouterOS console. + - ubuntu: a small Ubuntu server with a Linux login. + + Adding a value is a contract change. + enum: + - mikrotik + - ubuntu + AssessmentLabNode: + type: object + description: >- + A node of a lab by its task name and kind. It never carries an address, + a MAC address, a port, a password, a key, or an infrastructure name. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: "#/schemas/AssessmentLabNodeName" + kind: + $ref: "#/schemas/AssessmentLabNodeKind" + LabItemContent: + type: object + description: >- + Practical lab: configure or repair a small network of virtual nodes + through their consoles. The candidate starts the lab of the item with + CreateMyAssessmentLab, works in the node consoles, and submits with + SubmitMyAssessmentLab; the server then checks the state of the nodes. + The content lists only the nodes the statement names and the lifetime + of the lab, never the checker, its criteria, the seed, or an address. + SubmitMyAssessmentAnswer takes no answer to a lab item; its result is + submitted only with SubmitMyAssessmentLab. + additionalProperties: false + required: + - format + - nodes + - time_limit_seconds + properties: + format: + type: string + enum: + - lab + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the lab in the order of the statement. + items: + $ref: "#/schemas/AssessmentLabNode" + time_limit_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: >- + Lifetime of a lab of this item from its creation. The lab also ends + no later than the attempt deadline. + LabAnswer: + type: object + description: >- + Answer of a lab item: the state of the nodes of the named lab at the + moment of submission. The server reads that state with the checker of + the task; the body carries no configuration text, score, or + correctness flag. Two answers are equal when they name the same lab. + It is the answer of SubmitMyAssessmentLab only and is not a member of + AssessmentAnswer. + additionalProperties: false + required: + - format + - lab_id + properties: + format: + type: string + enum: + - lab + lab_id: + type: string + format: uuid + description: The lab of this item that the candidate worked in. + AssessmentLabState: + type: string + description: |- + State of a lab of an attempt item. + + - provisioning: the nodes are being prepared; poll GetMyAssessmentLab. + - ready: the consoles can be opened until `expires_at`. + - checking: the answer was accepted; the consoles are closed and the server checks the nodes. + - submitted: the check finished and the answer is recorded; the lab is deleted. The state never says whether the answer was correct. + - expired: the lifetime or the attempt deadline ended before a submission; the lab is deleted and the item cannot start another lab. + - failed: the lab infrastructure failed, independently of the candidate; `failure_reason` is `lab_error`. Nothing was recorded or consumed, and the candidate may start a new lab of the same item while the item is current. + + Adding a value is a contract change. + enum: + - provisioning + - ready + - checking + - submitted + - expired + - failed + AssessmentLabFailureReason: + type: string + description: >- + Why a lab failed: `lab_error` for an infrastructure failure, such as a + node that did not boot or a check that could not reach a node. It never + depends on the candidate and is never a failed check. + enum: + - lab_error + AssessmentLab: + type: object + description: >- + Candidate view of the lab of one attempt item. It contains no node + address, MAC address, port, password, key, token, seed, checker state, + criteria, score, or infrastructure name. + additionalProperties: false + required: + - id + - item_id + - state + - nodes + - created_at + - ready_at + - expires_at + - finished_at + - failure_reason + properties: + id: + type: string + format: uuid + description: Identifier of the lab. + item_id: + $ref: "./assessment_schemas.yml#/schemas/AssessmentItemId" + state: + $ref: "#/schemas/AssessmentLabState" + nodes: + type: array + minItems: 1 + maxItems: 8 + items: + $ref: "#/schemas/AssessmentLabNode" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + ready_at: + description: Time the lab became `ready`, or null before. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + expires_at: + description: >- + Time the lab ends unless it was submitted before: the earlier of the + lifetime of the item and the attempt deadline. It never moves. + $ref: "./common_schemas.yml#/schemas/Timestamp" + finished_at: + description: Time the lab reached `submitted`, `expired`, or `failed`, or null. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + failure_reason: + description: "`lab_error` when `state` is `failed`, otherwise null." + oneOf: + - $ref: "#/schemas/AssessmentLabFailureReason" + - type: "null" + AssessmentLabCreate: + type: object + description: Start the lab of the current lab item. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + properties: + item_id: + $ref: "./assessment_schemas.yml#/schemas/AssessmentItemId" + AssessmentLabConsoleSessionCreate: + type: object + description: Open a console of one node of a ready lab. Unknown fields are rejected. + additionalProperties: false + required: + - node + properties: + node: + $ref: "#/schemas/AssessmentLabNodeName" + AssessmentLabConsoleSession: + type: object + description: >- + A console session of one node. The client opens a WebSocket to + `websocket_path` on the same origin before `expires_at`; the session + cookie and the Origin check authorize the upgrade, so no secret travels + in the path, the body, or a query string. A session can be attached + once and ends with the lab. + additionalProperties: false + required: + - id + - node + - websocket_path + - expires_at + properties: + id: + type: string + format: uuid + description: Identifier of the console session; it is not a secret. + node: + $ref: "#/schemas/AssessmentLabNodeName" + websocket_path: + type: string + maxLength: 128 + pattern: "^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$" + description: Same-origin path of the console WebSocket. + expires_at: + description: Time by which the WebSocket must be opened. + $ref: "./common_schemas.yml#/schemas/Timestamp" + AssessmentLabSubmission: + type: object + description: >- + Submit the lab of the current lab item as its answer. Unknown fields + are rejected, so a request cannot send a score or a correctness flag. + additionalProperties: false + required: + - expected_version + - answer + properties: + expected_version: + $ref: "./assessment_schemas.yml#/schemas/AssessmentAttemptVersion" + answer: + $ref: "#/schemas/LabAnswer" diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 96861b9..51f3fd6 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -1201,6 +1201,8 @@ paths: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision. + Lab: an item with format `lab` takes no answer here. Its lab is started with CreateMyAssessmentLab and submitted with SubmitMyAssessmentLab; any answer to a lab item answers 400 validation_failed with the pointer `/answer/format`, like an answer in the wrong format, and stores nothing. + The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command never starts one or consumes session quota. Reading the attempt or result is always read-only. A command that finds a due deadline transition may commit it before returning; a command that finds an expired idle session answers 409 until the candidate explicitly starts the next session. @@ -3832,6 +3834,310 @@ paths: $ref: '#/components/responses/NotFound' default: $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/labs: + post: + operationId: CreateMyAssessmentLab + summary: Start the lab of the current lab item of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the current item, whose content has the format `lab`. + + The server asks the lab provisioner for a lab of the variant fixed for this item instance and answers 201 with the lab `provisioning`; the client polls GetMyAssessmentLab until it is `ready`. The lab lives until `expires_at`, the earlier of the item's `time_limit_seconds` and the attempt deadline, and is then deleted with everything done in it. Creating a lab does not change the attempt version, the current item, or any answer. + + One lab per item at a time. While the item has a lab in `provisioning`, `ready`, or `checking`, the server answers 200 with that lab and starts no second one. After a `failed` lab the candidate may start a new one while the item is current; after `submitted` or `expired` the item cannot start another lab (409 state_conflict). + + Busy pool. When the lab pool of the provisioner has no free capacity, the server answers 503 service_unavailable with Retry-After, for example `{"type": "urn:lincodex:problem:service_unavailable", "title": "Service unavailable", "status": 503, "code": "service_unavailable", "detail": "No lab capacity is free. The attempt is unchanged; retry later."}`. Nothing was stored: no lab exists, the attempt version and the current item are unchanged, the lab lifetime has not started, and the attempt is not consumed; the client retries after Retry-After with a new Idempotency-Key. When labs are not enabled on this server, or the provisioner cannot be reached, the server answers 503 service_unavailable without Retry-After and stores nothing either. The attempt deadline keeps running in both cases. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the item (404 not_found for an unknown attempt or item, or one of another candidate), the state (409 state_conflict: the attempt is terminal or its work session ended, the item is not current, its format is not `lab`, or its lab was submitted or expired), the rate limit (429), then the availability of labs and the capacity (503). Following the Idempotency-Key convention, 201, 200, 404, and 409 state_conflict are stored under the key and replayed; 400, 429, and 503 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLabCreate' + examples: + start: + summary: Start the lab of the current item. + value: + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + responses: + '200': + description: The item already has an active lab; it is returned and no second lab is started. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLab' + '201': + description: The lab was requested and is provisioning. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLab' + examples: + provisioning: + summary: A lab of two routers that is being prepared. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: provisioning + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: '2026-10-11T09:00:00Z' + ready_at: null + expires_at: '2026-10-11T09:45:00Z' + finished_at: null + failure_reason: 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/AssessmentCommandConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}: + get: + operationId: GetMyAssessmentLab + summary: Read the lab of an assessment attempt item. + description: |- + Requires the session cookie of a candidate account. Returns the state of a lab started with CreateMyAssessmentLab: whether it is still provisioning, ready for the consoles, being checked after the submission, or ended. It never contains a node address, a credential, the seed, the checker state, or the result of the check. This GET is read-only; the server may record a due timer transition, such as `ready` to `expired`, before it answers. + + A lab of another candidate's attempt, a lab of another attempt, and an unknown identifier all answer 404 not_found. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - name: lab_id + in: path + required: true + description: Identifier of a lab of this attempt. + schema: + type: string + format: uuid + responses: + '200': + description: The lab. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLab' + examples: + ready: + summary: A ready lab whose consoles can be opened. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: ready + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: '2026-10-11T09:00:00Z' + ready_at: '2026-10-11T09:00:40Z' + expires_at: '2026-10-11T09:45:00Z' + finished_at: null + failure_reason: 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}/labs/{lab_id}/console-sessions: + post: + operationId: CreateMyAssessmentLabConsoleSession + summary: Open a console session of one node of a ready lab. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body names a node of the lab by its task name. + + The response describes one console session: the client opens a WebSocket to `websocket_path` on the same origin before `expires_at`. The upgrade is authorized by the session cookie and the Origin check, and the server relays the serial console of the node through the lab provisioner. The response never carries a node address, a port, a password, a key, or a token; the browser never connects to a node or to the provisioner. Console traffic is not stored as an answer and is not logged. + + The WebSocket relay is planned together with the candidate interface of labs; this contract fixes the session shape it uses. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt and the lab (404 not_found for an unknown attempt, lab, or one of another candidate), the node (400 with the pointer `/node`), the state (409 state_conflict: the lab is not `ready`, the attempt is terminal, or its work session ended), the limit of open sessions per lab (429 rate_limited with Retry-After), then the provisioner (503 service_unavailable without Retry-After; nothing was opened). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - name: lab_id + in: path + required: true + description: Identifier of a lab of this attempt. + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLabConsoleSessionCreate' + examples: + r1: + summary: Open the console of r1. + value: + node: r1 + responses: + '201': + description: The console session was opened. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLabConsoleSession' + examples: + opened: + summary: A console session of r1. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a90 + node: r1 + websocket_path: /api/v1/me/assessment-lab-consoles/0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a90 + expires_at: '2026-10-11T09:02:00Z' + '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' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/submission: + post: + operationId: SubmitMyAssessmentLab + summary: Submit the lab of the current lab item as its answer. + 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 carries the attempt version last read and the answer with format `lab`, which names the lab. + + The server closes the consoles, freezes the lab, and answers 202 with the lab `checking`; the checker of the task reads the state of the nodes asynchronously, the answer is recorded, and the lab becomes `submitted` and is deleted. The client polls GetMyAssessmentLab and then reads the attempt, which moves to the next item. Neither response says whether the answer was correct, and the candidate never sees the checker criteria or their results. + + When the checker cannot reach the nodes because of the lab infrastructure, the lab becomes `failed` with `lab_error`: nothing is recorded or consumed, the attempt version is unchanged, and the candidate may start a new lab of the item while it is current. A failure of the infrastructure is never scored as a wrong answer. + + Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the lab (404 not_found for an unknown attempt or lab, or one of another candidate), the version (412), the state (409 state_conflict: the lab is not `ready`, `answer.lab_id` is not the lab in the path, the item is not current, the attempt is terminal, or its work session ended), then the provisioner (503 service_unavailable without Retry-After; nothing was stored and the lab keeps running). Following the Idempotency-Key convention, 202, 404, and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + - name: lab_id + in: path + required: true + description: Identifier of the lab to submit. + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLabSubmission' + examples: + submit: + summary: Submit the lab as the answer of its item. + value: + expected_version: 7 + answer: + format: lab + lab_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + responses: + '202': + description: The submission was accepted and the lab is being checked. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLab' + examples: + checking: + summary: A submitted lab whose nodes are being checked. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: checking + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: '2026-10-11T09:00:00Z' + ready_at: '2026-10-11T09:00:40Z' + expires_at: '2026-10-11T09:45:00Z' + finished_at: null + failure_reason: 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/AssessmentCommandConflict' + '412': + $ref: '#/components/responses/AssessmentVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/Problem' components: schemas: Problem: @@ -5712,6 +6018,7 @@ components: - $ref: '#/components/schemas/FindErrorItemContent' - $ref: '#/components/schemas/ConfigurationItemContent' - $ref: '#/components/schemas/PracticeItemContent' + - $ref: '#/components/schemas/LabItemContent' AssessmentItem: type: object description: 'Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.' @@ -10531,6 +10838,206 @@ components: description: Identifier of the marked item. read_at: $ref: '#/components/schemas/Timestamp' + AssessmentLabNodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: ^[a-z][a-z0-9-]{0,14}$ + description: Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address. + AssessmentLabNodeKind: + type: string + description: |- + What the console of a node shows. + + - mikrotik: a MikroTik router with the RouterOS console. + - ubuntu: a small Ubuntu server with a Linux login. + + Adding a value is a contract change. + enum: + - mikrotik + - ubuntu + AssessmentLabNode: + type: object + description: A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: '#/components/schemas/AssessmentLabNodeName' + kind: + $ref: '#/components/schemas/AssessmentLabNodeKind' + LabItemContent: + type: object + description: 'Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.' + additionalProperties: false + required: + - format + - nodes + - time_limit_seconds + properties: + format: + type: string + enum: + - lab + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the lab in the order of the statement. + items: + $ref: '#/components/schemas/AssessmentLabNode' + time_limit_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline. + LabAnswer: + type: object + description: 'Answer of a lab item: the state of the nodes of the named lab at the moment of submission. The server reads that state with the checker of the task; the body carries no configuration text, score, or correctness flag. Two answers are equal when they name the same lab. It is the answer of SubmitMyAssessmentLab only and is not a member of AssessmentAnswer.' + additionalProperties: false + required: + - format + - lab_id + properties: + format: + type: string + enum: + - lab + lab_id: + type: string + format: uuid + description: The lab of this item that the candidate worked in. + AssessmentLabState: + type: string + description: |- + State of a lab of an attempt item. + + - provisioning: the nodes are being prepared; poll GetMyAssessmentLab. + - ready: the consoles can be opened until `expires_at`. + - checking: the answer was accepted; the consoles are closed and the server checks the nodes. + - submitted: the check finished and the answer is recorded; the lab is deleted. The state never says whether the answer was correct. + - expired: the lifetime or the attempt deadline ended before a submission; the lab is deleted and the item cannot start another lab. + - failed: the lab infrastructure failed, independently of the candidate; `failure_reason` is `lab_error`. Nothing was recorded or consumed, and the candidate may start a new lab of the same item while the item is current. + + Adding a value is a contract change. + enum: + - provisioning + - ready + - checking + - submitted + - expired + - failed + AssessmentLabFailureReason: + type: string + description: 'Why a lab failed: `lab_error` for an infrastructure failure, such as a node that did not boot or a check that could not reach a node. It never depends on the candidate and is never a failed check.' + enum: + - lab_error + AssessmentLab: + type: object + description: Candidate view of the lab of one attempt item. It contains no node address, MAC address, port, password, key, token, seed, checker state, criteria, score, or infrastructure name. + additionalProperties: false + required: + - id + - item_id + - state + - nodes + - created_at + - ready_at + - expires_at + - finished_at + - failure_reason + properties: + id: + type: string + format: uuid + description: Identifier of the lab. + item_id: + $ref: '#/components/schemas/AssessmentItemId' + state: + $ref: '#/components/schemas/AssessmentLabState' + nodes: + type: array + minItems: 1 + maxItems: 8 + items: + $ref: '#/components/schemas/AssessmentLabNode' + created_at: + $ref: '#/components/schemas/Timestamp' + ready_at: + description: Time the lab became `ready`, or null before. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + expires_at: + description: 'Time the lab ends unless it was submitted before: the earlier of the lifetime of the item and the attempt deadline. It never moves.' + $ref: '#/components/schemas/Timestamp' + finished_at: + description: Time the lab reached `submitted`, `expired`, or `failed`, or null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + failure_reason: + description: '`lab_error` when `state` is `failed`, otherwise null.' + oneOf: + - $ref: '#/components/schemas/AssessmentLabFailureReason' + - type: 'null' + AssessmentLabCreate: + type: object + description: Start the lab of the current lab item. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + properties: + item_id: + $ref: '#/components/schemas/AssessmentItemId' + AssessmentLabConsoleSessionCreate: + type: object + description: Open a console of one node of a ready lab. Unknown fields are rejected. + additionalProperties: false + required: + - node + properties: + node: + $ref: '#/components/schemas/AssessmentLabNodeName' + AssessmentLabConsoleSession: + type: object + description: A console session of one node. The client opens a WebSocket to `websocket_path` on the same origin before `expires_at`; the session cookie and the Origin check authorize the upgrade, so no secret travels in the path, the body, or a query string. A session can be attached once and ends with the lab. + additionalProperties: false + required: + - id + - node + - websocket_path + - expires_at + properties: + id: + type: string + format: uuid + description: Identifier of the console session; it is not a secret. + node: + $ref: '#/components/schemas/AssessmentLabNodeName' + websocket_path: + type: string + maxLength: 128 + pattern: ^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$ + description: Same-origin path of the console WebSocket. + expires_at: + description: Time by which the WebSocket must be opened. + $ref: '#/components/schemas/Timestamp' + AssessmentLabSubmission: + type: object + description: Submit the lab of the current lab item as its answer. Unknown fields are rejected, so a request cannot send a score or a correctness flag. + additionalProperties: false + required: + - expected_version + - answer + properties: + expected_version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + answer: + $ref: '#/components/schemas/LabAnswer' HealthResponse: type: object additionalProperties: false diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 871f084..054f39b 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -225,6 +225,14 @@ paths: $ref: ./routes/support_cases.yml /api/v1/me/support-cases/{case_id}: $ref: ./routes/support_case.yml + /api/v1/me/assessment-attempts/{attempt_id}/labs: + $ref: ./routes/candidate_assessment_attempt_labs.yml + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}: + $ref: ./routes/candidate_assessment_attempt_lab.yml + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/console-sessions: + $ref: ./routes/candidate_assessment_attempt_lab_console_sessions.yml + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/submission: + $ref: ./routes/candidate_assessment_attempt_lab_submission.yml components: schemas: Problem: @@ -963,6 +971,30 @@ components: $ref: ./components/schemas.yml#/NotificationList NotificationReadReceipt: $ref: ./components/schemas.yml#/NotificationReadReceipt + AssessmentLabNodeName: + $ref: ./components/schemas.yml#/AssessmentLabNodeName + AssessmentLabNodeKind: + $ref: ./components/schemas.yml#/AssessmentLabNodeKind + AssessmentLabNode: + $ref: ./components/schemas.yml#/AssessmentLabNode + LabItemContent: + $ref: ./components/schemas.yml#/LabItemContent + LabAnswer: + $ref: ./components/schemas.yml#/LabAnswer + AssessmentLabState: + $ref: ./components/schemas.yml#/AssessmentLabState + AssessmentLabFailureReason: + $ref: ./components/schemas.yml#/AssessmentLabFailureReason + AssessmentLab: + $ref: ./components/schemas.yml#/AssessmentLab + AssessmentLabCreate: + $ref: ./components/schemas.yml#/AssessmentLabCreate + AssessmentLabConsoleSessionCreate: + $ref: ./components/schemas.yml#/AssessmentLabConsoleSessionCreate + AssessmentLabConsoleSession: + $ref: ./components/schemas.yml#/AssessmentLabConsoleSession + AssessmentLabSubmission: + $ref: ./components/schemas.yml#/AssessmentLabSubmission parameters: IdempotencyKey: $ref: ./components/parameters.yml#/IdempotencyKey diff --git a/api/core/routes/candidate_assessment_attempt_answers.yml b/api/core/routes/candidate_assessment_attempt_answers.yml index 28dd937..2e1ef04 100644 --- a/api/core/routes/candidate_assessment_attempt_answers.yml +++ b/api/core/routes/candidate_assessment_attempt_answers.yml @@ -4,6 +4,8 @@ post: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision. + Lab: an item with format `lab` takes no answer here. Its lab is started with CreateMyAssessmentLab and submitted with SubmitMyAssessmentLab; any answer to a lab item answers 400 validation_failed with the pointer `/answer/format`, like an answer in the wrong format, and stores nothing. + The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command never starts one or consumes session quota. Reading the attempt or result is always read-only. A command that finds a due deadline transition may commit it before returning; a command that finds an expired idle session answers 409 until the candidate explicitly starts the next session. diff --git a/api/core/routes/candidate_assessment_attempt_lab.yml b/api/core/routes/candidate_assessment_attempt_lab.yml new file mode 100644 index 0000000..1b63c1b --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_lab.yml @@ -0,0 +1,55 @@ +get: + operationId: GetMyAssessmentLab + summary: Read the lab of an assessment attempt item. + description: |- + Requires the session cookie of a candidate account. Returns the state of a lab started with CreateMyAssessmentLab: whether it is still provisioning, ready for the consoles, being checked after the submission, or ended. It never contains a node address, a credential, the seed, the checker state, or the result of the check. This GET is read-only; the server may record a due timer transition, such as `ready` to `expired`, before it answers. + + A lab of another candidate's attempt, a lab of another attempt, and an unknown identifier all answer 404 not_found. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - name: lab_id + in: path + required: true + description: Identifier of a lab of this attempt. + schema: + type: string + format: uuid + responses: + "200": + description: The lab. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLab + examples: + ready: + summary: A ready lab whose consoles can be opened. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: ready + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: "2026-10-11T09:00:00Z" + ready_at: "2026-10-11T09:00:40Z" + expires_at: "2026-10-11T09:45:00Z" + finished_at: null + failure_reason: 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_lab_console_sessions.yml b/api/core/routes/candidate_assessment_attempt_lab_console_sessions.yml new file mode 100644 index 0000000..fc5cf56 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_lab_console_sessions.yml @@ -0,0 +1,70 @@ +post: + operationId: CreateMyAssessmentLabConsoleSession + summary: Open a console session of one node of a ready lab. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body names a node of the lab by its task name. + + The response describes one console session: the client opens a WebSocket to `websocket_path` on the same origin before `expires_at`. The upgrade is authorized by the session cookie and the Origin check, and the server relays the serial console of the node through the lab provisioner. The response never carries a node address, a port, a password, a key, or a token; the browser never connects to a node or to the provisioner. Console traffic is not stored as an answer and is not logged. + + The WebSocket relay is planned together with the candidate interface of labs; this contract fixes the session shape it uses. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt and the lab (404 not_found for an unknown attempt, lab, or one of another candidate), the node (400 with the pointer `/node`), the state (409 state_conflict: the lab is not `ready`, the attempt is terminal, or its work session ended), the limit of open sessions per lab (429 rate_limited with Retry-After), then the provisioner (503 service_unavailable without Retry-After; nothing was opened). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - name: lab_id + in: path + required: true + description: Identifier of a lab of this attempt. + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLabConsoleSessionCreate + examples: + r1: + summary: Open the console of r1. + value: + node: r1 + responses: + "201": + description: The console session was opened. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLabConsoleSession + examples: + opened: + summary: A console session of r1. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a90 + node: r1 + websocket_path: /api/v1/me/assessment-lab-consoles/0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a90 + expires_at: "2026-10-11T09:02:00Z" + "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 + "429": + $ref: ../components/responses.yml#/TooManyRequests + "503": + $ref: ../components/responses.yml#/ServiceUnavailable + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_lab_submission.yml b/api/core/routes/candidate_assessment_attempt_lab_submission.yml new file mode 100644 index 0000000..f0241d1 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_lab_submission.yml @@ -0,0 +1,89 @@ +post: + operationId: SubmitMyAssessmentLab + summary: Submit the lab of the current lab item as its answer. + 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 carries the attempt version last read and the answer with format `lab`, which names the lab. + + The server closes the consoles, freezes the lab, and answers 202 with the lab `checking`; the checker of the task reads the state of the nodes asynchronously, the answer is recorded, and the lab becomes `submitted` and is deleted. The client polls GetMyAssessmentLab and then reads the attempt, which moves to the next item. Neither response says whether the answer was correct, and the candidate never sees the checker criteria or their results. + + When the checker cannot reach the nodes because of the lab infrastructure, the lab becomes `failed` with `lab_error`: nothing is recorded or consumed, the attempt version is unchanged, and the candidate may start a new lab of the item while it is current. A failure of the infrastructure is never scored as a wrong answer. + + Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the lab (404 not_found for an unknown attempt or lab, or one of another candidate), the version (412), the state (409 state_conflict: the lab is not `ready`, `answer.lab_id` is not the lab in the path, the item is not current, the attempt is terminal, or its work session ended), then the provisioner (503 service_unavailable without Retry-After; nothing was stored and the lab keeps running). Following the Idempotency-Key convention, 202, 404, and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + - name: lab_id + in: path + required: true + description: Identifier of the lab to submit. + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLabSubmission + examples: + submit: + summary: Submit the lab as the answer of its item. + value: + expected_version: 7 + answer: + format: lab + lab_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + responses: + "202": + description: The submission was accepted and the lab is being checked. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLab + examples: + checking: + summary: A submitted lab whose nodes are being checked. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: checking + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: "2026-10-11T09:00:00Z" + ready_at: "2026-10-11T09:00:40Z" + expires_at: "2026-10-11T09:45:00Z" + finished_at: null + failure_reason: 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#/AssessmentCommandConflict + "412": + $ref: ../components/responses.yml#/AssessmentVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + "503": + $ref: ../components/responses.yml#/ServiceUnavailable + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_labs.yml b/api/core/routes/candidate_assessment_attempt_labs.yml new file mode 100644 index 0000000..53a8be7 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_labs.yml @@ -0,0 +1,86 @@ +post: + operationId: CreateMyAssessmentLab + summary: Start the lab of the current lab item of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the current item, whose content has the format `lab`. + + The server asks the lab provisioner for a lab of the variant fixed for this item instance and answers 201 with the lab `provisioning`; the client polls GetMyAssessmentLab until it is `ready`. The lab lives until `expires_at`, the earlier of the item's `time_limit_seconds` and the attempt deadline, and is then deleted with everything done in it. Creating a lab does not change the attempt version, the current item, or any answer. + + One lab per item at a time. While the item has a lab in `provisioning`, `ready`, or `checking`, the server answers 200 with that lab and starts no second one. After a `failed` lab the candidate may start a new one while the item is current; after `submitted` or `expired` the item cannot start another lab (409 state_conflict). + + Busy pool. When the lab pool of the provisioner has no free capacity, the server answers 503 service_unavailable with Retry-After, for example `{"type": "urn:lincodex:problem:service_unavailable", "title": "Service unavailable", "status": 503, "code": "service_unavailable", "detail": "No lab capacity is free. The attempt is unchanged; retry later."}`. Nothing was stored: no lab exists, the attempt version and the current item are unchanged, the lab lifetime has not started, and the attempt is not consumed; the client retries after Retry-After with a new Idempotency-Key. When labs are not enabled on this server, or the provisioner cannot be reached, the server answers 503 service_unavailable without Retry-After and stores nothing either. The attempt deadline keeps running in both cases. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the item (404 not_found for an unknown attempt or item, or one of another candidate), the state (409 state_conflict: the attempt is terminal or its work session ended, the item is not current, its format is not `lab`, or its lab was submitted or expired), the rate limit (429), then the availability of labs and the capacity (503). Following the Idempotency-Key convention, 201, 200, 404, and 409 state_conflict are stored under the key and replayed; 400, 429, and 503 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLabCreate + examples: + start: + summary: Start the lab of the current item. + value: + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + responses: + "200": + description: The item already has an active lab; it is returned and no second lab is started. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLab + "201": + description: The lab was requested and is provisioning. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLab + examples: + provisioning: + summary: A lab of two routers that is being prepared. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: provisioning + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: "2026-10-11T09:00:00Z" + ready_at: null + expires_at: "2026-10-11T09:45:00Z" + finished_at: null + failure_reason: 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#/AssessmentCommandConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + "503": + $ref: ../components/responses.yml#/ServiceUnavailable + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/components/parameters.yml b/api/labd/components/parameters.yml new file mode 100644 index 0000000..e1e714b --- /dev/null +++ b/api/labd/components/parameters.yml @@ -0,0 +1,11 @@ +LabId: + name: lab_id + in: path + required: true + description: >- + Random UUID chosen by the backend for one lab. It is the idempotency key + of CreateLab and must not encode a candidate, attempt, or task + identifier. + schema: + type: string + format: uuid diff --git a/api/labd/components/responses.yml b/api/labd/components/responses.yml new file mode 100644 index 0000000..cf67c53 --- /dev/null +++ b/api/labd/components/responses.yml @@ -0,0 +1,67 @@ +Problem: + description: >- + Any error response. The body is a Problem whose `status` equals the HTTP + status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + summary: The template is unknown + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: body + pointer: /template_id + code: invalid + message: The value does not match the contract. + state_conflict: + summary: The lab is not ready + value: + type: urn:lincodex:problem:state_conflict + title: State conflict + status: 409 + code: state_conflict + detail: The lab is not ready. + lab_unavailable: + summary: The checker could not reach a node + value: + type: urn:lincodex:problem:lab_unavailable + title: Lab unavailable + status: 503 + code: lab_unavailable + detail: The lab could not be evaluated. Nothing was checked. +LabPoolBusy: + description: >- + The lab does not fit the memory budget or the lab limit of the + provisioner, or the provisioner is draining; code lab_pool_busy. Nothing + was stored and no capacity was reserved. Retry with the same lab ID after + Retry-After. + headers: + Retry-After: + description: Number of seconds to wait before retrying the request. + required: true + schema: + type: integer + format: int32 + minimum: 0 + maximum: 3600 + example: 30 + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + lab_pool_busy: + summary: No capacity for another lab + value: + type: urn:lincodex:problem:lab_pool_busy + title: Lab pool busy + status: 503 + code: lab_pool_busy + detail: No capacity for another lab. Retry later with the same lab ID. diff --git a/api/labd/components/schemas.yml b/api/labd/components/schemas.yml new file mode 100644 index 0000000..38a7441 --- /dev/null +++ b/api/labd/components/schemas.yml @@ -0,0 +1,391 @@ +LabdHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok +LabdReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready +TemplateId: + type: string + minLength: 1 + maxLength: 48 + pattern: ^[a-z0-9][a-z0-9-]{0,47}$ + description: Identifier of a lab template known to the provisioner, such as `mikrotik-ospf-pair`. Templates are part of the provisioner build; the request never carries node images, commands, or configuration. +NodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: ^[a-z][a-z0-9-]{0,14}$ + description: Name of a node inside its template, such as `r1` or `srv`. It is the same in every lab of the template and is not an LXD instance name or a host name. +NodeKind: + type: string + description: 'Guest system of a node. + + + - mikrotik: a MikroTik Cloud Hosted Router VM; its console is RouterOS. + + - ubuntu: a small Ubuntu VM; its console is a Linux login. + + + Adding a value is a contract change.' + enum: + - mikrotik + - ubuntu +LabCreateRequest: + type: object + description: A lab of one template variant. It has no field for a candidate, account, attempt, task, or company. + additionalProperties: false + required: + - template_id + - template_version + - seed + - ttl_seconds + properties: + template_id: + $ref: '#/TemplateId' + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + description: Version of the template. The provisioner refuses a version it does not hold, so a lab always matches the variant the backend served. + seed: + type: string + minLength: 64 + maxLength: 64 + pattern: ^[0-9a-f]{64}$ + description: 'Variant seed: 32 random bytes in lowercase hex chosen by the backend for the item instance. The template renders the variant configuration of every node and the checker criteria from it. It is never returned by the provisioner.' + ttl_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: Lifetime of the lab from its creation. The provisioner refuses a value above its configured maximum. +LabState: + type: string + description: 'State of a lab. + + + - provisioning: capacity is reserved and the nodes are being cloned, connected, and booted. + + - ready: every node answers on its management port; console tokens and checks are allowed. + + - deleting: the timer ended, DeleteLab was called, or provisioning failed; the instances and bridges are being removed. + + - deleted: every instance and bridge of the lab is gone and its capacity is free. + + - failed: provisioning failed or timed out, or the provisioner restarted while provisioning; `failure_reason` says which. Its resources are removed as for `deleting` and the capacity returns once they are gone; create a new lab with a new ID. + + + Adding a value is a contract change.' + enum: + - provisioning + - ready + - deleting + - deleted + - failed +LabFailureReason: + type: string + description: 'Why a lab failed. None of the reasons depends on the person who uses the lab. + + + - provisioning_failed: LXD refused or failed an operation of the provisioning. + + - provisioning_timed_out: a node did not answer on its management port within the provisioning timeout. + + - interrupted: the provisioner process stopped while the lab was provisioning.' + enum: + - provisioning_failed + - provisioning_timed_out + - interrupted +LabNode: + type: object + description: A node of a lab by its template name and kind. It never carries an address, a MAC address, an instance name, or a credential. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: '#/NodeName' + kind: + $ref: '#/NodeKind' +LabStatus: + type: object + description: State of a lab after one call. It never contains the seed, a node address, a key, a password, or an LXD object name. + additionalProperties: false + required: + - lab_id + - state + - template_id + - template_version + - created_at + - expires_at + - nodes + properties: + lab_id: + type: string + format: uuid + state: + $ref: '#/LabState' + template_id: + $ref: '#/TemplateId' + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + created_at: + type: string + format: date-time + ready_at: + type: string + format: date-time + description: Time the lab became `ready`; absent before. + expires_at: + type: string + format: date-time + description: Time the provisioner deletes the lab. It never moves, also not across restarts of the provisioner. + deleted_at: + type: string + format: date-time + description: Time the last resource of the lab was removed; absent before. + failure_reason: + $ref: '#/LabFailureReason' + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the template in template order. + items: + $ref: '#/LabNode' +ConsoleTokenRequest: + type: object + additionalProperties: false + required: + - node + properties: + node: + $ref: '#/NodeName' +ConsoleToken: + type: object + description: 'Single-use console token for one node. The token is a secret of the console gateway: it is never logged, stored by the backend, or passed to a browser.' + additionalProperties: false + required: + - token + - node + - expires_at + - attach_path + properties: + token: + type: string + minLength: 43 + maxLength: 43 + pattern: ^[A-Za-z0-9_-]{43}$ + description: 32 random bytes in unpadded base64url. + node: + $ref: '#/NodeName' + expires_at: + type: string + format: date-time + attach_path: + type: string + maxLength: 128 + pattern: ^/v1/labs/[0-9a-f-]{36}/console$ + description: Path of the WebSocket attach on the provisioner origin. +CriterionId: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9][a-z0-9_-]{0,31}$ + description: Opaque identifier of a checker criterion of the template. +CriterionResult: + type: object + additionalProperties: false + required: + - id + - passed + properties: + id: + $ref: '#/CriterionId' + passed: + type: boolean +LabCheckResult: + type: object + description: 'Result of one check: whether each criterion of the variant holds on the nodes. It carries no node output, address, or configuration text.' + additionalProperties: false + required: + - lab_id + - checked_at + - score + - max_score + - criteria + properties: + lab_id: + type: string + format: uuid + checked_at: + type: string + format: date-time + score: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of passed criteria. + max_score: + type: integer + format: int32 + minimum: 1 + maximum: 50 + description: Number of criteria. + criteria: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: '#/CriterionResult' +Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the lab provisioner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/ProblemFieldError' +ProblemCode: + type: string + description: 'Stable error code of the lab provisioner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + + - validation_failed (400): parameters or body do not match the contract or a semantic rule, such as an unknown template or node; `errors` points at the fields. + + - unauthenticated (401): the bearer token is missing or wrong. + + - not_found (404): the route or the lab does not exist. + + - method_not_allowed (405): the route does not support the method. + + - state_conflict (409): the lab is not in a state that allows the operation, for example a console token or a check for a lab that is not ready. + + - payload_too_large (413): the request body exceeds the limit. + + - unsupported_media_type (415): the request Content-Type is not accepted. + + - idempotency_key_reused (422): the lab ID was already used with a different payload. + + - internal (500): unexpected server error. + + - not_implemented (501): the route is described but not implemented yet, such as the console attach. + + - lab_pool_busy (503): the lab does not fit the capacity or the provisioner is draining; see Retry-After. + + - lab_unavailable (503): LXD or a node could not be reached, so nothing was done or evaluated. It is an infrastructure failure, never a failed check. + + + The Problem shape is the api/core shape; only this enum is specific to the lab provisioner.' + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - state_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - not_implemented + - lab_pool_busy + - lab_unavailable +ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/ttl_seconds`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/lab_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. +ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/labd/components/schemas/health_schemas.yml b/api/labd/components/schemas/health_schemas.yml new file mode 100644 index 0000000..353249e --- /dev/null +++ b/api/labd/components/schemas/health_schemas.yml @@ -0,0 +1,22 @@ +schemas: + LabdHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok + LabdReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready diff --git a/api/labd/components/schemas/lab_schemas.yml b/api/labd/components/schemas/lab_schemas.yml new file mode 100644 index 0000000..d79ce65 --- /dev/null +++ b/api/labd/components/schemas/lab_schemas.yml @@ -0,0 +1,259 @@ +schemas: + TemplateId: + type: string + minLength: 1 + maxLength: 48 + pattern: "^[a-z0-9][a-z0-9-]{0,47}$" + description: >- + Identifier of a lab template known to the provisioner, such as + `mikrotik-ospf-pair`. Templates are part of the provisioner build; the + request never carries node images, commands, or configuration. + NodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: "^[a-z][a-z0-9-]{0,14}$" + description: >- + Name of a node inside its template, such as `r1` or `srv`. It is the + same in every lab of the template and is not an LXD instance name or a + host name. + NodeKind: + type: string + description: |- + Guest system of a node. + + - mikrotik: a MikroTik Cloud Hosted Router VM; its console is RouterOS. + - ubuntu: a small Ubuntu VM; its console is a Linux login. + + Adding a value is a contract change. + enum: + - mikrotik + - ubuntu + LabCreateRequest: + type: object + description: >- + A lab of one template variant. It has no field for a candidate, + account, attempt, task, or company. + additionalProperties: false + required: + - template_id + - template_version + - seed + - ttl_seconds + properties: + template_id: + $ref: "#/schemas/TemplateId" + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + description: >- + Version of the template. The provisioner refuses a version it does + not hold, so a lab always matches the variant the backend served. + seed: + type: string + minLength: 64 + maxLength: 64 + pattern: "^[0-9a-f]{64}$" + description: >- + Variant seed: 32 random bytes in lowercase hex chosen by the + backend for the item instance. The template renders the variant + configuration of every node and the checker criteria from it. It + is never returned by the provisioner. + ttl_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: >- + Lifetime of the lab from its creation. The provisioner refuses a + value above its configured maximum. + LabState: + type: string + description: |- + State of a lab. + + - provisioning: capacity is reserved and the nodes are being cloned, connected, and booted. + - ready: every node answers on its management port; console tokens and checks are allowed. + - deleting: the timer ended, DeleteLab was called, or provisioning failed; the instances and bridges are being removed. + - deleted: every instance and bridge of the lab is gone and its capacity is free. + - failed: provisioning failed or timed out, or the provisioner restarted while provisioning; `failure_reason` says which. Its resources are removed as for `deleting` and the capacity returns once they are gone; create a new lab with a new ID. + + Adding a value is a contract change. + enum: + - provisioning + - ready + - deleting + - deleted + - failed + LabFailureReason: + type: string + description: |- + Why a lab failed. None of the reasons depends on the person who uses the lab. + + - provisioning_failed: LXD refused or failed an operation of the provisioning. + - provisioning_timed_out: a node did not answer on its management port within the provisioning timeout. + - interrupted: the provisioner process stopped while the lab was provisioning. + enum: + - provisioning_failed + - provisioning_timed_out + - interrupted + LabNode: + type: object + description: >- + A node of a lab by its template name and kind. It never carries an + address, a MAC address, an instance name, or a credential. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: "#/schemas/NodeName" + kind: + $ref: "#/schemas/NodeKind" + LabStatus: + type: object + description: >- + State of a lab after one call. It never contains the seed, a node + address, a key, a password, or an LXD object name. + additionalProperties: false + required: + - lab_id + - state + - template_id + - template_version + - created_at + - expires_at + - nodes + properties: + lab_id: + type: string + format: uuid + state: + $ref: "#/schemas/LabState" + template_id: + $ref: "#/schemas/TemplateId" + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + created_at: + type: string + format: date-time + ready_at: + type: string + format: date-time + description: Time the lab became `ready`; absent before. + expires_at: + type: string + format: date-time + description: >- + Time the provisioner deletes the lab. It never moves, also not + across restarts of the provisioner. + deleted_at: + type: string + format: date-time + description: Time the last resource of the lab was removed; absent before. + failure_reason: + $ref: "#/schemas/LabFailureReason" + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the template in template order. + items: + $ref: "#/schemas/LabNode" + ConsoleTokenRequest: + type: object + additionalProperties: false + required: + - node + properties: + node: + $ref: "#/schemas/NodeName" + ConsoleToken: + type: object + description: >- + Single-use console token for one node. The token is a secret of the + console gateway: it is never logged, stored by the backend, or passed + to a browser. + additionalProperties: false + required: + - token + - node + - expires_at + - attach_path + properties: + token: + type: string + minLength: 43 + maxLength: 43 + pattern: "^[A-Za-z0-9_-]{43}$" + description: 32 random bytes in unpadded base64url. + node: + $ref: "#/schemas/NodeName" + expires_at: + type: string + format: date-time + attach_path: + type: string + maxLength: 128 + pattern: "^/v1/labs/[0-9a-f-]{36}/console$" + description: Path of the WebSocket attach on the provisioner origin. + CriterionId: + type: string + minLength: 1 + maxLength: 32 + pattern: "^[a-z0-9][a-z0-9_-]{0,31}$" + description: Opaque identifier of a checker criterion of the template. + CriterionResult: + type: object + additionalProperties: false + required: + - id + - passed + properties: + id: + $ref: "#/schemas/CriterionId" + passed: + type: boolean + LabCheckResult: + type: object + description: >- + Result of one check: whether each criterion of the variant holds on the + nodes. It carries no node output, address, or configuration text. + additionalProperties: false + required: + - lab_id + - checked_at + - score + - max_score + - criteria + properties: + lab_id: + type: string + format: uuid + checked_at: + type: string + format: date-time + score: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of passed criteria. + max_score: + type: integer + format: int32 + minimum: 1 + maximum: 50 + description: Number of criteria. + criteria: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: "#/schemas/CriterionResult" diff --git a/api/labd/components/schemas/problem_schemas.yml b/api/labd/components/schemas/problem_schemas.yml new file mode 100644 index 0000000..dfa0cda --- /dev/null +++ b/api/labd/components/schemas/problem_schemas.yml @@ -0,0 +1,144 @@ +schemas: + Problem: + type: object + description: >- + Problem details (RFC 9457) returned with the application/problem+json + media type for every error response. This is the lab provisioner copy of + the public api/core Problem schema; keep both copies identical except + for descriptions and the ProblemCode enum. `code` is the stable, + machine-readable reason; clients branch on it rather than on `title`, + `detail`, or the HTTP status alone. The body never contains internal + error text, stack traces, SQL, file paths, credentials, contact data, or + echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: >- + URI that identifies the problem type. It has the form + `urn:lincodex:problem:` and is an identifier, not a link to + dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: >- + Short, fixed English summary of the problem type. It does not change + between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: >- + Safe English explanation of this occurrence. It never contains + internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Request identifier of the call when the caller propagated one; it is + not a secret. + errors: + type: array + maxItems: 100 + description: >- + Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: "#/schemas/ProblemFieldError" + ProblemCode: + type: string + description: |- + Stable error code of the lab provisioner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract or a semantic rule, such as an unknown template or node; `errors` points at the fields. + - unauthenticated (401): the bearer token is missing or wrong. + - not_found (404): the route or the lab does not exist. + - method_not_allowed (405): the route does not support the method. + - state_conflict (409): the lab is not in a state that allows the operation, for example a console token or a check for a lab that is not ready. + - payload_too_large (413): the request body exceeds the limit. + - unsupported_media_type (415): the request Content-Type is not accepted. + - idempotency_key_reused (422): the lab ID was already used with a different payload. + - internal (500): unexpected server error. + - not_implemented (501): the route is described but not implemented yet, such as the console attach. + - lab_pool_busy (503): the lab does not fit the capacity or the provisioner is draining; see Retry-After. + - lab_unavailable (503): LXD or a node could not be reached, so nothing was done or evaluated. It is an infrastructure failure, never a failed check. + + The Problem shape is the api/core shape; only this enum is specific to the lab provisioner. + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - state_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - not_implemented + - lab_pool_busy + - lab_unavailable + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: "#/schemas/ProblemFieldLocation" + pointer: + type: string + maxLength: 1024 + pattern: "^(/([^~/]|~[01])*)*$" + description: >- + JSON Pointer (RFC 6901). For `body` it points into the request body + document, for example `/ttl_seconds`; an empty string means the whole + body. For a parameter it is `/` followed by the parameter name, for + example `/lab_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z][a-z0-9_]*$" + description: >- + Stable field reason. Current values are `required` (missing value) + and `invalid` (malformed value or a value outside the schema). + Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/labd/openapi.bundle.yml b/api/labd/openapi.bundle.yml new file mode 100644 index 0000000..460916b --- /dev/null +++ b/api/labd/openapi.bundle.yml @@ -0,0 +1,721 @@ +openapi: 3.2.0 +info: + title: Lincodex Lab Provisioner API + version: 0.1.0 + description: |- + Internal API of the lab provisioner `labd`. Only the Go backend calls it; + it is never exposed to browsers or to the public network. `labd` is the + only component that talks to the LXD API on the app host: the backend + never receives the LXD socket, an LXD certificate, or a node address. + + Transport and authentication: `labd` listens on a private address of the + app host that only the backend network reaches and serves HTTPS (TLS + 1.3). Every operation except the health routes requires `Authorization: + Bearer `; the token is a shared random secret of at least 32 + characters that comes from the deployment secret store, never from this + repository. A missing or wrong token answers 401 `unauthenticated`. Plain + HTTP exists only behind an explicit development switch. + + Data minimization: a lab request carries only a template reference, a + variant seed, and a lifetime. It has no candidate, account, attempt, + task, or company identifier. The lab ID is a random UUID chosen by the + backend for idempotency. Responses never carry node addresses, MAC + addresses, bridge or instance names, keys, or passwords: the backend + reaches a node only through a console token and learns a lab's state + only through these operations. + + Lifecycle: CreateLab reserves capacity and answers immediately with the + lab in `provisioning`; `labd` clones the nodes of the template from + prepared snapshots, connects them with per-lab L2-only bridges, boots + them, and waits until their management ports answer. The caller polls + GetLab until `ready`. Every lab has a fixed `expires_at`; `labd` deletes + it at that time even after a restart of its own process, and DeleteLab + deletes it earlier. A deleted lab stays readable as `deleted` for a + bounded time, then answers 404. + + Capacity: the number of concurrent labs follows the host memory budget of + `labd`. A request that does not fit answers 503 `lab_pool_busy` with + Retry-After and stores nothing; it is a capacity signal, not an + infrastructure failure. `labd` does not queue labs. +servers: + - url: / +security: + - bearerAuth: [] +paths: + /healthz: + get: + operationId: GetLabdHealthz + summary: Check whether the lab provisioner process is responding. + security: [] + tags: + - health + responses: + '200': + description: The process is responding. + content: + application/json: + schema: + $ref: '#/components/schemas/LabdHealthResponse' + default: + $ref: '#/components/responses/Problem' + /readyz: + get: + operationId: GetLabdReadyz + summary: Check whether the provisioner can create and delete labs. + description: Ready means that the lab records were loaded, the startup reconciliation with LXD finished, the LXD API answered the latest probe, and the process is not draining. A provisioner without free capacity is still ready; capacity is reported by CreateLab. + security: [] + tags: + - health + responses: + '200': + description: The provisioner is ready. + content: + application/json: + schema: + $ref: '#/components/schemas/LabdReadinessResponse' + '503': + description: The provisioner is not ready or is draining. + content: + application/json: + schema: + $ref: '#/components/schemas/LabdReadinessResponse' + default: + $ref: '#/components/responses/Problem' + /v1/labs/{lab_id}: + parameters: + - $ref: '#/components/parameters/LabId' + put: + operationId: CreateLab + summary: Create a lab from a template and a variant seed. + description: |- + Idempotent by `lab_id`: + + - a new ID that fits the capacity reserves it, stores the lab, and answers 202 with `state: provisioning`; the nodes are cloned and booted in the background; + - the same ID with the same payload answers 200 with the current state of that lab, including `deleted` or `failed`, and never creates a second one; + - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + - a new ID that does not fit the memory budget or the lab limit, or arrives while the provisioner is draining, answers 503 `lab_pool_busy` with Retry-After; nothing is stored, so the caller retries with the same ID. + + Payloads are compared by a SHA-256 fingerprint of the decoded request. + An unknown template or template version, or a lifetime above the + configured maximum, answers 400 `validation_failed` with a pointer such + as `/template_id` or `/ttl_seconds`. + + The lab is deleted at `expires_at` = creation time + `ttl_seconds`, also + when it is still provisioning. A lab that fails to provision or does not + answer within the provisioning timeout becomes `failed` and its + resources are deleted; its capacity returns when they are gone. + + A record of a deleted or failed lab is kept for a bounded retention time; + after it, the ID is unknown again and a CreateLab with it starts a new + lab. + tags: + - labs + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LabCreateRequest' + examples: + two_routers: + summary: A lab of a networking template for one attempt item + value: + template_id: mikrotik-ospf-pair + template_version: 1 + seed: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 + ttl_seconds: 3600 + responses: + '200': + description: A lab with this ID and the same payload already exists. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + '202': + description: The lab was accepted and is provisioning. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + examples: + provisioning: + summary: A lab that is being cloned and booted + value: + lab_id: 2f1c7a52-0d3e-4b8e-9b61-3c7b1f2e9a40 + state: provisioning + template_id: mikrotik-ospf-pair + template_version: 1 + created_at: '2026-10-11T09:00:00Z' + expires_at: '2026-10-11T10:00:00Z' + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + '503': + $ref: '#/components/responses/LabPoolBusy' + default: + $ref: '#/components/responses/Problem' + get: + operationId: GetLab + summary: Read the state of a lab. + description: Answers 404 `not_found` for an ID the provisioner does not hold, including a lab whose `deleted` record outlived its retention time. The response never contains an address, a key, or an LXD object name. + tags: + - labs + responses: + '200': + description: The current state of the lab. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + default: + $ref: '#/components/responses/Problem' + delete: + operationId: DeleteLab + summary: Delete a lab before its timer. + description: 'Marks the lab for deletion and answers 202 with `state: deleting`; the provisioner removes its instances and bridges in the background and retries until LXD confirms that they are gone, also across its own restarts. Deleting a lab that is already `deleting` or `deleted` answers 200 with its state and changes nothing. An unknown ID answers 404 `not_found`.' + tags: + - labs + responses: + '200': + description: The lab was already being deleted or is deleted. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + '202': + description: The lab is being deleted. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + default: + $ref: '#/components/responses/Problem' + /v1/labs/{lab_id}/console-tokens: + parameters: + - $ref: '#/components/parameters/LabId' + post: + operationId: CreateLabConsoleToken + summary: Issue a short-lived console token for one node of a ready lab. + description: |- + The token lets the console gateway of the backend attach to the serial + console of one node. It is random, single-use, bound to the lab and the + node, and valid for at most 120 seconds; `labd` keeps only its SHA-256 + digest in memory, so a restart invalidates every unused token. The token + is never a node password or an SSH key, and the response carries no node + address. + + Attaching: the gateway opens a WebSocket to `attach_path` on the same + `labd` origin with the service bearer token and sends the console token + in the `X-Lab-Console-Token` header. The WebSocket attach is described + here as the planned interface; until it is implemented, `labd` answers + the attach path with 501 and issuing a token changes nothing else. + + A lab that is not `ready` answers 409 `state_conflict`; an unknown node + answers 400 `validation_failed` with the pointer `/node`. + tags: + - consoles + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ConsoleTokenRequest' + responses: + '201': + description: The token was issued. + headers: + Cache-Control: + description: The token must not be stored by any cache. + required: true + schema: + type: string + enum: + - no-store + content: + application/json: + schema: + $ref: '#/components/schemas/ConsoleToken' + default: + $ref: '#/components/responses/Problem' + /v1/labs/{lab_id}/check: + parameters: + - $ref: '#/components/parameters/LabId' + post: + operationId: CheckLab + summary: Run the checker of the template against the nodes of a ready lab. + description: |- + The checker of the template connects from the host side of the lab + management bridge to the nodes (SSH or the RouterOS API) and evaluates + the criteria of the variant that the seed selected. It only reads the + node state and never changes it, so a repeated call is harmless; the + result is not stored by `labd`. The call is synchronous and bounded by + the check timeout of the provisioner. + + The result is checker state for the backend only: the backend scores the + lab answer with it and never forwards it to the candidate. + + A lab that is not `ready` answers 409 `state_conflict`. When the + checker cannot reach a node or the template has no working checker, the + provisioner answers 503 `lab_unavailable`: nothing was evaluated, and the + outcome is never a failed check. + tags: + - checks + responses: + '200': + description: The checker evaluated every criterion. + content: + application/json: + schema: + $ref: '#/components/schemas/LabCheckResult' + default: + $ref: '#/components/responses/Problem' +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: 'Shared random service token sent as `Authorization: Bearer ` over TLS. `labd` compares it in constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user tokens.' + responses: + Problem: + description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + summary: The template is unknown + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: body + pointer: /template_id + code: invalid + message: The value does not match the contract. + state_conflict: + summary: The lab is not ready + value: + type: urn:lincodex:problem:state_conflict + title: State conflict + status: 409 + code: state_conflict + detail: The lab is not ready. + lab_unavailable: + summary: The checker could not reach a node + value: + type: urn:lincodex:problem:lab_unavailable + title: Lab unavailable + status: 503 + code: lab_unavailable + detail: The lab could not be evaluated. Nothing was checked. + LabPoolBusy: + description: The lab does not fit the memory budget or the lab limit of the provisioner, or the provisioner is draining; code lab_pool_busy. Nothing was stored and no capacity was reserved. Retry with the same lab ID after Retry-After. + headers: + Retry-After: + description: Number of seconds to wait before retrying the request. + required: true + schema: + type: integer + format: int32 + minimum: 0 + maximum: 3600 + example: 30 + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + lab_pool_busy: + summary: No capacity for another lab + value: + type: urn:lincodex:problem:lab_pool_busy + title: Lab pool busy + status: 503 + code: lab_pool_busy + detail: No capacity for another lab. Retry later with the same lab ID. + schemas: + ProblemCode: + type: string + description: |- + Stable error code of the lab provisioner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract or a semantic rule, such as an unknown template or node; `errors` points at the fields. + - unauthenticated (401): the bearer token is missing or wrong. + - not_found (404): the route or the lab does not exist. + - method_not_allowed (405): the route does not support the method. + - state_conflict (409): the lab is not in a state that allows the operation, for example a console token or a check for a lab that is not ready. + - payload_too_large (413): the request body exceeds the limit. + - unsupported_media_type (415): the request Content-Type is not accepted. + - idempotency_key_reused (422): the lab ID was already used with a different payload. + - internal (500): unexpected server error. + - not_implemented (501): the route is described but not implemented yet, such as the console attach. + - lab_pool_busy (503): the lab does not fit the capacity or the provisioner is draining; see Retry-After. + - lab_unavailable (503): LXD or a node could not be reached, so nothing was done or evaluated. It is an infrastructure failure, never a failed check. + + The Problem shape is the api/core shape; only this enum is specific to the lab provisioner. + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - state_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - not_implemented + - lab_pool_busy + - lab_unavailable + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/components/schemas/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/ttl_seconds`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/lab_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the lab provisioner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/components/schemas/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/components/schemas/ProblemFieldError' + LabdHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok + LabdReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready + LabState: + type: string + description: |- + State of a lab. + + - provisioning: capacity is reserved and the nodes are being cloned, connected, and booted. + - ready: every node answers on its management port; console tokens and checks are allowed. + - deleting: the timer ended, DeleteLab was called, or provisioning failed; the instances and bridges are being removed. + - deleted: every instance and bridge of the lab is gone and its capacity is free. + - failed: provisioning failed or timed out, or the provisioner restarted while provisioning; `failure_reason` says which. Its resources are removed as for `deleting` and the capacity returns once they are gone; create a new lab with a new ID. + + Adding a value is a contract change. + enum: + - provisioning + - ready + - deleting + - deleted + - failed + TemplateId: + type: string + minLength: 1 + maxLength: 48 + pattern: ^[a-z0-9][a-z0-9-]{0,47}$ + description: Identifier of a lab template known to the provisioner, such as `mikrotik-ospf-pair`. Templates are part of the provisioner build; the request never carries node images, commands, or configuration. + LabFailureReason: + type: string + description: |- + Why a lab failed. None of the reasons depends on the person who uses the lab. + + - provisioning_failed: LXD refused or failed an operation of the provisioning. + - provisioning_timed_out: a node did not answer on its management port within the provisioning timeout. + - interrupted: the provisioner process stopped while the lab was provisioning. + enum: + - provisioning_failed + - provisioning_timed_out + - interrupted + NodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: ^[a-z][a-z0-9-]{0,14}$ + description: Name of a node inside its template, such as `r1` or `srv`. It is the same in every lab of the template and is not an LXD instance name or a host name. + NodeKind: + type: string + description: |- + Guest system of a node. + + - mikrotik: a MikroTik Cloud Hosted Router VM; its console is RouterOS. + - ubuntu: a small Ubuntu VM; its console is a Linux login. + + Adding a value is a contract change. + enum: + - mikrotik + - ubuntu + LabNode: + type: object + description: A node of a lab by its template name and kind. It never carries an address, a MAC address, an instance name, or a credential. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: '#/components/schemas/NodeName' + kind: + $ref: '#/components/schemas/NodeKind' + LabStatus: + type: object + description: State of a lab after one call. It never contains the seed, a node address, a key, a password, or an LXD object name. + additionalProperties: false + required: + - lab_id + - state + - template_id + - template_version + - created_at + - expires_at + - nodes + properties: + lab_id: + type: string + format: uuid + state: + $ref: '#/components/schemas/LabState' + template_id: + $ref: '#/components/schemas/TemplateId' + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + created_at: + type: string + format: date-time + ready_at: + type: string + format: date-time + description: Time the lab became `ready`; absent before. + expires_at: + type: string + format: date-time + description: Time the provisioner deletes the lab. It never moves, also not across restarts of the provisioner. + deleted_at: + type: string + format: date-time + description: Time the last resource of the lab was removed; absent before. + failure_reason: + $ref: '#/components/schemas/LabFailureReason' + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the template in template order. + items: + $ref: '#/components/schemas/LabNode' + LabCreateRequest: + type: object + description: A lab of one template variant. It has no field for a candidate, account, attempt, task, or company. + additionalProperties: false + required: + - template_id + - template_version + - seed + - ttl_seconds + properties: + template_id: + $ref: '#/components/schemas/TemplateId' + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + description: Version of the template. The provisioner refuses a version it does not hold, so a lab always matches the variant the backend served. + seed: + type: string + minLength: 64 + maxLength: 64 + pattern: ^[0-9a-f]{64}$ + description: 'Variant seed: 32 random bytes in lowercase hex chosen by the backend for the item instance. The template renders the variant configuration of every node and the checker criteria from it. It is never returned by the provisioner.' + ttl_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: Lifetime of the lab from its creation. The provisioner refuses a value above its configured maximum. + ConsoleTokenRequest: + type: object + additionalProperties: false + required: + - node + properties: + node: + $ref: '#/components/schemas/NodeName' + ConsoleToken: + type: object + description: 'Single-use console token for one node. The token is a secret of the console gateway: it is never logged, stored by the backend, or passed to a browser.' + additionalProperties: false + required: + - token + - node + - expires_at + - attach_path + properties: + token: + type: string + minLength: 43 + maxLength: 43 + pattern: ^[A-Za-z0-9_-]{43}$ + description: 32 random bytes in unpadded base64url. + node: + $ref: '#/components/schemas/NodeName' + expires_at: + type: string + format: date-time + attach_path: + type: string + maxLength: 128 + pattern: ^/v1/labs/[0-9a-f-]{36}/console$ + description: Path of the WebSocket attach on the provisioner origin. + CriterionId: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9][a-z0-9_-]{0,31}$ + description: Opaque identifier of a checker criterion of the template. + CriterionResult: + type: object + additionalProperties: false + required: + - id + - passed + properties: + id: + $ref: '#/components/schemas/CriterionId' + passed: + type: boolean + LabCheckResult: + type: object + description: 'Result of one check: whether each criterion of the variant holds on the nodes. It carries no node output, address, or configuration text.' + additionalProperties: false + required: + - lab_id + - checked_at + - score + - max_score + - criteria + properties: + lab_id: + type: string + format: uuid + checked_at: + type: string + format: date-time + score: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of passed criteria. + max_score: + type: integer + format: int32 + minimum: 1 + maximum: 50 + description: Number of criteria. + criteria: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: '#/components/schemas/CriterionResult' + parameters: + LabId: + name: lab_id + in: path + required: true + description: Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not encode a candidate, attempt, or task identifier. + schema: + type: string + format: uuid diff --git a/api/labd/openapi.yml b/api/labd/openapi.yml new file mode 100644 index 0000000..783ef51 --- /dev/null +++ b/api/labd/openapi.yml @@ -0,0 +1,67 @@ +openapi: 3.2.0 +info: + title: Lincodex Lab Provisioner API + version: 0.1.0 + description: |- + Internal API of the lab provisioner `labd`. Only the Go backend calls it; + it is never exposed to browsers or to the public network. `labd` is the + only component that talks to the LXD API on the app host: the backend + never receives the LXD socket, an LXD certificate, or a node address. + + Transport and authentication: `labd` listens on a private address of the + app host that only the backend network reaches and serves HTTPS (TLS + 1.3). Every operation except the health routes requires `Authorization: + Bearer `; the token is a shared random secret of at least 32 + characters that comes from the deployment secret store, never from this + repository. A missing or wrong token answers 401 `unauthenticated`. Plain + HTTP exists only behind an explicit development switch. + + Data minimization: a lab request carries only a template reference, a + variant seed, and a lifetime. It has no candidate, account, attempt, + task, or company identifier. The lab ID is a random UUID chosen by the + backend for idempotency. Responses never carry node addresses, MAC + addresses, bridge or instance names, keys, or passwords: the backend + reaches a node only through a console token and learns a lab's state + only through these operations. + + Lifecycle: CreateLab reserves capacity and answers immediately with the + lab in `provisioning`; `labd` clones the nodes of the template from + prepared snapshots, connects them with per-lab L2-only bridges, boots + them, and waits until their management ports answer. The caller polls + GetLab until `ready`. Every lab has a fixed `expires_at`; `labd` deletes + it at that time even after a restart of its own process, and DeleteLab + deletes it earlier. A deleted lab stays readable as `deleted` for a + bounded time, then answers 404. + + Capacity: the number of concurrent labs follows the host memory budget of + `labd`. A request that does not fit answers 503 `lab_pool_busy` with + Retry-After and stores nothing; it is a capacity signal, not an + infrastructure failure. `labd` does not queue labs. +servers: + - url: / +security: + - bearerAuth: [] +paths: + /healthz: + $ref: ./routes/healthz.yml + /readyz: + $ref: ./routes/readyz.yml + /v1/labs/{lab_id}: + $ref: ./routes/labs.yml + /v1/labs/{lab_id}/console-tokens: + $ref: ./routes/lab_console_tokens.yml + /v1/labs/{lab_id}/check: + $ref: ./routes/lab_check.yml +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: >- + Shared random service token sent as `Authorization: Bearer ` + over TLS. `labd` compares it in constant time and never logs it. + Rotation replaces the secret on both sides; there are no per-user + tokens. + responses: + Problem: + $ref: ./components/responses.yml#/Problem diff --git a/api/labd/routes/healthz.yml b/api/labd/routes/healthz.yml new file mode 100644 index 0000000..1dbd779 --- /dev/null +++ b/api/labd/routes/healthz.yml @@ -0,0 +1,15 @@ +get: + operationId: GetLabdHealthz + summary: Check whether the lab provisioner process is responding. + security: [] + tags: + - health + responses: + "200": + description: The process is responding. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabdHealthResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/routes/lab_check.yml b/api/labd/routes/lab_check.yml new file mode 100644 index 0000000..a38707d --- /dev/null +++ b/api/labd/routes/lab_check.yml @@ -0,0 +1,31 @@ +parameters: + - $ref: ../components/parameters.yml#/LabId +post: + operationId: CheckLab + summary: Run the checker of the template against the nodes of a ready lab. + description: |- + The checker of the template connects from the host side of the lab + management bridge to the nodes (SSH or the RouterOS API) and evaluates + the criteria of the variant that the seed selected. It only reads the + node state and never changes it, so a repeated call is harmless; the + result is not stored by `labd`. The call is synchronous and bounded by + the check timeout of the provisioner. + + The result is checker state for the backend only: the backend scores the + lab answer with it and never forwards it to the candidate. + + A lab that is not `ready` answers 409 `state_conflict`. When the + checker cannot reach a node or the template has no working checker, the + provisioner answers 503 `lab_unavailable`: nothing was evaluated, and the + outcome is never a failed check. + tags: + - checks + responses: + "200": + description: The checker evaluated every criterion. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabCheckResult + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/routes/lab_console_tokens.yml b/api/labd/routes/lab_console_tokens.yml new file mode 100644 index 0000000..5141334 --- /dev/null +++ b/api/labd/routes/lab_console_tokens.yml @@ -0,0 +1,46 @@ +parameters: + - $ref: ../components/parameters.yml#/LabId +post: + operationId: CreateLabConsoleToken + summary: Issue a short-lived console token for one node of a ready lab. + description: |- + The token lets the console gateway of the backend attach to the serial + console of one node. It is random, single-use, bound to the lab and the + node, and valid for at most 120 seconds; `labd` keeps only its SHA-256 + digest in memory, so a restart invalidates every unused token. The token + is never a node password or an SSH key, and the response carries no node + address. + + Attaching: the gateway opens a WebSocket to `attach_path` on the same + `labd` origin with the service bearer token and sends the console token + in the `X-Lab-Console-Token` header. The WebSocket attach is described + here as the planned interface; until it is implemented, `labd` answers + the attach path with 501 and issuing a token changes nothing else. + + A lab that is not `ready` answers 409 `state_conflict`; an unknown node + answers 400 `validation_failed` with the pointer `/node`. + tags: + - consoles + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsoleTokenRequest + responses: + "201": + description: The token was issued. + headers: + Cache-Control: + description: The token must not be stored by any cache. + required: true + schema: + type: string + enum: + - no-store + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsoleToken + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/routes/labs.yml b/api/labd/routes/labs.yml new file mode 100644 index 0000000..d7f3eef --- /dev/null +++ b/api/labd/routes/labs.yml @@ -0,0 +1,119 @@ +parameters: + - $ref: ../components/parameters.yml#/LabId +put: + operationId: CreateLab + summary: Create a lab from a template and a variant seed. + description: |- + Idempotent by `lab_id`: + + - a new ID that fits the capacity reserves it, stores the lab, and answers 202 with `state: provisioning`; the nodes are cloned and booted in the background; + - the same ID with the same payload answers 200 with the current state of that lab, including `deleted` or `failed`, and never creates a second one; + - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + - a new ID that does not fit the memory budget or the lab limit, or arrives while the provisioner is draining, answers 503 `lab_pool_busy` with Retry-After; nothing is stored, so the caller retries with the same ID. + + Payloads are compared by a SHA-256 fingerprint of the decoded request. + An unknown template or template version, or a lifetime above the + configured maximum, answers 400 `validation_failed` with a pointer such + as `/template_id` or `/ttl_seconds`. + + The lab is deleted at `expires_at` = creation time + `ttl_seconds`, also + when it is still provisioning. A lab that fails to provision or does not + answer within the provisioning timeout becomes `failed` and its + resources are deleted; its capacity returns when they are gone. + + A record of a deleted or failed lab is kept for a bounded retention time; + after it, the ID is unknown again and a CreateLab with it starts a new + lab. + tags: + - labs + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabCreateRequest + examples: + two_routers: + summary: A lab of a networking template for one attempt item + value: + template_id: mikrotik-ospf-pair + template_version: 1 + seed: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 + ttl_seconds: 3600 + responses: + "200": + description: A lab with this ID and the same payload already exists. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + "202": + description: The lab was accepted and is provisioning. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + examples: + provisioning: + summary: A lab that is being cloned and booted + value: + lab_id: 2f1c7a52-0d3e-4b8e-9b61-3c7b1f2e9a40 + state: provisioning + template_id: mikrotik-ospf-pair + template_version: 1 + created_at: "2026-10-11T09:00:00Z" + expires_at: "2026-10-11T10:00:00Z" + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + "503": + $ref: ../components/responses.yml#/LabPoolBusy + default: + $ref: ../components/responses.yml#/Problem +get: + operationId: GetLab + summary: Read the state of a lab. + description: >- + Answers 404 `not_found` for an ID the provisioner does not hold, + including a lab whose `deleted` record outlived its retention time. The + response never contains an address, a key, or an LXD object name. + tags: + - labs + responses: + "200": + description: The current state of the lab. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + default: + $ref: ../components/responses.yml#/Problem +delete: + operationId: DeleteLab + summary: Delete a lab before its timer. + description: >- + Marks the lab for deletion and answers 202 with `state: deleting`; the + provisioner removes its instances and bridges in the background and + retries until LXD confirms that they are gone, also across its own + restarts. Deleting a lab that is already `deleting` or `deleted` + answers 200 with its state and changes nothing. An unknown ID answers + 404 `not_found`. + tags: + - labs + responses: + "200": + description: The lab was already being deleted or is deleted. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + "202": + description: The lab is being deleted. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/routes/readyz.yml b/api/labd/routes/readyz.yml new file mode 100644 index 0000000..afb53ad --- /dev/null +++ b/api/labd/routes/readyz.yml @@ -0,0 +1,26 @@ +get: + operationId: GetLabdReadyz + summary: Check whether the provisioner can create and delete labs. + description: >- + Ready means that the lab records were loaded, the startup reconciliation + with LXD finished, the LXD API answered the latest probe, and the process + is not draining. A provisioner without free capacity is still ready; + capacity is reported by CreateLab. + security: [] + tags: + - health + responses: + "200": + description: The provisioner is ready. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabdReadinessResponse + "503": + description: The provisioner is not ready or is draining. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabdReadinessResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/.golangci.yml b/backend/.golangci.yml index 4f080f6..cfda3fd 100644 --- a/backend/.golangci.yml +++ b/backend/.golangci.yml @@ -126,6 +126,7 @@ linters: - internal/adapter/primary/http/api/ - internal/adapter/secondary/ml/api/ - internal/adapter/secondary/code_runner/api/ + - internal/adapter/secondary/lab_provisioner/api/ - internal/adapter/secondary/postgres/sqlc/ - internal/bootstrap/wire_gen\.go$ - (^|/)mocks/ @@ -162,6 +163,7 @@ formatters: - internal/adapter/primary/http/api/ - internal/adapter/secondary/ml/api/ - internal/adapter/secondary/code_runner/api/ + - internal/adapter/secondary/lab_provisioner/api/ - internal/adapter/secondary/postgres/sqlc/ - internal/bootstrap/wire_gen\.go$ - (^|/)mocks/ diff --git a/backend/Makefile b/backend/Makefile index d932fa6..4e09906 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -115,6 +115,7 @@ generate gen: ## Regenerate API, SQL, and dependency-injection code in dependenc $(MAKE) --no-print-directory gen-openapi API_PREPARED=1 $(MAKE) --no-print-directory gen-ml API_PREPARED=1 $(MAKE) --no-print-directory gen-code-runner API_PREPARED=1 + $(MAKE) --no-print-directory gen-lab-provisioner API_PREPARED=1 $(MAKE) --no-print-directory gen-sqlc $(MAKE) --no-print-directory gen-wire $(MAKE) --no-print-directory mocks @@ -134,6 +135,11 @@ gen-code-runner: ## Generate the internal code runner client @if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi $(GO_TOOL) ogen -config codegen/ogen-code-runner.yml --target internal/adapter/secondary/code_runner/api --package api --clean ../api/runner/openapi.bundle.yml +.PHONY: gen-lab-provisioner +gen-lab-provisioner: ## Generate the internal lab provisioner client + @if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi + $(GO_TOOL) ogen -config codegen/ogen-labd.yml --target internal/adapter/secondary/lab_provisioner/api --package api --clean ../api/labd/openapi.bundle.yml + .PHONY: gen-sqlc gen-sqlc: ## Generate PostgreSQL query code from migrations and queries $(GO_TOOL) sqlc generate -f codegen/sqlc.yml diff --git a/backend/codegen/ogen-labd.yml b/backend/codegen/ogen-labd.yml new file mode 100644 index 0000000..b2e7216 --- /dev/null +++ b/backend/codegen/ogen-labd.yml @@ -0,0 +1,5 @@ +generator: + features: + disable: + - paths/server + - webhooks/server diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index de8cef0..f9b711a 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -17,27 +17,29 @@ import ( ) var regexMap = map[string]ogenregex.Regexp{ - "\\S": ogenregex.MustCompile("\\S"), - "^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"), - "^/[A-Za-z0-9/_-]{0,255}$": ogenregex.MustCompile("^/[A-Za-z0-9/_-]{0,255}$"), - "^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"), - "^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"), - "^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$": ogenregex.MustCompile("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$"), - "^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"), - "^[0-9]{6}$": ogenregex.MustCompile("^[0-9]{6}$"), - "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), - "^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"), - "^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"), - "^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"), - "^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"), - "^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"), - "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), - "^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"), - "^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"), - "^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"), - "^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="), - "^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"), - "^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"), + "\\S": ogenregex.MustCompile("\\S"), + "^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"), + "^/[A-Za-z0-9/_-]{0,255}$": ogenregex.MustCompile("^/[A-Za-z0-9/_-]{0,255}$"), + "^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$": ogenregex.MustCompile("^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$"), + "^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"), + "^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"), + "^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$": ogenregex.MustCompile("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$"), + "^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"), + "^[0-9]{6}$": ogenregex.MustCompile("^[0-9]{6}$"), + "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), + "^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"), + "^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"), + "^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"), + "^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"), + "^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"), + "^[a-z][a-z0-9-]{0,14}$": ogenregex.MustCompile("^[a-z][a-z0-9-]{0,14}$"), + "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), + "^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"), + "^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"), + "^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"), + "^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="), + "^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"), + "^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"), "^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$": ogenregex.MustCompile("^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$"), } var ( 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 7806dd8..2720563 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,529 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca } } +// handleCreateMyAssessmentLabRequest handles CreateMyAssessmentLab 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 current item, whose content has the +// format `lab`. +// +// The server asks the lab provisioner for a lab of the variant fixed for this item instance and +// answers 201 with the lab `provisioning`; the client polls GetMyAssessmentLab until it is `ready`. +// The lab lives until `expires_at`, the earlier of the item's `time_limit_seconds` and the attempt +// deadline, and is then deleted with everything done in it. Creating a lab does not change the attempt +// version, the current item, or any answer. +// +// One lab per item at a time. While the item has a lab in `provisioning`, `ready`, or `checking`, the +// server answers 200 with that lab and starts no second one. After a `failed` lab the candidate may +// start a new one while the item is current; after `submitted` or `expired` the item cannot start +// another lab (409 state_conflict). +// +// Busy pool. When the lab pool of the provisioner has no free capacity, the server answers 503 +// service_unavailable with Retry-After, for example +// `{"type": "urn:lincodex:problem:service_unavailable", "title": "Service unavailable", "status": 503, "code": "service_unavailable", "detail": "No lab capacity is free. The attempt is unchanged; retry later."}`. +// Nothing was stored: no lab exists, the attempt version and the current item are unchanged, the lab +// lifetime has not started, and the attempt is not consumed; the client retries after Retry-After with +// a new Idempotency-Key. When labs are not enabled on this server, or the provisioner cannot be +// reached, the server answers 503 service_unavailable without Retry-After and stores nothing either. +// The attempt deadline keeps running in both cases. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), +// the attempt and the item (404 not_found for an unknown attempt or item, or one of another +// candidate), the state (409 state_conflict: the attempt is terminal or its work session ended, the +// item is not current, its format is not `lab`, or its lab was submitted or expired), the rate limit +// (429), then the availability of labs and the capacity (503). Following the Idempotency-Key +// convention, 201, 200, 404, and 409 state_conflict are stored under the key and replayed; 400, 429, +// and 503 are not. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/labs +func (s *Server) handleCreateMyAssessmentLabRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CreateMyAssessmentLab"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/labs"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateMyAssessmentLabOperation, + 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: CreateMyAssessmentLabOperation, + ID: "CreateMyAssessmentLab", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, CreateMyAssessmentLabOperation, 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, CreateMyAssessmentLabOperation, 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 := decodeCreateMyAssessmentLabParams(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.decodeCreateMyAssessmentLabRequest(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 CreateMyAssessmentLabRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CreateMyAssessmentLabOperation, + OperationSummary: "Start the lab of the current lab item of an assessment attempt.", + OperationID: "CreateMyAssessmentLab", + 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 = *AssessmentLabCreate + Params = CreateMyAssessmentLabParams + Response = CreateMyAssessmentLabRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackCreateMyAssessmentLabParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.CreateMyAssessmentLab(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.CreateMyAssessmentLab(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 := encodeCreateMyAssessmentLabResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleCreateMyAssessmentLabConsoleSessionRequest handles CreateMyAssessmentLabConsoleSession operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The body names a node of the lab by its task name. +// +// The response describes one console session: the client opens a WebSocket to `websocket_path` on the +// same origin before `expires_at`. The upgrade is authorized by the session cookie and the Origin +// check, and the server relays the serial console of the node through the lab provisioner. The +// response never carries a node address, a port, a password, a key, or a token; the browser never +// connects to a node or to the provisioner. Console traffic is not stored as an answer and is not +// logged. +// +// The WebSocket relay is planned together with the candidate interface of labs; this contract fixes +// the session shape it uses. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the attempt and the lab (404 not_found for an unknown attempt, +// lab, or one of another candidate), the node (400 with the pointer `/node`), the state (409 +// state_conflict: the lab is not `ready`, the attempt is terminal, or its work session ended), the +// limit of open sessions per lab (429 rate_limited with Retry-After), then the provisioner (503 +// service_unavailable without Retry-After; nothing was opened). +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/console-sessions +func (s *Server) handleCreateMyAssessmentLabConsoleSessionRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CreateMyAssessmentLabConsoleSession"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/console-sessions"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateMyAssessmentLabConsoleSessionOperation, + 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: CreateMyAssessmentLabConsoleSessionOperation, + ID: "CreateMyAssessmentLabConsoleSession", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, CreateMyAssessmentLabConsoleSessionOperation, 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, CreateMyAssessmentLabConsoleSessionOperation, 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 := decodeCreateMyAssessmentLabConsoleSessionParams(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.decodeCreateMyAssessmentLabConsoleSessionRequest(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 CreateMyAssessmentLabConsoleSessionRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CreateMyAssessmentLabConsoleSessionOperation, + OperationSummary: "Open a console session of one node of a ready lab.", + OperationID: "CreateMyAssessmentLabConsoleSession", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "attempt_id", + In: "path", + }: params.AttemptID, + { + Name: "lab_id", + In: "path", + }: params.LabID, + }, + Raw: r, + } + + type ( + Request = *AssessmentLabConsoleSessionCreate + Params = CreateMyAssessmentLabConsoleSessionParams + Response = CreateMyAssessmentLabConsoleSessionRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackCreateMyAssessmentLabConsoleSessionParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.CreateMyAssessmentLabConsoleSession(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.CreateMyAssessmentLabConsoleSession(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 := encodeCreateMyAssessmentLabConsoleSessionResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleCreateMyAssessmentPracticeRunRequest handles CreateMyAssessmentPracticeRun operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -4532,6 +5055,217 @@ func (s *Server) handleGetMyAssessmentAvailabilityRequest(args [0]string, argsEs } } +// handleGetMyAssessmentLabRequest handles GetMyAssessmentLab operation. +// +// Requires the session cookie of a candidate account. Returns the state of a lab started with +// CreateMyAssessmentLab: whether it is still provisioning, ready for the consoles, being checked after +// the submission, or ended. It never contains a node address, a credential, the seed, the checker +// state, or the result of the check. This GET is read-only; the server may record a due timer +// transition, such as `ready` to `expired`, before it answers. +// +// A lab of another candidate's attempt, a lab of another attempt, and an unknown identifier all answer +// 404 not_found. +// +// GET /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id} +func (s *Server) handleGetMyAssessmentLabRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyAssessmentLab"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_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(), GetMyAssessmentLabOperation, + 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: GetMyAssessmentLabOperation, + ID: "GetMyAssessmentLab", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentLabOperation, 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 := decodeGetMyAssessmentLabParams(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 GetMyAssessmentLabRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyAssessmentLabOperation, + OperationSummary: "Read the lab of an assessment attempt item.", + OperationID: "GetMyAssessmentLab", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "attempt_id", + In: "path", + }: params.AttemptID, + { + Name: "lab_id", + In: "path", + }: params.LabID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetMyAssessmentLabParams + Response = GetMyAssessmentLabRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetMyAssessmentLabParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyAssessmentLab(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetMyAssessmentLab(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 := encodeGetMyAssessmentLabResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetMyAssessmentPracticeRunRequest handles GetMyAssessmentPracticeRun operation. // // Requires the session cookie of a candidate account. Returns the state of a debug run started with @@ -16456,6 +17190,10 @@ func (s *Server) handleStartMyAssessmentAttemptSessionRequest(args [1]string, ar // times itself and scores the answer with the key of the fixed item instance. Time never enters the // ability estimate or the grade decision. // +// Lab: an item with format `lab` takes no answer here. Its lab is started with CreateMyAssessmentLab +// and submitted with SubmitMyAssessmentLab; any answer to a lab item answers 400 validation_failed +// with the pointer `/answer/format`, like an answer in the wrong format, and stores nothing. +// // The response is the attempt with the next item to answer. It never says whether the answer was // correct. Items are answered in order and each answer is final. // @@ -16749,6 +17487,272 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap } } +// handleSubmitMyAssessmentLabRequest handles SubmitMyAssessmentLab 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 carries the attempt version last read and the +// answer with format `lab`, which names the lab. +// +// The server closes the consoles, freezes the lab, and answers 202 with the lab `checking`; the +// checker of the task reads the state of the nodes asynchronously, the answer is recorded, and the lab +// becomes `submitted` and is deleted. The client polls GetMyAssessmentLab and then reads the attempt, +// which moves to the next item. Neither response says whether the answer was correct, and the +// candidate never sees the checker criteria or their results. +// +// When the checker cannot reach the nodes because of the lab infrastructure, the lab becomes `failed` +// with `lab_error`: nothing is recorded or consumed, the attempt version is unchanged, and the +// candidate may start a new lab of the item while it is current. A failure of the infrastructure is +// never scored as a wrong answer. +// +// Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the +// server answers 412 version_conflict and stores nothing. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), +// the attempt and the lab (404 not_found for an unknown attempt or lab, or one of another candidate), +// the version (412), the state (409 state_conflict: the lab is not `ready`, `answer.lab_id` is not the +// lab in the path, the item is not current, the attempt is terminal, or its work session ended), then +// the provisioner (503 service_unavailable without Retry-After; nothing was stored and the lab keeps +// running). Following the Idempotency-Key convention, 202, 404, and 409 state_conflict are stored +// under the key and replayed; 400, 412, 429, and 5xx are not. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/submission +func (s *Server) handleSubmitMyAssessmentLabRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("SubmitMyAssessmentLab"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/submission"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), SubmitMyAssessmentLabOperation, + 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: SubmitMyAssessmentLabOperation, + ID: "SubmitMyAssessmentLab", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, SubmitMyAssessmentLabOperation, 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, SubmitMyAssessmentLabOperation, 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 := decodeSubmitMyAssessmentLabParams(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.decodeSubmitMyAssessmentLabRequest(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 SubmitMyAssessmentLabRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: SubmitMyAssessmentLabOperation, + OperationSummary: "Submit the lab of the current lab item as its answer.", + OperationID: "SubmitMyAssessmentLab", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "attempt_id", + In: "path", + }: params.AttemptID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + { + Name: "lab_id", + In: "path", + }: params.LabID, + }, + Raw: r, + } + + type ( + Request = *AssessmentLabSubmission + Params = SubmitMyAssessmentLabParams + Response = SubmitMyAssessmentLabRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackSubmitMyAssessmentLabParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.SubmitMyAssessmentLab(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.SubmitMyAssessmentLab(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 := encodeSubmitMyAssessmentLabResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleUnhideOrganizationRequest handles UnhideOrganization operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, 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 5e8e678..afb3cca 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,14 @@ type CreateMyAssessmentAttemptRes interface { createMyAssessmentAttemptRes() } +type CreateMyAssessmentLabConsoleSessionRes interface { + createMyAssessmentLabConsoleSessionRes() +} + +type CreateMyAssessmentLabRes interface { + createMyAssessmentLabRes() +} + type CreateMyAssessmentPracticeRunRes interface { createMyAssessmentPracticeRunRes() } @@ -73,6 +81,10 @@ type GetMyAssessmentAvailabilityRes interface { getMyAssessmentAvailabilityRes() } +type GetMyAssessmentLabRes interface { + getMyAssessmentLabRes() +} + type GetMyAssessmentPracticeRunRes interface { getMyAssessmentPracticeRunRes() } @@ -285,6 +297,10 @@ type SubmitMyAssessmentAnswerRes interface { submitMyAssessmentAnswerRes() } +type SubmitMyAssessmentLabRes interface { + submitMyAssessmentLabRes() +} + type UnhideOrganizationRes interface { unhideOrganizationRes() } 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 481d73c..f9edf25 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -6779,6 +6779,950 @@ func (s *AssessmentItemId) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AssessmentLab) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentLab) 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("nodes") + e.ArrStart() + for _, elem := range s.Nodes { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("created_at") + s.CreatedAt.Encode(e) + } + { + e.FieldStart("ready_at") + s.ReadyAt.Encode(e) + } + { + e.FieldStart("expires_at") + s.ExpiresAt.Encode(e) + } + { + e.FieldStart("finished_at") + s.FinishedAt.Encode(e) + } + { + e.FieldStart("failure_reason") + s.FailureReason.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentLab = [9]string{ + 0: "id", + 1: "item_id", + 2: "state", + 3: "nodes", + 4: "created_at", + 5: "ready_at", + 6: "expires_at", + 7: "finished_at", + 8: "failure_reason", +} + +// Decode decodes AssessmentLab from json. +func (s *AssessmentLab) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLab to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "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 "nodes": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + s.Nodes = make([]AssessmentLabNode, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentLabNode + if err := elem.Decode(d); err != nil { + return err + } + s.Nodes = append(s.Nodes, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"nodes\"") + } + case "created_at": + requiredBitSet[0] |= 1 << 4 + 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 "ready_at": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.ReadyAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ready_at\"") + } + case "expires_at": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.ExpiresAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expires_at\"") + } + case "finished_at": + requiredBitSet[0] |= 1 << 7 + 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[1] |= 1 << 0 + if err := func() error { + if err := s.FailureReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"failure_reason\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentLab") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentLab) { + name = jsonFieldsNameOfAssessmentLab[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 *AssessmentLab) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLab) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentLabConsoleSession) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentLabConsoleSession) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("node") + s.Node.Encode(e) + } + { + e.FieldStart("websocket_path") + e.Str(s.WebsocketPath) + } + { + e.FieldStart("expires_at") + s.ExpiresAt.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentLabConsoleSession = [4]string{ + 0: "id", + 1: "node", + 2: "websocket_path", + 3: "expires_at", +} + +// Decode decodes AssessmentLabConsoleSession from json. +func (s *AssessmentLabConsoleSession) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLabConsoleSession 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 "node": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Node.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"node\"") + } + case "websocket_path": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.WebsocketPath = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"websocket_path\"") + } + case "expires_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.ExpiresAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expires_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentLabConsoleSession") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentLabConsoleSession) { + name = jsonFieldsNameOfAssessmentLabConsoleSession[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 *AssessmentLabConsoleSession) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLabConsoleSession) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentLabConsoleSessionCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentLabConsoleSessionCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("node") + s.Node.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentLabConsoleSessionCreate = [1]string{ + 0: "node", +} + +// Decode decodes AssessmentLabConsoleSessionCreate from json. +func (s *AssessmentLabConsoleSessionCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLabConsoleSessionCreate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "node": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Node.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"node\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentLabConsoleSessionCreate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentLabConsoleSessionCreate) { + name = jsonFieldsNameOfAssessmentLabConsoleSessionCreate[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 *AssessmentLabConsoleSessionCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLabConsoleSessionCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentLabCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentLabCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("item_id") + s.ItemID.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentLabCreate = [1]string{ + 0: "item_id", +} + +// Decode decodes AssessmentLabCreate from json. +func (s *AssessmentLabCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLabCreate 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\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentLabCreate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentLabCreate) { + name = jsonFieldsNameOfAssessmentLabCreate[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 *AssessmentLabCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLabCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentLabFailureReason as json. +func (s AssessmentLabFailureReason) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentLabFailureReason from json. +func (s *AssessmentLabFailureReason) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLabFailureReason to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentLabFailureReason(v) { + case AssessmentLabFailureReasonLabError: + *s = AssessmentLabFailureReasonLabError + default: + *s = AssessmentLabFailureReason(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentLabFailureReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLabFailureReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentLabNode) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentLabNode) encodeFields(e *jx.Encoder) { + { + e.FieldStart("name") + s.Name.Encode(e) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentLabNode = [2]string{ + 0: "name", + 1: "kind", +} + +// Decode decodes AssessmentLabNode from json. +func (s *AssessmentLabNode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLabNode to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "name": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Name.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"name\"") + } + case "kind": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentLabNode") + } + // 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(jsonFieldsNameOfAssessmentLabNode) { + name = jsonFieldsNameOfAssessmentLabNode[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 *AssessmentLabNode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLabNode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentLabNodeKind as json. +func (s AssessmentLabNodeKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentLabNodeKind from json. +func (s *AssessmentLabNodeKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLabNodeKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentLabNodeKind(v) { + case AssessmentLabNodeKindMikrotik: + *s = AssessmentLabNodeKindMikrotik + case AssessmentLabNodeKindUbuntu: + *s = AssessmentLabNodeKindUbuntu + default: + *s = AssessmentLabNodeKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentLabNodeKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLabNodeKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentLabNodeName as json. +func (s AssessmentLabNodeName) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes AssessmentLabNodeName from json. +func (s *AssessmentLabNodeName) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLabNodeName to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AssessmentLabNodeName(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentLabNodeName) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLabNodeName) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentLabState as json. +func (s AssessmentLabState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentLabState from json. +func (s *AssessmentLabState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLabState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentLabState(v) { + case AssessmentLabStateProvisioning: + *s = AssessmentLabStateProvisioning + case AssessmentLabStateReady: + *s = AssessmentLabStateReady + case AssessmentLabStateChecking: + *s = AssessmentLabStateChecking + case AssessmentLabStateSubmitted: + *s = AssessmentLabStateSubmitted + case AssessmentLabStateExpired: + *s = AssessmentLabStateExpired + case AssessmentLabStateFailed: + *s = AssessmentLabStateFailed + default: + *s = AssessmentLabState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentLabState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLabState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentLabSubmission) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentLabSubmission) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + e.FieldStart("answer") + s.Answer.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentLabSubmission = [2]string{ + 0: "expected_version", + 1: "answer", +} + +// Decode decodes AssessmentLabSubmission from json. +func (s *AssessmentLabSubmission) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentLabSubmission to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "answer": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Answer.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"answer\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentLabSubmission") + } + // 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(jsonFieldsNameOfAssessmentLabSubmission) { + name = jsonFieldsNameOfAssessmentLabSubmission[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 *AssessmentLabSubmission) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentLabSubmission) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes AssessmentLimitation as json. func (s AssessmentLimitation) Encode(e *jx.Encoder) { e.Str(string(s)) @@ -18763,6 +19707,424 @@ func (s *CreateMyAssessmentAttemptUnprocessableEntity) UnmarshalJSON(data []byte return s.Decode(d) } +// Encode encodes CreateMyAssessmentLabBadRequest as json. +func (s *CreateMyAssessmentLabBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabBadRequest from json. +func (s *CreateMyAssessmentLabBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabBadRequest 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 = CreateMyAssessmentLabBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabConflict as json. +func (s *CreateMyAssessmentLabConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabConflict from json. +func (s *CreateMyAssessmentLabConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabConflict 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 = CreateMyAssessmentLabConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabConsoleSessionBadRequest as json. +func (s *CreateMyAssessmentLabConsoleSessionBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabConsoleSessionBadRequest from json. +func (s *CreateMyAssessmentLabConsoleSessionBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabConsoleSessionBadRequest 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 = CreateMyAssessmentLabConsoleSessionBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabConsoleSessionBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabConsoleSessionBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabConsoleSessionConflict as json. +func (s *CreateMyAssessmentLabConsoleSessionConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabConsoleSessionConflict from json. +func (s *CreateMyAssessmentLabConsoleSessionConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabConsoleSessionConflict 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 = CreateMyAssessmentLabConsoleSessionConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabConsoleSessionConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabConsoleSessionConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabConsoleSessionForbidden as json. +func (s *CreateMyAssessmentLabConsoleSessionForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabConsoleSessionForbidden from json. +func (s *CreateMyAssessmentLabConsoleSessionForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabConsoleSessionForbidden 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 = CreateMyAssessmentLabConsoleSessionForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabConsoleSessionForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabConsoleSessionForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabConsoleSessionNotFound as json. +func (s *CreateMyAssessmentLabConsoleSessionNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabConsoleSessionNotFound from json. +func (s *CreateMyAssessmentLabConsoleSessionNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabConsoleSessionNotFound 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 = CreateMyAssessmentLabConsoleSessionNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabConsoleSessionNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabConsoleSessionNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabConsoleSessionUnauthorized as json. +func (s *CreateMyAssessmentLabConsoleSessionUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabConsoleSessionUnauthorized from json. +func (s *CreateMyAssessmentLabConsoleSessionUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabConsoleSessionUnauthorized 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 = CreateMyAssessmentLabConsoleSessionUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabConsoleSessionUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabConsoleSessionUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabForbidden as json. +func (s *CreateMyAssessmentLabForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabForbidden from json. +func (s *CreateMyAssessmentLabForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabForbidden 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 = CreateMyAssessmentLabForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabNotFound as json. +func (s *CreateMyAssessmentLabNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabNotFound from json. +func (s *CreateMyAssessmentLabNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabNotFound 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 = CreateMyAssessmentLabNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabUnauthorized as json. +func (s *CreateMyAssessmentLabUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabUnauthorized from json. +func (s *CreateMyAssessmentLabUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabUnauthorized 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 = CreateMyAssessmentLabUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMyAssessmentLabUnprocessableEntity as json. +func (s *CreateMyAssessmentLabUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMyAssessmentLabUnprocessableEntity from json. +func (s *CreateMyAssessmentLabUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMyAssessmentLabUnprocessableEntity 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 = CreateMyAssessmentLabUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMyAssessmentLabUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMyAssessmentLabUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CreateMyAssessmentPracticeRunBadRequest as json. func (s *CreateMyAssessmentPracticeRunBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -22492,6 +23854,120 @@ func (s *GetMyAssessmentAvailabilityUnauthorized) UnmarshalJSON(data []byte) err return s.Decode(d) } +// Encode encodes GetMyAssessmentLabForbidden as json. +func (s *GetMyAssessmentLabForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentLabForbidden from json. +func (s *GetMyAssessmentLabForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentLabForbidden 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 = GetMyAssessmentLabForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentLabForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentLabForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentLabNotFound as json. +func (s *GetMyAssessmentLabNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentLabNotFound from json. +func (s *GetMyAssessmentLabNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentLabNotFound 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 = GetMyAssessmentLabNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentLabNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentLabNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentLabUnauthorized as json. +func (s *GetMyAssessmentLabUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentLabUnauthorized from json. +func (s *GetMyAssessmentLabUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentLabUnauthorized 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 = GetMyAssessmentLabUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentLabUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentLabUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetMyAssessmentPracticeRunForbidden as json. func (s *GetMyAssessmentPracticeRunForbidden) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -27945,6 +29421,8 @@ func (s ItemContent) Encode(e *jx.Encoder) { s.ConfigurationItemContent.Encode(e) case PracticeItemContentItemContent: s.PracticeItemContent.Encode(e) + case LabItemContentItemContent: + s.LabItemContent.Encode(e) } } @@ -27964,6 +29442,8 @@ func (s ItemContent) encodeFields(e *jx.Encoder) { s.ConfigurationItemContent.encodeFields(e) case PracticeItemContentItemContent: s.PracticeItemContent.encodeFields(e) + case LabItemContentItemContent: + s.LabItemContent.encodeFields(e) } } @@ -28072,6 +29552,19 @@ func (s *ItemContent) Decode(d *jx.Decoder) error { } found = true s.Type = match + case "nodes": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Array { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := LabItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match case "options": // Type-based discrimination: check if field has expected JSON type if typ := d.Next(); typ != jx.Array { @@ -28098,6 +29591,19 @@ func (s *ItemContent) Decode(d *jx.Decoder) error { } found = true s.Type = match + case "time_limit_seconds": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.Number { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := LabItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match case "unit": // Type-based discrimination: check if field has expected JSON type (nullable) typ := d.Next() @@ -28146,6 +29652,14 @@ func (s *ItemContent) Decode(d *jx.Decoder) error { } found = true s.Type = match + case "lab": + match := LabItemContentItemContent + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match case "number": match := NumberItemContentItemContent if found && s.Type != match { @@ -28220,6 +29734,10 @@ func (s *ItemContent) Decode(d *jx.Decoder) error { if err := s.PracticeItemContent.Decode(d); err != nil { return err } + case LabItemContentItemContent: + if err := s.LabItemContent.Decode(d); err != nil { + return err + } default: return errors.Errorf("inferred invalid type: %s", s.Type) } @@ -28239,6 +29757,331 @@ func (s *ItemContent) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *LabAnswer) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *LabAnswer) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("lab_id") + json.EncodeUUID(e, s.LabID) + } +} + +var jsonFieldsNameOfLabAnswer = [2]string{ + 0: "format", + 1: "lab_id", +} + +// Decode decodes LabAnswer from json. +func (s *LabAnswer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabAnswer to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "lab_id": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := json.DecodeUUID(d) + s.LabID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"lab_id\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode LabAnswer") + } + // 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(jsonFieldsNameOfLabAnswer) { + name = jsonFieldsNameOfLabAnswer[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 *LabAnswer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabAnswer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LabAnswerFormat as json. +func (s LabAnswerFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes LabAnswerFormat from json. +func (s *LabAnswerFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabAnswerFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch LabAnswerFormat(v) { + case LabAnswerFormatLab: + *s = LabAnswerFormatLab + default: + *s = LabAnswerFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s LabAnswerFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabAnswerFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *LabItemContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *LabItemContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("format") + s.Format.Encode(e) + } + { + e.FieldStart("nodes") + e.ArrStart() + for _, elem := range s.Nodes { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("time_limit_seconds") + e.Int32(s.TimeLimitSeconds) + } +} + +var jsonFieldsNameOfLabItemContent = [3]string{ + 0: "format", + 1: "nodes", + 2: "time_limit_seconds", +} + +// Decode decodes LabItemContent from json. +func (s *LabItemContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabItemContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "format": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Format.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"format\"") + } + case "nodes": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Nodes = make([]AssessmentLabNode, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentLabNode + if err := elem.Decode(d); err != nil { + return err + } + s.Nodes = append(s.Nodes, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"nodes\"") + } + case "time_limit_seconds": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.TimeLimitSeconds = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"time_limit_seconds\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode LabItemContent") + } + // 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(jsonFieldsNameOfLabItemContent) { + name = jsonFieldsNameOfLabItemContent[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 *LabItemContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabItemContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LabItemContentFormat as json. +func (s LabItemContentFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes LabItemContentFormat from json. +func (s *LabItemContentFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabItemContentFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch LabItemContentFormat(v) { + case LabItemContentFormatLab: + *s = LabItemContentFormatLab + default: + *s = LabItemContentFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s LabItemContentFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabItemContentFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ListMyAssessmentResultsBadRequest as json. func (s *ListMyAssessmentResultsBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -39968,6 +41811,50 @@ func (s *NilAssessmentItem) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AssessmentLabFailureReason as json. +func (o NilAssessmentLabFailureReason) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes AssessmentLabFailureReason from json. +func (o *NilAssessmentLabFailureReason) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentLabFailureReason to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentLabFailureReason + 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 NilAssessmentLabFailureReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentLabFailureReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes AssessmentNotDeterminedReason as json. func (o NilAssessmentNotDeterminedReason) Encode(e *jx.Encoder) { if o.Null { @@ -62384,6 +64271,272 @@ func (s *SubmitMyAssessmentAnswerUnprocessableEntity) UnmarshalJSON(data []byte) return s.Decode(d) } +// Encode encodes SubmitMyAssessmentLabBadRequest as json. +func (s *SubmitMyAssessmentLabBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentLabBadRequest from json. +func (s *SubmitMyAssessmentLabBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentLabBadRequest 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 = SubmitMyAssessmentLabBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentLabBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentLabBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentLabConflict as json. +func (s *SubmitMyAssessmentLabConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentLabConflict from json. +func (s *SubmitMyAssessmentLabConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentLabConflict 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 = SubmitMyAssessmentLabConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentLabConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentLabConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentLabForbidden as json. +func (s *SubmitMyAssessmentLabForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentLabForbidden from json. +func (s *SubmitMyAssessmentLabForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentLabForbidden 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 = SubmitMyAssessmentLabForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentLabForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentLabForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentLabNotFound as json. +func (s *SubmitMyAssessmentLabNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentLabNotFound from json. +func (s *SubmitMyAssessmentLabNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentLabNotFound 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 = SubmitMyAssessmentLabNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentLabNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentLabNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentLabPreconditionFailed as json. +func (s *SubmitMyAssessmentLabPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentLabPreconditionFailed from json. +func (s *SubmitMyAssessmentLabPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentLabPreconditionFailed 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 = SubmitMyAssessmentLabPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentLabPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentLabPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentLabUnauthorized as json. +func (s *SubmitMyAssessmentLabUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentLabUnauthorized from json. +func (s *SubmitMyAssessmentLabUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentLabUnauthorized 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 = SubmitMyAssessmentLabUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentLabUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentLabUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitMyAssessmentLabUnprocessableEntity as json. +func (s *SubmitMyAssessmentLabUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitMyAssessmentLabUnprocessableEntity from json. +func (s *SubmitMyAssessmentLabUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitMyAssessmentLabUnprocessableEntity 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 = SubmitMyAssessmentLabUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitMyAssessmentLabUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitMyAssessmentLabUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *SupportCase) Encode(e *jx.Encoder) { e.ObjStart() 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 61ab725..77f32b2 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,8 @@ const ( ConfirmEmailOperation OperationName = "ConfirmEmail" ConfirmEmailByCodeOperation OperationName = "ConfirmEmailByCode" CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt" + CreateMyAssessmentLabOperation OperationName = "CreateMyAssessmentLab" + CreateMyAssessmentLabConsoleSessionOperation OperationName = "CreateMyAssessmentLabConsoleSession" CreateMyAssessmentPracticeRunOperation OperationName = "CreateMyAssessmentPracticeRun" CreateMySupportCaseOperation OperationName = "CreateMySupportCase" CreateOrganizationOperation OperationName = "CreateOrganization" @@ -25,6 +27,7 @@ const ( GetHealthzOperation OperationName = "GetHealthz" GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt" GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability" + GetMyAssessmentLabOperation OperationName = "GetMyAssessmentLab" GetMyAssessmentPracticeRunOperation OperationName = "GetMyAssessmentPracticeRun" GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult" GetMyAssessmentSignalNoticeOperation OperationName = "GetMyAssessmentSignalNotice" @@ -79,6 +82,7 @@ const ( SetMySearchStatusOperation OperationName = "SetMySearchStatus" StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession" SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer" + SubmitMyAssessmentLabOperation OperationName = "SubmitMyAssessmentLab" UnhideOrganizationOperation OperationName = "UnhideOrganization" UpdateOrganizationOperation OperationName = "UpdateOrganization" UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation" 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 bc0f880..6f84a02 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,276 @@ func decodeCreateMyAssessmentAttemptParams(args [0]string, argsEscaped bool, r * return params, nil } +// CreateMyAssessmentLabParams is parameters of CreateMyAssessmentLab operation. +type CreateMyAssessmentLabParams 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 unpackCreateMyAssessmentLabParams(packed middleware.Parameters) (params CreateMyAssessmentLabParams) { + { + 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 decodeCreateMyAssessmentLabParams(args [1]string, argsEscaped bool, r *http.Request) (params CreateMyAssessmentLabParams, _ 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 +} + +// CreateMyAssessmentLabConsoleSessionParams is parameters of CreateMyAssessmentLabConsoleSession operation. +type CreateMyAssessmentLabConsoleSessionParams 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 lab of this attempt. + LabID uuid.UUID +} + +func unpackCreateMyAssessmentLabConsoleSessionParams(packed middleware.Parameters) (params CreateMyAssessmentLabConsoleSessionParams) { + { + key := middleware.ParameterKey{ + Name: "attempt_id", + In: "path", + } + params.AttemptID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "lab_id", + In: "path", + } + params.LabID = packed[key].(uuid.UUID) + } + return params +} + +func decodeCreateMyAssessmentLabConsoleSessionParams(args [2]string, argsEscaped bool, r *http.Request) (params CreateMyAssessmentLabConsoleSessionParams, _ 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: lab_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: "lab_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.LabID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "lab_id", + In: "path", + Err: err, + } + } + 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 @@ -1672,6 +1942,127 @@ func decodeGetMyAssessmentAttemptParams(args [1]string, argsEscaped bool, r *htt return params, nil } +// GetMyAssessmentLabParams is parameters of GetMyAssessmentLab operation. +type GetMyAssessmentLabParams 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 lab of this attempt. + LabID uuid.UUID +} + +func unpackGetMyAssessmentLabParams(packed middleware.Parameters) (params GetMyAssessmentLabParams) { + { + key := middleware.ParameterKey{ + Name: "attempt_id", + In: "path", + } + params.AttemptID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "lab_id", + In: "path", + } + params.LabID = packed[key].(uuid.UUID) + } + return params +} + +func decodeGetMyAssessmentLabParams(args [2]string, argsEscaped bool, r *http.Request) (params GetMyAssessmentLabParams, _ 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: lab_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: "lab_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.LabID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "lab_id", + In: "path", + Err: err, + } + } + 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 @@ -7249,6 +7640,209 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h return params, nil } +// SubmitMyAssessmentLabParams is parameters of SubmitMyAssessmentLab operation. +type SubmitMyAssessmentLabParams 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 + // Identifier of the lab to submit. + LabID uuid.UUID +} + +func unpackSubmitMyAssessmentLabParams(packed middleware.Parameters) (params SubmitMyAssessmentLabParams) { + { + 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) + } + { + key := middleware.ParameterKey{ + Name: "lab_id", + In: "path", + } + params.LabID = packed[key].(uuid.UUID) + } + return params +} + +func decodeSubmitMyAssessmentLabParams(args [2]string, argsEscaped bool, r *http.Request) (params SubmitMyAssessmentLabParams, _ 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, + } + } + // Decode path: lab_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: "lab_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.LabID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "lab_id", + In: "path", + Err: err, + } + } + return params, nil +} + // UnhideOrganizationParams is parameters of UnhideOrganization operation. type UnhideOrganizationParams struct { // Identifier of the organization that the current candidate hides or stops hiding the profile from. It 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 85596ad..323b979 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,156 @@ func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) ( } } +func (s *Server) decodeCreateMyAssessmentLabRequest(r *http.Request) ( + req *AssessmentLabCreate, + 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 AssessmentLabCreate + 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 + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + +func (s *Server) decodeCreateMyAssessmentLabConsoleSessionRequest(r *http.Request) ( + req *AssessmentLabConsoleSessionCreate, + 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 AssessmentLabConsoleSessionCreate + 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) decodeCreateMyAssessmentPracticeRunRequest(r *http.Request) ( req *PracticeRunCreate, rawBody []byte, @@ -2147,6 +2297,85 @@ func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) ( } } +func (s *Server) decodeSubmitMyAssessmentLabRequest(r *http.Request) ( + req *AssessmentLabSubmission, + 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 AssessmentLabSubmission + 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) decodeUpdateOrganizationRequest(r *http.Request) ( req *OrganizationUpdate, 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 9bd2997..20a8ac6 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,366 @@ func encodeCreateMyAssessmentAttemptResponse(response CreateMyAssessmentAttemptR } } +func encodeCreateMyAssessmentLabResponse(response CreateMyAssessmentLabRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CreateMyAssessmentLabOK: + 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 *CreateMyAssessmentLabCreated: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(201) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateMyAssessmentLabBadRequest: + 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 *CreateMyAssessmentLabUnauthorized: + 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 *CreateMyAssessmentLabForbidden: + 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 *CreateMyAssessmentLabNotFound: + 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 *CreateMyAssessmentLabConflict: + 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 *CreateMyAssessmentLabUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + 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 encodeCreateMyAssessmentLabConsoleSessionResponse(response CreateMyAssessmentLabConsoleSessionRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentLabConsoleSessionHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(201) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateMyAssessmentLabConsoleSessionBadRequest: + 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 *CreateMyAssessmentLabConsoleSessionUnauthorized: + 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 *CreateMyAssessmentLabConsoleSessionForbidden: + 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 *CreateMyAssessmentLabConsoleSessionNotFound: + 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 *CreateMyAssessmentLabConsoleSessionConflict: + 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 *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + 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 encodeCreateMyAssessmentPracticeRunResponse(response CreateMyAssessmentPracticeRunRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *PracticeRunHeaders: @@ -1930,6 +2290,77 @@ func encodeGetMyAssessmentAvailabilityResponse(response GetMyAssessmentAvailabil } } +func encodeGetMyAssessmentLabResponse(response GetMyAssessmentLabRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentLabHeaders: + 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 *GetMyAssessmentLabUnauthorized: + 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 *GetMyAssessmentLabForbidden: + 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 *GetMyAssessmentLabNotFound: + 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 encodeGetMyAssessmentPracticeRunResponse(response GetMyAssessmentPracticeRunRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *PracticeRunHeaders: @@ -6465,6 +6896,190 @@ func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes } } +func encodeSubmitMyAssessmentLabResponse(response SubmitMyAssessmentLabRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentLabHeaders: + 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 *SubmitMyAssessmentLabBadRequest: + 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 *SubmitMyAssessmentLabUnauthorized: + 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 *SubmitMyAssessmentLabForbidden: + 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 *SubmitMyAssessmentLabNotFound: + 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 *SubmitMyAssessmentLabConflict: + 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 *SubmitMyAssessmentLabPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SubmitMyAssessmentLabUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + 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 encodeUnhideOrganizationResponse(response UnhideOrganizationRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *UnhideOrganizationNoContent: 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 6b2ec06..422ef73 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 ( - rn89AllowedHeaders = map[string]string{ + rn93AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn9AllowedHeaders = map[string]string{ @@ -20,47 +20,56 @@ var ( rn10AllowedHeaders = map[string]string{ "POST": "Content-Type,Origin", } - rn84AllowedHeaders = map[string]string{ + rn88AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn74AllowedHeaders = map[string]string{ + rn78AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn30AllowedHeaders = map[string]string{ + rn34AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } - rn86AllowedHeaders = map[string]string{ + rn90AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } rn12AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn100AllowedHeaders = map[string]string{ + rn104AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token", } - rn25AllowedHeaders = map[string]string{ + rn29AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } 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", + rn18AllowedHeaders = map[string]string{ + "POST": "Content-Type,X-Csrf-Token", } - rn83AllowedHeaders = map[string]string{ + rn106AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn61AllowedHeaders = map[string]string{ + rn20AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn103AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token", + } + rn87AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn65AllowedHeaders = 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", } - rn91AllowedHeaders = map[string]string{ + rn95AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } - rn57AllowedHeaders = map[string]string{ + rn61AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "Content-Type,X-Csrf-Token", } @@ -70,68 +79,68 @@ var ( rn7AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn23AllowedHeaders = map[string]string{ + rn28AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn101AllowedHeaders = map[string]string{ + rn107AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn77AllowedHeaders = map[string]string{ + rn81AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn60AllowedHeaders = map[string]string{ + rn64AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "X-Csrf-Token", } - rn96AllowedHeaders = map[string]string{ + rn100AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn97AllowedHeaders = map[string]string{ + rn101AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn42AllowedHeaders = map[string]string{ + rn46AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn87AllowedHeaders = map[string]string{ + rn91AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn43AllowedHeaders = map[string]string{ + rn47AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn16AllowedHeaders = map[string]string{ + rn21AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn17AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn19AllowedHeaders = map[string]string{ - "PATCH": "Content-Type,X-Csrf-Token", - } - rn20AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn50AllowedHeaders = map[string]string{ - "PATCH": "Content-Type,X-Csrf-Token", - } - 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{ + rn24AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn80AllowedHeaders = map[string]string{ + rn25AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn54AllowedHeaders = map[string]string{ + "PATCH": "Content-Type,X-Csrf-Token", + } + rn86AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn98AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn108AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn96AllowedHeaders = map[string]string{ + "POST": "Content-Type,X-Csrf-Token", + } + rn27AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn57AllowedHeaders = map[string]string{ + "PATCH": "Content-Type,X-Csrf-Token", + } + rn84AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } ) @@ -288,7 +297,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn89AllowedHeaders, + allowedHeaders: rn93AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -391,7 +400,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn84AllowedHeaders, + allowedHeaders: rn88AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -415,7 +424,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn74AllowedHeaders, + allowedHeaders: rn78AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -442,7 +451,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,GET", - allowedHeaders: rn30AllowedHeaders, + allowedHeaders: rn34AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -495,7 +504,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn86AllowedHeaders, + allowedHeaders: rn90AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -617,7 +626,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn100AllowedHeaders, + allowedHeaders: rn104AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -644,7 +653,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn25AllowedHeaders, + allowedHeaders: rn29AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -653,6 +662,142 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + case 'l': // Prefix: "labs" + + if l := len("labs"); len(elem) >= l && elem[0:l] == "labs" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "POST": + s.handleCreateMyAssessmentLabRequest([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: "lab_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[1] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleGetMyAssessmentLabRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'c': // Prefix: "console-sessions" + + if l := len("console-sessions"); len(elem) >= l && elem[0:l] == "console-sessions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleCreateMyAssessmentLabConsoleSessionRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn18AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 's': // Prefix: "submission" + + if l := len("submission"); len(elem) >= l && elem[0:l] == "submission" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleSubmitMyAssessmentLabRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn106AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + } + + } + + } + case 'p': // Prefix: "practice-runs" if l := len("practice-runs"); len(elem) >= l && elem[0:l] == "practice-runs" { @@ -670,7 +815,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn15AllowedHeaders, + allowedHeaders: rn20AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -775,7 +920,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn99AllowedHeaders, + allowedHeaders: rn103AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -802,7 +947,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn83AllowedHeaders, + allowedHeaders: rn87AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -835,7 +980,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn61AllowedHeaders, + allowedHeaders: rn65AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1044,7 +1189,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE", - allowedHeaders: rn91AllowedHeaders, + allowedHeaders: rn95AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1078,7 +1223,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn57AllowedHeaders, + allowedHeaders: rn61AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1259,7 +1404,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn23AllowedHeaders, + allowedHeaders: rn28AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1286,7 +1431,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn101AllowedHeaders, + allowedHeaders: rn107AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1364,7 +1509,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn77AllowedHeaders, + allowedHeaders: rn81AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1542,7 +1687,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn60AllowedHeaders, + allowedHeaders: rn64AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1633,7 +1778,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn96AllowedHeaders, + allowedHeaders: rn100AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1660,7 +1805,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn97AllowedHeaders, + allowedHeaders: rn101AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1690,7 +1835,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn42AllowedHeaders, + allowedHeaders: rn46AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1715,7 +1860,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn87AllowedHeaders, + allowedHeaders: rn91AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1746,7 +1891,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn43AllowedHeaders, + allowedHeaders: rn47AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1772,7 +1917,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn16AllowedHeaders, + allowedHeaders: rn21AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1836,7 +1981,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn17AllowedHeaders, + allowedHeaders: rn22AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1875,7 +2020,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn19AllowedHeaders, + allowedHeaders: rn24AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -1983,7 +2128,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn20AllowedHeaders, + allowedHeaders: rn25AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2024,7 +2169,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn50AllowedHeaders, + allowedHeaders: rn54AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -2104,7 +2249,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn82AllowedHeaders, + allowedHeaders: rn86AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2132,7 +2277,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn94AllowedHeaders, + allowedHeaders: rn98AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2162,7 +2307,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn102AllowedHeaders, + allowedHeaders: rn108AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2195,7 +2340,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn92AllowedHeaders, + allowedHeaders: rn96AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2237,7 +2382,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn22AllowedHeaders, + allowedHeaders: rn27AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2279,7 +2424,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn53AllowedHeaders, + allowedHeaders: rn57AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -2356,7 +2501,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn80AllowedHeaders, + allowedHeaders: rn84AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -2967,6 +3112,131 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } + case 'l': // Prefix: "labs" + + if l := len("labs"); len(elem) >= l && elem[0:l] == "labs" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "POST": + r.name = CreateMyAssessmentLabOperation + r.summary = "Start the lab of the current lab item of an assessment attempt." + r.operationID = "CreateMyAssessmentLab" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/labs" + 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: "lab_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[1] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + switch method { + case "GET": + r.name = GetMyAssessmentLabOperation + r.summary = "Read the lab of an assessment attempt item." + r.operationID = "GetMyAssessmentLab" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'c': // Prefix: "console-sessions" + + if l := len("console-sessions"); len(elem) >= l && elem[0:l] == "console-sessions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = CreateMyAssessmentLabConsoleSessionOperation + r.summary = "Open a console session of one node of a ready lab." + r.operationID = "CreateMyAssessmentLabConsoleSession" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/console-sessions" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + case 's': // Prefix: "submission" + + if l := len("submission"); len(elem) >= l && elem[0:l] == "submission" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = SubmitMyAssessmentLabOperation + r.summary = "Submit the lab of the current lab item as its answer." + r.operationID = "SubmitMyAssessmentLab" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/submission" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + } + + } + + } + case 'p': // Prefix: "practice-runs" if l := len("practice-runs"); len(elem) >= l && elem[0:l] == "practice-runs" { 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 6d0d032..85aa746 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -3610,6 +3610,488 @@ func (s *AssessmentItem) SetContent(val ItemContent) { type AssessmentItemId uuid.UUID +// Candidate view of the lab of one attempt item. It contains no node address, MAC address, port, +// password, key, token, seed, checker state, criteria, score, or infrastructure name. +// Ref: #/components/schemas/AssessmentLab +type AssessmentLab struct { + // Identifier of the lab. + ID uuid.UUID `json:"id"` + ItemID AssessmentItemId `json:"item_id"` + State AssessmentLabState `json:"state"` + Nodes []AssessmentLabNode `json:"nodes"` + CreatedAt Timestamp `json:"created_at"` + // Time the lab became `ready`, or null before. + ReadyAt NilTimestamp `json:"ready_at"` + // Time the lab ends unless it was submitted before: the earlier of the lifetime of the item and the + // attempt deadline. It never moves. + ExpiresAt Timestamp `json:"expires_at"` + // Time the lab reached `submitted`, `expired`, or `failed`, or null. + FinishedAt NilTimestamp `json:"finished_at"` + // `lab_error` when `state` is `failed`, otherwise null. + FailureReason NilAssessmentLabFailureReason `json:"failure_reason"` +} + +// GetID returns the value of ID. +func (s *AssessmentLab) GetID() uuid.UUID { + return s.ID +} + +// GetItemID returns the value of ItemID. +func (s *AssessmentLab) GetItemID() AssessmentItemId { + return s.ItemID +} + +// GetState returns the value of State. +func (s *AssessmentLab) GetState() AssessmentLabState { + return s.State +} + +// GetNodes returns the value of Nodes. +func (s *AssessmentLab) GetNodes() []AssessmentLabNode { + return s.Nodes +} + +// GetCreatedAt returns the value of CreatedAt. +func (s *AssessmentLab) GetCreatedAt() Timestamp { + return s.CreatedAt +} + +// GetReadyAt returns the value of ReadyAt. +func (s *AssessmentLab) GetReadyAt() NilTimestamp { + return s.ReadyAt +} + +// GetExpiresAt returns the value of ExpiresAt. +func (s *AssessmentLab) GetExpiresAt() Timestamp { + return s.ExpiresAt +} + +// GetFinishedAt returns the value of FinishedAt. +func (s *AssessmentLab) GetFinishedAt() NilTimestamp { + return s.FinishedAt +} + +// GetFailureReason returns the value of FailureReason. +func (s *AssessmentLab) GetFailureReason() NilAssessmentLabFailureReason { + return s.FailureReason +} + +// SetID sets the value of ID. +func (s *AssessmentLab) SetID(val uuid.UUID) { + s.ID = val +} + +// SetItemID sets the value of ItemID. +func (s *AssessmentLab) SetItemID(val AssessmentItemId) { + s.ItemID = val +} + +// SetState sets the value of State. +func (s *AssessmentLab) SetState(val AssessmentLabState) { + s.State = val +} + +// SetNodes sets the value of Nodes. +func (s *AssessmentLab) SetNodes(val []AssessmentLabNode) { + s.Nodes = val +} + +// SetCreatedAt sets the value of CreatedAt. +func (s *AssessmentLab) SetCreatedAt(val Timestamp) { + s.CreatedAt = val +} + +// SetReadyAt sets the value of ReadyAt. +func (s *AssessmentLab) SetReadyAt(val NilTimestamp) { + s.ReadyAt = val +} + +// SetExpiresAt sets the value of ExpiresAt. +func (s *AssessmentLab) SetExpiresAt(val Timestamp) { + s.ExpiresAt = val +} + +// SetFinishedAt sets the value of FinishedAt. +func (s *AssessmentLab) SetFinishedAt(val NilTimestamp) { + s.FinishedAt = val +} + +// SetFailureReason sets the value of FailureReason. +func (s *AssessmentLab) SetFailureReason(val NilAssessmentLabFailureReason) { + s.FailureReason = val +} + +// A console session of one node. The client opens a WebSocket to `websocket_path` on the same origin +// before `expires_at`; the session cookie and the Origin check authorize the upgrade, so no secret +// travels in the path, the body, or a query string. A session can be attached once and ends with the +// lab. +// Ref: #/components/schemas/AssessmentLabConsoleSession +type AssessmentLabConsoleSession struct { + // Identifier of the console session; it is not a secret. + ID uuid.UUID `json:"id"` + Node AssessmentLabNodeName `json:"node"` + // Same-origin path of the console WebSocket. + WebsocketPath string `json:"websocket_path"` + // Time by which the WebSocket must be opened. + ExpiresAt Timestamp `json:"expires_at"` +} + +// GetID returns the value of ID. +func (s *AssessmentLabConsoleSession) GetID() uuid.UUID { + return s.ID +} + +// GetNode returns the value of Node. +func (s *AssessmentLabConsoleSession) GetNode() AssessmentLabNodeName { + return s.Node +} + +// GetWebsocketPath returns the value of WebsocketPath. +func (s *AssessmentLabConsoleSession) GetWebsocketPath() string { + return s.WebsocketPath +} + +// GetExpiresAt returns the value of ExpiresAt. +func (s *AssessmentLabConsoleSession) GetExpiresAt() Timestamp { + return s.ExpiresAt +} + +// SetID sets the value of ID. +func (s *AssessmentLabConsoleSession) SetID(val uuid.UUID) { + s.ID = val +} + +// SetNode sets the value of Node. +func (s *AssessmentLabConsoleSession) SetNode(val AssessmentLabNodeName) { + s.Node = val +} + +// SetWebsocketPath sets the value of WebsocketPath. +func (s *AssessmentLabConsoleSession) SetWebsocketPath(val string) { + s.WebsocketPath = val +} + +// SetExpiresAt sets the value of ExpiresAt. +func (s *AssessmentLabConsoleSession) SetExpiresAt(val Timestamp) { + s.ExpiresAt = val +} + +// Open a console of one node of a ready lab. Unknown fields are rejected. +// Ref: #/components/schemas/AssessmentLabConsoleSessionCreate +type AssessmentLabConsoleSessionCreate struct { + Node AssessmentLabNodeName `json:"node"` +} + +// GetNode returns the value of Node. +func (s *AssessmentLabConsoleSessionCreate) GetNode() AssessmentLabNodeName { + return s.Node +} + +// SetNode sets the value of Node. +func (s *AssessmentLabConsoleSessionCreate) SetNode(val AssessmentLabNodeName) { + s.Node = val +} + +// AssessmentLabConsoleSessionHeaders wraps AssessmentLabConsoleSession with response headers. +type AssessmentLabConsoleSessionHeaders struct { + CacheControl CacheControlNoStore + Response AssessmentLabConsoleSession +} + +// GetCacheControl returns the value of CacheControl. +func (s *AssessmentLabConsoleSessionHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AssessmentLabConsoleSessionHeaders) GetResponse() AssessmentLabConsoleSession { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AssessmentLabConsoleSessionHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AssessmentLabConsoleSessionHeaders) SetResponse(val AssessmentLabConsoleSession) { + s.Response = val +} + +func (*AssessmentLabConsoleSessionHeaders) createMyAssessmentLabConsoleSessionRes() {} + +// Start the lab of the current lab item. Unknown fields are rejected. +// Ref: #/components/schemas/AssessmentLabCreate +type AssessmentLabCreate struct { + ItemID AssessmentItemId `json:"item_id"` +} + +// GetItemID returns the value of ItemID. +func (s *AssessmentLabCreate) GetItemID() AssessmentItemId { + return s.ItemID +} + +// SetItemID sets the value of ItemID. +func (s *AssessmentLabCreate) SetItemID(val AssessmentItemId) { + s.ItemID = val +} + +// Why a lab failed: `lab_error` for an infrastructure failure, such as a node that did not boot or a +// check that could not reach a node. It never depends on the candidate and is never a failed check. +// Ref: #/components/schemas/AssessmentLabFailureReason +type AssessmentLabFailureReason string + +const ( + AssessmentLabFailureReasonLabError AssessmentLabFailureReason = "lab_error" +) + +// AllValues returns all AssessmentLabFailureReason values. +func (AssessmentLabFailureReason) AllValues() []AssessmentLabFailureReason { + return []AssessmentLabFailureReason{ + AssessmentLabFailureReasonLabError, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentLabFailureReason) MarshalText() ([]byte, error) { + switch s { + case AssessmentLabFailureReasonLabError: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentLabFailureReason) UnmarshalText(data []byte) error { + switch AssessmentLabFailureReason(data) { + case AssessmentLabFailureReasonLabError: + *s = AssessmentLabFailureReasonLabError + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// AssessmentLabHeaders wraps AssessmentLab with response headers. +type AssessmentLabHeaders struct { + CacheControl CacheControlNoStore + Response AssessmentLab +} + +// GetCacheControl returns the value of CacheControl. +func (s *AssessmentLabHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AssessmentLabHeaders) GetResponse() AssessmentLab { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AssessmentLabHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AssessmentLabHeaders) SetResponse(val AssessmentLab) { + s.Response = val +} + +func (*AssessmentLabHeaders) getMyAssessmentLabRes() {} +func (*AssessmentLabHeaders) submitMyAssessmentLabRes() {} + +// A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a +// password, a key, or an infrastructure name. +// Ref: #/components/schemas/AssessmentLabNode +type AssessmentLabNode struct { + Name AssessmentLabNodeName `json:"name"` + Kind AssessmentLabNodeKind `json:"kind"` +} + +// GetName returns the value of Name. +func (s *AssessmentLabNode) GetName() AssessmentLabNodeName { + return s.Name +} + +// GetKind returns the value of Kind. +func (s *AssessmentLabNode) GetKind() AssessmentLabNodeKind { + return s.Kind +} + +// SetName sets the value of Name. +func (s *AssessmentLabNode) SetName(val AssessmentLabNodeName) { + s.Name = val +} + +// SetKind sets the value of Kind. +func (s *AssessmentLabNode) SetKind(val AssessmentLabNodeKind) { + s.Kind = val +} + +// What the console of a node shows. +// +// - mikrotik: a MikroTik router with the RouterOS console. +// - ubuntu: a small Ubuntu server with a Linux login. +// +// Adding a value is a contract change. +// Ref: #/components/schemas/AssessmentLabNodeKind +type AssessmentLabNodeKind string + +const ( + AssessmentLabNodeKindMikrotik AssessmentLabNodeKind = "mikrotik" + AssessmentLabNodeKindUbuntu AssessmentLabNodeKind = "ubuntu" +) + +// AllValues returns all AssessmentLabNodeKind values. +func (AssessmentLabNodeKind) AllValues() []AssessmentLabNodeKind { + return []AssessmentLabNodeKind{ + AssessmentLabNodeKindMikrotik, + AssessmentLabNodeKindUbuntu, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentLabNodeKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentLabNodeKindMikrotik: + return []byte(s), nil + case AssessmentLabNodeKindUbuntu: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentLabNodeKind) UnmarshalText(data []byte) error { + switch AssessmentLabNodeKind(data) { + case AssessmentLabNodeKindMikrotik: + *s = AssessmentLabNodeKindMikrotik + return nil + case AssessmentLabNodeKindUbuntu: + *s = AssessmentLabNodeKindUbuntu + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentLabNodeName string + +// State of a lab of an attempt item. +// +// - provisioning: the nodes are being prepared; poll GetMyAssessmentLab. +// - ready: the consoles can be opened until `expires_at`. +// - checking: the answer was accepted; the consoles are closed and the server checks the nodes. +// - submitted: the check finished and the answer is recorded; the lab is deleted. The state never +// says whether the answer was correct. +// - expired: the lifetime or the attempt deadline ended before a submission; the lab is deleted and +// the item cannot start another lab. +// - failed: the lab infrastructure failed, independently of the candidate; `failure_reason` is +// `lab_error`. Nothing was recorded or consumed, and the candidate may start a new lab of the same +// item while the item is current. +// +// Adding a value is a contract change. +// Ref: #/components/schemas/AssessmentLabState +type AssessmentLabState string + +const ( + AssessmentLabStateProvisioning AssessmentLabState = "provisioning" + AssessmentLabStateReady AssessmentLabState = "ready" + AssessmentLabStateChecking AssessmentLabState = "checking" + AssessmentLabStateSubmitted AssessmentLabState = "submitted" + AssessmentLabStateExpired AssessmentLabState = "expired" + AssessmentLabStateFailed AssessmentLabState = "failed" +) + +// AllValues returns all AssessmentLabState values. +func (AssessmentLabState) AllValues() []AssessmentLabState { + return []AssessmentLabState{ + AssessmentLabStateProvisioning, + AssessmentLabStateReady, + AssessmentLabStateChecking, + AssessmentLabStateSubmitted, + AssessmentLabStateExpired, + AssessmentLabStateFailed, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentLabState) MarshalText() ([]byte, error) { + switch s { + case AssessmentLabStateProvisioning: + return []byte(s), nil + case AssessmentLabStateReady: + return []byte(s), nil + case AssessmentLabStateChecking: + return []byte(s), nil + case AssessmentLabStateSubmitted: + return []byte(s), nil + case AssessmentLabStateExpired: + return []byte(s), nil + case AssessmentLabStateFailed: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentLabState) UnmarshalText(data []byte) error { + switch AssessmentLabState(data) { + case AssessmentLabStateProvisioning: + *s = AssessmentLabStateProvisioning + return nil + case AssessmentLabStateReady: + *s = AssessmentLabStateReady + return nil + case AssessmentLabStateChecking: + *s = AssessmentLabStateChecking + return nil + case AssessmentLabStateSubmitted: + *s = AssessmentLabStateSubmitted + return nil + case AssessmentLabStateExpired: + *s = AssessmentLabStateExpired + return nil + case AssessmentLabStateFailed: + *s = AssessmentLabStateFailed + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Submit the lab of the current lab item as its answer. Unknown fields are rejected, so a request +// cannot send a score or a correctness flag. +// Ref: #/components/schemas/AssessmentLabSubmission +type AssessmentLabSubmission struct { + ExpectedVersion AssessmentAttemptVersion `json:"expected_version"` + Answer LabAnswer `json:"answer"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *AssessmentLabSubmission) GetExpectedVersion() AssessmentAttemptVersion { + return s.ExpectedVersion +} + +// GetAnswer returns the value of Answer. +func (s *AssessmentLabSubmission) GetAnswer() LabAnswer { + return s.Answer +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *AssessmentLabSubmission) SetExpectedVersion(val AssessmentAttemptVersion) { + s.ExpectedVersion = val +} + +// SetAnswer sets the value of Answer. +func (s *AssessmentLabSubmission) SetAnswer(val LabAnswer) { + s.Answer = val +} + // Known limitation of the method behind a real-assessment result, shown with the result. // // - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. @@ -9746,6 +10228,58 @@ type CreateMyAssessmentAttemptUnprocessableEntity Problem func (*CreateMyAssessmentAttemptUnprocessableEntity) createMyAssessmentAttemptRes() {} +type CreateMyAssessmentLabBadRequest Problem + +func (*CreateMyAssessmentLabBadRequest) createMyAssessmentLabRes() {} + +type CreateMyAssessmentLabConflict Problem + +func (*CreateMyAssessmentLabConflict) createMyAssessmentLabRes() {} + +type CreateMyAssessmentLabConsoleSessionBadRequest Problem + +func (*CreateMyAssessmentLabConsoleSessionBadRequest) createMyAssessmentLabConsoleSessionRes() {} + +type CreateMyAssessmentLabConsoleSessionConflict Problem + +func (*CreateMyAssessmentLabConsoleSessionConflict) createMyAssessmentLabConsoleSessionRes() {} + +type CreateMyAssessmentLabConsoleSessionForbidden Problem + +func (*CreateMyAssessmentLabConsoleSessionForbidden) createMyAssessmentLabConsoleSessionRes() {} + +type CreateMyAssessmentLabConsoleSessionNotFound Problem + +func (*CreateMyAssessmentLabConsoleSessionNotFound) createMyAssessmentLabConsoleSessionRes() {} + +type CreateMyAssessmentLabConsoleSessionUnauthorized Problem + +func (*CreateMyAssessmentLabConsoleSessionUnauthorized) createMyAssessmentLabConsoleSessionRes() {} + +type CreateMyAssessmentLabCreated AssessmentLabHeaders + +func (*CreateMyAssessmentLabCreated) createMyAssessmentLabRes() {} + +type CreateMyAssessmentLabForbidden Problem + +func (*CreateMyAssessmentLabForbidden) createMyAssessmentLabRes() {} + +type CreateMyAssessmentLabNotFound Problem + +func (*CreateMyAssessmentLabNotFound) createMyAssessmentLabRes() {} + +type CreateMyAssessmentLabOK AssessmentLabHeaders + +func (*CreateMyAssessmentLabOK) createMyAssessmentLabRes() {} + +type CreateMyAssessmentLabUnauthorized Problem + +func (*CreateMyAssessmentLabUnauthorized) createMyAssessmentLabRes() {} + +type CreateMyAssessmentLabUnprocessableEntity Problem + +func (*CreateMyAssessmentLabUnprocessableEntity) createMyAssessmentLabRes() {} + type CreateMyAssessmentPracticeRunBadRequest Problem func (*CreateMyAssessmentPracticeRunBadRequest) createMyAssessmentPracticeRunRes() {} @@ -11015,6 +11549,18 @@ type GetMyAssessmentAvailabilityUnauthorized Problem func (*GetMyAssessmentAvailabilityUnauthorized) getMyAssessmentAvailabilityRes() {} +type GetMyAssessmentLabForbidden Problem + +func (*GetMyAssessmentLabForbidden) getMyAssessmentLabRes() {} + +type GetMyAssessmentLabNotFound Problem + +func (*GetMyAssessmentLabNotFound) getMyAssessmentLabRes() {} + +type GetMyAssessmentLabUnauthorized Problem + +func (*GetMyAssessmentLabUnauthorized) getMyAssessmentLabRes() {} + type GetMyAssessmentPracticeRunForbidden Problem func (*GetMyAssessmentPracticeRunForbidden) getMyAssessmentPracticeRunRes() {} @@ -12862,6 +13408,7 @@ type ItemContent struct { FindErrorItemContent FindErrorItemContent ConfigurationItemContent ConfigurationItemContent PracticeItemContent PracticeItemContent + LabItemContent LabItemContent } // ItemContentType is oneOf type of ItemContent. @@ -12876,6 +13423,7 @@ const ( FindErrorItemContentItemContent ItemContentType = "FindErrorItemContent" ConfigurationItemContentItemContent ItemContentType = "ConfigurationItemContent" PracticeItemContentItemContent ItemContentType = "PracticeItemContent" + LabItemContentItemContent ItemContentType = "LabItemContent" ) // IsChoiceItemContent reports whether ItemContent is ChoiceItemContent. @@ -12901,6 +13449,9 @@ func (s ItemContent) IsConfigurationItemContent() bool { // IsPracticeItemContent reports whether ItemContent is PracticeItemContent. func (s ItemContent) IsPracticeItemContent() bool { return s.Type == PracticeItemContentItemContent } +// IsLabItemContent reports whether ItemContent is LabItemContent. +func (s ItemContent) IsLabItemContent() bool { return s.Type == LabItemContentItemContent } + // SetChoiceItemContent sets ItemContent to ChoiceItemContent. func (s *ItemContent) SetChoiceItemContent(v ChoiceItemContent) { s.Type = ChoiceItemContentItemContent @@ -13048,6 +13599,172 @@ func NewPracticeItemContentItemContent(v PracticeItemContent) ItemContent { return s } +// SetLabItemContent sets ItemContent to LabItemContent. +func (s *ItemContent) SetLabItemContent(v LabItemContent) { + s.Type = LabItemContentItemContent + s.LabItemContent = v +} + +// GetLabItemContent returns LabItemContent and true boolean if ItemContent is LabItemContent. +func (s ItemContent) GetLabItemContent() (v LabItemContent, ok bool) { + if !s.IsLabItemContent() { + return v, false + } + return s.LabItemContent, true +} + +// NewLabItemContentItemContent returns new ItemContent from LabItemContent. +func NewLabItemContentItemContent(v LabItemContent) ItemContent { + var s ItemContent + s.SetLabItemContent(v) + return s +} + +// Answer of a lab item: the state of the nodes of the named lab at the moment of submission. The +// server reads that state with the checker of the task; the body carries no configuration text, score, +// or correctness flag. Two answers are equal when they name the same lab. It is the answer of +// SubmitMyAssessmentLab only and is not a member of AssessmentAnswer. +// Ref: #/components/schemas/LabAnswer +type LabAnswer struct { + Format LabAnswerFormat `json:"format"` + // The lab of this item that the candidate worked in. + LabID uuid.UUID `json:"lab_id"` +} + +// GetFormat returns the value of Format. +func (s *LabAnswer) GetFormat() LabAnswerFormat { + return s.Format +} + +// GetLabID returns the value of LabID. +func (s *LabAnswer) GetLabID() uuid.UUID { + return s.LabID +} + +// SetFormat sets the value of Format. +func (s *LabAnswer) SetFormat(val LabAnswerFormat) { + s.Format = val +} + +// SetLabID sets the value of LabID. +func (s *LabAnswer) SetLabID(val uuid.UUID) { + s.LabID = val +} + +type LabAnswerFormat string + +const ( + LabAnswerFormatLab LabAnswerFormat = "lab" +) + +// AllValues returns all LabAnswerFormat values. +func (LabAnswerFormat) AllValues() []LabAnswerFormat { + return []LabAnswerFormat{ + LabAnswerFormatLab, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s LabAnswerFormat) MarshalText() ([]byte, error) { + switch s { + case LabAnswerFormatLab: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *LabAnswerFormat) UnmarshalText(data []byte) error { + switch LabAnswerFormat(data) { + case LabAnswerFormatLab: + *s = LabAnswerFormatLab + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Practical lab: configure or repair a small network of virtual nodes through their consoles. The +// candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and +// submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists +// only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the +// seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted +// only with SubmitMyAssessmentLab. +// Ref: #/components/schemas/LabItemContent +type LabItemContent struct { + Format LabItemContentFormat `json:"format"` + // Nodes of the lab in the order of the statement. + Nodes []AssessmentLabNode `json:"nodes"` + // Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt + // deadline. + TimeLimitSeconds int32 `json:"time_limit_seconds"` +} + +// GetFormat returns the value of Format. +func (s *LabItemContent) GetFormat() LabItemContentFormat { + return s.Format +} + +// GetNodes returns the value of Nodes. +func (s *LabItemContent) GetNodes() []AssessmentLabNode { + return s.Nodes +} + +// GetTimeLimitSeconds returns the value of TimeLimitSeconds. +func (s *LabItemContent) GetTimeLimitSeconds() int32 { + return s.TimeLimitSeconds +} + +// SetFormat sets the value of Format. +func (s *LabItemContent) SetFormat(val LabItemContentFormat) { + s.Format = val +} + +// SetNodes sets the value of Nodes. +func (s *LabItemContent) SetNodes(val []AssessmentLabNode) { + s.Nodes = val +} + +// SetTimeLimitSeconds sets the value of TimeLimitSeconds. +func (s *LabItemContent) SetTimeLimitSeconds(val int32) { + s.TimeLimitSeconds = val +} + +type LabItemContentFormat string + +const ( + LabItemContentFormatLab LabItemContentFormat = "lab" +) + +// AllValues returns all LabItemContentFormat values. +func (LabItemContentFormat) AllValues() []LabItemContentFormat { + return []LabItemContentFormat{ + LabItemContentFormatLab, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s LabItemContentFormat) MarshalText() ([]byte, error) { + switch s { + case LabItemContentFormatLab: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *LabItemContentFormat) UnmarshalText(data []byte) error { + switch LabItemContentFormat(data) { + case LabItemContentFormatLab: + *s = LabItemContentFormatLab + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + type ListMyAssessmentResultsBadRequest Problem func (*ListMyAssessmentResultsBadRequest) listMyAssessmentResultsRes() {} @@ -17873,6 +18590,51 @@ func (o NilAssessmentItem) Or(d AssessmentItem) AssessmentItem { return d } +// NewNilAssessmentLabFailureReason returns new NilAssessmentLabFailureReason with value set to v. +func NewNilAssessmentLabFailureReason(v AssessmentLabFailureReason) NilAssessmentLabFailureReason { + return NilAssessmentLabFailureReason{ + Value: v, + } +} + +// NilAssessmentLabFailureReason is nullable AssessmentLabFailureReason. +type NilAssessmentLabFailureReason struct { + Value AssessmentLabFailureReason + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentLabFailureReason) SetTo(v AssessmentLabFailureReason) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentLabFailureReason) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentLabFailureReason) SetToNull() { + o.Null = true + var v AssessmentLabFailureReason + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentLabFailureReason) Get() (v AssessmentLabFailureReason, 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 NilAssessmentLabFailureReason) Or(d AssessmentLabFailureReason) AssessmentLabFailureReason { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilAssessmentNotDeterminedReason returns new NilAssessmentNotDeterminedReason with value set to v. func NewNilAssessmentNotDeterminedReason(v AssessmentNotDeterminedReason) NilAssessmentNotDeterminedReason { return NilAssessmentNotDeterminedReason{ @@ -30237,7 +30999,10 @@ func (s *ServiceUnavailableHeaders) SetResponse(val Problem) { s.Response = val } -func (*ServiceUnavailableHeaders) createMyAssessmentPracticeRunRes() {} +func (*ServiceUnavailableHeaders) createMyAssessmentLabConsoleSessionRes() {} +func (*ServiceUnavailableHeaders) createMyAssessmentLabRes() {} +func (*ServiceUnavailableHeaders) createMyAssessmentPracticeRunRes() {} +func (*ServiceUnavailableHeaders) submitMyAssessmentLabRes() {} // 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. @@ -30717,6 +31482,34 @@ type SubmitMyAssessmentAnswerUnprocessableEntity Problem func (*SubmitMyAssessmentAnswerUnprocessableEntity) submitMyAssessmentAnswerRes() {} +type SubmitMyAssessmentLabBadRequest Problem + +func (*SubmitMyAssessmentLabBadRequest) submitMyAssessmentLabRes() {} + +type SubmitMyAssessmentLabConflict Problem + +func (*SubmitMyAssessmentLabConflict) submitMyAssessmentLabRes() {} + +type SubmitMyAssessmentLabForbidden Problem + +func (*SubmitMyAssessmentLabForbidden) submitMyAssessmentLabRes() {} + +type SubmitMyAssessmentLabNotFound Problem + +func (*SubmitMyAssessmentLabNotFound) submitMyAssessmentLabRes() {} + +type SubmitMyAssessmentLabPreconditionFailed Problem + +func (*SubmitMyAssessmentLabPreconditionFailed) submitMyAssessmentLabRes() {} + +type SubmitMyAssessmentLabUnauthorized Problem + +func (*SubmitMyAssessmentLabUnauthorized) submitMyAssessmentLabRes() {} + +type SubmitMyAssessmentLabUnprocessableEntity Problem + +func (*SubmitMyAssessmentLabUnprocessableEntity) submitMyAssessmentLabRes() {} + // Case of the current account. It contains what the author sent, the public processing state, and the // public history. It never contains the identity of a moderator, an expert, or a support agent, // internal notes, evidence, assessment answers or anti-cheat signals, risk signals, or contact data of @@ -32837,36 +33630,39 @@ func (s *TooManyRequestsHeaders) SetResponse(val Problem) { s.Response = val } -func (*TooManyRequestsHeaders) acceptMyInvitationRes() {} -func (*TooManyRequestsHeaders) cancelMyInvitationRes() {} -func (*TooManyRequestsHeaders) confirmEmailByCodeRes() {} -func (*TooManyRequestsHeaders) confirmEmailRes() {} -func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {} -func (*TooManyRequestsHeaders) createMyAssessmentPracticeRunRes() {} -func (*TooManyRequestsHeaders) createMySupportCaseRes() {} -func (*TooManyRequestsHeaders) createOrganizationInvitationRes() {} -func (*TooManyRequestsHeaders) createOrganizationNeedRes() {} -func (*TooManyRequestsHeaders) createOrganizationRes() {} -func (*TooManyRequestsHeaders) declineMyInvitationRes() {} -func (*TooManyRequestsHeaders) getOrganizationCandidateCardRes() {} -func (*TooManyRequestsHeaders) getOrganizationCandidateEvidenceRes() {} -func (*TooManyRequestsHeaders) hideOrganizationRes() {} -func (*TooManyRequestsHeaders) loginRes() {} -func (*TooManyRequestsHeaders) markMyNotificationReadRes() {} -func (*TooManyRequestsHeaders) markOrganizationNotificationReadRes() {} -func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {} -func (*TooManyRequestsHeaders) recordMyAssessmentAttemptSignalsRes() {} -func (*TooManyRequestsHeaders) registerAccountRes() {} -func (*TooManyRequestsHeaders) requestMyRepositoryChecksRes() {} -func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} -func (*TooManyRequestsHeaders) sendOrganizationInvitationRes() {} -func (*TooManyRequestsHeaders) startMyAssessmentAttemptSessionRes() {} -func (*TooManyRequestsHeaders) submitMyAssessmentAnswerRes() {} -func (*TooManyRequestsHeaders) updateOrganizationInvitationRes() {} -func (*TooManyRequestsHeaders) updateOrganizationNeedRes() {} -func (*TooManyRequestsHeaders) updateOrganizationRes() {} -func (*TooManyRequestsHeaders) viewMyInvitationRes() {} -func (*TooManyRequestsHeaders) withdrawOrganizationInvitationRes() {} +func (*TooManyRequestsHeaders) acceptMyInvitationRes() {} +func (*TooManyRequestsHeaders) cancelMyInvitationRes() {} +func (*TooManyRequestsHeaders) confirmEmailByCodeRes() {} +func (*TooManyRequestsHeaders) confirmEmailRes() {} +func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {} +func (*TooManyRequestsHeaders) createMyAssessmentLabConsoleSessionRes() {} +func (*TooManyRequestsHeaders) createMyAssessmentLabRes() {} +func (*TooManyRequestsHeaders) createMyAssessmentPracticeRunRes() {} +func (*TooManyRequestsHeaders) createMySupportCaseRes() {} +func (*TooManyRequestsHeaders) createOrganizationInvitationRes() {} +func (*TooManyRequestsHeaders) createOrganizationNeedRes() {} +func (*TooManyRequestsHeaders) createOrganizationRes() {} +func (*TooManyRequestsHeaders) declineMyInvitationRes() {} +func (*TooManyRequestsHeaders) getOrganizationCandidateCardRes() {} +func (*TooManyRequestsHeaders) getOrganizationCandidateEvidenceRes() {} +func (*TooManyRequestsHeaders) hideOrganizationRes() {} +func (*TooManyRequestsHeaders) loginRes() {} +func (*TooManyRequestsHeaders) markMyNotificationReadRes() {} +func (*TooManyRequestsHeaders) markOrganizationNotificationReadRes() {} +func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {} +func (*TooManyRequestsHeaders) recordMyAssessmentAttemptSignalsRes() {} +func (*TooManyRequestsHeaders) registerAccountRes() {} +func (*TooManyRequestsHeaders) requestMyRepositoryChecksRes() {} +func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} +func (*TooManyRequestsHeaders) sendOrganizationInvitationRes() {} +func (*TooManyRequestsHeaders) startMyAssessmentAttemptSessionRes() {} +func (*TooManyRequestsHeaders) submitMyAssessmentAnswerRes() {} +func (*TooManyRequestsHeaders) submitMyAssessmentLabRes() {} +func (*TooManyRequestsHeaders) updateOrganizationInvitationRes() {} +func (*TooManyRequestsHeaders) updateOrganizationNeedRes() {} +func (*TooManyRequestsHeaders) updateOrganizationRes() {} +func (*TooManyRequestsHeaders) viewMyInvitationRes() {} +func (*TooManyRequestsHeaders) withdrawOrganizationInvitationRes() {} type UnhideOrganizationBadRequest Problem 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 51b1004..0c442e9 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,8 @@ var operationRolesSessionCookie = map[string][]string{ AcknowledgeMyAssessmentSignalNoticeOperation: []string{}, CancelMyInvitationOperation: []string{}, CreateMyAssessmentAttemptOperation: []string{}, + CreateMyAssessmentLabOperation: []string{}, + CreateMyAssessmentLabConsoleSessionOperation: []string{}, CreateMyAssessmentPracticeRunOperation: []string{}, CreateMySupportCaseOperation: []string{}, CreateOrganizationOperation: []string{}, @@ -71,6 +73,7 @@ var operationRolesSessionCookie = map[string][]string{ GetCurrentSessionOperation: []string{}, GetMyAssessmentAttemptOperation: []string{}, GetMyAssessmentAvailabilityOperation: []string{}, + GetMyAssessmentLabOperation: []string{}, GetMyAssessmentPracticeRunOperation: []string{}, GetMyAssessmentResultOperation: []string{}, GetMyAssessmentSignalNoticeOperation: []string{}, @@ -121,6 +124,7 @@ var operationRolesSessionCookie = map[string][]string{ SetMySearchStatusOperation: []string{}, StartMyAssessmentAttemptSessionOperation: []string{}, SubmitMyAssessmentAnswerOperation: []string{}, + SubmitMyAssessmentLabOperation: []string{}, UnhideOrganizationOperation: []string{}, UpdateOrganizationOperation: []string{}, UpdateOrganizationInvitationOperation: []string{}, @@ -156,6 +160,8 @@ var operationRolesSessionCsrf = map[string][]string{ AcknowledgeMyAssessmentSignalNoticeOperation: []string{}, CancelMyInvitationOperation: []string{}, CreateMyAssessmentAttemptOperation: []string{}, + CreateMyAssessmentLabOperation: []string{}, + CreateMyAssessmentLabConsoleSessionOperation: []string{}, CreateMyAssessmentPracticeRunOperation: []string{}, CreateMySupportCaseOperation: []string{}, CreateOrganizationOperation: []string{}, @@ -184,6 +190,7 @@ var operationRolesSessionCsrf = map[string][]string{ SetMySearchStatusOperation: []string{}, StartMyAssessmentAttemptSessionOperation: []string{}, SubmitMyAssessmentAnswerOperation: []string{}, + SubmitMyAssessmentLabOperation: []string{}, UnhideOrganizationOperation: []string{}, UpdateOrganizationOperation: []string{}, UpdateOrganizationInvitationOperation: []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 79f87c1..d6e21ea 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,67 @@ type Handler interface { // // POST /api/v1/me/assessment-attempts CreateMyAssessmentAttempt(ctx context.Context, req AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (CreateMyAssessmentAttemptRes, error) + // CreateMyAssessmentLab implements CreateMyAssessmentLab 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 current item, whose content has the + // format `lab`. + // + // The server asks the lab provisioner for a lab of the variant fixed for this item instance and + // answers 201 with the lab `provisioning`; the client polls GetMyAssessmentLab until it is `ready`. + // The lab lives until `expires_at`, the earlier of the item's `time_limit_seconds` and the attempt + // deadline, and is then deleted with everything done in it. Creating a lab does not change the attempt + // version, the current item, or any answer. + // + // One lab per item at a time. While the item has a lab in `provisioning`, `ready`, or `checking`, the + // server answers 200 with that lab and starts no second one. After a `failed` lab the candidate may + // start a new one while the item is current; after `submitted` or `expired` the item cannot start + // another lab (409 state_conflict). + // + // Busy pool. When the lab pool of the provisioner has no free capacity, the server answers 503 + // service_unavailable with Retry-After, for example + // `{"type": "urn:lincodex:problem:service_unavailable", "title": "Service unavailable", "status": 503, "code": "service_unavailable", "detail": "No lab capacity is free. The attempt is unchanged; retry later."}`. + // Nothing was stored: no lab exists, the attempt version and the current item are unchanged, the lab + // lifetime has not started, and the attempt is not consumed; the client retries after Retry-After with + // a new Idempotency-Key. When labs are not enabled on this server, or the provisioner cannot be + // reached, the server answers 503 service_unavailable without Retry-After and stores nothing either. + // The attempt deadline keeps running in both cases. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), + // the attempt and the item (404 not_found for an unknown attempt or item, or one of another + // candidate), the state (409 state_conflict: the attempt is terminal or its work session ended, the + // item is not current, its format is not `lab`, or its lab was submitted or expired), the rate limit + // (429), then the availability of labs and the capacity (503). Following the Idempotency-Key + // convention, 201, 200, 404, and 409 state_conflict are stored under the key and replayed; 400, 429, + // and 503 are not. + // + // POST /api/v1/me/assessment-attempts/{attempt_id}/labs + CreateMyAssessmentLab(ctx context.Context, req *AssessmentLabCreate, params CreateMyAssessmentLabParams) (CreateMyAssessmentLabRes, error) + // CreateMyAssessmentLabConsoleSession implements CreateMyAssessmentLabConsoleSession operation. + // + // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, + // and an allowed Origin. The body names a node of the lab by its task name. + // + // The response describes one console session: the client opens a WebSocket to `websocket_path` on the + // same origin before `expires_at`. The upgrade is authorized by the session cookie and the Origin + // check, and the server relays the serial console of the node through the lab provisioner. The + // response never carries a node address, a port, a password, a key, or a token; the browser never + // connects to a node or to the provisioner. Console traffic is not stored as an answer and is not + // logged. + // + // The WebSocket relay is planned together with the candidate interface of labs; this contract fixes + // the session shape it uses. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden), the attempt and the lab (404 not_found for an unknown attempt, + // lab, or one of another candidate), the node (400 with the pointer `/node`), the state (409 + // state_conflict: the lab is not `ready`, the attempt is terminal, or its work session ended), the + // limit of open sessions per lab (429 rate_limited with Retry-After), then the provisioner (503 + // service_unavailable without Retry-After; nothing was opened). + // + // POST /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/console-sessions + CreateMyAssessmentLabConsoleSession(ctx context.Context, req *AssessmentLabConsoleSessionCreate, params CreateMyAssessmentLabConsoleSessionParams) (CreateMyAssessmentLabConsoleSessionRes, error) // CreateMyAssessmentPracticeRun implements CreateMyAssessmentPracticeRun operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -663,6 +724,19 @@ type Handler interface { // // GET /api/v1/me/assessment-availability GetMyAssessmentAvailability(ctx context.Context) (GetMyAssessmentAvailabilityRes, error) + // GetMyAssessmentLab implements GetMyAssessmentLab operation. + // + // Requires the session cookie of a candidate account. Returns the state of a lab started with + // CreateMyAssessmentLab: whether it is still provisioning, ready for the consoles, being checked after + // the submission, or ended. It never contains a node address, a credential, the seed, the checker + // state, or the result of the check. This GET is read-only; the server may record a due timer + // transition, such as `ready` to `expired`, before it answers. + // + // A lab of another candidate's attempt, a lab of another attempt, and an unknown identifier all answer + // 404 not_found. + // + // GET /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id} + GetMyAssessmentLab(ctx context.Context, params GetMyAssessmentLabParams) (GetMyAssessmentLabRes, error) // GetMyAssessmentPracticeRun implements GetMyAssessmentPracticeRun operation. // // Requires the session cookie of a candidate account. Returns the state of a debug run started with @@ -2031,6 +2105,10 @@ type Handler interface { // times itself and scores the answer with the key of the fixed item instance. Time never enters the // ability estimate or the grade decision. // + // Lab: an item with format `lab` takes no answer here. Its lab is started with CreateMyAssessmentLab + // and submitted with SubmitMyAssessmentLab; any answer to a lab item answers 400 validation_failed + // with the pointer `/answer/format`, like an answer in the wrong format, and stores nothing. + // // The response is the attempt with the next item to answer. It never says whether the answer was // correct. Items are answered in order and each answer is final. // @@ -2089,6 +2167,37 @@ type Handler interface { // // POST /api/v1/me/assessment-attempts/{attempt_id}/answers SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error) + // SubmitMyAssessmentLab implements SubmitMyAssessmentLab 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 carries the attempt version last read and the + // answer with format `lab`, which names the lab. + // + // The server closes the consoles, freezes the lab, and answers 202 with the lab `checking`; the + // checker of the task reads the state of the nodes asynchronously, the answer is recorded, and the lab + // becomes `submitted` and is deleted. The client polls GetMyAssessmentLab and then reads the attempt, + // which moves to the next item. Neither response says whether the answer was correct, and the + // candidate never sees the checker criteria or their results. + // + // When the checker cannot reach the nodes because of the lab infrastructure, the lab becomes `failed` + // with `lab_error`: nothing is recorded or consumed, the attempt version is unchanged, and the + // candidate may start a new lab of the item while it is current. A failure of the infrastructure is + // never scored as a wrong answer. + // + // Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the + // server answers 412 version_conflict and stores nothing. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), + // the attempt and the lab (404 not_found for an unknown attempt or lab, or one of another candidate), + // the version (412), the state (409 state_conflict: the lab is not `ready`, `answer.lab_id` is not the + // lab in the path, the item is not current, the attempt is terminal, or its work session ended), then + // the provisioner (503 service_unavailable without Retry-After; nothing was stored and the lab keeps + // running). Following the Idempotency-Key convention, 202, 404, and 409 state_conflict are stored + // under the key and replayed; 400, 412, 429, and 5xx are not. + // + // POST /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/submission + SubmitMyAssessmentLab(ctx context.Context, req *AssessmentLabSubmission, params SubmitMyAssessmentLabParams) (SubmitMyAssessmentLabRes, error) // UnhideOrganization implements UnhideOrganization operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, 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 bb33017..f8b832a 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,73 @@ func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req A return r, ht.ErrNotImplemented } +// CreateMyAssessmentLab implements CreateMyAssessmentLab 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 current item, whose content has the +// format `lab`. +// +// The server asks the lab provisioner for a lab of the variant fixed for this item instance and +// answers 201 with the lab `provisioning`; the client polls GetMyAssessmentLab until it is `ready`. +// The lab lives until `expires_at`, the earlier of the item's `time_limit_seconds` and the attempt +// deadline, and is then deleted with everything done in it. Creating a lab does not change the attempt +// version, the current item, or any answer. +// +// One lab per item at a time. While the item has a lab in `provisioning`, `ready`, or `checking`, the +// server answers 200 with that lab and starts no second one. After a `failed` lab the candidate may +// start a new one while the item is current; after `submitted` or `expired` the item cannot start +// another lab (409 state_conflict). +// +// Busy pool. When the lab pool of the provisioner has no free capacity, the server answers 503 +// service_unavailable with Retry-After, for example +// `{"type": "urn:lincodex:problem:service_unavailable", "title": "Service unavailable", "status": 503, "code": "service_unavailable", "detail": "No lab capacity is free. The attempt is unchanged; retry later."}`. +// Nothing was stored: no lab exists, the attempt version and the current item are unchanged, the lab +// lifetime has not started, and the attempt is not consumed; the client retries after Retry-After with +// a new Idempotency-Key. When labs are not enabled on this server, or the provisioner cannot be +// reached, the server answers 503 service_unavailable without Retry-After and stores nothing either. +// The attempt deadline keeps running in both cases. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), +// the attempt and the item (404 not_found for an unknown attempt or item, or one of another +// candidate), the state (409 state_conflict: the attempt is terminal or its work session ended, the +// item is not current, its format is not `lab`, or its lab was submitted or expired), the rate limit +// (429), then the availability of labs and the capacity (503). Following the Idempotency-Key +// convention, 201, 200, 404, and 409 state_conflict are stored under the key and replayed; 400, 429, +// and 503 are not. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/labs +func (UnimplementedHandler) CreateMyAssessmentLab(ctx context.Context, req *AssessmentLabCreate, params CreateMyAssessmentLabParams) (r CreateMyAssessmentLabRes, _ error) { + return r, ht.ErrNotImplemented +} + +// CreateMyAssessmentLabConsoleSession implements CreateMyAssessmentLabConsoleSession operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The body names a node of the lab by its task name. +// +// The response describes one console session: the client opens a WebSocket to `websocket_path` on the +// same origin before `expires_at`. The upgrade is authorized by the session cookie and the Origin +// check, and the server relays the serial console of the node through the lab provisioner. The +// response never carries a node address, a port, a password, a key, or a token; the browser never +// connects to a node or to the provisioner. Console traffic is not stored as an answer and is not +// logged. +// +// The WebSocket relay is planned together with the candidate interface of labs; this contract fixes +// the session shape it uses. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the attempt and the lab (404 not_found for an unknown attempt, +// lab, or one of another candidate), the node (400 with the pointer `/node`), the state (409 +// state_conflict: the lab is not `ready`, the attempt is terminal, or its work session ended), the +// limit of open sessions per lab (429 rate_limited with Retry-After), then the provisioner (503 +// service_unavailable without Retry-After; nothing was opened). +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/console-sessions +func (UnimplementedHandler) CreateMyAssessmentLabConsoleSession(ctx context.Context, req *AssessmentLabConsoleSessionCreate, params CreateMyAssessmentLabConsoleSessionParams) (r CreateMyAssessmentLabConsoleSessionRes, _ error) { + 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, @@ -725,6 +792,22 @@ func (UnimplementedHandler) GetMyAssessmentAvailability(ctx context.Context) (r return r, ht.ErrNotImplemented } +// GetMyAssessmentLab implements GetMyAssessmentLab operation. +// +// Requires the session cookie of a candidate account. Returns the state of a lab started with +// CreateMyAssessmentLab: whether it is still provisioning, ready for the consoles, being checked after +// the submission, or ended. It never contains a node address, a credential, the seed, the checker +// state, or the result of the check. This GET is read-only; the server may record a due timer +// transition, such as `ready` to `expired`, before it answers. +// +// A lab of another candidate's attempt, a lab of another attempt, and an unknown identifier all answer +// 404 not_found. +// +// GET /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id} +func (UnimplementedHandler) GetMyAssessmentLab(ctx context.Context, params GetMyAssessmentLabParams) (r GetMyAssessmentLabRes, _ error) { + 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 @@ -2252,6 +2335,10 @@ func (UnimplementedHandler) StartMyAssessmentAttemptSession(ctx context.Context, // times itself and scores the answer with the key of the fixed item instance. Time never enters the // ability estimate or the grade decision. // +// Lab: an item with format `lab` takes no answer here. Its lab is started with CreateMyAssessmentLab +// and submitted with SubmitMyAssessmentLab; any answer to a lab item answers 400 validation_failed +// with the pointer `/answer/format`, like an answer in the wrong format, and stores nothing. +// // The response is the attempt with the next item to answer. It never says whether the answer was // correct. Items are answered in order and each answer is final. // @@ -2313,6 +2400,40 @@ func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *A return r, ht.ErrNotImplemented } +// SubmitMyAssessmentLab implements SubmitMyAssessmentLab 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 carries the attempt version last read and the +// answer with format `lab`, which names the lab. +// +// The server closes the consoles, freezes the lab, and answers 202 with the lab `checking`; the +// checker of the task reads the state of the nodes asynchronously, the answer is recorded, and the lab +// becomes `submitted` and is deleted. The client polls GetMyAssessmentLab and then reads the attempt, +// which moves to the next item. Neither response says whether the answer was correct, and the +// candidate never sees the checker criteria or their results. +// +// When the checker cannot reach the nodes because of the lab infrastructure, the lab becomes `failed` +// with `lab_error`: nothing is recorded or consumed, the attempt version is unchanged, and the +// candidate may start a new lab of the item while it is current. A failure of the infrastructure is +// never scored as a wrong answer. +// +// Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the +// server answers 412 version_conflict and stores nothing. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), +// the attempt and the lab (404 not_found for an unknown attempt or lab, or one of another candidate), +// the version (412), the state (409 state_conflict: the lab is not `ready`, `answer.lab_id` is not the +// lab in the path, the item is not current, the attempt is terminal, or its work session ended), then +// the provisioner (503 service_unavailable without Retry-After; nothing was stored and the lab keeps +// running). Following the Idempotency-Key convention, 202, 404, and 409 state_conflict are stored +// under the key and replayed; 400, 412, 429, and 5xx are not. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/submission +func (UnimplementedHandler) SubmitMyAssessmentLab(ctx context.Context, req *AssessmentLabSubmission, params SubmitMyAssessmentLabParams) (r SubmitMyAssessmentLabRes, _ error) { + return r, ht.ErrNotImplemented +} + // UnhideOrganization implements UnhideOrganization operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, 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 200a0e8..9611d6c 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -3016,6 +3016,347 @@ func (s *AssessmentItem) Validate() error { return nil } +func (s *AssessmentLab) 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 s.Nodes == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 8, + MaxLengthSet: true, + }).ValidateLength(len(s.Nodes)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Nodes { + 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: "nodes", + Error: err, + }) + } + if err := func() error { + if value, ok := s.FailureReason.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "failure_reason", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentLabConsoleSession) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Node.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "node", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.WebsocketPath)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "websocket_path", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentLabConsoleSessionCreate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Node.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "node", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentLabConsoleSessionHeaders) 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 AssessmentLabFailureReason) Validate() error { + switch s { + case "lab_error": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentLabHeaders) 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 *AssessmentLabNode) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Name.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "name", + Error: err, + }) + } + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentLabNodeKind) Validate() error { + switch s { + case "mikrotik": + return nil + case "ubuntu": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentLabNodeName) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 15, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z][a-z0-9-]{0,14}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s AssessmentLabState) Validate() error { + switch s { + case "provisioning": + return nil + case "ready": + return nil + case "checking": + return nil + case "submitted": + return nil + case "expired": + return nil + case "failed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentLabSubmission) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if err := s.Answer.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "answer", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s AssessmentLimitation) Validate() error { switch s { case "uncalibrated_thresholds": @@ -8873,6 +9214,110 @@ func (s *CreateMyAssessmentAttemptUnprocessableEntity) Validate() error { return nil } +func (s *CreateMyAssessmentLabBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabConsoleSessionBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabConsoleSessionConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabConsoleSessionForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabConsoleSessionNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabConsoleSessionUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabCreated) Validate() error { + alias := (*AssessmentLabHeaders)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabOK) Validate() error { + alias := (*AssessmentLabHeaders)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMyAssessmentLabUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *CreateMyAssessmentPracticeRunBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -10120,6 +10565,30 @@ func (s *GetMyAssessmentAvailabilityUnauthorized) Validate() error { return nil } +func (s *GetMyAssessmentLabForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentLabNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentLabUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetMyAssessmentPracticeRunForbidden) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -11906,11 +12375,137 @@ func (s ItemContent) Validate() error { return err } return nil + case LabItemContentItemContent: + if err := s.LabItemContent.Validate(); err != nil { + return err + } + return nil default: return errors.Errorf("invalid type %q", s.Type) } } +func (s *LabAnswer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s LabAnswerFormat) Validate() error { + switch s { + case "lab": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *LabItemContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Format.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "format", + Error: err, + }) + } + if err := func() error { + if s.Nodes == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 8, + MaxLengthSet: true, + }).ValidateLength(len(s.Nodes)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Nodes { + 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: "nodes", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 300, + MaxSet: true, + Max: 14400, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TimeLimitSeconds)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "time_limit_seconds", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s LabItemContentFormat) Validate() error { + switch s { + case "lab": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *ListMyAssessmentResultsBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -24811,6 +25406,62 @@ func (s *SubmitMyAssessmentAnswerUnprocessableEntity) Validate() error { return nil } +func (s *SubmitMyAssessmentLabBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentLabConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentLabForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentLabNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentLabPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentLabUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitMyAssessmentLabUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *SupportCase) Validate() error { if s == nil { return validate.ErrNilPointer diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_cfg_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_cfg_gen.go new file mode 100644 index 0000000..e759559 --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_cfg_gen.go @@ -0,0 +1,156 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "net/http" + + ht "github.com/ogen-go/ogen/http" + "github.com/ogen-go/ogen/ogenregex" + "github.com/ogen-go/ogen/otelogen" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/trace" +) + +var regexMap = map[string]ogenregex.Regexp{ + "^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"), + "^/v1/labs/[0-9a-f-]{36}/console$": ogenregex.MustCompile("^/v1/labs/[0-9a-f-]{36}/console$"), + "^[0-9a-f]{64}$": ogenregex.MustCompile("^[0-9a-f]{64}$"), + "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), + "^[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^[A-Za-z0-9_-]{43}$"), + "^[a-z0-9][a-z0-9-]{0,47}$": ogenregex.MustCompile("^[a-z0-9][a-z0-9-]{0,47}$"), + "^[a-z0-9][a-z0-9_-]{0,31}$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_-]{0,31}$"), + "^[a-z][a-z0-9-]{0,14}$": ogenregex.MustCompile("^[a-z][a-z0-9-]{0,14}$"), + "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), +} +var ( + // Allocate option closure once. + clientSpanKind = trace.WithSpanKind(trace.SpanKindClient) +) + +type ( + optionFunc[C any] func(*C) + otelOptionFunc func(*otelConfig) +) + +type otelConfig struct { + TracerProvider trace.TracerProvider + Tracer trace.Tracer + MeterProvider metric.MeterProvider + Meter metric.Meter + Attributes []attribute.KeyValue +} + +func (cfg *otelConfig) initOTEL() { + if cfg.TracerProvider == nil { + cfg.TracerProvider = otel.GetTracerProvider() + } + if cfg.MeterProvider == nil { + cfg.MeterProvider = otel.GetMeterProvider() + } + cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name, + trace.WithInstrumentationVersion(otelogen.SemVersion()), + ) + cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name, + metric.WithInstrumentationVersion(otelogen.SemVersion()), + ) +} + +type clientConfig struct { + otelConfig + Client ht.Client +} + +// ClientOption is client config option. +type ClientOption interface { + applyClient(*clientConfig) +} + +var _ ClientOption = (optionFunc[clientConfig])(nil) + +func (o optionFunc[C]) applyClient(c *C) { + o(c) +} + +var _ ClientOption = (otelOptionFunc)(nil) + +func (o otelOptionFunc) applyClient(c *clientConfig) { + o(&c.otelConfig) +} + +func newClientConfig(opts ...ClientOption) clientConfig { + cfg := clientConfig{ + Client: http.DefaultClient, + } + for _, opt := range opts { + opt.applyClient(&cfg) + } + cfg.initOTEL() + return cfg +} + +type baseClient struct { + cfg clientConfig + requests metric.Int64Counter + errors metric.Int64Counter + duration metric.Float64Histogram +} + +func (cfg clientConfig) baseClient() (c baseClient, err error) { + c = baseClient{cfg: cfg} + if c.requests, err = otelogen.ClientRequestCountCounter(c.cfg.Meter); err != nil { + return c, err + } + if c.errors, err = otelogen.ClientErrorsCountCounter(c.cfg.Meter); err != nil { + return c, err + } + if c.duration, err = otelogen.ClientDurationHistogram(c.cfg.Meter); err != nil { + return c, err + } + return c, nil +} + +// Option is config option. +type Option interface { + ClientOption +} + +// WithTracerProvider specifies a tracer provider to use for creating a tracer. +// +// If none is specified, the global provider is used. +func WithTracerProvider(provider trace.TracerProvider) Option { + return otelOptionFunc(func(cfg *otelConfig) { + if provider != nil { + cfg.TracerProvider = provider + } + }) +} + +// WithMeterProvider specifies a meter provider to use for creating a meter. +// +// If none is specified, the otel.GetMeterProvider() is used. +func WithMeterProvider(provider metric.MeterProvider) Option { + return otelOptionFunc(func(cfg *otelConfig) { + if provider != nil { + cfg.MeterProvider = provider + } + }) +} + +// WithAttributes specifies default otel attributes. +func WithAttributes(attributes ...attribute.KeyValue) Option { + return otelOptionFunc(func(cfg *otelConfig) { + cfg.Attributes = attributes + }) +} + +// WithClient specifies http client to use. +func WithClient(client ht.Client) ClientOption { + return optionFunc[clientConfig](func(cfg *clientConfig) { + if client != nil { + cfg.Client = client + } + }) +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_client_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_client_gen.go new file mode 100644 index 0000000..cbb7dcf --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_client_gen.go @@ -0,0 +1,1034 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" + "io" + "net/url" + "strings" + "time" + + "github.com/go-faster/errors" + "github.com/ogen-go/ogen/conv" + ht "github.com/ogen-go/ogen/http" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/otelogen" + "github.com/ogen-go/ogen/uri" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/metric" + semconv "go.opentelemetry.io/otel/semconv/v1.39.0" + "go.opentelemetry.io/otel/trace" +) + +func trimTrailingSlashes(u *url.URL) { + u.Path = strings.TrimRight(u.Path, "/") + u.RawPath = strings.TrimRight(u.RawPath, "/") +} + +// Invoker invokes operations described by OpenAPI v3 specification. +type Invoker interface { + // CheckLab invokes CheckLab operation. + // + // The checker of the template connects from the host side of the lab management bridge to the nodes + // (SSH or the RouterOS API) and evaluates the criteria of the variant that the seed selected. It only + // reads the node state and never changes it, so a repeated call is harmless; the result is not stored + // by `labd`. The call is synchronous and bounded by the check timeout of the provisioner. + // + // The result is checker state for the backend only: the backend scores the lab answer with it and + // never forwards it to the candidate. + // + // A lab that is not `ready` answers 409 `state_conflict`. When the checker cannot reach a node or the + // template has no working checker, the provisioner answers 503 `lab_unavailable`: nothing was + // evaluated, and the outcome is never a failed check. + // + // POST /v1/labs/{lab_id}/check + CheckLab(ctx context.Context, params CheckLabParams) (*LabCheckResult, error) + // CreateLab invokes CreateLab operation. + // + // Idempotent by `lab_id`: + // + // - a new ID that fits the capacity reserves it, stores the lab, and answers 202 with + // `state: provisioning`; the nodes are cloned and booted in the background; + // - the same ID with the same payload answers 200 with the current state of that lab, including + // `deleted` or `failed`, and never creates a second one; + // - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + // - a new ID that does not fit the memory budget or the lab limit, or arrives while the provisioner + // is draining, answers 503 `lab_pool_busy` with Retry-After; nothing is stored, so the caller + // retries with the same ID. + // + // Payloads are compared by a SHA-256 fingerprint of the decoded request. An unknown template or + // template version, or a lifetime above the configured maximum, answers 400 `validation_failed` with a + // pointer such as `/template_id` or `/ttl_seconds`. + // + // The lab is deleted at `expires_at` = creation time + `ttl_seconds`, also when it is still + // provisioning. A lab that fails to provision or does not answer within the provisioning timeout + // becomes `failed` and its resources are deleted; its capacity returns when they are gone. + // + // A record of a deleted or failed lab is kept for a bounded retention time; after it, the ID is + // unknown again and a CreateLab with it starts a new lab. + // + // PUT /v1/labs/{lab_id} + CreateLab(ctx context.Context, request *LabCreateRequest, params CreateLabParams) (CreateLabRes, error) + // CreateLabConsoleToken invokes CreateLabConsoleToken operation. + // + // The token lets the console gateway of the backend attach to the serial console of one node. It is + // random, single-use, bound to the lab and the node, and valid for at most 120 seconds; `labd` keeps + // only its SHA-256 digest in memory, so a restart invalidates every unused token. The token is never a + // node password or an SSH key, and the response carries no node address. + // + // Attaching: the gateway opens a WebSocket to `attach_path` on the same `labd` origin with the service + // bearer token and sends the console token in the `X-Lab-Console-Token` header. The WebSocket attach + // is described here as the planned interface; until it is implemented, `labd` answers the attach path + // with 501 and issuing a token changes nothing else. + // + // A lab that is not `ready` answers 409 `state_conflict`; an unknown node answers 400 + // `validation_failed` with the pointer `/node`. + // + // POST /v1/labs/{lab_id}/console-tokens + CreateLabConsoleToken(ctx context.Context, request *ConsoleTokenRequest, params CreateLabConsoleTokenParams) (*ConsoleTokenHeaders, error) + // DeleteLab invokes DeleteLab operation. + // + // Marks the lab for deletion and answers 202 with `state: deleting`; the provisioner removes its + // instances and bridges in the background and retries until LXD confirms that they are gone, also + // across its own restarts. Deleting a lab that is already `deleting` or `deleted` answers 200 with its + // state and changes nothing. An unknown ID answers 404 `not_found`. + // + // DELETE /v1/labs/{lab_id} + DeleteLab(ctx context.Context, params DeleteLabParams) (DeleteLabRes, error) + // GetLab invokes GetLab operation. + // + // Answers 404 `not_found` for an ID the provisioner does not hold, including a lab whose `deleted` + // record outlived its retention time. The response never contains an address, a key, or an LXD object + // name. + // + // GET /v1/labs/{lab_id} + GetLab(ctx context.Context, params GetLabParams) (*LabStatus, error) + // GetLabdHealthz invokes GetLabdHealthz operation. + // + // Check whether the lab provisioner process is responding. + // + // GET /healthz + GetLabdHealthz(ctx context.Context) (*LabdHealthResponse, error) + // GetLabdReadyz invokes GetLabdReadyz operation. + // + // Ready means that the lab records were loaded, the startup reconciliation with LXD finished, the LXD + // API answered the latest probe, and the process is not draining. A provisioner without free capacity + // is still ready; capacity is reported by CreateLab. + // + // GET /readyz + GetLabdReadyz(ctx context.Context) (GetLabdReadyzRes, error) +} + +// Client implements OAS client. +type Client struct { + serverURL *url.URL + sec SecuritySource + baseClient +} + +// NewClient initializes new Client defined by OAS. +func NewClient(serverURL string, sec SecuritySource, opts ...ClientOption) (*Client, error) { + u, err := url.Parse(serverURL) + if err != nil { + return nil, err + } + trimTrailingSlashes(u) + + c, err := newClientConfig(opts...).baseClient() + if err != nil { + return nil, err + } + return &Client{ + serverURL: u, + sec: sec, + baseClient: c, + }, nil +} + +type serverURLKey struct{} + +// WithServerURL sets context key to override server URL. +func WithServerURL(ctx context.Context, u *url.URL) context.Context { + return context.WithValue(ctx, serverURLKey{}, u) +} + +func (c *Client) requestURL(ctx context.Context) *url.URL { + u, ok := ctx.Value(serverURLKey{}).(*url.URL) + if !ok { + return c.serverURL + } + return u +} + +// CheckLab invokes CheckLab operation. +// +// The checker of the template connects from the host side of the lab management bridge to the nodes +// (SSH or the RouterOS API) and evaluates the criteria of the variant that the seed selected. It only +// reads the node state and never changes it, so a repeated call is harmless; the result is not stored +// by `labd`. The call is synchronous and bounded by the check timeout of the provisioner. +// +// The result is checker state for the backend only: the backend scores the lab answer with it and +// never forwards it to the candidate. +// +// A lab that is not `ready` answers 409 `state_conflict`. When the checker cannot reach a node or the +// template has no working checker, the provisioner answers 503 `lab_unavailable`: nothing was +// evaluated, and the outcome is never a failed check. +// +// POST /v1/labs/{lab_id}/check +func (c *Client) CheckLab(ctx context.Context, params CheckLabParams) (*LabCheckResult, error) { + res, err := c.sendCheckLab(ctx, params) + return res, err +} + +func (c *Client) sendCheckLab(ctx context.Context, params CheckLabParams) (res *LabCheckResult, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CheckLab"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.URLTemplateKey.String("/v1/labs/{lab_id}/check"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, CheckLabOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [3]string + pathParts[0] = "/v1/labs/" + { + // Encode "lab_id" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "lab_id", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.UUIDToString(params.LabID)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[1] = encoded + } + pathParts[2] = "/check" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "POST", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + + { + type bitset = [1]uint8 + var satisfied bitset + { + stage = "Security:BearerAuth" + switch err := c.securityBearerAuth(ctx, CheckLabOperation, r); { + case err == nil: // if NO error + satisfied[0] |= 1 << 0 + case errors.Is(err, ogenerrors.ErrSkipClientSecurity): + // Skip this security. + default: + return res, errors.Wrap(err, "security \"BearerAuth\"") + } + } + + 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 { + return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied + } + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeCheckLabResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// CreateLab invokes CreateLab operation. +// +// Idempotent by `lab_id`: +// +// - a new ID that fits the capacity reserves it, stores the lab, and answers 202 with +// `state: provisioning`; the nodes are cloned and booted in the background; +// - the same ID with the same payload answers 200 with the current state of that lab, including +// `deleted` or `failed`, and never creates a second one; +// - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; +// - a new ID that does not fit the memory budget or the lab limit, or arrives while the provisioner +// is draining, answers 503 `lab_pool_busy` with Retry-After; nothing is stored, so the caller +// retries with the same ID. +// +// Payloads are compared by a SHA-256 fingerprint of the decoded request. An unknown template or +// template version, or a lifetime above the configured maximum, answers 400 `validation_failed` with a +// pointer such as `/template_id` or `/ttl_seconds`. +// +// The lab is deleted at `expires_at` = creation time + `ttl_seconds`, also when it is still +// provisioning. A lab that fails to provision or does not answer within the provisioning timeout +// becomes `failed` and its resources are deleted; its capacity returns when they are gone. +// +// A record of a deleted or failed lab is kept for a bounded retention time; after it, the ID is +// unknown again and a CreateLab with it starts a new lab. +// +// PUT /v1/labs/{lab_id} +func (c *Client) CreateLab(ctx context.Context, request *LabCreateRequest, params CreateLabParams) (CreateLabRes, error) { + res, err := c.sendCreateLab(ctx, request, params) + return res, err +} + +func (c *Client) sendCreateLab(ctx context.Context, request *LabCreateRequest, params CreateLabParams) (res CreateLabRes, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CreateLab"), + semconv.HTTPRequestMethodKey.String("PUT"), + semconv.URLTemplateKey.String("/v1/labs/{lab_id}"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, CreateLabOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [2]string + pathParts[0] = "/v1/labs/" + { + // Encode "lab_id" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "lab_id", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.UUIDToString(params.LabID)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[1] = encoded + } + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "PUT", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + if err := encodeCreateLabRequest(request, r); err != nil { + return res, errors.Wrap(err, "encode request") + } + + { + type bitset = [1]uint8 + var satisfied bitset + { + stage = "Security:BearerAuth" + switch err := c.securityBearerAuth(ctx, CreateLabOperation, r); { + case err == nil: // if NO error + satisfied[0] |= 1 << 0 + case errors.Is(err, ogenerrors.ErrSkipClientSecurity): + // Skip this security. + default: + return res, errors.Wrap(err, "security \"BearerAuth\"") + } + } + + 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 { + return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied + } + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeCreateLabResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// CreateLabConsoleToken invokes CreateLabConsoleToken operation. +// +// The token lets the console gateway of the backend attach to the serial console of one node. It is +// random, single-use, bound to the lab and the node, and valid for at most 120 seconds; `labd` keeps +// only its SHA-256 digest in memory, so a restart invalidates every unused token. The token is never a +// node password or an SSH key, and the response carries no node address. +// +// Attaching: the gateway opens a WebSocket to `attach_path` on the same `labd` origin with the service +// bearer token and sends the console token in the `X-Lab-Console-Token` header. The WebSocket attach +// is described here as the planned interface; until it is implemented, `labd` answers the attach path +// with 501 and issuing a token changes nothing else. +// +// A lab that is not `ready` answers 409 `state_conflict`; an unknown node answers 400 +// `validation_failed` with the pointer `/node`. +// +// POST /v1/labs/{lab_id}/console-tokens +func (c *Client) CreateLabConsoleToken(ctx context.Context, request *ConsoleTokenRequest, params CreateLabConsoleTokenParams) (*ConsoleTokenHeaders, error) { + res, err := c.sendCreateLabConsoleToken(ctx, request, params) + return res, err +} + +func (c *Client) sendCreateLabConsoleToken(ctx context.Context, request *ConsoleTokenRequest, params CreateLabConsoleTokenParams) (res *ConsoleTokenHeaders, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CreateLabConsoleToken"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.URLTemplateKey.String("/v1/labs/{lab_id}/console-tokens"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, CreateLabConsoleTokenOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [3]string + pathParts[0] = "/v1/labs/" + { + // Encode "lab_id" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "lab_id", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.UUIDToString(params.LabID)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[1] = encoded + } + pathParts[2] = "/console-tokens" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "POST", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + if err := encodeCreateLabConsoleTokenRequest(request, r); err != nil { + return res, errors.Wrap(err, "encode request") + } + + { + type bitset = [1]uint8 + var satisfied bitset + { + stage = "Security:BearerAuth" + switch err := c.securityBearerAuth(ctx, CreateLabConsoleTokenOperation, r); { + case err == nil: // if NO error + satisfied[0] |= 1 << 0 + case errors.Is(err, ogenerrors.ErrSkipClientSecurity): + // Skip this security. + default: + return res, errors.Wrap(err, "security \"BearerAuth\"") + } + } + + 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 { + return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied + } + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeCreateLabConsoleTokenResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// DeleteLab invokes DeleteLab operation. +// +// Marks the lab for deletion and answers 202 with `state: deleting`; the provisioner removes its +// instances and bridges in the background and retries until LXD confirms that they are gone, also +// across its own restarts. Deleting a lab that is already `deleting` or `deleted` answers 200 with its +// state and changes nothing. An unknown ID answers 404 `not_found`. +// +// DELETE /v1/labs/{lab_id} +func (c *Client) DeleteLab(ctx context.Context, params DeleteLabParams) (DeleteLabRes, error) { + res, err := c.sendDeleteLab(ctx, params) + return res, err +} + +func (c *Client) sendDeleteLab(ctx context.Context, params DeleteLabParams) (res DeleteLabRes, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("DeleteLab"), + semconv.HTTPRequestMethodKey.String("DELETE"), + semconv.URLTemplateKey.String("/v1/labs/{lab_id}"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, DeleteLabOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [2]string + pathParts[0] = "/v1/labs/" + { + // Encode "lab_id" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "lab_id", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.UUIDToString(params.LabID)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[1] = encoded + } + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "DELETE", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + + { + type bitset = [1]uint8 + var satisfied bitset + { + stage = "Security:BearerAuth" + switch err := c.securityBearerAuth(ctx, DeleteLabOperation, r); { + case err == nil: // if NO error + satisfied[0] |= 1 << 0 + case errors.Is(err, ogenerrors.ErrSkipClientSecurity): + // Skip this security. + default: + return res, errors.Wrap(err, "security \"BearerAuth\"") + } + } + + 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 { + return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied + } + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeDeleteLabResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// GetLab invokes GetLab operation. +// +// Answers 404 `not_found` for an ID the provisioner does not hold, including a lab whose `deleted` +// record outlived its retention time. The response never contains an address, a key, or an LXD object +// name. +// +// GET /v1/labs/{lab_id} +func (c *Client) GetLab(ctx context.Context, params GetLabParams) (*LabStatus, error) { + res, err := c.sendGetLab(ctx, params) + return res, err +} + +func (c *Client) sendGetLab(ctx context.Context, params GetLabParams) (res *LabStatus, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetLab"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.URLTemplateKey.String("/v1/labs/{lab_id}"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, GetLabOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [2]string + pathParts[0] = "/v1/labs/" + { + // Encode "lab_id" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "lab_id", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.UUIDToString(params.LabID)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[1] = encoded + } + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "GET", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + + { + type bitset = [1]uint8 + var satisfied bitset + { + stage = "Security:BearerAuth" + switch err := c.securityBearerAuth(ctx, GetLabOperation, r); { + case err == nil: // if NO error + satisfied[0] |= 1 << 0 + case errors.Is(err, ogenerrors.ErrSkipClientSecurity): + // Skip this security. + default: + return res, errors.Wrap(err, "security \"BearerAuth\"") + } + } + + 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 { + return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied + } + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeGetLabResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// GetLabdHealthz invokes GetLabdHealthz operation. +// +// Check whether the lab provisioner process is responding. +// +// GET /healthz +func (c *Client) GetLabdHealthz(ctx context.Context) (*LabdHealthResponse, error) { + res, err := c.sendGetLabdHealthz(ctx) + return res, err +} + +func (c *Client) sendGetLabdHealthz(ctx context.Context) (res *LabdHealthResponse, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetLabdHealthz"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.URLTemplateKey.String("/healthz"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, GetLabdHealthzOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [1]string + pathParts[0] = "/healthz" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "GET", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeGetLabdHealthzResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// GetLabdReadyz invokes GetLabdReadyz operation. +// +// Ready means that the lab records were loaded, the startup reconciliation with LXD finished, the LXD +// API answered the latest probe, and the process is not draining. A provisioner without free capacity +// is still ready; capacity is reported by CreateLab. +// +// GET /readyz +func (c *Client) GetLabdReadyz(ctx context.Context) (GetLabdReadyzRes, error) { + res, err := c.sendGetLabdReadyz(ctx) + return res, err +} + +func (c *Client) sendGetLabdReadyz(ctx context.Context) (res GetLabdReadyzRes, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetLabdReadyz"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.URLTemplateKey.String("/readyz"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, GetLabdReadyzOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [1]string + pathParts[0] = "/readyz" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "GET", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeGetLabdReadyzResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_interfaces_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_interfaces_gen.go new file mode 100644 index 0000000..5255aea --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_interfaces_gen.go @@ -0,0 +1,14 @@ +// Code generated by ogen, DO NOT EDIT. +package api + +type CreateLabRes interface { + createLabRes() +} + +type DeleteLabRes interface { + deleteLabRes() +} + +type GetLabdReadyzRes interface { + getLabdReadyzRes() +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_json_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_json_gen.go new file mode 100644 index 0000000..4e0efbb --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_json_gen.go @@ -0,0 +1,2368 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "math/bits" + "strconv" + "time" + + "github.com/go-faster/errors" + "github.com/go-faster/jx" + "github.com/ogen-go/ogen/json" + "github.com/ogen-go/ogen/validate" +) + +// Encode implements json.Marshaler. +func (s *ConsoleToken) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConsoleToken) encodeFields(e *jx.Encoder) { + { + e.FieldStart("token") + e.Str(s.Token) + } + { + e.FieldStart("node") + s.Node.Encode(e) + } + { + e.FieldStart("expires_at") + json.EncodeDateTime(e, s.ExpiresAt) + } + { + e.FieldStart("attach_path") + e.Str(s.AttachPath) + } +} + +var jsonFieldsNameOfConsoleToken = [4]string{ + 0: "token", + 1: "node", + 2: "expires_at", + 3: "attach_path", +} + +// Decode decodes ConsoleToken from json. +func (s *ConsoleToken) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsoleToken to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "token": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Token = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"token\"") + } + case "node": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Node.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"node\"") + } + case "expires_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := json.DecodeDateTime(d) + s.ExpiresAt = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expires_at\"") + } + case "attach_path": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Str() + s.AttachPath = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"attach_path\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConsoleToken") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfConsoleToken) { + name = jsonFieldsNameOfConsoleToken[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 *ConsoleToken) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsoleToken) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ConsoleTokenRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConsoleTokenRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("node") + s.Node.Encode(e) + } +} + +var jsonFieldsNameOfConsoleTokenRequest = [1]string{ + 0: "node", +} + +// Decode decodes ConsoleTokenRequest from json. +func (s *ConsoleTokenRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsoleTokenRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "node": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Node.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"node\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConsoleTokenRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfConsoleTokenRequest) { + name = jsonFieldsNameOfConsoleTokenRequest[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 *ConsoleTokenRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsoleTokenRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateLabAccepted as json. +func (s *CreateLabAccepted) Encode(e *jx.Encoder) { + unwrapped := (*LabStatus)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateLabAccepted from json. +func (s *CreateLabAccepted) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateLabAccepted to nil") + } + var unwrapped LabStatus + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateLabAccepted(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateLabAccepted) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateLabAccepted) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateLabOK as json. +func (s *CreateLabOK) Encode(e *jx.Encoder) { + unwrapped := (*LabStatus)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateLabOK from json. +func (s *CreateLabOK) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateLabOK to nil") + } + var unwrapped LabStatus + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateLabOK(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateLabOK) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateLabOK) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CriterionId as json. +func (s CriterionId) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes CriterionId from json. +func (s *CriterionId) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CriterionId to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CriterionId(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CriterionId) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CriterionId) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CriterionResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CriterionResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("passed") + e.Bool(s.Passed) + } +} + +var jsonFieldsNameOfCriterionResult = [2]string{ + 0: "id", + 1: "passed", +} + +// Decode decodes CriterionResult from json. +func (s *CriterionResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CriterionResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "passed": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Bool() + s.Passed = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"passed\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CriterionResult") + } + // 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(jsonFieldsNameOfCriterionResult) { + name = jsonFieldsNameOfCriterionResult[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 *CriterionResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CriterionResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes DeleteLabAccepted as json. +func (s *DeleteLabAccepted) Encode(e *jx.Encoder) { + unwrapped := (*LabStatus)(s) + + unwrapped.Encode(e) +} + +// Decode decodes DeleteLabAccepted from json. +func (s *DeleteLabAccepted) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DeleteLabAccepted to nil") + } + var unwrapped LabStatus + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = DeleteLabAccepted(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *DeleteLabAccepted) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DeleteLabAccepted) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes DeleteLabOK as json. +func (s *DeleteLabOK) Encode(e *jx.Encoder) { + unwrapped := (*LabStatus)(s) + + unwrapped.Encode(e) +} + +// Decode decodes DeleteLabOK from json. +func (s *DeleteLabOK) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DeleteLabOK to nil") + } + var unwrapped LabStatus + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = DeleteLabOK(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *DeleteLabOK) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DeleteLabOK) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetLabdReadyzOK as json. +func (s *GetLabdReadyzOK) Encode(e *jx.Encoder) { + unwrapped := (*LabdReadinessResponse)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetLabdReadyzOK from json. +func (s *GetLabdReadyzOK) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetLabdReadyzOK to nil") + } + var unwrapped LabdReadinessResponse + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetLabdReadyzOK(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetLabdReadyzOK) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetLabdReadyzOK) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetLabdReadyzServiceUnavailable as json. +func (s *GetLabdReadyzServiceUnavailable) Encode(e *jx.Encoder) { + unwrapped := (*LabdReadinessResponse)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetLabdReadyzServiceUnavailable from json. +func (s *GetLabdReadyzServiceUnavailable) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetLabdReadyzServiceUnavailable to nil") + } + var unwrapped LabdReadinessResponse + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetLabdReadyzServiceUnavailable(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetLabdReadyzServiceUnavailable) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetLabdReadyzServiceUnavailable) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *LabCheckResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *LabCheckResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("lab_id") + json.EncodeUUID(e, s.LabID) + } + { + e.FieldStart("checked_at") + json.EncodeDateTime(e, s.CheckedAt) + } + { + e.FieldStart("score") + e.Int32(s.Score) + } + { + e.FieldStart("max_score") + e.Int32(s.MaxScore) + } + { + e.FieldStart("criteria") + e.ArrStart() + for _, elem := range s.Criteria { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfLabCheckResult = [5]string{ + 0: "lab_id", + 1: "checked_at", + 2: "score", + 3: "max_score", + 4: "criteria", +} + +// Decode decodes LabCheckResult from json. +func (s *LabCheckResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabCheckResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "lab_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.LabID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"lab_id\"") + } + case "checked_at": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := json.DecodeDateTime(d) + s.CheckedAt = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"checked_at\"") + } + case "score": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.Score = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"score\"") + } + case "max_score": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.MaxScore = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_score\"") + } + case "criteria": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + s.Criteria = make([]CriterionResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CriterionResult + if err := elem.Decode(d); err != nil { + return err + } + s.Criteria = append(s.Criteria, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"criteria\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode LabCheckResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00011111, + } { + 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(jsonFieldsNameOfLabCheckResult) { + name = jsonFieldsNameOfLabCheckResult[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 *LabCheckResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabCheckResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *LabCreateRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *LabCreateRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("template_id") + s.TemplateID.Encode(e) + } + { + e.FieldStart("template_version") + e.Int32(s.TemplateVersion) + } + { + e.FieldStart("seed") + e.Str(s.Seed) + } + { + e.FieldStart("ttl_seconds") + e.Int32(s.TTLSeconds) + } +} + +var jsonFieldsNameOfLabCreateRequest = [4]string{ + 0: "template_id", + 1: "template_version", + 2: "seed", + 3: "ttl_seconds", +} + +// Decode decodes LabCreateRequest from json. +func (s *LabCreateRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabCreateRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "template_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.TemplateID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"template_id\"") + } + case "template_version": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.TemplateVersion = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"template_version\"") + } + case "seed": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Seed = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"seed\"") + } + case "ttl_seconds": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.TTLSeconds = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ttl_seconds\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode LabCreateRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfLabCreateRequest) { + name = jsonFieldsNameOfLabCreateRequest[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 *LabCreateRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabCreateRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LabFailureReason as json. +func (s LabFailureReason) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes LabFailureReason from json. +func (s *LabFailureReason) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabFailureReason to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch LabFailureReason(v) { + case LabFailureReasonProvisioningFailed: + *s = LabFailureReasonProvisioningFailed + case LabFailureReasonProvisioningTimedOut: + *s = LabFailureReasonProvisioningTimedOut + case LabFailureReasonInterrupted: + *s = LabFailureReasonInterrupted + default: + *s = LabFailureReason(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s LabFailureReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabFailureReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *LabNode) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *LabNode) encodeFields(e *jx.Encoder) { + { + e.FieldStart("name") + s.Name.Encode(e) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } +} + +var jsonFieldsNameOfLabNode = [2]string{ + 0: "name", + 1: "kind", +} + +// Decode decodes LabNode from json. +func (s *LabNode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabNode to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "name": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Name.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"name\"") + } + case "kind": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode LabNode") + } + // 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(jsonFieldsNameOfLabNode) { + name = jsonFieldsNameOfLabNode[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 *LabNode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabNode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LabState as json. +func (s LabState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes LabState from json. +func (s *LabState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch LabState(v) { + case LabStateProvisioning: + *s = LabStateProvisioning + case LabStateReady: + *s = LabStateReady + case LabStateDeleting: + *s = LabStateDeleting + case LabStateDeleted: + *s = LabStateDeleted + case LabStateFailed: + *s = LabStateFailed + default: + *s = LabState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s LabState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *LabStatus) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *LabStatus) encodeFields(e *jx.Encoder) { + { + e.FieldStart("lab_id") + json.EncodeUUID(e, s.LabID) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("template_id") + s.TemplateID.Encode(e) + } + { + e.FieldStart("template_version") + e.Int32(s.TemplateVersion) + } + { + e.FieldStart("created_at") + json.EncodeDateTime(e, s.CreatedAt) + } + { + if s.ReadyAt.Set { + e.FieldStart("ready_at") + s.ReadyAt.Encode(e, json.EncodeDateTime) + } + } + { + e.FieldStart("expires_at") + json.EncodeDateTime(e, s.ExpiresAt) + } + { + if s.DeletedAt.Set { + e.FieldStart("deleted_at") + s.DeletedAt.Encode(e, json.EncodeDateTime) + } + } + { + if s.FailureReason.Set { + e.FieldStart("failure_reason") + s.FailureReason.Encode(e) + } + } + { + e.FieldStart("nodes") + e.ArrStart() + for _, elem := range s.Nodes { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfLabStatus = [10]string{ + 0: "lab_id", + 1: "state", + 2: "template_id", + 3: "template_version", + 4: "created_at", + 5: "ready_at", + 6: "expires_at", + 7: "deleted_at", + 8: "failure_reason", + 9: "nodes", +} + +// Decode decodes LabStatus from json. +func (s *LabStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabStatus to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "lab_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.LabID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"lab_id\"") + } + case "state": + requiredBitSet[0] |= 1 << 1 + 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 "template_id": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.TemplateID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"template_id\"") + } + case "template_version": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.TemplateVersion = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"template_version\"") + } + case "created_at": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + v, err := json.DecodeDateTime(d) + s.CreatedAt = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"created_at\"") + } + case "ready_at": + if err := func() error { + s.ReadyAt.Reset() + if err := s.ReadyAt.Decode(d, json.DecodeDateTime); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ready_at\"") + } + case "expires_at": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + v, err := json.DecodeDateTime(d) + s.ExpiresAt = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expires_at\"") + } + case "deleted_at": + if err := func() error { + s.DeletedAt.Reset() + if err := s.DeletedAt.Decode(d, json.DecodeDateTime); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"deleted_at\"") + } + case "failure_reason": + if err := func() error { + s.FailureReason.Reset() + if err := s.FailureReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"failure_reason\"") + } + case "nodes": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + s.Nodes = make([]LabNode, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem LabNode + if err := elem.Decode(d); err != nil { + return err + } + s.Nodes = append(s.Nodes, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"nodes\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode LabStatus") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b01011111, + 0b00000010, + } { + 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(jsonFieldsNameOfLabStatus) { + name = jsonFieldsNameOfLabStatus[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 *LabStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *LabdHealthResponse) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *LabdHealthResponse) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfLabdHealthResponse = [1]string{ + 0: "status", +} + +// Decode decodes LabdHealthResponse from json. +func (s *LabdHealthResponse) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabdHealthResponse to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode LabdHealthResponse") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfLabdHealthResponse) { + name = jsonFieldsNameOfLabdHealthResponse[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 *LabdHealthResponse) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabdHealthResponse) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LabdHealthResponseStatus as json. +func (s LabdHealthResponseStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes LabdHealthResponseStatus from json. +func (s *LabdHealthResponseStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabdHealthResponseStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch LabdHealthResponseStatus(v) { + case LabdHealthResponseStatusOk: + *s = LabdHealthResponseStatusOk + default: + *s = LabdHealthResponseStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s LabdHealthResponseStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabdHealthResponseStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *LabdReadinessResponse) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *LabdReadinessResponse) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfLabdReadinessResponse = [1]string{ + 0: "status", +} + +// Decode decodes LabdReadinessResponse from json. +func (s *LabdReadinessResponse) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabdReadinessResponse to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode LabdReadinessResponse") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfLabdReadinessResponse) { + name = jsonFieldsNameOfLabdReadinessResponse[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 *LabdReadinessResponse) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabdReadinessResponse) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LabdReadinessResponseStatus as json. +func (s LabdReadinessResponseStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes LabdReadinessResponseStatus from json. +func (s *LabdReadinessResponseStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LabdReadinessResponseStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch LabdReadinessResponseStatus(v) { + case LabdReadinessResponseStatusReady: + *s = LabdReadinessResponseStatusReady + case LabdReadinessResponseStatusNotReady: + *s = LabdReadinessResponseStatusNotReady + default: + *s = LabdReadinessResponseStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s LabdReadinessResponseStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LabdReadinessResponseStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes NodeKind as json. +func (s NodeKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes NodeKind from json. +func (s *NodeKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NodeKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch NodeKind(v) { + case NodeKindMikrotik: + *s = NodeKindMikrotik + case NodeKindUbuntu: + *s = NodeKindUbuntu + default: + *s = NodeKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NodeKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NodeKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes NodeName as json. +func (s NodeName) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes NodeName from json. +func (s *NodeName) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NodeName to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = NodeName(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NodeName) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NodeName) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes time.Time as json. +func (o OptDateTime) Encode(e *jx.Encoder, format func(*jx.Encoder, time.Time)) { + if !o.Set { + return + } + format(e, o.Value) +} + +// Decode decodes time.Time from json. +func (o *OptDateTime) Decode(d *jx.Decoder, format func(*jx.Decoder) (time.Time, error)) error { + if o == nil { + return errors.New("invalid: unable to decode OptDateTime to nil") + } + o.Set = true + v, err := format(d) + if err != nil { + return err + } + o.Value = v + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptDateTime) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e, json.EncodeDateTime) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptDateTime) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d, json.DecodeDateTime) +} + +// Encode encodes LabFailureReason as json. +func (o OptLabFailureReason) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Str(string(o.Value)) +} + +// Decode decodes LabFailureReason from json. +func (o *OptLabFailureReason) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptLabFailureReason to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptLabFailureReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptLabFailureReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes string as json. +func (o OptString) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Str(string(o.Value)) +} + +// Decode decodes string from json. +func (o *OptString) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptString to nil") + } + o.Set = true + v, err := d.Str() + if err != nil { + return err + } + o.Value = string(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptString) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptString) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *Problem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Problem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + e.Str(s.Type) + } + { + e.FieldStart("title") + e.Str(s.Title) + } + { + e.FieldStart("status") + e.Int32(s.Status) + } + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + if s.Detail.Set { + e.FieldStart("detail") + s.Detail.Encode(e) + } + } + { + if s.Instance.Set { + e.FieldStart("instance") + s.Instance.Encode(e) + } + } + { + if s.TraceID.Set { + e.FieldStart("trace_id") + s.TraceID.Encode(e) + } + } + { + if s.Errors != nil { + e.FieldStart("errors") + e.ArrStart() + for _, elem := range s.Errors { + elem.Encode(e) + } + e.ArrEnd() + } + } +} + +var jsonFieldsNameOfProblem = [8]string{ + 0: "type", + 1: "title", + 2: "status", + 3: "code", + 4: "detail", + 5: "instance", + 6: "trace_id", + 7: "errors", +} + +// Decode decodes Problem from json. +func (s *Problem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Problem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Type = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.Status = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "code": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "detail": + if err := func() error { + s.Detail.Reset() + if err := s.Detail.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"detail\"") + } + case "instance": + if err := func() error { + s.Instance.Reset() + if err := s.Instance.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"instance\"") + } + case "trace_id": + if err := func() error { + s.TraceID.Reset() + if err := s.TraceID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"trace_id\"") + } + case "errors": + if err := func() error { + s.Errors = make([]ProblemFieldError, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProblemFieldError + if err := elem.Decode(d); err != nil { + return err + } + s.Errors = append(s.Errors, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"errors\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Problem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblem) { + name = jsonFieldsNameOfProblem[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 *Problem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Problem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemCode as json. +func (s ProblemCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemCode from json. +func (s *ProblemCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemCode(v) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + case ProblemCodeStateConflict: + *s = ProblemCodeStateConflict + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + case ProblemCodeInternal: + *s = ProblemCodeInternal + case ProblemCodeNotImplemented: + *s = ProblemCodeNotImplemented + case ProblemCodeLabPoolBusy: + *s = ProblemCodeLabPoolBusy + case ProblemCodeLabUnavailable: + *s = ProblemCodeLabUnavailable + default: + *s = ProblemCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProblemFieldError) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProblemFieldError) encodeFields(e *jx.Encoder) { + { + e.FieldStart("in") + s.In.Encode(e) + } + { + e.FieldStart("pointer") + e.Str(s.Pointer) + } + { + e.FieldStart("code") + e.Str(s.Code) + } + { + e.FieldStart("message") + e.Str(s.Message) + } +} + +var jsonFieldsNameOfProblemFieldError = [4]string{ + 0: "in", + 1: "pointer", + 2: "code", + 3: "message", +} + +// Decode decodes ProblemFieldError from json. +func (s *ProblemFieldError) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldError to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "in": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.In.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"in\"") + } + case "pointer": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Pointer = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"pointer\"") + } + case "code": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Code = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "message": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Str() + s.Message = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"message\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProblemFieldError") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblemFieldError) { + name = jsonFieldsNameOfProblemFieldError[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 *ProblemFieldError) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldError) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemFieldLocation as json. +func (s ProblemFieldLocation) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemFieldLocation from json. +func (s *ProblemFieldLocation) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldLocation to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemFieldLocation(v) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + default: + *s = ProblemFieldLocation(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemFieldLocation) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldLocation) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TemplateId as json. +func (s TemplateId) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes TemplateId from json. +func (s *TemplateId) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TemplateId to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = TemplateId(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TemplateId) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TemplateId) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_operations_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_operations_gen.go new file mode 100644 index 0000000..0c50611 --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_operations_gen.go @@ -0,0 +1,16 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +// OperationName is the ogen operation name +type OperationName = string + +const ( + CheckLabOperation OperationName = "CheckLab" + CreateLabOperation OperationName = "CreateLab" + CreateLabConsoleTokenOperation OperationName = "CreateLabConsoleToken" + DeleteLabOperation OperationName = "DeleteLab" + GetLabOperation OperationName = "GetLab" + GetLabdHealthzOperation OperationName = "GetLabdHealthz" + GetLabdReadyzOperation OperationName = "GetLabdReadyz" +) diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_parameters_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_parameters_gen.go new file mode 100644 index 0000000..2e5d9f2 --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_parameters_gen.go @@ -0,0 +1,42 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "github.com/google/uuid" +) + +// CheckLabParams is parameters of CheckLab operation. +type CheckLabParams struct { + // Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not + // encode a candidate, attempt, or task identifier. + LabID uuid.UUID +} + +// CreateLabParams is parameters of CreateLab operation. +type CreateLabParams struct { + // Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not + // encode a candidate, attempt, or task identifier. + LabID uuid.UUID +} + +// CreateLabConsoleTokenParams is parameters of CreateLabConsoleToken operation. +type CreateLabConsoleTokenParams struct { + // Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not + // encode a candidate, attempt, or task identifier. + LabID uuid.UUID +} + +// DeleteLabParams is parameters of DeleteLab operation. +type DeleteLabParams struct { + // Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not + // encode a candidate, attempt, or task identifier. + LabID uuid.UUID +} + +// GetLabParams is parameters of GetLab operation. +type GetLabParams struct { + // Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not + // encode a candidate, attempt, or task identifier. + LabID uuid.UUID +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_request_encoders_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_request_encoders_gen.go new file mode 100644 index 0000000..c5d4238 --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_request_encoders_gen.go @@ -0,0 +1,39 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "bytes" + "net/http" + + "github.com/go-faster/jx" + ht "github.com/ogen-go/ogen/http" +) + +func encodeCreateLabRequest( + req *LabCreateRequest, + r *http.Request, +) error { + const contentType = "application/json" + e := new(jx.Encoder) + { + req.Encode(e) + } + encoded := e.Bytes() + ht.SetBody(r, bytes.NewReader(encoded), contentType) + return nil +} + +func encodeCreateLabConsoleTokenRequest( + req *ConsoleTokenRequest, + r *http.Request, +) error { + const contentType = "application/json" + e := new(jx.Encoder) + { + req.Encode(e) + } + encoded := e.Bytes() + ht.SetBody(r, bytes.NewReader(encoded), contentType) + return nil +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_response_decoders_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_response_decoders_gen.go new file mode 100644 index 0000000..dcf423a --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_response_decoders_gen.go @@ -0,0 +1,995 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "io" + "mime" + "net/http" + + "github.com/go-faster/errors" + "github.com/go-faster/jx" + "github.com/ogen-go/ogen/conv" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/uri" + "github.com/ogen-go/ogen/validate" +) + +func decodeCheckLabResponse(resp *http.Response) (res *LabCheckResult, _ error) { + switch resp.StatusCode { + case 200: + // Code 200. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response LabCheckResult + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &response, nil + default: + return res, validate.InvalidContentType(ct) + } + } + // Convenient error response. + defRes, err := func() (res *ProblemStatusCode, err error) { + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &ProblemStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") +} + +func decodeCreateLabResponse(resp *http.Response) (res CreateLabRes, _ error) { + switch resp.StatusCode { + case 200: + // Code 200. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response CreateLabOK + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &response, nil + default: + return res, validate.InvalidContentType(ct) + } + case 202: + // Code 202. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response CreateLabAccepted + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &response, nil + default: + return res, validate.InvalidContentType(ct) + } + case 503: + // Code 503. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + var wrapper LabPoolBusyHeaders + wrapper.Response = response + h := uri.NewHeaderDecoder(resp.Header) + // Parse "Retry-After" header. + { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := func() error { + 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.ToInt32(val) + if err != nil { + return err + } + + wrapper.RetryAfter = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 3600, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(wrapper.RetryAfter)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "parse Retry-After header") + } + } + return &wrapper, nil + default: + return res, validate.InvalidContentType(ct) + } + } + // Convenient error response. + defRes, err := func() (res *ProblemStatusCode, err error) { + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &ProblemStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") +} + +func decodeCreateLabConsoleTokenResponse(resp *http.Response) (res *ConsoleTokenHeaders, _ error) { + switch resp.StatusCode { + case 201: + // Code 201. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response ConsoleToken + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + var wrapper ConsoleTokenHeaders + wrapper.Response = response + h := uri.NewHeaderDecoder(resp.Header) + // Parse "Cache-Control" header. + { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := func() error { + 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 + } + + wrapper.CacheControl = CreateLabConsoleTokenCreatedCacheControl(c) + return nil + }); err != nil { + return err + } + if err := func() error { + if err := wrapper.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "parse Cache-Control header") + } + } + return &wrapper, nil + default: + return res, validate.InvalidContentType(ct) + } + } + // Convenient error response. + defRes, err := func() (res *ProblemStatusCode, err error) { + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &ProblemStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") +} + +func decodeDeleteLabResponse(resp *http.Response) (res DeleteLabRes, _ error) { + switch resp.StatusCode { + case 200: + // Code 200. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response DeleteLabOK + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &response, nil + default: + return res, validate.InvalidContentType(ct) + } + case 202: + // Code 202. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response DeleteLabAccepted + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &response, nil + default: + return res, validate.InvalidContentType(ct) + } + } + // Convenient error response. + defRes, err := func() (res *ProblemStatusCode, err error) { + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &ProblemStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") +} + +func decodeGetLabResponse(resp *http.Response) (res *LabStatus, _ error) { + switch resp.StatusCode { + case 200: + // Code 200. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response LabStatus + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &response, nil + default: + return res, validate.InvalidContentType(ct) + } + } + // Convenient error response. + defRes, err := func() (res *ProblemStatusCode, err error) { + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &ProblemStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") +} + +func decodeGetLabdHealthzResponse(resp *http.Response) (res *LabdHealthResponse, _ error) { + switch resp.StatusCode { + case 200: + // Code 200. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response LabdHealthResponse + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &response, nil + default: + return res, validate.InvalidContentType(ct) + } + } + // Convenient error response. + defRes, err := func() (res *ProblemStatusCode, err error) { + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &ProblemStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") +} + +func decodeGetLabdReadyzResponse(resp *http.Response) (res GetLabdReadyzRes, _ error) { + switch resp.StatusCode { + case 200: + // Code 200. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response GetLabdReadyzOK + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &response, nil + default: + return res, validate.InvalidContentType(ct) + } + case 503: + // Code 503. + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response GetLabdReadyzServiceUnavailable + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &response, nil + default: + return res, validate.InvalidContentType(ct) + } + } + // Convenient error response. + defRes, err := func() (res *ProblemStatusCode, err error) { + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.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 res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &ProblemStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_schemas_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_schemas_gen.go new file mode 100644 index 0000000..68dfdd7 --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_schemas_gen.go @@ -0,0 +1,1325 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "fmt" + "time" + + "github.com/go-faster/errors" + "github.com/google/uuid" +) + +func (s *ProblemStatusCode) Error() string { + return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response) +} + +type BearerAuth struct { + Token string + Roles []string +} + +// GetToken returns the value of Token. +func (s *BearerAuth) GetToken() string { + return s.Token +} + +// GetRoles returns the value of Roles. +func (s *BearerAuth) GetRoles() []string { + return s.Roles +} + +// SetToken sets the value of Token. +func (s *BearerAuth) SetToken(val string) { + s.Token = val +} + +// SetRoles sets the value of Roles. +func (s *BearerAuth) SetRoles(val []string) { + s.Roles = val +} + +// Single-use console token for one node. The token is a secret of the console gateway: it is never +// logged, stored by the backend, or passed to a browser. +// Ref: #/components/schemas/ConsoleToken +type ConsoleToken struct { + // 32 random bytes in unpadded base64url. + Token string `json:"token"` + Node NodeName `json:"node"` + ExpiresAt time.Time `json:"expires_at"` + // Path of the WebSocket attach on the provisioner origin. + AttachPath string `json:"attach_path"` +} + +// GetToken returns the value of Token. +func (s *ConsoleToken) GetToken() string { + return s.Token +} + +// GetNode returns the value of Node. +func (s *ConsoleToken) GetNode() NodeName { + return s.Node +} + +// GetExpiresAt returns the value of ExpiresAt. +func (s *ConsoleToken) GetExpiresAt() time.Time { + return s.ExpiresAt +} + +// GetAttachPath returns the value of AttachPath. +func (s *ConsoleToken) GetAttachPath() string { + return s.AttachPath +} + +// SetToken sets the value of Token. +func (s *ConsoleToken) SetToken(val string) { + s.Token = val +} + +// SetNode sets the value of Node. +func (s *ConsoleToken) SetNode(val NodeName) { + s.Node = val +} + +// SetExpiresAt sets the value of ExpiresAt. +func (s *ConsoleToken) SetExpiresAt(val time.Time) { + s.ExpiresAt = val +} + +// SetAttachPath sets the value of AttachPath. +func (s *ConsoleToken) SetAttachPath(val string) { + s.AttachPath = val +} + +// ConsoleTokenHeaders wraps ConsoleToken with response headers. +type ConsoleTokenHeaders struct { + CacheControl CreateLabConsoleTokenCreatedCacheControl + Response ConsoleToken +} + +// GetCacheControl returns the value of CacheControl. +func (s *ConsoleTokenHeaders) GetCacheControl() CreateLabConsoleTokenCreatedCacheControl { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *ConsoleTokenHeaders) GetResponse() ConsoleToken { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *ConsoleTokenHeaders) SetCacheControl(val CreateLabConsoleTokenCreatedCacheControl) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *ConsoleTokenHeaders) SetResponse(val ConsoleToken) { + s.Response = val +} + +// Ref: #/components/schemas/ConsoleTokenRequest +type ConsoleTokenRequest struct { + Node NodeName `json:"node"` +} + +// GetNode returns the value of Node. +func (s *ConsoleTokenRequest) GetNode() NodeName { + return s.Node +} + +// SetNode sets the value of Node. +func (s *ConsoleTokenRequest) SetNode(val NodeName) { + s.Node = val +} + +type CreateLabAccepted LabStatus + +func (*CreateLabAccepted) createLabRes() {} + +type CreateLabConsoleTokenCreatedCacheControl string + +const ( + CreateLabConsoleTokenCreatedCacheControlNoStore CreateLabConsoleTokenCreatedCacheControl = "no-store" +) + +// AllValues returns all CreateLabConsoleTokenCreatedCacheControl values. +func (CreateLabConsoleTokenCreatedCacheControl) AllValues() []CreateLabConsoleTokenCreatedCacheControl { + return []CreateLabConsoleTokenCreatedCacheControl{ + CreateLabConsoleTokenCreatedCacheControlNoStore, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CreateLabConsoleTokenCreatedCacheControl) MarshalText() ([]byte, error) { + switch s { + case CreateLabConsoleTokenCreatedCacheControlNoStore: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CreateLabConsoleTokenCreatedCacheControl) UnmarshalText(data []byte) error { + switch CreateLabConsoleTokenCreatedCacheControl(data) { + case CreateLabConsoleTokenCreatedCacheControlNoStore: + *s = CreateLabConsoleTokenCreatedCacheControlNoStore + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type CreateLabOK LabStatus + +func (*CreateLabOK) createLabRes() {} + +type CriterionId string + +// Ref: #/components/schemas/CriterionResult +type CriterionResult struct { + ID CriterionId `json:"id"` + Passed bool `json:"passed"` +} + +// GetID returns the value of ID. +func (s *CriterionResult) GetID() CriterionId { + return s.ID +} + +// GetPassed returns the value of Passed. +func (s *CriterionResult) GetPassed() bool { + return s.Passed +} + +// SetID sets the value of ID. +func (s *CriterionResult) SetID(val CriterionId) { + s.ID = val +} + +// SetPassed sets the value of Passed. +func (s *CriterionResult) SetPassed(val bool) { + s.Passed = val +} + +type DeleteLabAccepted LabStatus + +func (*DeleteLabAccepted) deleteLabRes() {} + +type DeleteLabOK LabStatus + +func (*DeleteLabOK) deleteLabRes() {} + +type GetLabdReadyzOK LabdReadinessResponse + +func (*GetLabdReadyzOK) getLabdReadyzRes() {} + +type GetLabdReadyzServiceUnavailable LabdReadinessResponse + +func (*GetLabdReadyzServiceUnavailable) getLabdReadyzRes() {} + +// Result of one check: whether each criterion of the variant holds on the nodes. It carries no node +// output, address, or configuration text. +// Ref: #/components/schemas/LabCheckResult +type LabCheckResult struct { + LabID uuid.UUID `json:"lab_id"` + CheckedAt time.Time `json:"checked_at"` + // Number of passed criteria. + Score int32 `json:"score"` + // Number of criteria. + MaxScore int32 `json:"max_score"` + Criteria []CriterionResult `json:"criteria"` +} + +// GetLabID returns the value of LabID. +func (s *LabCheckResult) GetLabID() uuid.UUID { + return s.LabID +} + +// GetCheckedAt returns the value of CheckedAt. +func (s *LabCheckResult) GetCheckedAt() time.Time { + return s.CheckedAt +} + +// GetScore returns the value of Score. +func (s *LabCheckResult) GetScore() int32 { + return s.Score +} + +// GetMaxScore returns the value of MaxScore. +func (s *LabCheckResult) GetMaxScore() int32 { + return s.MaxScore +} + +// GetCriteria returns the value of Criteria. +func (s *LabCheckResult) GetCriteria() []CriterionResult { + return s.Criteria +} + +// SetLabID sets the value of LabID. +func (s *LabCheckResult) SetLabID(val uuid.UUID) { + s.LabID = val +} + +// SetCheckedAt sets the value of CheckedAt. +func (s *LabCheckResult) SetCheckedAt(val time.Time) { + s.CheckedAt = val +} + +// SetScore sets the value of Score. +func (s *LabCheckResult) SetScore(val int32) { + s.Score = val +} + +// SetMaxScore sets the value of MaxScore. +func (s *LabCheckResult) SetMaxScore(val int32) { + s.MaxScore = val +} + +// SetCriteria sets the value of Criteria. +func (s *LabCheckResult) SetCriteria(val []CriterionResult) { + s.Criteria = val +} + +// A lab of one template variant. It has no field for a candidate, account, attempt, task, or company. +// Ref: #/components/schemas/LabCreateRequest +type LabCreateRequest struct { + TemplateID TemplateId `json:"template_id"` + // Version of the template. The provisioner refuses a version it does not hold, so a lab always matches + // the variant the backend served. + TemplateVersion int32 `json:"template_version"` + // Variant seed: 32 random bytes in lowercase hex chosen by the backend for the item instance. The + // template renders the variant configuration of every node and the checker criteria from it. It is + // never returned by the provisioner. + Seed string `json:"seed"` + // Lifetime of the lab from its creation. The provisioner refuses a value above its configured maximum. + TTLSeconds int32 `json:"ttl_seconds"` +} + +// GetTemplateID returns the value of TemplateID. +func (s *LabCreateRequest) GetTemplateID() TemplateId { + return s.TemplateID +} + +// GetTemplateVersion returns the value of TemplateVersion. +func (s *LabCreateRequest) GetTemplateVersion() int32 { + return s.TemplateVersion +} + +// GetSeed returns the value of Seed. +func (s *LabCreateRequest) GetSeed() string { + return s.Seed +} + +// GetTTLSeconds returns the value of TTLSeconds. +func (s *LabCreateRequest) GetTTLSeconds() int32 { + return s.TTLSeconds +} + +// SetTemplateID sets the value of TemplateID. +func (s *LabCreateRequest) SetTemplateID(val TemplateId) { + s.TemplateID = val +} + +// SetTemplateVersion sets the value of TemplateVersion. +func (s *LabCreateRequest) SetTemplateVersion(val int32) { + s.TemplateVersion = val +} + +// SetSeed sets the value of Seed. +func (s *LabCreateRequest) SetSeed(val string) { + s.Seed = val +} + +// SetTTLSeconds sets the value of TTLSeconds. +func (s *LabCreateRequest) SetTTLSeconds(val int32) { + s.TTLSeconds = val +} + +// Why a lab failed. None of the reasons depends on the person who uses the lab. +// +// - provisioning_failed: LXD refused or failed an operation of the provisioning. +// - provisioning_timed_out: a node did not answer on its management port within the provisioning +// timeout. +// - interrupted: the provisioner process stopped while the lab was provisioning. +// +// Ref: #/components/schemas/LabFailureReason +type LabFailureReason string + +const ( + LabFailureReasonProvisioningFailed LabFailureReason = "provisioning_failed" + LabFailureReasonProvisioningTimedOut LabFailureReason = "provisioning_timed_out" + LabFailureReasonInterrupted LabFailureReason = "interrupted" +) + +// AllValues returns all LabFailureReason values. +func (LabFailureReason) AllValues() []LabFailureReason { + return []LabFailureReason{ + LabFailureReasonProvisioningFailed, + LabFailureReasonProvisioningTimedOut, + LabFailureReasonInterrupted, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s LabFailureReason) MarshalText() ([]byte, error) { + switch s { + case LabFailureReasonProvisioningFailed: + return []byte(s), nil + case LabFailureReasonProvisioningTimedOut: + return []byte(s), nil + case LabFailureReasonInterrupted: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *LabFailureReason) UnmarshalText(data []byte) error { + switch LabFailureReason(data) { + case LabFailureReasonProvisioningFailed: + *s = LabFailureReasonProvisioningFailed + return nil + case LabFailureReasonProvisioningTimedOut: + *s = LabFailureReasonProvisioningTimedOut + return nil + case LabFailureReasonInterrupted: + *s = LabFailureReasonInterrupted + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// A node of a lab by its template name and kind. It never carries an address, a MAC address, an +// instance name, or a credential. +// Ref: #/components/schemas/LabNode +type LabNode struct { + Name NodeName `json:"name"` + Kind NodeKind `json:"kind"` +} + +// GetName returns the value of Name. +func (s *LabNode) GetName() NodeName { + return s.Name +} + +// GetKind returns the value of Kind. +func (s *LabNode) GetKind() NodeKind { + return s.Kind +} + +// SetName sets the value of Name. +func (s *LabNode) SetName(val NodeName) { + s.Name = val +} + +// SetKind sets the value of Kind. +func (s *LabNode) SetKind(val NodeKind) { + s.Kind = val +} + +// LabPoolBusyHeaders wraps Problem with response headers. +type LabPoolBusyHeaders struct { + RetryAfter int32 + Response Problem +} + +// GetRetryAfter returns the value of RetryAfter. +func (s *LabPoolBusyHeaders) GetRetryAfter() int32 { + return s.RetryAfter +} + +// GetResponse returns the value of Response. +func (s *LabPoolBusyHeaders) GetResponse() Problem { + return s.Response +} + +// SetRetryAfter sets the value of RetryAfter. +func (s *LabPoolBusyHeaders) SetRetryAfter(val int32) { + s.RetryAfter = val +} + +// SetResponse sets the value of Response. +func (s *LabPoolBusyHeaders) SetResponse(val Problem) { + s.Response = val +} + +func (*LabPoolBusyHeaders) createLabRes() {} + +// State of a lab. +// +// - provisioning: capacity is reserved and the nodes are being cloned, connected, and booted. +// - ready: every node answers on its management port; console tokens and checks are allowed. +// - deleting: the timer ended, DeleteLab was called, or provisioning failed; the instances and +// bridges are being removed. +// - deleted: every instance and bridge of the lab is gone and its capacity is free. +// - failed: provisioning failed or timed out, or the provisioner restarted while provisioning; +// `failure_reason` says which. Its resources are removed as for `deleting` and the capacity returns +// once they are gone; create a new lab with a new ID. +// +// Adding a value is a contract change. +// Ref: #/components/schemas/LabState +type LabState string + +const ( + LabStateProvisioning LabState = "provisioning" + LabStateReady LabState = "ready" + LabStateDeleting LabState = "deleting" + LabStateDeleted LabState = "deleted" + LabStateFailed LabState = "failed" +) + +// AllValues returns all LabState values. +func (LabState) AllValues() []LabState { + return []LabState{ + LabStateProvisioning, + LabStateReady, + LabStateDeleting, + LabStateDeleted, + LabStateFailed, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s LabState) MarshalText() ([]byte, error) { + switch s { + case LabStateProvisioning: + return []byte(s), nil + case LabStateReady: + return []byte(s), nil + case LabStateDeleting: + return []byte(s), nil + case LabStateDeleted: + return []byte(s), nil + case LabStateFailed: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *LabState) UnmarshalText(data []byte) error { + switch LabState(data) { + case LabStateProvisioning: + *s = LabStateProvisioning + return nil + case LabStateReady: + *s = LabStateReady + return nil + case LabStateDeleting: + *s = LabStateDeleting + return nil + case LabStateDeleted: + *s = LabStateDeleted + return nil + case LabStateFailed: + *s = LabStateFailed + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// State of a lab after one call. It never contains the seed, a node address, a key, a password, or an +// LXD object name. +// Ref: #/components/schemas/LabStatus +type LabStatus struct { + LabID uuid.UUID `json:"lab_id"` + State LabState `json:"state"` + TemplateID TemplateId `json:"template_id"` + TemplateVersion int32 `json:"template_version"` + CreatedAt time.Time `json:"created_at"` + // Time the lab became `ready`; absent before. + ReadyAt OptDateTime `json:"ready_at"` + // Time the provisioner deletes the lab. It never moves, also not across restarts of the provisioner. + ExpiresAt time.Time `json:"expires_at"` + // Time the last resource of the lab was removed; absent before. + DeletedAt OptDateTime `json:"deleted_at"` + FailureReason OptLabFailureReason `json:"failure_reason"` + // Nodes of the template in template order. + Nodes []LabNode `json:"nodes"` +} + +// GetLabID returns the value of LabID. +func (s *LabStatus) GetLabID() uuid.UUID { + return s.LabID +} + +// GetState returns the value of State. +func (s *LabStatus) GetState() LabState { + return s.State +} + +// GetTemplateID returns the value of TemplateID. +func (s *LabStatus) GetTemplateID() TemplateId { + return s.TemplateID +} + +// GetTemplateVersion returns the value of TemplateVersion. +func (s *LabStatus) GetTemplateVersion() int32 { + return s.TemplateVersion +} + +// GetCreatedAt returns the value of CreatedAt. +func (s *LabStatus) GetCreatedAt() time.Time { + return s.CreatedAt +} + +// GetReadyAt returns the value of ReadyAt. +func (s *LabStatus) GetReadyAt() OptDateTime { + return s.ReadyAt +} + +// GetExpiresAt returns the value of ExpiresAt. +func (s *LabStatus) GetExpiresAt() time.Time { + return s.ExpiresAt +} + +// GetDeletedAt returns the value of DeletedAt. +func (s *LabStatus) GetDeletedAt() OptDateTime { + return s.DeletedAt +} + +// GetFailureReason returns the value of FailureReason. +func (s *LabStatus) GetFailureReason() OptLabFailureReason { + return s.FailureReason +} + +// GetNodes returns the value of Nodes. +func (s *LabStatus) GetNodes() []LabNode { + return s.Nodes +} + +// SetLabID sets the value of LabID. +func (s *LabStatus) SetLabID(val uuid.UUID) { + s.LabID = val +} + +// SetState sets the value of State. +func (s *LabStatus) SetState(val LabState) { + s.State = val +} + +// SetTemplateID sets the value of TemplateID. +func (s *LabStatus) SetTemplateID(val TemplateId) { + s.TemplateID = val +} + +// SetTemplateVersion sets the value of TemplateVersion. +func (s *LabStatus) SetTemplateVersion(val int32) { + s.TemplateVersion = val +} + +// SetCreatedAt sets the value of CreatedAt. +func (s *LabStatus) SetCreatedAt(val time.Time) { + s.CreatedAt = val +} + +// SetReadyAt sets the value of ReadyAt. +func (s *LabStatus) SetReadyAt(val OptDateTime) { + s.ReadyAt = val +} + +// SetExpiresAt sets the value of ExpiresAt. +func (s *LabStatus) SetExpiresAt(val time.Time) { + s.ExpiresAt = val +} + +// SetDeletedAt sets the value of DeletedAt. +func (s *LabStatus) SetDeletedAt(val OptDateTime) { + s.DeletedAt = val +} + +// SetFailureReason sets the value of FailureReason. +func (s *LabStatus) SetFailureReason(val OptLabFailureReason) { + s.FailureReason = val +} + +// SetNodes sets the value of Nodes. +func (s *LabStatus) SetNodes(val []LabNode) { + s.Nodes = val +} + +// Ref: #/components/schemas/LabdHealthResponse +type LabdHealthResponse struct { + Status LabdHealthResponseStatus `json:"status"` +} + +// GetStatus returns the value of Status. +func (s *LabdHealthResponse) GetStatus() LabdHealthResponseStatus { + return s.Status +} + +// SetStatus sets the value of Status. +func (s *LabdHealthResponse) SetStatus(val LabdHealthResponseStatus) { + s.Status = val +} + +type LabdHealthResponseStatus string + +const ( + LabdHealthResponseStatusOk LabdHealthResponseStatus = "ok" +) + +// AllValues returns all LabdHealthResponseStatus values. +func (LabdHealthResponseStatus) AllValues() []LabdHealthResponseStatus { + return []LabdHealthResponseStatus{ + LabdHealthResponseStatusOk, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s LabdHealthResponseStatus) MarshalText() ([]byte, error) { + switch s { + case LabdHealthResponseStatusOk: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *LabdHealthResponseStatus) UnmarshalText(data []byte) error { + switch LabdHealthResponseStatus(data) { + case LabdHealthResponseStatusOk: + *s = LabdHealthResponseStatusOk + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/LabdReadinessResponse +type LabdReadinessResponse struct { + Status LabdReadinessResponseStatus `json:"status"` +} + +// GetStatus returns the value of Status. +func (s *LabdReadinessResponse) GetStatus() LabdReadinessResponseStatus { + return s.Status +} + +// SetStatus sets the value of Status. +func (s *LabdReadinessResponse) SetStatus(val LabdReadinessResponseStatus) { + s.Status = val +} + +type LabdReadinessResponseStatus string + +const ( + LabdReadinessResponseStatusReady LabdReadinessResponseStatus = "ready" + LabdReadinessResponseStatusNotReady LabdReadinessResponseStatus = "not_ready" +) + +// AllValues returns all LabdReadinessResponseStatus values. +func (LabdReadinessResponseStatus) AllValues() []LabdReadinessResponseStatus { + return []LabdReadinessResponseStatus{ + LabdReadinessResponseStatusReady, + LabdReadinessResponseStatusNotReady, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s LabdReadinessResponseStatus) MarshalText() ([]byte, error) { + switch s { + case LabdReadinessResponseStatusReady: + return []byte(s), nil + case LabdReadinessResponseStatusNotReady: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *LabdReadinessResponseStatus) UnmarshalText(data []byte) error { + switch LabdReadinessResponseStatus(data) { + case LabdReadinessResponseStatusReady: + *s = LabdReadinessResponseStatusReady + return nil + case LabdReadinessResponseStatusNotReady: + *s = LabdReadinessResponseStatusNotReady + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Guest system of a node. +// +// - mikrotik: a MikroTik Cloud Hosted Router VM; its console is RouterOS. +// - ubuntu: a small Ubuntu VM; its console is a Linux login. +// +// Adding a value is a contract change. +// Ref: #/components/schemas/NodeKind +type NodeKind string + +const ( + NodeKindMikrotik NodeKind = "mikrotik" + NodeKindUbuntu NodeKind = "ubuntu" +) + +// AllValues returns all NodeKind values. +func (NodeKind) AllValues() []NodeKind { + return []NodeKind{ + NodeKindMikrotik, + NodeKindUbuntu, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s NodeKind) MarshalText() ([]byte, error) { + switch s { + case NodeKindMikrotik: + return []byte(s), nil + case NodeKindUbuntu: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *NodeKind) UnmarshalText(data []byte) error { + switch NodeKind(data) { + case NodeKindMikrotik: + *s = NodeKindMikrotik + return nil + case NodeKindUbuntu: + *s = NodeKindUbuntu + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type NodeName string + +// NewOptDateTime returns new OptDateTime with value set to v. +func NewOptDateTime(v time.Time) OptDateTime { + return OptDateTime{ + Value: v, + Set: true, + } +} + +// OptDateTime is optional time.Time. +type OptDateTime struct { + Value time.Time + Set bool +} + +// IsSet returns true if OptDateTime was set. +func (o OptDateTime) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptDateTime) Reset() { + var v time.Time + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptDateTime) SetTo(v time.Time) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptDateTime) Get() (v time.Time, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptDateTime) Or(d time.Time) time.Time { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptLabFailureReason returns new OptLabFailureReason with value set to v. +func NewOptLabFailureReason(v LabFailureReason) OptLabFailureReason { + return OptLabFailureReason{ + Value: v, + Set: true, + } +} + +// OptLabFailureReason is optional LabFailureReason. +type OptLabFailureReason struct { + Value LabFailureReason + Set bool +} + +// IsSet returns true if OptLabFailureReason was set. +func (o OptLabFailureReason) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptLabFailureReason) Reset() { + var v LabFailureReason + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptLabFailureReason) SetTo(v LabFailureReason) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptLabFailureReason) Get() (v LabFailureReason, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptLabFailureReason) Or(d LabFailureReason) LabFailureReason { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptString returns new OptString with value set to v. +func NewOptString(v string) OptString { + return OptString{ + Value: v, + Set: true, + } +} + +// OptString is optional string. +type OptString struct { + Value string + Set bool +} + +// IsSet returns true if OptString was set. +func (o OptString) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptString) Reset() { + var v string + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptString) SetTo(v string) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptString) Get() (v string, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptString) Or(d string) string { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// Problem details (RFC 9457) returned with the application/problem+json media type for every error +// response. This is the lab provisioner copy of the public api/core Problem schema; keep both copies +// identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable +// reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body +// never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or +// echoed request values. +// Ref: #/components/schemas/Problem +type Problem struct { + // URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an + // identifier, not a link to dereference. + Type string `json:"type"` + // Short, fixed English summary of the problem type. It does not change between occurrences. + Title string `json:"title"` + // HTTP status code generated by the origin server. + Status int32 `json:"status"` + Code ProblemCode `json:"code"` + // Safe English explanation of this occurrence. It never contains internal error text or request + // values. + Detail OptString `json:"detail"` + // URI reference that identifies this occurrence, when one exists. + Instance OptString `json:"instance"` + // Request identifier of the call when the caller propagated one; it is not a secret. + TraceID OptString `json:"trace_id"` + // Field-level reasons for validation_failed. Other codes omit it. + Errors []ProblemFieldError `json:"errors"` +} + +// GetType returns the value of Type. +func (s *Problem) GetType() string { + return s.Type +} + +// GetTitle returns the value of Title. +func (s *Problem) GetTitle() string { + return s.Title +} + +// GetStatus returns the value of Status. +func (s *Problem) GetStatus() int32 { + return s.Status +} + +// GetCode returns the value of Code. +func (s *Problem) GetCode() ProblemCode { + return s.Code +} + +// GetDetail returns the value of Detail. +func (s *Problem) GetDetail() OptString { + return s.Detail +} + +// GetInstance returns the value of Instance. +func (s *Problem) GetInstance() OptString { + return s.Instance +} + +// GetTraceID returns the value of TraceID. +func (s *Problem) GetTraceID() OptString { + return s.TraceID +} + +// GetErrors returns the value of Errors. +func (s *Problem) GetErrors() []ProblemFieldError { + return s.Errors +} + +// SetType sets the value of Type. +func (s *Problem) SetType(val string) { + s.Type = val +} + +// SetTitle sets the value of Title. +func (s *Problem) SetTitle(val string) { + s.Title = val +} + +// SetStatus sets the value of Status. +func (s *Problem) SetStatus(val int32) { + s.Status = val +} + +// SetCode sets the value of Code. +func (s *Problem) SetCode(val ProblemCode) { + s.Code = val +} + +// SetDetail sets the value of Detail. +func (s *Problem) SetDetail(val OptString) { + s.Detail = val +} + +// SetInstance sets the value of Instance. +func (s *Problem) SetInstance(val OptString) { + s.Instance = val +} + +// SetTraceID sets the value of TraceID. +func (s *Problem) SetTraceID(val OptString) { + s.TraceID = val +} + +// SetErrors sets the value of Errors. +func (s *Problem) SetErrors(val []ProblemFieldError) { + s.Errors = val +} + +// Stable error code of the lab provisioner API. Adding a code is a contract change; renaming or +// removing one is a breaking change. Clients must handle an unknown code by its HTTP status. +// +// - validation_failed (400): parameters or body do not match the contract or a semantic rule, such as +// an unknown template or node; `errors` points at the fields. +// - unauthenticated (401): the bearer token is missing or wrong. +// - not_found (404): the route or the lab does not exist. +// - method_not_allowed (405): the route does not support the method. +// - state_conflict (409): the lab is not in a state that allows the operation, for example a console +// token or a check for a lab that is not ready. +// - payload_too_large (413): the request body exceeds the limit. +// - unsupported_media_type (415): the request Content-Type is not accepted. +// - idempotency_key_reused (422): the lab ID was already used with a different payload. +// - internal (500): unexpected server error. +// - not_implemented (501): the route is described but not implemented yet, such as the console +// attach. +// - lab_pool_busy (503): the lab does not fit the capacity or the provisioner is draining; see +// Retry-After. +// - lab_unavailable (503): LXD or a node could not be reached, so nothing was done or evaluated. It +// is an infrastructure failure, never a failed check. +// +// The Problem shape is the api/core shape; only this enum is specific to the lab provisioner. +// Ref: #/components/schemas/ProblemCode +type ProblemCode string + +const ( + ProblemCodeValidationFailed ProblemCode = "validation_failed" + ProblemCodeUnauthenticated ProblemCode = "unauthenticated" + ProblemCodeNotFound ProblemCode = "not_found" + ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed" + ProblemCodeStateConflict ProblemCode = "state_conflict" + ProblemCodePayloadTooLarge ProblemCode = "payload_too_large" + ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type" + ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused" + ProblemCodeInternal ProblemCode = "internal" + ProblemCodeNotImplemented ProblemCode = "not_implemented" + ProblemCodeLabPoolBusy ProblemCode = "lab_pool_busy" + ProblemCodeLabUnavailable ProblemCode = "lab_unavailable" +) + +// AllValues returns all ProblemCode values. +func (ProblemCode) AllValues() []ProblemCode { + return []ProblemCode{ + ProblemCodeValidationFailed, + ProblemCodeUnauthenticated, + ProblemCodeNotFound, + ProblemCodeMethodNotAllowed, + ProblemCodeStateConflict, + ProblemCodePayloadTooLarge, + ProblemCodeUnsupportedMediaType, + ProblemCodeIdempotencyKeyReused, + ProblemCodeInternal, + ProblemCodeNotImplemented, + ProblemCodeLabPoolBusy, + ProblemCodeLabUnavailable, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemCode) MarshalText() ([]byte, error) { + switch s { + case ProblemCodeValidationFailed: + return []byte(s), nil + case ProblemCodeUnauthenticated: + return []byte(s), nil + case ProblemCodeNotFound: + return []byte(s), nil + case ProblemCodeMethodNotAllowed: + return []byte(s), nil + case ProblemCodeStateConflict: + return []byte(s), nil + case ProblemCodePayloadTooLarge: + return []byte(s), nil + case ProblemCodeUnsupportedMediaType: + return []byte(s), nil + case ProblemCodeIdempotencyKeyReused: + return []byte(s), nil + case ProblemCodeInternal: + return []byte(s), nil + case ProblemCodeNotImplemented: + return []byte(s), nil + case ProblemCodeLabPoolBusy: + return []byte(s), nil + case ProblemCodeLabUnavailable: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemCode) UnmarshalText(data []byte) error { + switch ProblemCode(data) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + return nil + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + return nil + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + return nil + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + return nil + case ProblemCodeStateConflict: + *s = ProblemCodeStateConflict + return nil + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + return nil + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + return nil + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + return nil + case ProblemCodeInternal: + *s = ProblemCodeInternal + return nil + case ProblemCodeNotImplemented: + *s = ProblemCodeNotImplemented + return nil + case ProblemCodeLabPoolBusy: + *s = ProblemCodeLabPoolBusy + return nil + case ProblemCodeLabUnavailable: + *s = ProblemCodeLabUnavailable + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One reason why a request field or parameter is invalid. +// Ref: #/components/schemas/ProblemFieldError +type ProblemFieldError struct { + In ProblemFieldLocation `json:"in"` + // JSON Pointer (RFC 6901). For `body` it points into the request body document, for example + // `/ttl_seconds`; an empty string means the whole body. For a parameter it is `/` followed by the + // parameter name, for example `/lab_id`. + Pointer string `json:"pointer"` + // Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or + // a value outside the schema). Clients must tolerate new values. + Code string `json:"code"` + // Fixed English message that never echoes the submitted value. + Message string `json:"message"` +} + +// GetIn returns the value of In. +func (s *ProblemFieldError) GetIn() ProblemFieldLocation { + return s.In +} + +// GetPointer returns the value of Pointer. +func (s *ProblemFieldError) GetPointer() string { + return s.Pointer +} + +// GetCode returns the value of Code. +func (s *ProblemFieldError) GetCode() string { + return s.Code +} + +// GetMessage returns the value of Message. +func (s *ProblemFieldError) GetMessage() string { + return s.Message +} + +// SetIn sets the value of In. +func (s *ProblemFieldError) SetIn(val ProblemFieldLocation) { + s.In = val +} + +// SetPointer sets the value of Pointer. +func (s *ProblemFieldError) SetPointer(val string) { + s.Pointer = val +} + +// SetCode sets the value of Code. +func (s *ProblemFieldError) SetCode(val string) { + s.Code = val +} + +// SetMessage sets the value of Message. +func (s *ProblemFieldError) SetMessage(val string) { + s.Message = val +} + +// Part of the request that contains the invalid field. +// Ref: #/components/schemas/ProblemFieldLocation +type ProblemFieldLocation string + +const ( + ProblemFieldLocationBody ProblemFieldLocation = "body" + ProblemFieldLocationQuery ProblemFieldLocation = "query" + ProblemFieldLocationPath ProblemFieldLocation = "path" + ProblemFieldLocationHeader ProblemFieldLocation = "header" + ProblemFieldLocationCookie ProblemFieldLocation = "cookie" +) + +// AllValues returns all ProblemFieldLocation values. +func (ProblemFieldLocation) AllValues() []ProblemFieldLocation { + return []ProblemFieldLocation{ + ProblemFieldLocationBody, + ProblemFieldLocationQuery, + ProblemFieldLocationPath, + ProblemFieldLocationHeader, + ProblemFieldLocationCookie, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemFieldLocation) MarshalText() ([]byte, error) { + switch s { + case ProblemFieldLocationBody: + return []byte(s), nil + case ProblemFieldLocationQuery: + return []byte(s), nil + case ProblemFieldLocationPath: + return []byte(s), nil + case ProblemFieldLocationHeader: + return []byte(s), nil + case ProblemFieldLocationCookie: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemFieldLocation) UnmarshalText(data []byte) error { + switch ProblemFieldLocation(data) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + return nil + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + return nil + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + return nil + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + return nil + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// ProblemStatusCode wraps Problem with StatusCode. +type ProblemStatusCode struct { + StatusCode int + Response Problem +} + +// GetStatusCode returns the value of StatusCode. +func (s *ProblemStatusCode) GetStatusCode() int { + return s.StatusCode +} + +// GetResponse returns the value of Response. +func (s *ProblemStatusCode) GetResponse() Problem { + return s.Response +} + +// SetStatusCode sets the value of StatusCode. +func (s *ProblemStatusCode) SetStatusCode(val int) { + s.StatusCode = val +} + +// SetResponse sets the value of Response. +func (s *ProblemStatusCode) SetResponse(val Problem) { + s.Response = val +} + +type TemplateId string diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_security_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_security_gen.go new file mode 100644 index 0000000..0dafe26 --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_security_gen.go @@ -0,0 +1,58 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" + "net/http" + + "github.com/go-faster/errors" +) + +// SecuritySource is provider of security values (tokens, passwords, etc.). +type SecuritySource interface { + // BearerAuth provides bearerAuth security value. + // Shared random service token sent as `Authorization: Bearer ` over TLS. `labd` compares it in + // constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user + // tokens. + BearerAuth(ctx context.Context, operationName OperationName) (BearerAuth, error) +} + +// operationRolesBearerAuth is a private map storing roles per operation. +var operationRolesBearerAuth = map[string][]string{ + CheckLabOperation: []string{}, + CreateLabOperation: []string{}, + CreateLabConsoleTokenOperation: []string{}, + DeleteLabOperation: []string{}, + GetLabOperation: []string{}, +} + +// GetRolesForBearerAuth returns the required roles for the given operation. +// +// This is useful for authorization scenarios where you need to know which roles +// are required for an operation. +// +// Example: +// +// requiredRoles := GetRolesForBearerAuth(AddPetOperation) +// +// Returns nil if the operation has no role requirements or if the operation is unknown. +func GetRolesForBearerAuth(operation string) []string { + roles, ok := operationRolesBearerAuth[operation] + if !ok { + return nil + } + // Return a copy to prevent external modification + result := make([]string, len(roles)) + copy(result, roles) + return result +} + +func (s *Client) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) error { + t, err := s.sec.BearerAuth(ctx, operationName) + if err != nil { + return errors.Wrap(err, "security source \"BearerAuth\"") + } + req.Header.Set("Authorization", "Bearer "+t.Token) + return nil +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/api/oas_validators_gen.go b/backend/internal/adapter/secondary/lab_provisioner/api/oas_validators_gen.go new file mode 100644 index 0000000..02e4206 --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/api/oas_validators_gen.go @@ -0,0 +1,1127 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "fmt" + + "github.com/go-faster/errors" + "github.com/ogen-go/ogen/validate" +) + +func (s *ConsoleToken) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 43, + MinLengthSet: true, + MaxLength: 43, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]{43}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Token)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "token", + Error: err, + }) + } + if err := func() error { + if err := s.Node.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "node", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^/v1/labs/[0-9a-f-]{36}/console$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.AttachPath)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "attach_path", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ConsoleTokenHeaders) 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 *ConsoleTokenRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Node.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "node", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CreateLabAccepted) Validate() error { + alias := (*LabStatus)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s CreateLabConsoleTokenCreatedCacheControl) Validate() error { + switch s { + case "no-store": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *CreateLabOK) Validate() error { + alias := (*LabStatus)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s CriterionId) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 32, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z0-9][a-z0-9_-]{0,31}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *CriterionResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *DeleteLabAccepted) Validate() error { + alias := (*LabStatus)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *DeleteLabOK) Validate() error { + alias := (*LabStatus)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetLabdReadyzOK) Validate() error { + alias := (*LabdReadinessResponse)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetLabdReadyzServiceUnavailable) Validate() error { + alias := (*LabdReadinessResponse)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *LabCheckResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 50, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Score)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "score", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 50, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MaxScore)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_score", + Error: err, + }) + } + if err := func() error { + if s.Criteria == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 50, + MaxLengthSet: true, + }).ValidateLength(len(s.Criteria)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Criteria { + 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: "criteria", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *LabCreateRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.TemplateID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "template_id", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 10000, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TemplateVersion)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "template_version", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 64, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[0-9a-f]{64}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Seed)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "seed", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 300, + MaxSet: true, + Max: 14400, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TTLSeconds)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "ttl_seconds", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s LabFailureReason) Validate() error { + switch s { + case "provisioning_failed": + return nil + case "provisioning_timed_out": + return nil + case "interrupted": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *LabNode) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Name.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "name", + Error: err, + }) + } + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *LabPoolBusyHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 3600, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.RetryAfter)); err != nil { + return errors.Wrap(err, "int") + } + 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 LabState) Validate() error { + switch s { + case "provisioning": + return nil + case "ready": + return nil + case "deleting": + return nil + case "deleted": + return nil + case "failed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *LabStatus) 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 err := s.TemplateID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "template_id", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 10000, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TemplateVersion)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "template_version", + 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 s.Nodes == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 8, + MaxLengthSet: true, + }).ValidateLength(len(s.Nodes)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Nodes { + 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: "nodes", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *LabdHealthResponse) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s LabdHealthResponseStatus) Validate() error { + switch s { + case "ok": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *LabdReadinessResponse) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s LabdReadinessResponseStatus) Validate() error { + switch s { + case "ready": + return nil + case "not_ready": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s NodeKind) Validate() error { + switch s { + case "mikrotik": + return nil + case "ubuntu": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s NodeName) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 15, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z][a-z0-9-]{0,14}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *Problem) 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: 256, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Type)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 400, + MaxSet: true, + Max: 599, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Status)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Detail.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "detail", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Instance.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: "instance", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TraceID.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "trace_id", + Error: err, + }) + } + if err := func() error { + if s.Errors == nil { + return nil // optional + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Errors)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Errors { + 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: "errors", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemCode) Validate() error { + switch s { + case "validation_failed": + return nil + case "unauthenticated": + return nil + case "not_found": + return nil + case "method_not_allowed": + return nil + case "state_conflict": + return nil + case "payload_too_large": + return nil + case "unsupported_media_type": + return nil + case "idempotency_key_reused": + return nil + case "internal": + return nil + case "not_implemented": + return nil + case "lab_pool_busy": + return nil + case "lab_unavailable": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemFieldError) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.In.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "in", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1024, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^(/([^~/]|~[01])*)*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Pointer)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "pointer", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z][a-z0-9_]*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Code)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 500, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Message)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "message", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemFieldLocation) Validate() error { + switch s { + case "body": + return nil + case "query": + return nil + case "path": + return nil + case "header": + return nil + case "cookie": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemStatusCode) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + 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 TemplateId) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 48, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z0-9][a-z0-9-]{0,47}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/disabled/provisioner.go b/backend/internal/adapter/secondary/lab_provisioner/disabled/provisioner.go new file mode 100644 index 0000000..e07ca24 --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/disabled/provisioner.go @@ -0,0 +1,67 @@ +// Package disabled provides the lab provisioner for an unset +// LAB_PROVISIONER_URL. +package disabled + +import ( + "context" + "fmt" + + "github.com/google/uuid" + + "lincodex/backend/internal/port/outbound" +) + +// Provisioner creates nothing. Every valid call is reported as +// outbound.ErrLabProvisionerDisabled, never as a lab, a busy pool, or a check +// result, so a caller cannot start or score a lab while labs are off. +type Provisioner struct{} + +var _ outbound.LabProvisioner = (*Provisioner)(nil) + +func NewProvisioner() *Provisioner { + return &Provisioner{} +} + +// Create validates the request first so that local runs without a +// provisioner still expose invalid task content, then reports the +// provisioner as disabled. It keeps no copy of the seed. +func (provisioner *Provisioner) Create(_ context.Context, request outbound.LabRequest) (outbound.LabStatus, error) { + if err := request.Validate(); err != nil { + return outbound.LabStatus{}, fmt.Errorf("Provisioner.Create - validate request: %w", err) + } + return outbound.LabStatus{}, disabled("Provisioner.Create") +} + +// Status reports the provisioner as disabled. +func (provisioner *Provisioner) Status(_ context.Context, key outbound.LabKey) (outbound.LabStatus, error) { + return outbound.LabStatus{}, refuse("Provisioner.Status", key) +} + +// Delete reports the provisioner as disabled. +func (provisioner *Provisioner) Delete(_ context.Context, key outbound.LabKey) (outbound.LabStatus, error) { + return outbound.LabStatus{}, refuse("Provisioner.Delete", key) +} + +// ConsoleToken reports the provisioner as disabled. +func (provisioner *Provisioner) ConsoleToken(_ context.Context, key outbound.LabKey, node string) (outbound.LabConsoleToken, error) { + if err := outbound.ValidateLabNodeName(node); err != nil { + return outbound.LabConsoleToken{}, fmt.Errorf("Provisioner.ConsoleToken - validate node: %w", err) + } + return outbound.LabConsoleToken{}, refuse("Provisioner.ConsoleToken", key) +} + +// Check reports the provisioner as disabled. It is never a failed check. +func (provisioner *Provisioner) Check(_ context.Context, key outbound.LabKey) (outbound.LabCheckResult, error) { + return outbound.LabCheckResult{}, refuse("Provisioner.Check", key) +} + +func refuse(location string, key outbound.LabKey) error { + if key.AttemptItemID == uuid.Nil { + return fmt.Errorf("%s - key must name the attempt item: %w", location, outbound.ErrInvalidLabRequest) + } + return disabled(location) +} + +func disabled(location string) error { + return fmt.Errorf("%s - LAB_PROVISIONER_URL is not set: %w", location, outbound.ErrLabProvisionerDisabled) +} diff --git a/backend/internal/adapter/secondary/lab_provisioner/disabled/provisioner_test.go b/backend/internal/adapter/secondary/lab_provisioner/disabled/provisioner_test.go new file mode 100644 index 0000000..e43684c --- /dev/null +++ b/backend/internal/adapter/secondary/lab_provisioner/disabled/provisioner_test.go @@ -0,0 +1,64 @@ +package disabled_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/lab_provisioner/disabled" + "lincodex/backend/internal/port/outbound" +) + +func TestDisabledProvisionerReportsUnavailableForEveryCall(t *testing.T) { + provisioner := disabled.NewProvisioner() + ctx := context.Background() + key := outbound.LabKey{AttemptItemID: uuid.New()} + request := outbound.LabRequest{ + Key: key, + Template: outbound.LabTemplateRef{ID: "ubuntu-dns", Version: 1}, + Seed: outbound.LabSeed{1}, + Lifetime: 30 * time.Minute, + } + + status, err := provisioner.Create(ctx, request) + assertDisabled(t, "Create", err) + if status.State != "" { + t.Fatalf("Create() state = %q, want none", status.State) + } + _, err = provisioner.Status(ctx, key) + assertDisabled(t, "Status", err) + _, err = provisioner.Delete(ctx, key) + assertDisabled(t, "Delete", err) + _, err = provisioner.ConsoleToken(ctx, key, "r1") + assertDisabled(t, "ConsoleToken", err) + result, err := provisioner.Check(ctx, key) + assertDisabled(t, "Check", err) + if result.MaxScore != 0 || len(result.Criteria) != 0 { + t.Fatal("Check() returned a result while disabled") + } +} + +func TestDisabledProvisionerStillRejectsInvalidInput(t *testing.T) { + provisioner := disabled.NewProvisioner() + ctx := context.Background() + if _, err := provisioner.Create(ctx, outbound.LabRequest{}); !errors.Is(err, outbound.ErrInvalidLabRequest) { + t.Fatalf("Create() error = %v, want ErrInvalidLabRequest", err) + } + if _, err := provisioner.Status(ctx, outbound.LabKey{}); !errors.Is(err, outbound.ErrInvalidLabRequest) { + t.Fatalf("Status() error = %v, want ErrInvalidLabRequest", err) + } + key := outbound.LabKey{AttemptItemID: uuid.New()} + if _, err := provisioner.ConsoleToken(ctx, key, "Router 1"); !errors.Is(err, outbound.ErrInvalidLabRequest) { + t.Fatalf("ConsoleToken() error = %v, want ErrInvalidLabRequest", err) + } +} + +func assertDisabled(t *testing.T, method string, err error) { + t.Helper() + if !errors.Is(err, outbound.ErrLabProvisionerDisabled) || !errors.Is(err, outbound.ErrLabProvisionerUnavailable) { + t.Fatalf("%s() error = %v, want ErrLabProvisionerDisabled", method, err) + } +} diff --git a/backend/internal/port/outbound/lab_provisioner.go b/backend/internal/port/outbound/lab_provisioner.go new file mode 100644 index 0000000..e90257d --- /dev/null +++ b/backend/internal/port/outbound/lab_provisioner.go @@ -0,0 +1,374 @@ +package outbound + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "log/slog" + "regexp" + "time" + + "github.com/google/uuid" +) + +// Bounds of the lab provisioner contract (api/labd). They are checked before +// a request leaves the process, so a task family that breaks one fails in the +// caller's tests instead of as a provisioner rejection in production. +const ( + // MaxLabNodes and MaxLabCriteria also bound a response. + MaxLabNodes = 8 + MaxLabCriteria = 50 + + // MinLabLifetime and MaxLabLifetime bound LabRequest.Lifetime. The + // provisioner may configure a lower maximum. + MinLabLifetime = 5 * time.Minute + MaxLabLifetime = 4 * time.Hour + + // LabSeedBytes is the size of a variant seed. + LabSeedBytes = 32 + + maxLabTemplateVersion = 10000 + redactedLabRequest = "[redacted lab request]" + redactedLabSeed = "[redacted lab seed]" + redactedConsoleAccess = "[redacted lab console token]" + redactedLabCheckResult = "[lab check result]" +) + +var ( + // ErrLabProvisionerUnavailable is the umbrella of every failure that + // leaves a lab operation without an answer although the candidate did + // nothing wrong: the provisioner is disabled, unreachable, too slow, + // refuses the service token, fails with a server error, answers outside + // the contract, or reports that LXD or a node could not be reached. A + // check that ends with it evaluated nothing: the caller must never score + // it as a failed check, and it reports the service as unavailable. Check + // it with errors.Is before the specific errors below. + // + // A busy lab pool is not this error: Create reports it as LabBusy. + ErrLabProvisionerUnavailable = errors.New("lab provisioner unavailable") + + // ErrLabProvisionerDisabled means LAB_PROVISIONER_URL is not set, so no + // request was made. + ErrLabProvisionerDisabled = fmt.Errorf("lab provisioner is disabled: %w", ErrLabProvisionerUnavailable) + + // ErrLabProvisionerUnauthorized means the provisioner refused the + // service token (401). It points at deployment configuration and needs an + // operator, not a retry. + ErrLabProvisionerUnauthorized = fmt.Errorf("lab provisioner refused the service token: %w", ErrLabProvisionerUnavailable) + + // ErrLabProvisionerBadResponse means the provisioner answered, but not as + // the contract says: a malformed body, an unexpected status, or a status + // that contradicts the request or itself. + ErrLabProvisionerBadResponse = fmt.Errorf("lab provisioner answered outside its contract: %w", ErrLabProvisionerUnavailable) + + // ErrInvalidLabRequest reports a request that fails LabRequest.Validate, + // or that the provisioner rejected as invalid (400), for example an + // unknown template version. It is a caller or task content bug; nothing + // was created. + ErrInvalidLabRequest = errors.New("invalid lab request") + + // ErrLabNotFound means the provisioner does not hold the lab: it was + // never created, or its deleted record outlived the retention time. + ErrLabNotFound = errors.New("lab not found") + + // ErrLabKeyReused means the provisioner already holds a lab under this + // key with a different payload (422). The caller bumps LabKey.Generation + // for a new lab. + ErrLabKeyReused = errors.New("lab key reused with another payload") + + // ErrLabNotReady means the lab is not ready for a console token or a + // check (409): it is still provisioning, or it is being deleted, deleted, + // or failed. Read its status. + ErrLabNotReady = errors.New("lab is not ready") +) + +var ( + labTemplateIDPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,47}$`) + labNodeNamePattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,14}$`) +) + +// LabKey identifies one lab of an attempt item. The adapter turns it into +// the opaque lab ID that the provisioner stores, so the provisioner never sees +// these values and every retry of the same key reaches the same lab. +type LabKey struct { + // AttemptItemID is the attempt item whose lab this is. + AttemptItemID uuid.UUID + // Generation is 0 for the first lab of the item. After a failed lab the + // caller increments it; the provisioner would return the failed lab for + // the old key. + Generation uint32 +} + +func (key LabKey) validate() error { + if key.AttemptItemID == uuid.Nil { + return invalidLabRequest("key must name the attempt item") + } + return nil +} + +// LabTemplateRef names a template of the provisioner build. +type LabTemplateRef struct { + ID string + Version int32 +} + +// LabSeed is the variant seed of an item instance. The template renders the +// node configuration and the checker criteria of the variant from it, so it +// is as secret as an answer key: String, GoString, Format, and LogValue +// redact it. Hex returns the wire form. +type LabSeed [LabSeedBytes]byte + +func (seed LabSeed) Hex() string { return hex.EncodeToString(seed[:]) } + +func (seed LabSeed) String() string { return redactedLabSeed } + +func (seed LabSeed) GoString() string { return redactedLabSeed } + +// Format redacts every verb; without it %x would print the bytes. +func (seed LabSeed) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(redactedLabSeed)) +} + +func (seed LabSeed) LogValue() slog.Value { return slog.StringValue(redactedLabSeed) } + +// LabRequest asks for one lab of a template variant. It carries nothing about +// the candidate: the provisioner receives only a template reference, a seed, +// and a lifetime. The whole request is redacted when printed or logged +// because it holds the seed. +type LabRequest struct { + Key LabKey + Template LabTemplateRef + Seed LabSeed + // Lifetime counts from the creation of the lab. The provisioner deletes + // the lab when it ends, also across its own restarts. + Lifetime time.Duration +} + +func (request LabRequest) String() string { return redactedLabRequest } + +func (request LabRequest) GoString() string { return redactedLabRequest } + +// Format redacts every verb; without it %+v would print the fields. +func (request LabRequest) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(redactedLabRequest)) +} + +func (request LabRequest) LogValue() slog.Value { return slog.StringValue(redactedLabRequest) } + +// Validate reports a request that the provisioner would reject by its +// contract. Errors wrap ErrInvalidLabRequest and never include the seed. +func (request LabRequest) Validate() error { + if err := request.Key.validate(); err != nil { + return err + } + switch { + case !labTemplateIDPattern.MatchString(request.Template.ID): + return invalidLabRequest("template ID must match [a-z0-9][a-z0-9-]{0,47}") + case request.Template.Version < 1 || request.Template.Version > maxLabTemplateVersion: + return invalidLabRequest("template version must be 1 to 10000") + case request.Seed == (LabSeed{}): + return invalidLabRequest("seed must not be zero") + case request.Lifetime < MinLabLifetime || request.Lifetime > MaxLabLifetime: + return invalidLabRequest("lifetime must be 5 minutes to 4 hours") + case request.Lifetime%time.Second != 0: + return invalidLabRequest("lifetime must be whole seconds") + } + return nil +} + +// ValidateLabNodeName reports a node name that the contract does not allow. +func ValidateLabNodeName(name string) error { + if !labNodeNamePattern.MatchString(name) { + return fmt.Errorf("outbound.ValidateLabNodeName - node name must match [a-z][a-z0-9-]{0,14}: %w", ErrInvalidLabRequest) + } + return nil +} + +func invalidLabRequest(reason string) error { + return fmt.Errorf("LabRequest.Validate - %s: %w", reason, ErrInvalidLabRequest) +} + +// LabState is what a provisioner call established about a lab. The zero +// value is not a state and must never be read as readiness. +type LabState string + +const ( + // LabProvisioning means capacity is reserved and the nodes are being + // prepared. Poll Status later. + LabProvisioning LabState = "provisioning" + // LabReady means every node answers; console tokens and checks work. + LabReady LabState = "ready" + // LabDeleting means the lab ended and its resources are being removed. + LabDeleting LabState = "deleting" + // LabDeleted means every resource of the lab is gone. + LabDeleted LabState = "deleted" + // LabFailed means the provisioning failed for an infrastructure reason; + // FailureReason says which. It never depends on the candidate. Its + // resources are removed; the caller starts a new lab with the next + // LabKey.Generation. + LabFailed LabState = "failed" + // LabBusy means the lab does not fit the capacity of the provisioner, or + // the provisioner is draining. Nothing was stored and nothing of the + // attempt is consumed; create again with the same key after RetryAfter. + // Only Create reports it, and it is a capacity signal, never an + // infrastructure failure. + LabBusy LabState = "busy" +) + +// LabFailureReason says why a lab failed. +type LabFailureReason string + +const ( + LabFailureProvisioning LabFailureReason = "provisioning_failed" + LabFailureTimedOut LabFailureReason = "provisioning_timed_out" + LabFailureInterrupted LabFailureReason = "interrupted" +) + +// LabNodeKind is the guest system of a node. +type LabNodeKind string + +const ( + LabNodeMikroTik LabNodeKind = "mikrotik" + LabNodeUbuntu LabNodeKind = "ubuntu" +) + +// LabNode is a node of a lab by its template name. It never carries an +// address or a credential: the backend reaches a node only through a console +// token, and the provisioner checks it itself. +type LabNode struct { + Name string + Kind LabNodeKind +} + +// LabStatus is the state of a lab after one provisioner call. +type LabStatus struct { + State LabState + + // LabID is the opaque ID the provisioner holds the lab under. It + // identifies no user, attempt, or task; it is safe to log and matches the + // provisioner's logs. + LabID string + + // RetryAfter is the provisioner's wait hint for LabBusy only. + RetryAfter time.Duration + + // The fields below are set for every state except LabBusy. ReadyAt, + // DeletedAt, and FailureReason are zero until they apply. + Template LabTemplateRef + CreatedAt time.Time + ReadyAt time.Time + ExpiresAt time.Time + DeletedAt time.Time + FailureReason LabFailureReason + Nodes []LabNode +} + +// Active reports whether the lab holds or is about to hold resources that a +// candidate can use. +func (status LabStatus) Active() bool { + return status.State == LabProvisioning || status.State == LabReady +} + +// LabConsoleToken lets the console gateway attach to the serial console of +// one node once. The token is a secret of the gateway: String, GoString, +// Format, and LogValue redact it, and it must never reach a browser or a log. +type LabConsoleToken struct { + Token string + Node string + ExpiresAt time.Time + AttachPath string +} + +func (token LabConsoleToken) String() string { return redactedConsoleAccess } + +func (token LabConsoleToken) GoString() string { return redactedConsoleAccess } + +// Format redacts every verb; without it %+v would print the token. +func (token LabConsoleToken) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(redactedConsoleAccess)) +} + +func (token LabConsoleToken) LogValue() slog.Value { return slog.StringValue(redactedConsoleAccess) } + +// LabCriterionResult says whether one criterion of the variant holds. +type LabCriterionResult struct { + ID string + Passed bool +} + +// LabCheckResult is a validated check of a ready lab. It is checker state for +// scoring only and must never reach the candidate. +type LabCheckResult struct { + CheckedAt time.Time + Score int + MaxScore int + Criteria []LabCriterionResult +} + +// Validate reports a result that contradicts itself, so a malformed answer +// of the provisioner can never become a score. +func (result LabCheckResult) Validate() error { + if len(result.Criteria) < 1 || len(result.Criteria) > MaxLabCriteria { + return errors.New("LabCheckResult.Validate - criteria must have 1 to 50 entries") + } + passed := 0 + seen := make(map[string]struct{}, len(result.Criteria)) + for _, criterion := range result.Criteria { + if _, duplicate := seen[criterion.ID]; duplicate || criterion.ID == "" { + return errors.New("LabCheckResult.Validate - criterion IDs must be unique and not empty") + } + seen[criterion.ID] = struct{}{} + if criterion.Passed { + passed++ + } + } + if result.MaxScore != len(result.Criteria) || result.Score != passed { + return errors.New("LabCheckResult.Validate - score must count the passed criteria") + } + if result.CheckedAt.IsZero() { + return errors.New("LabCheckResult.Validate - check time must be set") + } + return nil +} + +// LogValue summarizes the result without criterion IDs, which describe the +// variant. +func (result LabCheckResult) LogValue() slog.Value { + return slog.GroupValue(slog.Int("score", result.Score), slog.Int("max_score", result.MaxScore)) +} + +func (result LabCheckResult) String() string { return redactedLabCheckResult } + +// LabProvisioner creates, inspects, checks, and deletes practical labs +// through the lab provisioner service (api/labd). Only that service talks to +// LXD; the backend never holds the LXD socket or a node address. +// +// Every method makes exactly one provisioner call and never retries or +// sleeps; polling and backoff belong to the caller. Create is idempotent by +// request.Key: the same key with the same payload returns the current state +// of one lab and never creates a second one. +// +// A nil error from Create comes with provisioning, ready, deleting, deleted, +// failed, or busy. Busy holds RetryAfter, stores nothing, and is the only +// capacity outcome; it is never an error. An error means that nothing +// happened that the caller may rely on: +// - ErrInvalidLabRequest: the request is invalid or unknown to the +// provisioner; nothing was created. +// - ErrLabProvisionerUnavailable (including the disabled, unauthorized, +// and bad-response forms): no answer could be obtained. For Check it is +// never a failed check and never a reason to fail the candidate. +// - ErrLabNotFound: the provisioner does not hold the lab. +// - ErrLabKeyReused (Create): the key was used with another payload. +// - ErrLabNotReady (ConsoleToken, Check): the lab is not ready. +// - the context error when ctx ended. +// +// The returned values are zero when err is not nil. Errors and logs never +// include the seed, a console token, or the service token. +type LabProvisioner interface { + Create(ctx context.Context, request LabRequest) (LabStatus, error) + Status(ctx context.Context, key LabKey) (LabStatus, error) + Delete(ctx context.Context, key LabKey) (LabStatus, error) + ConsoleToken(ctx context.Context, key LabKey, node string) (LabConsoleToken, error) + Check(ctx context.Context, key LabKey) (LabCheckResult, error) +} diff --git a/backend/internal/port/outbound/lab_provisioner_test.go b/backend/internal/port/outbound/lab_provisioner_test.go new file mode 100644 index 0000000..593ae7b --- /dev/null +++ b/backend/internal/port/outbound/lab_provisioner_test.go @@ -0,0 +1,172 @@ +package outbound_test + +import ( + "errors" + "fmt" + "log/slog" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/port/outbound" +) + +func validLabRequest() outbound.LabRequest { + var seed outbound.LabSeed + for index := range seed { + seed[index] = byte(0xa0 + index%16) + } + return outbound.LabRequest{ + Key: outbound.LabKey{AttemptItemID: uuid.New()}, + Template: outbound.LabTemplateRef{ID: "mikrotik-ospf-pair", Version: 1}, + Seed: seed, + Lifetime: 45 * time.Minute, + } +} + +func TestLabRequestValidateAcceptsAContractRequest(t *testing.T) { + if err := validLabRequest().Validate(); err != nil { + t.Fatalf("Validate() error = %v", err) + } +} + +func TestLabRequestValidateRejectsWhatTheProvisionerRejects(t *testing.T) { + tests := []struct { + name string + change func(*outbound.LabRequest) + }{ + {"no attempt item", func(r *outbound.LabRequest) { r.Key.AttemptItemID = uuid.Nil }}, + {"empty template", func(r *outbound.LabRequest) { r.Template.ID = "" }}, + {"template with capitals", func(r *outbound.LabRequest) { r.Template.ID = "MikroTik" }}, + {"template too long", func(r *outbound.LabRequest) { r.Template.ID = strings.Repeat("a", 49) }}, + {"template version zero", func(r *outbound.LabRequest) { r.Template.Version = 0 }}, + {"template version above range", func(r *outbound.LabRequest) { r.Template.Version = 10001 }}, + {"zero seed", func(r *outbound.LabRequest) { r.Seed = outbound.LabSeed{} }}, + {"lifetime below range", func(r *outbound.LabRequest) { r.Lifetime = 4 * time.Minute }}, + {"lifetime above range", func(r *outbound.LabRequest) { r.Lifetime = 4*time.Hour + time.Second }}, + {"lifetime with a fraction of a second", func(r *outbound.LabRequest) { r.Lifetime = 10*time.Minute + time.Millisecond }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + request := validLabRequest() + test.change(&request) + err := request.Validate() + if !errors.Is(err, outbound.ErrInvalidLabRequest) { + t.Fatalf("Validate() error = %v, want ErrInvalidLabRequest", err) + } + }) + } +} + +func TestLabRequestAndSeedNeverPrintTheSeed(t *testing.T) { + request := validLabRequest() + seedHex := request.Seed.Hex() + if len(seedHex) != 2*outbound.LabSeedBytes { + t.Fatalf("Hex() length = %d", len(seedHex)) + } + var logged strings.Builder + logger := slog.New(slog.NewJSONHandler(&logged, nil)) + logger.Info("lab", slog.Any("request", request), slog.Any("seed", request.Seed)) + printed := []string{ + fmt.Sprint(request), fmt.Sprintf("%+v", request), fmt.Sprintf("%#v", request), + fmt.Sprintf("%x", request.Seed), fmt.Sprintf("%v", request.Seed), logged.String(), + } + for _, text := range printed { + if strings.Contains(text, seedHex) || strings.Contains(text, "mikrotik-ospf-pair") { + t.Fatalf("printed form leaks the request: %q", text) + } + } +} + +func TestLabConsoleTokenIsRedacted(t *testing.T) { + token := outbound.LabConsoleToken{Token: "console-token-marker", Node: "r1", AttachPath: "/v1/labs/x/console"} + var logged strings.Builder + slog.New(slog.NewJSONHandler(&logged, nil)).Info("token", slog.Any("token", token)) + for _, text := range []string{fmt.Sprint(token), fmt.Sprintf("%+v", token), fmt.Sprintf("%#v", token), logged.String()} { + if strings.Contains(text, "console-token-marker") { + t.Fatalf("printed form leaks the token: %q", text) + } + } +} + +func TestBusyIsACapacityStateAndNotAnInfrastructureError(t *testing.T) { + busy := outbound.LabStatus{State: outbound.LabBusy, RetryAfter: 30 * time.Second} + if busy.Active() { + t.Fatal("a busy answer holds no lab") + } + for _, err := range []error{ + outbound.ErrLabProvisionerDisabled, + outbound.ErrLabProvisionerUnauthorized, + outbound.ErrLabProvisionerBadResponse, + } { + if !errors.Is(err, outbound.ErrLabProvisionerUnavailable) { + t.Fatalf("%v must be an unavailable provisioner", err) + } + } + for _, err := range []error{ + outbound.ErrInvalidLabRequest, outbound.ErrLabNotFound, + outbound.ErrLabKeyReused, outbound.ErrLabNotReady, + } { + if errors.Is(err, outbound.ErrLabProvisionerUnavailable) { + t.Fatalf("%v must not be an unavailable provisioner", err) + } + } +} + +func TestLabStatusActive(t *testing.T) { + for state, active := range map[outbound.LabState]bool{ + outbound.LabProvisioning: true, outbound.LabReady: true, + outbound.LabDeleting: false, outbound.LabDeleted: false, outbound.LabFailed: false, outbound.LabBusy: false, + } { + if got := (outbound.LabStatus{State: state}).Active(); got != active { + t.Fatalf("Active() for %s = %v, want %v", state, got, active) + } + } +} + +func TestValidateLabNodeName(t *testing.T) { + if err := outbound.ValidateLabNodeName("r1"); err != nil { + t.Fatalf("ValidateLabNodeName(r1) error = %v", err) + } + for _, name := range []string{"", "R1", "1r", "r_1", strings.Repeat("a", 16)} { + if err := outbound.ValidateLabNodeName(name); !errors.Is(err, outbound.ErrInvalidLabRequest) { + t.Fatalf("ValidateLabNodeName(%q) error = %v", name, err) + } + } +} + +func TestLabCheckResultValidate(t *testing.T) { + valid := outbound.LabCheckResult{ + CheckedAt: time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC), + Score: 1, MaxScore: 2, + Criteria: []outbound.LabCriterionResult{{ID: "ospf", Passed: true}, {ID: "ping", Passed: false}}, + } + if err := valid.Validate(); err != nil { + t.Fatalf("Validate() error = %v", err) + } + tests := []struct { + name string + change func(*outbound.LabCheckResult) + }{ + {"no criteria", func(r *outbound.LabCheckResult) { r.Criteria, r.Score, r.MaxScore = nil, 0, 0 }}, + {"score above passed", func(r *outbound.LabCheckResult) { r.Score = 2 }}, + {"max score not the count", func(r *outbound.LabCheckResult) { r.MaxScore = 3 }}, + {"duplicate criterion", func(r *outbound.LabCheckResult) { r.Criteria[1].ID = "ospf" }}, + {"no check time", func(r *outbound.LabCheckResult) { r.CheckedAt = time.Time{} }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result := valid + result.Criteria = append([]outbound.LabCriterionResult(nil), valid.Criteria...) + test.change(&result) + if err := result.Validate(); err == nil { + t.Fatal("Validate() accepted a contradictory result") + } + }) + } + if text := fmt.Sprint(valid); strings.Contains(text, "ospf") { + t.Fatalf("printed result leaks a criterion: %q", text) + } +} diff --git a/frontend/src/features/answer-assessment/model/answer-draft-store.ts b/frontend/src/features/answer-assessment/model/answer-draft-store.ts index e49a899..aa8b980 100644 --- a/frontend/src/features/answer-assessment/model/answer-draft-store.ts +++ b/frontend/src/features/answer-assessment/model/answer-draft-store.ts @@ -128,5 +128,7 @@ function parseStoredDraft(raw: string, item: AssessmentItem): AnswerDraft | null sourceCode: value.sourceCode, }; } + case "lab": + return { format: "lab" }; } } diff --git a/frontend/src/features/answer-assessment/model/answer-draft.test.ts b/frontend/src/features/answer-assessment/model/answer-draft.test.ts index fe57d01..fbb772c 100644 --- a/frontend/src/features/answer-assessment/model/answer-draft.test.ts +++ b/frontend/src/features/answer-assessment/model/answer-draft.test.ts @@ -75,4 +75,24 @@ describe("assessment answer submission", () => { buildAnswerSubmission(attempt, item, { format: "order", elementIds: ["one", "one"] }), ).toMatchObject({ ok: false }); }); + + it("never builds an answer for a lab item, which is submitted with its lab", () => { + const item = { + id: numberItem.id, + sequence: 1, + prompt: "Настройте OSPF между r1 и r2", + content: { + format: "lab", + nodes: [ + { name: "r1", kind: "mikrotik" }, + { name: "r2", kind: "mikrotik" }, + ], + time_limit_seconds: 2700, + }, + } satisfies AssessmentItem; + const draft = emptyAnswerDraft(item); + + expect(draft).toEqual({ format: "lab" }); + expect(buildAnswerSubmission(attempt, item, draft)).toMatchObject({ ok: false }); + }); }); diff --git a/frontend/src/features/answer-assessment/model/answer-draft.ts b/frontend/src/features/answer-assessment/model/answer-draft.ts index d774b83..0b615cf 100644 --- a/frontend/src/features/answer-assessment/model/answer-draft.ts +++ b/frontend/src/features/answer-assessment/model/answer-draft.ts @@ -12,7 +12,10 @@ export type AnswerDraft = | { format: "order"; elementIds: string[] } | { format: "find_error"; lineNumbers: number[] } | { format: "configuration"; value: string } - | { format: "practice"; language: "python" | "go" | null; sourceCode: string }; + | { format: "practice"; language: "python" | "go" | null; sourceCode: string } + // A lab item has no answer in this form: its lab is submitted with + // SubmitMyAssessmentLab. + | { format: "lab" }; export type AnswerBuildResult = { ok: true; body: string; submission: AnswerSubmission | null } | { ok: false; message: string }; @@ -36,6 +39,8 @@ export function emptyAnswerDraft(item: AssessmentItem): AnswerDraft { return { format: "configuration", value: item.content.initial_config }; case "practice": return { format: "practice", language: item.content.languages[0] ?? null, sourceCode: "" }; + case "lab": + return { format: "lab" }; } } @@ -125,6 +130,8 @@ export function buildAnswerSubmission( } answer = { format: "practice", language: draft.language, source_code: draft.sourceCode }; break; + case "lab": + return { ok: false, message: "Лабораторная работа сдается отдельно, не через эту форму." }; } if (!answer) return { ok: false, message: "Проверьте ответ и повторите отправку." }; diff --git a/frontend/src/features/answer-assessment/ui/answer-form.test.tsx b/frontend/src/features/answer-assessment/ui/answer-form.test.tsx index 7bd2e8a..91bf43a 100644 --- a/frontend/src/features/answer-assessment/ui/answer-form.test.tsx +++ b/frontend/src/features/answer-assessment/ui/answer-form.test.tsx @@ -36,6 +36,20 @@ const practiceItem = { }, } satisfies AssessmentItem; +const labItem = { + id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d05", + sequence: 4, + prompt: "Настройте OSPF", + content: { + format: "lab", + nodes: [ + { name: "r1", kind: "mikrotik" }, + { name: "srv", kind: "ubuntu" }, + ], + time_limit_seconds: 2700, + }, +} satisfies AssessmentItem; + function render(concealed: boolean, answered: AssessmentItem = item): string { return renderToStaticMarkup( { expect(render(false, practiceItem)).toContain('data-paste="allowed"'); expect(render(false, numberItem)).not.toContain("data-paste"); }); + + it("shows the nodes of a lab item and offers no answer submission", () => { + const markup = render(false, labItem); + expect(markup).toContain("r1 (MikroTik)"); + expect(markup).toContain("srv (Ubuntu)"); + expect(markup).not.toContain("Отправить ответ"); + expect(markup).not.toContain("; return (
@@ -111,6 +112,28 @@ export function AnswerForm({ ); } +type LabPlaceholderProps = { + nodes: { name: string; kind: "mikrotik" | "ubuntu" }[]; +}; + +// A lab item is worked on in its own lab, not answered in this form. Until +// the lab screen exists the page only names the nodes and sends nothing. +function LabPlaceholder({ nodes }: LabPlaceholderProps) { + return ( +
+

Это задание выполняется в лаборатории из узлов:

+
    + {nodes.map((node) => ( +
  • + {node.name} ({node.kind === "mikrotik" ? "MikroTik" : "Ubuntu"}) +
  • + ))} +
+

Открыть лабораторию из этой страницы пока нельзя.

+
+ ); +} + type AnswerFieldsProps = { item: AssessmentItem; draft: AnswerDraft; @@ -339,5 +362,8 @@ function AnswerFields({ item, draft, setDraft }: AnswerFieldsProps) { ); + case "lab": + // AnswerForm shows LabPlaceholder instead of the form. + return null; } } diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts index aacd02a..a90ca71 100644 --- a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts +++ b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts @@ -28,6 +28,8 @@ import type { AssessmentExpressAttempt, AssessmentExpressResult, AssessmentItem, + AssessmentLab, + AssessmentLabConsoleSession, AssessmentQualifiedAttempt, AssessmentQualifiedResult, AssessmentResult, @@ -41,6 +43,7 @@ import type { ChoiceItemContent, ConfigurationItemContent, FindErrorItemContent, + LabItemContent, NumberItemContent, OrderItemContent, PracticeItemContent, @@ -83,7 +86,9 @@ export const getCreateMyAssessmentAttemptResponseConfigurationItemContentMock = export const getCreateMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); -export const getCreateMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseChoiceItemContentMock()},{...getCreateMyAssessmentAttemptResponseNumberItemContentMock()},{...getCreateMyAssessmentAttemptResponseStringItemContentMock()},{...getCreateMyAssessmentAttemptResponseOrderItemContentMock()},{...getCreateMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getCreateMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getCreateMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse}); +export const getCreateMyAssessmentAttemptResponseLabItemContentMock = (overrideResponse: Partial = {}): LabItemContent => ({...{format: faker.helpers.arrayElement(['lab'] as const), nodes: Array.from({ length: faker.number.int({min: 1, max: 8}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), kind: faker.helpers.arrayElement(['mikrotik','ubuntu'] as const)})), time_limit_seconds: faker.number.int({min: 300, max: 14400})}, ...overrideResponse}); + +export const getCreateMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseChoiceItemContentMock()},{...getCreateMyAssessmentAttemptResponseNumberItemContentMock()},{...getCreateMyAssessmentAttemptResponseStringItemContentMock()},{...getCreateMyAssessmentAttemptResponseOrderItemContentMock()},{...getCreateMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getCreateMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getCreateMyAssessmentAttemptResponsePracticeItemContentMock()},{...getCreateMyAssessmentAttemptResponseLabItemContentMock()},])}, ...overrideResponse}); export const getCreateMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); @@ -111,7 +116,9 @@ export const getGetMyAssessmentAttemptResponseConfigurationItemContentMock = (ov export const getGetMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); -export const getGetMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseChoiceItemContentMock()},{...getGetMyAssessmentAttemptResponseNumberItemContentMock()},{...getGetMyAssessmentAttemptResponseStringItemContentMock()},{...getGetMyAssessmentAttemptResponseOrderItemContentMock()},{...getGetMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getGetMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getGetMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse}); +export const getGetMyAssessmentAttemptResponseLabItemContentMock = (overrideResponse: Partial = {}): LabItemContent => ({...{format: faker.helpers.arrayElement(['lab'] as const), nodes: Array.from({ length: faker.number.int({min: 1, max: 8}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), kind: faker.helpers.arrayElement(['mikrotik','ubuntu'] as const)})), time_limit_seconds: faker.number.int({min: 300, max: 14400})}, ...overrideResponse}); + +export const getGetMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseChoiceItemContentMock()},{...getGetMyAssessmentAttemptResponseNumberItemContentMock()},{...getGetMyAssessmentAttemptResponseStringItemContentMock()},{...getGetMyAssessmentAttemptResponseOrderItemContentMock()},{...getGetMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getGetMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getGetMyAssessmentAttemptResponsePracticeItemContentMock()},{...getGetMyAssessmentAttemptResponseLabItemContentMock()},])}, ...overrideResponse}); export const getGetMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); @@ -139,7 +146,9 @@ export const getStartMyAssessmentAttemptSessionResponseConfigurationItemContentM export const getStartMyAssessmentAttemptSessionResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); -export const getStartMyAssessmentAttemptSessionResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseChoiceItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseNumberItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseStringItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseOrderItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseFindErrorItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseConfigurationItemContentMock()},{...getStartMyAssessmentAttemptSessionResponsePracticeItemContentMock()},])}, ...overrideResponse}); +export const getStartMyAssessmentAttemptSessionResponseLabItemContentMock = (overrideResponse: Partial = {}): LabItemContent => ({...{format: faker.helpers.arrayElement(['lab'] as const), nodes: Array.from({ length: faker.number.int({min: 1, max: 8}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), kind: faker.helpers.arrayElement(['mikrotik','ubuntu'] as const)})), time_limit_seconds: faker.number.int({min: 300, max: 14400})}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseChoiceItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseNumberItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseStringItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseOrderItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseFindErrorItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseConfigurationItemContentMock()},{...getStartMyAssessmentAttemptSessionResponsePracticeItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseLabItemContentMock()},])}, ...overrideResponse}); export const getStartMyAssessmentAttemptSessionResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); @@ -171,7 +180,9 @@ export const getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock = ( export const getSubmitMyAssessmentAnswerResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); -export const getSubmitMyAssessmentAnswerResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseChoiceItemContentMock()},{...getSubmitMyAssessmentAnswerResponseNumberItemContentMock()},{...getSubmitMyAssessmentAnswerResponseStringItemContentMock()},{...getSubmitMyAssessmentAnswerResponseOrderItemContentMock()},{...getSubmitMyAssessmentAnswerResponseFindErrorItemContentMock()},{...getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock()},{...getSubmitMyAssessmentAnswerResponsePracticeItemContentMock()},])}, ...overrideResponse}); +export const getSubmitMyAssessmentAnswerResponseLabItemContentMock = (overrideResponse: Partial = {}): LabItemContent => ({...{format: faker.helpers.arrayElement(['lab'] as const), nodes: Array.from({ length: faker.number.int({min: 1, max: 8}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), kind: faker.helpers.arrayElement(['mikrotik','ubuntu'] as const)})), time_limit_seconds: faker.number.int({min: 300, max: 14400})}, ...overrideResponse}); + +export const getSubmitMyAssessmentAnswerResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseChoiceItemContentMock()},{...getSubmitMyAssessmentAnswerResponseNumberItemContentMock()},{...getSubmitMyAssessmentAnswerResponseStringItemContentMock()},{...getSubmitMyAssessmentAnswerResponseOrderItemContentMock()},{...getSubmitMyAssessmentAnswerResponseFindErrorItemContentMock()},{...getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock()},{...getSubmitMyAssessmentAnswerResponsePracticeItemContentMock()},{...getSubmitMyAssessmentAnswerResponseLabItemContentMock()},])}, ...overrideResponse}); export const getSubmitMyAssessmentAnswerResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); @@ -207,7 +218,9 @@ export const getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock export const getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); -export const getFinalizeMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseChoiceItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseNumberItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseStringItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseOrderItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse}); +export const getFinalizeMyAssessmentAttemptResponseLabItemContentMock = (overrideResponse: Partial = {}): LabItemContent => ({...{format: faker.helpers.arrayElement(['lab'] as const), nodes: Array.from({ length: faker.number.int({min: 1, max: 8}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), kind: faker.helpers.arrayElement(['mikrotik','ubuntu'] as const)})), time_limit_seconds: faker.number.int({min: 300, max: 14400})}, ...overrideResponse}); + +export const getFinalizeMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseChoiceItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseNumberItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseStringItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseOrderItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseLabItemContentMock()},])}, ...overrideResponse}); export const getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); @@ -231,6 +244,14 @@ export const getGetMyAssessmentResultResponseAssessmentExpressResultMock = (over export const getGetMyAssessmentResultResponseMock = (): AssessmentResult => (faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentQualifiedResultMock()},{...getGetMyAssessmentResultResponseAssessmentCorrectiveResultMock()},{...getGetMyAssessmentResultResponseAssessmentExpressResultMock()},])) +export const getCreateMyAssessmentLabResponseMock = (overrideResponse: Partial> = {}): AssessmentLab => (faker.helpers.arrayElement([{id: faker.string.uuid(), item_id: faker.string.uuid(), state: faker.helpers.arrayElement(['provisioning','ready','checking','submitted','expired','failed'] as const), nodes: Array.from({ length: faker.number.int({min: 1, max: 8}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), kind: faker.helpers.arrayElement(['mikrotik','ubuntu'] as const)})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ready_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), expires_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(['lab_error'] as const),null,]), ...overrideResponse}, {id: faker.string.uuid(), item_id: faker.string.uuid(), state: faker.helpers.arrayElement(['provisioning','ready','checking','submitted','expired','failed'] as const), nodes: Array.from({ length: faker.number.int({min: 1, max: 8}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), kind: faker.helpers.arrayElement(['mikrotik','ubuntu'] as const)})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ready_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), expires_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(['lab_error'] as const),null,]), ...overrideResponse}])) + +export const getGetMyAssessmentLabResponseMock = (overrideResponse: Partial> = {}): AssessmentLab => ({id: faker.string.uuid(), item_id: faker.string.uuid(), state: faker.helpers.arrayElement(['provisioning','ready','checking','submitted','expired','failed'] as const), nodes: Array.from({ length: faker.number.int({min: 1, max: 8}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), kind: faker.helpers.arrayElement(['mikrotik','ubuntu'] as const)})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ready_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), expires_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(['lab_error'] as const),null,]), ...overrideResponse}) + +export const getCreateMyAssessmentLabConsoleSessionResponseMock = (overrideResponse: Partial> = {}): AssessmentLabConsoleSession => ({id: faker.string.uuid(), node: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), websocket_path: fakeFromPattern("^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$", {maxLength: 128}), expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + +export const getSubmitMyAssessmentLabResponseMock = (overrideResponse: Partial> = {}): AssessmentLab => ({id: faker.string.uuid(), item_id: faker.string.uuid(), state: faker.helpers.arrayElement(['provisioning','ready','checking','submitted','expired','failed'] as const), nodes: Array.from({ length: faker.number.int({min: 1, max: 8}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^[a-z][a-z0-9-]{0,14}$", {minLength: 1, maxLength: 15}), kind: faker.helpers.arrayElement(['mikrotik','ubuntu'] as const)})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ready_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), expires_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(['lab_error'] as const),null,]), ...overrideResponse}) + export const getGetMyAssessmentAvailabilityMockHandler = (overrideResponse?: AssessmentAvailability | ((info: Parameters[1]>[0]) => Promise | AssessmentAvailability), options?: RequestHandlerOptions) => { return http.get('*/api/v1/me/assessment-availability', async (info: Parameters[1]>[0]) => { @@ -409,6 +430,54 @@ export const getGetMyAssessmentResultMockHandler = (overrideResponse?: Assessmen }) }, options) } + +export const getCreateMyAssessmentLabMockHandler = (overrideResponse?: AssessmentLab | ((info: Parameters[1]>[0]) => Promise | AssessmentLab), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/assessment-attempts/:attemptId/labs', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getCreateMyAssessmentLabResponseMock(), + { status: 200 + }) + }, options) +} + +export const getGetMyAssessmentLabMockHandler = (overrideResponse?: AssessmentLab | ((info: Parameters[1]>[0]) => Promise | AssessmentLab), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/assessment-attempts/:attemptId/labs/:labId', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMyAssessmentLabResponseMock(), + { status: 200 + }) + }, options) +} + +export const getCreateMyAssessmentLabConsoleSessionMockHandler = (overrideResponse?: AssessmentLabConsoleSession | ((info: Parameters[1]>[0]) => Promise | AssessmentLabConsoleSession), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/assessment-attempts/:attemptId/labs/:labId/console-sessions', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getCreateMyAssessmentLabConsoleSessionResponseMock(), + { status: 201 + }) + }, options) +} + +export const getSubmitMyAssessmentLabMockHandler = (overrideResponse?: AssessmentLab | ((info: Parameters[1]>[0]) => Promise | AssessmentLab), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/assessment-attempts/:attemptId/labs/:labId/submission', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getSubmitMyAssessmentLabResponseMock(), + { status: 202 + }) + }, options) +} export const getAssessmentMock = () => [ getGetMyAssessmentAvailabilityMockHandler(), getListMyAssessmentResultsMockHandler(), @@ -424,5 +493,9 @@ export const getAssessmentMock = () => [ getCreateMyAssessmentPracticeRunMockHandler(), getGetMyAssessmentPracticeRunMockHandler(), getFinalizeMyAssessmentAttemptMockHandler(), - getGetMyAssessmentResultMockHandler() + getGetMyAssessmentResultMockHandler(), + getCreateMyAssessmentLabMockHandler(), + getGetMyAssessmentLabMockHandler(), + getCreateMyAssessmentLabConsoleSessionMockHandler(), + getSubmitMyAssessmentLabMockHandler() ] diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.ts b/frontend/src/shared/api/endpoints/assessment/assessment.ts index 27bd2ef..990b96a 100644 --- a/frontend/src/shared/api/endpoints/assessment/assessment.ts +++ b/frontend/src/shared/api/endpoints/assessment/assessment.ts @@ -31,6 +31,11 @@ import type { AssessmentAvailability, AssessmentFinalization, AssessmentFinalizeConflictProblem, + AssessmentLab, + AssessmentLabConsoleSession, + AssessmentLabConsoleSessionCreate, + AssessmentLabCreate, + AssessmentLabSubmission, AssessmentResult, AssessmentResultHistoryPage, AssessmentSignalBatch, @@ -39,6 +44,7 @@ import type { AssessmentSignalReceipt, AssessmentWorkSession, CreateMyAssessmentAttemptHeaders, + CreateMyAssessmentLabHeaders, CreateMyAssessmentPracticeRunHeaders, FinalizeMyAssessmentAttemptHeaders, HoldMyAssessmentWorkSessionHeaders, @@ -49,7 +55,8 @@ import type { RecordMyAssessmentAttemptSignalsHeaders, ReleaseMyAssessmentWorkSessionHeaders, StartMyAssessmentAttemptSessionHeaders, - SubmitMyAssessmentAnswerHeaders + SubmitMyAssessmentAnswerHeaders, + SubmitMyAssessmentLabHeaders } from '../../schemas'; import { apiRequest } from '../../client'; @@ -1082,6 +1089,8 @@ export const useReleaseMyAssessmentWorkSession = , /** * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision. * + * Lab: an item with format `lab` takes no answer here. Its lab is started with CreateMyAssessmentLab and submitted with SubmitMyAssessmentLab; any answer to a lab item answers 400 validation_failed with the pointer `/answer/format`, like an answer in the wrong format, and stores nothing. + * * The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. * * A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command never starts one or consumes session quota. Reading the attempt or result is always read-only. A command that finds a due deadline transition may commit it before returning; a command that finds an expired idle session answers 409 until the candidate explicitly starts the next session. @@ -1598,3 +1607,409 @@ export function useGetMyAssessmentResult { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/labs` +} + +/** + * 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 current item, whose content has the format `lab`. + * + * The server asks the lab provisioner for a lab of the variant fixed for this item instance and answers 201 with the lab `provisioning`; the client polls GetMyAssessmentLab until it is `ready`. The lab lives until `expires_at`, the earlier of the item's `time_limit_seconds` and the attempt deadline, and is then deleted with everything done in it. Creating a lab does not change the attempt version, the current item, or any answer. + * + * One lab per item at a time. While the item has a lab in `provisioning`, `ready`, or `checking`, the server answers 200 with that lab and starts no second one. After a `failed` lab the candidate may start a new one while the item is current; after `submitted` or `expired` the item cannot start another lab (409 state_conflict). + * + * Busy pool. When the lab pool of the provisioner has no free capacity, the server answers 503 service_unavailable with Retry-After, for example `{"type": "urn:lincodex:problem:service_unavailable", "title": "Service unavailable", "status": 503, "code": "service_unavailable", "detail": "No lab capacity is free. The attempt is unchanged; retry later."}`. Nothing was stored: no lab exists, the attempt version and the current item are unchanged, the lab lifetime has not started, and the attempt is not consumed; the client retries after Retry-After with a new Idempotency-Key. When labs are not enabled on this server, or the provisioner cannot be reached, the server answers 503 service_unavailable without Retry-After and stores nothing either. The attempt deadline keeps running in both cases. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the item (404 not_found for an unknown attempt or item, or one of another candidate), the state (409 state_conflict: the attempt is terminal or its work session ended, the item is not current, its format is not `lab`, or its lab was submitted or expired), the rate limit (429), then the availability of labs and the capacity (503). Following the Idempotency-Key convention, 201, 200, 404, and 409 state_conflict are stored under the key and replayed; 400, 429, and 503 are not. + * @summary Start the lab of the current lab item of an assessment attempt. + */ +export const createMyAssessmentLab = async (attemptId: string, + assessmentLabCreate: AssessmentLabCreate, + headers: CreateMyAssessmentLabHeaders, 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(getCreateMyAssessmentLabUrl(attemptId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(assessmentLabCreate) + } +);} + + + + + +export const getCreateMyAssessmentLabMutationKey = () => ['createMyAssessmentLab'] as const; + +export const getCreateMyAssessmentLabMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMyAssessmentLabMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,CreateMyAssessmentLabMutationVariables, TContext> => { + +const mutationKey = getCreateMyAssessmentLabMutationKey(); +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>, CreateMyAssessmentLabMutationVariables> = (props) => { + const {attemptId,data,headers} = props ?? {}; + + return createMyAssessmentLab(attemptId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type CreateMyAssessmentLabMutationResult = NonNullable>> + export type CreateMyAssessmentLabMutationBody = AssessmentLabCreate + export type CreateMyAssessmentLabMutationError = ErrorType + export type CreateMyAssessmentLabMutationVariables = {attemptId: string;data: AssessmentLabCreate;headers: CreateMyAssessmentLabHeaders} + + /** + * @summary Start the lab of the current lab item of an assessment attempt. + */ +export const useCreateMyAssessmentLab = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMyAssessmentLabMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + CreateMyAssessmentLabMutationVariables, + TContext + > => { + return useMutation(getCreateMyAssessmentLabMutationOptions(options), queryClient); + } + export const getGetMyAssessmentLabUrl = (attemptId: string, + labId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/labs/${labId}` +} + +/** + * Requires the session cookie of a candidate account. Returns the state of a lab started with CreateMyAssessmentLab: whether it is still provisioning, ready for the consoles, being checked after the submission, or ended. It never contains a node address, a credential, the seed, the checker state, or the result of the check. This GET is read-only; the server may record a due timer transition, such as `ready` to `expired`, before it answers. + * + * A lab of another candidate's attempt, a lab of another attempt, and an unknown identifier all answer 404 not_found. + * @summary Read the lab of an assessment attempt item. + */ +export const getMyAssessmentLab = async (attemptId: string, + labId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyAssessmentLabUrl(attemptId,labId), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyAssessmentLabQueryKey = (attemptId: string, + labId: string,) => { + return [ + `/api/v1/me/assessment-attempts/${attemptId}/labs/${labId}` + ] as const; + } + + +export const getGetMyAssessmentLabQueryOptions = >, TError = ErrorType>(attemptId: string, + labId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentLabQueryKey(attemptId,labId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyAssessmentLab(attemptId,labId, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: attemptId !== null && attemptId !== undefined && labId !== null && labId !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyAssessmentLabQueryResult = NonNullable>> +export type GetMyAssessmentLabQueryError = ErrorType + + +export function useGetMyAssessmentLab>, TError = ErrorType>( + attemptId: string, + labId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentLab>, TError = ErrorType>( + attemptId: string, + labId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyAssessmentLab>, TError = ErrorType>( + attemptId: string, + labId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the lab of an assessment attempt item. + */ + +export function useGetMyAssessmentLab>, TError = ErrorType>( + attemptId: string, + labId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyAssessmentLabQueryOptions(attemptId,labId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getCreateMyAssessmentLabConsoleSessionUrl = (attemptId: string, + labId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/labs/${labId}/console-sessions` +} + +/** + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body names a node of the lab by its task name. + * + * The response describes one console session: the client opens a WebSocket to `websocket_path` on the same origin before `expires_at`. The upgrade is authorized by the session cookie and the Origin check, and the server relays the serial console of the node through the lab provisioner. The response never carries a node address, a port, a password, a key, or a token; the browser never connects to a node or to the provisioner. Console traffic is not stored as an answer and is not logged. + * + * The WebSocket relay is planned together with the candidate interface of labs; this contract fixes the session shape it uses. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt and the lab (404 not_found for an unknown attempt, lab, or one of another candidate), the node (400 with the pointer `/node`), the state (409 state_conflict: the lab is not `ready`, the attempt is terminal, or its work session ended), the limit of open sessions per lab (429 rate_limited with Retry-After), then the provisioner (503 service_unavailable without Retry-After; nothing was opened). + * @summary Open a console session of one node of a ready lab. + */ +export const createMyAssessmentLabConsoleSession = async (attemptId: string, + labId: string, + assessmentLabConsoleSessionCreate: AssessmentLabConsoleSessionCreate, 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(getCreateMyAssessmentLabConsoleSessionUrl(attemptId,labId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) }, + body: JSON.stringify(assessmentLabConsoleSessionCreate) + } +);} + + + + + +export const getCreateMyAssessmentLabConsoleSessionMutationKey = () => ['createMyAssessmentLabConsoleSession'] as const; + +export const getCreateMyAssessmentLabConsoleSessionMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMyAssessmentLabConsoleSessionMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,CreateMyAssessmentLabConsoleSessionMutationVariables, TContext> => { + +const mutationKey = getCreateMyAssessmentLabConsoleSessionMutationKey(); +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>, CreateMyAssessmentLabConsoleSessionMutationVariables> = (props) => { + const {attemptId,labId,data} = props ?? {}; + + return createMyAssessmentLabConsoleSession(attemptId,labId,data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type CreateMyAssessmentLabConsoleSessionMutationResult = NonNullable>> + export type CreateMyAssessmentLabConsoleSessionMutationBody = AssessmentLabConsoleSessionCreate + export type CreateMyAssessmentLabConsoleSessionMutationError = ErrorType + export type CreateMyAssessmentLabConsoleSessionMutationVariables = {attemptId: string;labId: string;data: AssessmentLabConsoleSessionCreate} + + /** + * @summary Open a console session of one node of a ready lab. + */ +export const useCreateMyAssessmentLabConsoleSession = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMyAssessmentLabConsoleSessionMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + CreateMyAssessmentLabConsoleSessionMutationVariables, + TContext + > => { + return useMutation(getCreateMyAssessmentLabConsoleSessionMutationOptions(options), queryClient); + } + export const getSubmitMyAssessmentLabUrl = (attemptId: string, + labId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/labs/${labId}/submission` +} + +/** + * 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 carries the attempt version last read and the answer with format `lab`, which names the lab. + * + * The server closes the consoles, freezes the lab, and answers 202 with the lab `checking`; the checker of the task reads the state of the nodes asynchronously, the answer is recorded, and the lab becomes `submitted` and is deleted. The client polls GetMyAssessmentLab and then reads the attempt, which moves to the next item. Neither response says whether the answer was correct, and the candidate never sees the checker criteria or their results. + * + * When the checker cannot reach the nodes because of the lab infrastructure, the lab becomes `failed` with `lab_error`: nothing is recorded or consumed, the attempt version is unchanged, and the candidate may start a new lab of the item while it is current. A failure of the infrastructure is never scored as a wrong answer. + * + * Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the lab (404 not_found for an unknown attempt or lab, or one of another candidate), the version (412), the state (409 state_conflict: the lab is not `ready`, `answer.lab_id` is not the lab in the path, the item is not current, the attempt is terminal, or its work session ended), then the provisioner (503 service_unavailable without Retry-After; nothing was stored and the lab keeps running). Following the Idempotency-Key convention, 202, 404, and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. + * @summary Submit the lab of the current lab item as its answer. + */ +export const submitMyAssessmentLab = async (attemptId: string, + labId: string, + assessmentLabSubmission: AssessmentLabSubmission, + headers: SubmitMyAssessmentLabHeaders, 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(getSubmitMyAssessmentLabUrl(attemptId,labId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(assessmentLabSubmission) + } +);} + + + + + +export const getSubmitMyAssessmentLabMutationKey = () => ['submitMyAssessmentLab'] as const; + +export const getSubmitMyAssessmentLabMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SubmitMyAssessmentLabMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,SubmitMyAssessmentLabMutationVariables, TContext> => { + +const mutationKey = getSubmitMyAssessmentLabMutationKey(); +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>, SubmitMyAssessmentLabMutationVariables> = (props) => { + const {attemptId,labId,data,headers} = props ?? {}; + + return submitMyAssessmentLab(attemptId,labId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type SubmitMyAssessmentLabMutationResult = NonNullable>> + export type SubmitMyAssessmentLabMutationBody = AssessmentLabSubmission + export type SubmitMyAssessmentLabMutationError = ErrorType + export type SubmitMyAssessmentLabMutationVariables = {attemptId: string;labId: string;data: AssessmentLabSubmission;headers: SubmitMyAssessmentLabHeaders} + + /** + * @summary Submit the lab of the current lab item as its answer. + */ +export const useSubmitMyAssessmentLab = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SubmitMyAssessmentLabMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + SubmitMyAssessmentLabMutationVariables, + TContext + > => { + return useMutation(getSubmitMyAssessmentLabMutationOptions(options), queryClient); + } diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts index 9b5f70d..e725989 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts @@ -84,6 +84,15 @@ export const assessmentAttemptOneOneCurrentItemOneContentSevenPublicExamplesMax export const assessmentAttemptOneOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; +export const assessmentAttemptOneOneCurrentItemOneContentEightNodesItemNameMax = 15; + + +export const assessmentAttemptOneOneCurrentItemOneContentEightNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentAttemptOneOneCurrentItemOneContentEightNodesMax = 8; + +export const assessmentAttemptOneOneCurrentItemOneContentEightTimeLimitSecondsMin = 300; +export const assessmentAttemptOneOneCurrentItemOneContentEightTimeLimitSecondsMax = 14400; + export const assessmentAttemptOneOnePracticesItemVerdictOneScoreMin = 0; export const assessmentAttemptOneOnePracticesItemVerdictOneScoreMax = 3; @@ -180,6 +189,15 @@ export const assessmentAttemptTwoOneCurrentItemOneContentSevenPublicExamplesMax export const assessmentAttemptTwoOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; +export const assessmentAttemptTwoOneCurrentItemOneContentEightNodesItemNameMax = 15; + + +export const assessmentAttemptTwoOneCurrentItemOneContentEightNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentAttemptTwoOneCurrentItemOneContentEightNodesMax = 8; + +export const assessmentAttemptTwoOneCurrentItemOneContentEightTimeLimitSecondsMin = 300; +export const assessmentAttemptTwoOneCurrentItemOneContentEightTimeLimitSecondsMax = 14400; + export const assessmentAttemptTwoOnePracticesItemVerdictOneScoreMin = 0; export const assessmentAttemptTwoOnePracticesItemVerdictOneScoreMax = 3; @@ -276,6 +294,15 @@ export const assessmentAttemptThreeOneCurrentItemOneContentSevenPublicExamplesMa export const assessmentAttemptThreeOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; +export const assessmentAttemptThreeOneCurrentItemOneContentEightNodesItemNameMax = 15; + + +export const assessmentAttemptThreeOneCurrentItemOneContentEightNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentAttemptThreeOneCurrentItemOneContentEightNodesMax = 8; + +export const assessmentAttemptThreeOneCurrentItemOneContentEightTimeLimitSecondsMin = 300; +export const assessmentAttemptThreeOneCurrentItemOneContentEightTimeLimitSecondsMax = 14400; + export const assessmentAttemptThreeOnePracticesItemVerdictOneScoreMin = 0; export const assessmentAttemptThreeOnePracticesItemVerdictOneScoreMax = 3; @@ -367,7 +394,14 @@ export const AssessmentAttempt = zod.union([zod.object({ "expected_output": zod.string().max(assessmentAttemptOneOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) }).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptOneOneCurrentItemOneContentSevenPublicExamplesMax), "max_source_length": zod.int().min(1).max(assessmentAttemptOneOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') -}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.'),zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(assessmentAttemptOneOneCurrentItemOneContentEightNodesItemNameMax).regex(assessmentAttemptOneOneCurrentItemOneContentEightNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(assessmentAttemptOneOneCurrentItemOneContentEightNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(assessmentAttemptOneOneCurrentItemOneContentEightTimeLimitSecondsMin).max(assessmentAttemptOneOneCurrentItemOneContentEightTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') }).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), "practices": zod.array(zod.object({ "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), @@ -468,7 +502,14 @@ export const AssessmentAttempt = zod.union([zod.object({ "expected_output": zod.string().max(assessmentAttemptTwoOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) }).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptTwoOneCurrentItemOneContentSevenPublicExamplesMax), "max_source_length": zod.int().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') -}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.'),zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentEightNodesItemNameMax).regex(assessmentAttemptTwoOneCurrentItemOneContentEightNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(assessmentAttemptTwoOneCurrentItemOneContentEightNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(assessmentAttemptTwoOneCurrentItemOneContentEightTimeLimitSecondsMin).max(assessmentAttemptTwoOneCurrentItemOneContentEightTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') }).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), "practices": zod.array(zod.object({ "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), @@ -569,7 +610,14 @@ export const AssessmentAttempt = zod.union([zod.object({ "expected_output": zod.string().max(assessmentAttemptThreeOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) }).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptThreeOneCurrentItemOneContentSevenPublicExamplesMax), "max_source_length": zod.int().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') -}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.'),zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentEightNodesItemNameMax).regex(assessmentAttemptThreeOneCurrentItemOneContentEightNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(assessmentAttemptThreeOneCurrentItemOneContentEightNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(assessmentAttemptThreeOneCurrentItemOneContentEightTimeLimitSecondsMin).max(assessmentAttemptThreeOneCurrentItemOneContentEightTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') }).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), "practices": zod.array(zod.object({ "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptCommon.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptCommon.zod.ts index 8671014..cd0f13e 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentAttemptCommon.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptCommon.zod.ts @@ -84,6 +84,15 @@ export const assessmentAttemptCommonCurrentItemOneContentSevenPublicExamplesMax export const assessmentAttemptCommonCurrentItemOneContentSevenMaxSourceLengthMax = 65536; +export const assessmentAttemptCommonCurrentItemOneContentEightNodesItemNameMax = 15; + + +export const assessmentAttemptCommonCurrentItemOneContentEightNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentAttemptCommonCurrentItemOneContentEightNodesMax = 8; + +export const assessmentAttemptCommonCurrentItemOneContentEightTimeLimitSecondsMin = 300; +export const assessmentAttemptCommonCurrentItemOneContentEightTimeLimitSecondsMax = 14400; + export const assessmentAttemptCommonPracticesItemVerdictOneScoreMin = 0; export const assessmentAttemptCommonPracticesItemVerdictOneScoreMax = 3; @@ -175,7 +184,14 @@ export const AssessmentAttemptCommon = zod.object({ "expected_output": zod.string().max(assessmentAttemptCommonCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) }).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptCommonCurrentItemOneContentSevenPublicExamplesMax), "max_source_length": zod.int().min(1).max(assessmentAttemptCommonCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') -}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.'),zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(assessmentAttemptCommonCurrentItemOneContentEightNodesItemNameMax).regex(assessmentAttemptCommonCurrentItemOneContentEightNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(assessmentAttemptCommonCurrentItemOneContentEightNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(assessmentAttemptCommonCurrentItemOneContentEightTimeLimitSecondsMin).max(assessmentAttemptCommonCurrentItemOneContentEightTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') }).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), "practices": zod.array(zod.object({ "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), diff --git a/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttempt.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttempt.zod.ts index e8f6972..ac64620 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttempt.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttempt.zod.ts @@ -84,6 +84,15 @@ export const assessmentCorrectiveAttemptOneCurrentItemOneContentSevenPublicExamp export const assessmentCorrectiveAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; +export const assessmentCorrectiveAttemptOneCurrentItemOneContentEightNodesItemNameMax = 15; + + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentEightNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentCorrectiveAttemptOneCurrentItemOneContentEightNodesMax = 8; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentEightTimeLimitSecondsMin = 300; +export const assessmentCorrectiveAttemptOneCurrentItemOneContentEightTimeLimitSecondsMax = 14400; + export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneScoreMin = 0; export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneScoreMax = 3; @@ -175,7 +184,14 @@ export const AssessmentCorrectiveAttempt = zod.object({ "expected_output": zod.string().max(assessmentCorrectiveAttemptOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) }).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentCorrectiveAttemptOneCurrentItemOneContentSevenPublicExamplesMax), "max_source_length": zod.int().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') -}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.'),zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentEightNodesItemNameMax).regex(assessmentCorrectiveAttemptOneCurrentItemOneContentEightNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentEightNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(assessmentCorrectiveAttemptOneCurrentItemOneContentEightTimeLimitSecondsMin).max(assessmentCorrectiveAttemptOneCurrentItemOneContentEightTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') }).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), "practices": zod.array(zod.object({ "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), diff --git a/frontend/src/shared/api/schemas/assessment/assessmentExpressAttempt.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentExpressAttempt.zod.ts index c65c16d..28a032f 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentExpressAttempt.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentExpressAttempt.zod.ts @@ -84,6 +84,15 @@ export const assessmentExpressAttemptOneCurrentItemOneContentSevenPublicExamples export const assessmentExpressAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; +export const assessmentExpressAttemptOneCurrentItemOneContentEightNodesItemNameMax = 15; + + +export const assessmentExpressAttemptOneCurrentItemOneContentEightNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentExpressAttemptOneCurrentItemOneContentEightNodesMax = 8; + +export const assessmentExpressAttemptOneCurrentItemOneContentEightTimeLimitSecondsMin = 300; +export const assessmentExpressAttemptOneCurrentItemOneContentEightTimeLimitSecondsMax = 14400; + export const assessmentExpressAttemptOnePracticesItemVerdictOneScoreMin = 0; export const assessmentExpressAttemptOnePracticesItemVerdictOneScoreMax = 3; @@ -175,7 +184,14 @@ export const AssessmentExpressAttempt = zod.object({ "expected_output": zod.string().max(assessmentExpressAttemptOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) }).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentExpressAttemptOneCurrentItemOneContentSevenPublicExamplesMax), "max_source_length": zod.int().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') -}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.'),zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentEightNodesItemNameMax).regex(assessmentExpressAttemptOneCurrentItemOneContentEightNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(assessmentExpressAttemptOneCurrentItemOneContentEightNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(assessmentExpressAttemptOneCurrentItemOneContentEightTimeLimitSecondsMin).max(assessmentExpressAttemptOneCurrentItemOneContentEightTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') }).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), "practices": zod.array(zod.object({ "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), diff --git a/frontend/src/shared/api/schemas/assessment/assessmentItem.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentItem.zod.ts index 274e5ad..43288e6 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentItem.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentItem.zod.ts @@ -62,6 +62,15 @@ export const assessmentItemContentSevenPublicExamplesMax = 10; export const assessmentItemContentSevenMaxSourceLengthMax = 65536; +export const assessmentItemContentEightNodesItemNameMax = 15; + + +export const assessmentItemContentEightNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentItemContentEightNodesMax = 8; + +export const assessmentItemContentEightTimeLimitSecondsMin = 300; +export const assessmentItemContentEightTimeLimitSecondsMax = 14400; + export const AssessmentItem = zod.object({ "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), @@ -107,7 +116,14 @@ export const AssessmentItem = zod.object({ "expected_output": zod.string().max(assessmentItemContentSevenPublicExamplesItemExpectedOutputMax) }).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentItemContentSevenPublicExamplesMax), "max_source_length": zod.int().min(1).max(assessmentItemContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') -}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.'),zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(assessmentItemContentEightNodesItemNameMax).regex(assessmentItemContentEightNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(assessmentItemContentEightNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(assessmentItemContentEightTimeLimitSecondsMin).max(assessmentItemContentEightTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') }).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.') export type AssessmentItem = zod.input; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLab.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLab.zod.ts new file mode 100644 index 0000000..76419b2 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLab.zod.ts @@ -0,0 +1,32 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentLabNodesItemNameMax = 15; + + +export const assessmentLabNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentLabNodesMax = 8; + + +export const AssessmentLab = zod.object({ + "id": zod.uuid().describe('Identifier of the lab.'), + "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(['provisioning', 'ready', 'checking', 'submitted', 'expired', 'failed']).describe('State of a lab of an attempt item.\n\n- provisioning: the nodes are being prepared; poll GetMyAssessmentLab.\n- ready: the consoles can be opened until `expires_at`.\n- checking: the answer was accepted; the consoles are closed and the server checks the nodes.\n- submitted: the check finished and the answer is recorded; the lab is deleted. The state never says whether the answer was correct.\n- expired: the lifetime or the attempt deadline ended before a submission; the lab is deleted and the item cannot start another lab.\n- failed: the lab infrastructure failed, independently of the candidate; `failure_reason` is `lab_error`. Nothing was recorded or consumed, and the candidate may start a new lab of the same item while the item is current.\n\nAdding a value is a contract change.'), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(assessmentLabNodesItemNameMax).regex(assessmentLabNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(assessmentLabNodesMax), + "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.'), + "ready_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 lab became `ready`, or null before.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('Time the lab ends unless it was submitted before: the earlier of the lifetime of the item and the attempt deadline. It never moves.'), + "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 lab reached `submitted`, `expired`, or `failed`, or null.'), + "failure_reason": zod.union([zod.enum(['lab_error']).describe('Why a lab failed: `lab_error` for an infrastructure failure, such as a node that did not boot or a check that could not reach a node. It never depends on the candidate and is never a failed check.'),zod.null()]).describe('`lab_error` when `state` is `failed`, otherwise null.') +}).describe('Candidate view of the lab of one attempt item. It contains no node address, MAC address, port, password, key, token, seed, checker state, criteria, score, or infrastructure name.') + +export type AssessmentLab = zod.input; +export type AssessmentLabOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLabConsoleSession.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLabConsoleSession.zod.ts new file mode 100644 index 0000000..4ac2e41 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLabConsoleSession.zod.ts @@ -0,0 +1,26 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const assessmentLabConsoleSessionNodeMax = 15; + + +export const assessmentLabConsoleSessionNodeRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentLabConsoleSessionWebsocketPathMax = 128; + + +export const assessmentLabConsoleSessionWebsocketPathRegExp = new RegExp('^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$'); + +export const AssessmentLabConsoleSession = zod.object({ + "id": zod.uuid().describe('Identifier of the console session; it is not a secret.'), + "node": zod.string().min(1).max(assessmentLabConsoleSessionNodeMax).regex(assessmentLabConsoleSessionNodeRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "websocket_path": zod.string().max(assessmentLabConsoleSessionWebsocketPathMax).regex(assessmentLabConsoleSessionWebsocketPathRegExp).describe('Same-origin path of the console WebSocket.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('Time by which the WebSocket must be opened.') +}).describe('A console session of one node. The client opens a WebSocket to `websocket_path` on the same origin before `expires_at`; the session cookie and the Origin check authorize the upgrade, so no secret travels in the path, the body, or a query string. A session can be attached once and ends with the lab.') + +export type AssessmentLabConsoleSession = zod.input; +export type AssessmentLabConsoleSessionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLabConsoleSessionCreate.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLabConsoleSessionCreate.zod.ts new file mode 100644 index 0000000..9642219 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLabConsoleSessionCreate.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 assessmentLabConsoleSessionCreateNodeMax = 15; + + +export const assessmentLabConsoleSessionCreateNodeRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); + +export const AssessmentLabConsoleSessionCreate = zod.object({ + "node": zod.string().min(1).max(assessmentLabConsoleSessionCreateNodeMax).regex(assessmentLabConsoleSessionCreateNodeRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.') +}).describe('Open a console of one node of a ready lab. Unknown fields are rejected.') + +export type AssessmentLabConsoleSessionCreate = zod.input; +export type AssessmentLabConsoleSessionCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLabCreate.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLabCreate.zod.ts new file mode 100644 index 0000000..7734a9a --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLabCreate.zod.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentLabCreate = 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.') +}).describe('Start the lab of the current lab item. Unknown fields are rejected.') + +export type AssessmentLabCreate = zod.input; +export type AssessmentLabCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLabFailureReason.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLabFailureReason.zod.ts new file mode 100644 index 0000000..72f0e5f --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLabFailureReason.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 AssessmentLabFailureReason = zod.enum(['lab_error']).describe('Why a lab failed: `lab_error` for an infrastructure failure, such as a node that did not boot or a check that could not reach a node. It never depends on the candidate and is never a failed check.') + +export type AssessmentLabFailureReason = zod.input; +export type AssessmentLabFailureReasonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLabNode.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLabNode.zod.ts new file mode 100644 index 0000000..e39e5f7 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLabNode.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 assessmentLabNodeNameMax = 15; + + +export const assessmentLabNodeNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); + +export const AssessmentLabNode = zod.object({ + "name": zod.string().min(1).max(assessmentLabNodeNameMax).regex(assessmentLabNodeNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.') + +export type AssessmentLabNode = zod.input; +export type AssessmentLabNodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLabNodeKind.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLabNodeKind.zod.ts new file mode 100644 index 0000000..9759e8f --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLabNodeKind.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 AssessmentLabNodeKind = zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') + +export type AssessmentLabNodeKind = zod.input; +export type AssessmentLabNodeKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLabNodeName.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLabNodeName.zod.ts new file mode 100644 index 0000000..972ae40 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLabNodeName.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentLabNodeNameMax = 15; + + +export const AssessmentLabNodeNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); + +export const AssessmentLabNodeName = zod.string().min(1).max(AssessmentLabNodeNameMax).regex(AssessmentLabNodeNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.') + +export type AssessmentLabNodeName = zod.input; +export type AssessmentLabNodeNameOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLabState.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLabState.zod.ts new file mode 100644 index 0000000..e875bda --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLabState.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 AssessmentLabState = zod.enum(['provisioning', 'ready', 'checking', 'submitted', 'expired', 'failed']).describe('State of a lab of an attempt item.\n\n- provisioning: the nodes are being prepared; poll GetMyAssessmentLab.\n- ready: the consoles can be opened until `expires_at`.\n- checking: the answer was accepted; the consoles are closed and the server checks the nodes.\n- submitted: the check finished and the answer is recorded; the lab is deleted. The state never says whether the answer was correct.\n- expired: the lifetime or the attempt deadline ended before a submission; the lab is deleted and the item cannot start another lab.\n- failed: the lab infrastructure failed, independently of the candidate; `failure_reason` is `lab_error`. Nothing was recorded or consumed, and the candidate may start a new lab of the same item while the item is current.\n\nAdding a value is a contract change.') + +export type AssessmentLabState = zod.input; +export type AssessmentLabStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLabSubmission.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLabSubmission.zod.ts new file mode 100644 index 0000000..adccef2 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentLabSubmission.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 AssessmentLabSubmission = zod.object({ + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "answer": zod.object({ + "format": zod.enum(['lab']), + "lab_id": zod.uuid().describe('The lab of this item that the candidate worked in.') +}).describe('Answer of a lab item: the state of the nodes of the named lab at the moment of submission. The server reads that state with the checker of the task; the body carries no configuration text, score, or correctness flag. Two answers are equal when they name the same lab. It is the answer of SubmitMyAssessmentLab only and is not a member of AssessmentAnswer.') +}).describe('Submit the lab of the current lab item as its answer. Unknown fields are rejected, so a request cannot send a score or a correctness flag.') + +export type AssessmentLabSubmission = zod.input; +export type AssessmentLabSubmissionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttempt.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttempt.zod.ts index 7c64996..ce0a2f1 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttempt.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttempt.zod.ts @@ -84,6 +84,15 @@ export const assessmentQualifiedAttemptOneCurrentItemOneContentSevenPublicExampl export const assessmentQualifiedAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; +export const assessmentQualifiedAttemptOneCurrentItemOneContentEightNodesItemNameMax = 15; + + +export const assessmentQualifiedAttemptOneCurrentItemOneContentEightNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const assessmentQualifiedAttemptOneCurrentItemOneContentEightNodesMax = 8; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentEightTimeLimitSecondsMin = 300; +export const assessmentQualifiedAttemptOneCurrentItemOneContentEightTimeLimitSecondsMax = 14400; + export const assessmentQualifiedAttemptOnePracticesItemVerdictOneScoreMin = 0; export const assessmentQualifiedAttemptOnePracticesItemVerdictOneScoreMax = 3; @@ -175,7 +184,14 @@ export const AssessmentQualifiedAttempt = zod.object({ "expected_output": zod.string().max(assessmentQualifiedAttemptOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) }).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentQualifiedAttemptOneCurrentItemOneContentSevenPublicExamplesMax), "max_source_length": zod.int().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') -}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.'),zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentEightNodesItemNameMax).regex(assessmentQualifiedAttemptOneCurrentItemOneContentEightNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentEightNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(assessmentQualifiedAttemptOneCurrentItemOneContentEightTimeLimitSecondsMin).max(assessmentQualifiedAttemptOneCurrentItemOneContentEightTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') }).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), "practices": zod.array(zod.object({ "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), diff --git a/frontend/src/shared/api/schemas/assessment/createMyAssessmentLabBody.zod.ts b/frontend/src/shared/api/schemas/assessment/createMyAssessmentLabBody.zod.ts new file mode 100644 index 0000000..968cdc1 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/createMyAssessmentLabBody.zod.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const CreateMyAssessmentLabBody = 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.') +}).describe('Start the lab of the current lab item. Unknown fields are rejected.') + +export type CreateMyAssessmentLabBody = zod.input; +export type CreateMyAssessmentLabBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/createMyAssessmentLabConsoleSessionBody.zod.ts b/frontend/src/shared/api/schemas/assessment/createMyAssessmentLabConsoleSessionBody.zod.ts new file mode 100644 index 0000000..d241246 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/createMyAssessmentLabConsoleSessionBody.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 createMyAssessmentLabConsoleSessionBodyNodeMax = 15; + + +export const createMyAssessmentLabConsoleSessionBodyNodeRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); + +export const CreateMyAssessmentLabConsoleSessionBody = zod.object({ + "node": zod.string().min(1).max(createMyAssessmentLabConsoleSessionBodyNodeMax).regex(createMyAssessmentLabConsoleSessionBodyNodeRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.') +}).describe('Open a console of one node of a ready lab. Unknown fields are rejected.') + +export type CreateMyAssessmentLabConsoleSessionBody = zod.input; +export type CreateMyAssessmentLabConsoleSessionBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/createMyAssessmentLabHeaders.zod.ts b/frontend/src/shared/api/schemas/assessment/createMyAssessmentLabHeaders.zod.ts new file mode 100644 index 0000000..4fa9dfd --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/createMyAssessmentLabHeaders.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 createMyAssessmentLabHeadersIdempotencyKeyMax = 255; + + +export const createMyAssessmentLabHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const CreateMyAssessmentLabHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(createMyAssessmentLabHeadersIdempotencyKeyMax).regex(createMyAssessmentLabHeadersIdempotencyKeyRegExp) +}) + +export type CreateMyAssessmentLabHeaders = zod.input; +export type CreateMyAssessmentLabHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/index.ts b/frontend/src/shared/api/schemas/assessment/index.ts index f8d3cb4..06f3d8e 100644 --- a/frontend/src/shared/api/schemas/assessment/index.ts +++ b/frontend/src/shared/api/schemas/assessment/index.ts @@ -36,6 +36,16 @@ export * from './assessmentGradeAvailabilityStatus.zod'; export * from './assessmentInterval.zod'; export * from './assessmentItem.zod'; export * from './assessmentItemId.zod'; +export * from './assessmentLab.zod'; +export * from './assessmentLabConsoleSession.zod'; +export * from './assessmentLabConsoleSessionCreate.zod'; +export * from './assessmentLabCreate.zod'; +export * from './assessmentLabFailureReason.zod'; +export * from './assessmentLabNode.zod'; +export * from './assessmentLabNodeKind.zod'; +export * from './assessmentLabNodeName.zod'; +export * from './assessmentLabState.zod'; +export * from './assessmentLabSubmission.zod'; export * from './assessmentLimitation.zod'; export * from './assessmentMode.zod'; export * from './assessmentNextAction.zod'; @@ -78,6 +88,9 @@ export * from './configurationAnswer.zod'; export * from './configurationItemContent.zod'; export * from './createMyAssessmentAttemptBody.zod'; export * from './createMyAssessmentAttemptHeaders.zod'; +export * from './createMyAssessmentLabBody.zod'; +export * from './createMyAssessmentLabConsoleSessionBody.zod'; +export * from './createMyAssessmentLabHeaders.zod'; export * from './createMyAssessmentPracticeRunBody.zod'; export * from './createMyAssessmentPracticeRunHeaders.zod'; export * from './finalizeMyAssessmentAttemptBody.zod'; @@ -86,6 +99,8 @@ export * from './findErrorAnswer.zod'; export * from './findErrorItemContent.zod'; export * from './holdMyAssessmentWorkSessionHeaders.zod'; export * from './itemContent.zod'; +export * from './labAnswer.zod'; +export * from './labItemContent.zod'; export * from './listMyAssessmentResultsParams.zod'; export * from './numberAnswer.zod'; export * from './numberItemContent.zod'; @@ -116,3 +131,5 @@ export * from './stringAnswer.zod'; export * from './stringItemContent.zod'; export * from './submitMyAssessmentAnswerBody.zod'; export * from './submitMyAssessmentAnswerHeaders.zod'; +export * from './submitMyAssessmentLabBody.zod'; +export * from './submitMyAssessmentLabHeaders.zod'; diff --git a/frontend/src/shared/api/schemas/assessment/itemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/itemContent.zod.ts index 4224998..dea9bcf 100644 --- a/frontend/src/shared/api/schemas/assessment/itemContent.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/itemContent.zod.ts @@ -58,6 +58,15 @@ export const itemContentSevenPublicExamplesMax = 10; export const itemContentSevenMaxSourceLengthMax = 65536; +export const itemContentEightNodesItemNameMax = 15; + + +export const itemContentEightNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const itemContentEightNodesMax = 8; + +export const itemContentEightTimeLimitSecondsMin = 300; +export const itemContentEightTimeLimitSecondsMax = 14400; + export const ItemContent = zod.union([zod.object({ "format": zod.enum(['choice']), @@ -99,7 +108,14 @@ export const ItemContent = zod.union([zod.object({ "expected_output": zod.string().max(itemContentSevenPublicExamplesItemExpectedOutputMax) }).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(itemContentSevenPublicExamplesMax), "max_source_length": zod.int().min(1).max(itemContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') -}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.'),zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(itemContentEightNodesItemNameMax).regex(itemContentEightNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(itemContentEightNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(itemContentEightTimeLimitSecondsMin).max(itemContentEightTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') export type ItemContent = zod.input; export type ItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/labAnswer.zod.ts b/frontend/src/shared/api/schemas/assessment/labAnswer.zod.ts new file mode 100644 index 0000000..8bc0827 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/labAnswer.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const LabAnswer = zod.object({ + "format": zod.enum(['lab']), + "lab_id": zod.uuid().describe('The lab of this item that the candidate worked in.') +}).describe('Answer of a lab item: the state of the nodes of the named lab at the moment of submission. The server reads that state with the checker of the task; the body carries no configuration text, score, or correctness flag. Two answers are equal when they name the same lab. It is the answer of SubmitMyAssessmentLab only and is not a member of AssessmentAnswer.') + +export type LabAnswer = zod.input; +export type LabAnswerOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/labItemContent.zod.ts b/frontend/src/shared/api/schemas/assessment/labItemContent.zod.ts new file mode 100644 index 0000000..0e8f4eb --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/labItemContent.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 labItemContentNodesItemNameMax = 15; + + +export const labItemContentNodesItemNameRegExp = new RegExp('^[a-z][a-z0-9-]{0,14}$'); +export const labItemContentNodesMax = 8; + +export const labItemContentTimeLimitSecondsMin = 300; +export const labItemContentTimeLimitSecondsMax = 14400; + + +export const LabItemContent = zod.object({ + "format": zod.enum(['lab']), + "nodes": zod.array(zod.object({ + "name": zod.string().min(1).max(labItemContentNodesItemNameMax).regex(labItemContentNodesItemNameRegExp).describe('Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address.'), + "kind": zod.enum(['mikrotik', 'ubuntu']).describe('What the console of a node shows.\n\n- mikrotik: a MikroTik router with the RouterOS console.\n- ubuntu: a small Ubuntu server with a Linux login.\n\nAdding a value is a contract change.') +}).describe('A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name.')).min(1).max(labItemContentNodesMax).describe('Nodes of the lab in the order of the statement.'), + "time_limit_seconds": zod.int().min(labItemContentTimeLimitSecondsMin).max(labItemContentTimeLimitSecondsMax).describe('Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline.') +}).describe('Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.') + +export type LabItemContent = zod.input; +export type LabItemContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/submitMyAssessmentLabBody.zod.ts b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentLabBody.zod.ts new file mode 100644 index 0000000..11e97ac --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentLabBody.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 SubmitMyAssessmentLabBody = zod.object({ + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "answer": zod.object({ + "format": zod.enum(['lab']), + "lab_id": zod.uuid().describe('The lab of this item that the candidate worked in.') +}).describe('Answer of a lab item: the state of the nodes of the named lab at the moment of submission. The server reads that state with the checker of the task; the body carries no configuration text, score, or correctness flag. Two answers are equal when they name the same lab. It is the answer of SubmitMyAssessmentLab only and is not a member of AssessmentAnswer.') +}).describe('Submit the lab of the current lab item as its answer. Unknown fields are rejected, so a request cannot send a score or a correctness flag.') + +export type SubmitMyAssessmentLabBody = zod.input; +export type SubmitMyAssessmentLabBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/submitMyAssessmentLabHeaders.zod.ts b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentLabHeaders.zod.ts new file mode 100644 index 0000000..4fcba34 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentLabHeaders.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 submitMyAssessmentLabHeadersIdempotencyKeyMax = 255; + + +export const submitMyAssessmentLabHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const SubmitMyAssessmentLabHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(submitMyAssessmentLabHeadersIdempotencyKeyMax).regex(submitMyAssessmentLabHeadersIdempotencyKeyRegExp) +}) + +export type SubmitMyAssessmentLabHeaders = zod.input; +export type SubmitMyAssessmentLabHeadersOutput = zod.output; diff --git a/scripts/check-generated.py b/scripts/check-generated.py index 8bf8f84..ba16780 100644 --- a/scripts/check-generated.py +++ b/scripts/check-generated.py @@ -14,6 +14,7 @@ GENERATED_PREFIXES = ( "backend/internal/adapter/primary/http/api/", "backend/internal/adapter/secondary/ml/api/", "backend/internal/adapter/secondary/code_runner/api/", + "backend/internal/adapter/secondary/lab_provisioner/api/", "backend/internal/adapter/secondary/postgres/sqlc/", "frontend/src/shared/api/endpoints/", "frontend/src/shared/api/schemas/", @@ -27,6 +28,8 @@ GENERATED_FILES = { "api/ml/components/schemas.yml", "api/runner/openapi.bundle.yml", "api/runner/components/schemas.yml", + "api/labd/openapi.bundle.yml", + "api/labd/components/schemas.yml", "ml/src/lincodex_ml/api/models.py", } SOURCE_SUFFIXES = {".go", ".ts", ".tsx", ".js", ".sql", ".json", ".py"} diff --git a/scripts/test_assessment_contract.py b/scripts/test_assessment_contract.py index d0ac7a0..43530b3 100644 --- a/scripts/test_assessment_contract.py +++ b/scripts/test_assessment_contract.py @@ -333,7 +333,7 @@ class AssessmentContractTest(unittest.TestCase): self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}"]) self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}/result"]) - def test_attempt_items_and_answers_keep_the_seven_public_formats(self) -> None: + def test_attempt_items_and_answers_keep_the_public_formats(self) -> None: expected = { "choice", "number", @@ -343,7 +343,9 @@ class AssessmentContractTest(unittest.TestCase): "configuration", "practice", } - self.assertEqual(union_enum_values(self.schemas["ItemContent"], self.schemas), expected) + # A lab item is served like the others, but its lab is submitted only + # with SubmitMyAssessmentLab, so `lab` is not an answer format. + self.assertEqual(union_enum_values(self.schemas["ItemContent"], self.schemas), expected | {"lab"}) self.assertEqual(union_enum_values(self.schemas["AssessmentAnswer"], self.schemas), expected) def test_candidate_schemas_do_not_name_secrets_or_employer_access(self) -> None: diff --git a/scripts/test_lab_contract.py b/scripts/test_lab_contract.py new file mode 100644 index 0000000..df55b43 --- /dev/null +++ b/scripts/test_lab_contract.py @@ -0,0 +1,412 @@ +"""Pin the privacy, capacity, and authentication rules of the lab contracts. + +The candidate lab operations of api/core and the internal lab provisioner +contract api/labd must never return a node address, a credential, the +variant seed, or checker state to a party that does not need it, and a busy +lab pool must be a 503 with Retry-After that changes nothing. These tests read +the bundled contracts, so run them after `make -C api bundle`. +""" + +from __future__ import annotations + +import copy +import unittest +from pathlib import Path +from typing import Any, Iterator + +import yaml + +API_DIR = Path(__file__).resolve().parents[1] / "api" +CORE_BUNDLE = API_DIR / "core" / "openapi.bundle.yml" +LABD_BUNDLE = API_DIR / "labd" / "openapi.bundle.yml" +ML_BUNDLE = API_DIR / "ml" / "openapi.bundle.yml" +SCHEMA_PREFIX = "#/components/schemas/" +RESPONSE_PREFIX = "#/components/responses/" +PARAMETER_PREFIX = "#/components/parameters/" +EXAMPLE_PREFIX = "#/components/examples/" +HTTP_METHODS = ("get", "put", "post", "patch", "delete") + +CANDIDATE_LAB_OPERATIONS = { + "CreateMyAssessmentLab", + "GetMyAssessmentLab", + "CreateMyAssessmentLabConsoleSession", + "SubmitMyAssessmentLab", +} +LABD_HEALTH_OPERATIONS = {"GetLabdHealthz", "GetLabdReadyz"} + +# Property names that would reveal where a node lives, how to log in to it, +# or how the answer is checked. Fragments match inside longer names such as +# `mgmt_ipv4` or `ssh_key`. +INFRASTRUCTURE_FRAGMENTS = ( + "address", + "bridge", + "credential", + "gateway", + "host", + "instance", + "ipv4", + "ipv6", + "key", + "mac", + "netmask", + "password", + "port", + "secret", + "snapshot", + "ssh", + "subnet", +) +INFRASTRUCTURE_NAMES = {"ip", "cidr", "url", "uri"} +# The candidate additionally never sees the seed, the checker, or a token. +CANDIDATE_ONLY_FRAGMENTS = ( + "check", + "criteri", + "score", + "seed", + "template", + "token", + "verdict", +) +# Request fields that would link a lab to a person or a product record. The +# provisioner needs none of them. +PERSONAL_FRAGMENTS = ( + "account", + "attempt", + "candidate", + "company", + "contact", + "email", + "item", + "organization", + "person", + "phone", + "profile", + "session", + "user", +) + + +def load(path: Path) -> dict[str, Any]: + with path.open(encoding="utf-8") as stream: + document = yaml.safe_load(stream) + if not isinstance(document, dict): + raise AssertionError(f"{path} is not an OpenAPI document") + return document + + +def operations(document: dict[str, Any]) -> Iterator[tuple[str, str, dict[str, Any], dict[str, Any]]]: + for path, item in document["paths"].items(): + for method in HTTP_METHODS: + if method in item: + yield path, method, item, item[method] + + +def operation_by_id(document: dict[str, Any], operation_id: str) -> dict[str, Any]: + for _, _, _, operation in operations(document): + if operation["operationId"] == operation_id: + return operation + raise AssertionError(f"operation {operation_id} is missing") + + +def resolve_response(document: dict[str, Any], response: dict[str, Any]) -> dict[str, Any]: + reference = response.get("$ref") + if isinstance(reference, str): + if not reference.startswith(RESPONSE_PREFIX): + raise AssertionError(f"unexpected bundled reference: {reference}") + return document["components"]["responses"][reference[len(RESPONSE_PREFIX) :]] + return response + + +def resolve_parameter(document: dict[str, Any], parameter: dict[str, Any]) -> dict[str, Any]: + reference = parameter.get("$ref") + if isinstance(reference, str): + if not reference.startswith(PARAMETER_PREFIX): + raise AssertionError(f"unexpected bundled reference: {reference}") + return document["components"]["parameters"][reference[len(PARAMETER_PREFIX) :]] + return parameter + + +def walk_schema( + schema: Any, schemas: dict[str, Any], seen: set[str], location: str +) -> Iterator[tuple[str, dict[str, Any]]]: + """Yield every object schema reachable from schema with its location.""" + if isinstance(schema, list): + for index, item in enumerate(schema): + yield from walk_schema(item, schemas, seen, f"{location}[{index}]") + return + if not isinstance(schema, dict): + return + reference = schema.get("$ref") + if isinstance(reference, str): + if not reference.startswith(SCHEMA_PREFIX): + raise AssertionError(f"unexpected bundled reference: {reference}") + name = reference[len(SCHEMA_PREFIX) :] + if name not in seen: + seen.add(name) + yield from walk_schema(schemas[name], schemas, seen, location) + return + if schema.get("type") == "object" or "properties" in schema: + yield location, schema + for property_name, property_schema in schema.get("properties", {}).items(): + yield from walk_schema(property_schema, schemas, seen, f"{location}.{property_name}") + for key in ("items", "additionalProperties"): + if isinstance(schema.get(key), dict): + yield from walk_schema(schema[key], schemas, seen, f"{location}.{key}") + for key in ("allOf", "oneOf", "anyOf"): + if key in schema: + yield from walk_schema(schema[key], schemas, seen, f"{location}.{key}") + + +def success_schemas(document: dict[str, Any], operation_ids: set[str]) -> Iterator[tuple[str, Any]]: + """Yield the JSON schema of every 2xx response of the given operations.""" + for path, method, _, operation in operations(document): + if operation["operationId"] not in operation_ids: + continue + for status, response in operation["responses"].items(): + if not str(status).startswith("2"): + continue + for media in resolve_response(document, response).get("content", {}).values(): + yield f"{method.upper()} {path} {status}", media["schema"] + + +def matching_fields( + document: dict[str, Any], + sources: Iterator[tuple[str, Any]], + fragments: tuple[str, ...], + names: set[str], +) -> list[str]: + schemas = document["components"]["schemas"] + found: list[str] = [] + for location, source in sources: + for object_location, object_schema in walk_schema(source, schemas, set(), location): + for property_name in object_schema.get("properties", {}): + lowered = property_name.lower() + if lowered in names or any(fragment in lowered for fragment in fragments): + found.append(f"{object_location}.{property_name}") + return found + + +def candidate_lab_schemas(document: dict[str, Any]) -> Iterator[tuple[str, Any]]: + """Yield the lab responses and the lab item content that the attempt serves.""" + yield from success_schemas(document, CANDIDATE_LAB_OPERATIONS) + yield "ItemContent lab", {"$ref": SCHEMA_PREFIX + "LabItemContent"} + + +def candidate_leaks(document: dict[str, Any]) -> list[str]: + return matching_fields( + document, + candidate_lab_schemas(document), + INFRASTRUCTURE_FRAGMENTS + CANDIDATE_ONLY_FRAGMENTS, + INFRASTRUCTURE_NAMES, + ) + + +def labd_operation_ids(document: dict[str, Any]) -> set[str]: + return {operation["operationId"] for _, _, _, operation in operations(document)} + + +def labd_leaks(document: dict[str, Any]) -> list[str]: + return matching_fields( + document, + success_schemas(document, labd_operation_ids(document)), + INFRASTRUCTURE_FRAGMENTS + ("seed",), + INFRASTRUCTURE_NAMES, + ) + + +def labd_request_identifiers(document: dict[str, Any]) -> list[str]: + schemas = document["components"]["schemas"] + found: list[str] = [] + for path, method, item, operation in operations(document): + for reference in [*item.get("parameters", []), *operation.get("parameters", [])]: + parameter = resolve_parameter(document, reference) + name = parameter["name"].lower() + if any(fragment in name for fragment in PERSONAL_FRAGMENTS): + found.append(f"{method.upper()} {path} parameter {parameter['name']}") + for media in operation.get("requestBody", {}).get("content", {}).values(): + location = f"{method.upper()} {path} body" + for object_location, object_schema in walk_schema(media["schema"], schemas, set(), location): + for property_name in object_schema.get("properties", {}): + if any(fragment in property_name.lower() for fragment in PERSONAL_FRAGMENTS): + found.append(f"{object_location}.{property_name}") + return found + + +class CandidateLabContractTest(unittest.TestCase): + def setUp(self) -> None: + self.document = load(CORE_BUNDLE) + self.schemas = self.document["components"]["schemas"] + + def test_every_lab_operation_exists(self) -> None: + for operation_id in CANDIDATE_LAB_OPERATIONS: + with self.subTest(operation=operation_id): + operation_by_id(self.document, operation_id) + + def test_responses_carry_no_address_key_or_checker_state(self) -> None: + self.assertEqual(candidate_leaks(self.document), []) + + def test_detector_finds_planted_leaks(self) -> None: + planted = copy.deepcopy(self.document) + planted["components"]["schemas"]["AssessmentLabNode"]["properties"]["mgmt_ipv4"] = {"type": "string"} + planted["components"]["schemas"]["AssessmentLab"]["properties"]["checker_score"] = {"type": "integer"} + planted["components"]["schemas"]["AssessmentLabConsoleSession"]["properties"]["ssh_key"] = {"type": "string"} + leaks = candidate_leaks(planted) + for field in ("nodes.items.mgmt_ipv4", "checker_score", "ssh_key"): + with self.subTest(field=field): + self.assertTrue(any(leak.endswith(field) for leak in leaks), leaks) + + def test_lab_objects_reject_unknown_fields(self) -> None: + for name in ( + "AssessmentLab", + "AssessmentLabNode", + "AssessmentLabCreate", + "AssessmentLabConsoleSession", + "AssessmentLabConsoleSessionCreate", + "AssessmentLabSubmission", + "LabAnswer", + "LabItemContent", + ): + with self.subTest(schema=name): + self.assertIs(self.schemas[name].get("additionalProperties"), False) + + def test_answer_format_lab_names_only_the_lab(self) -> None: + answer = self.schemas["LabAnswer"] + self.assertEqual(answer["properties"]["format"]["enum"], ["lab"]) + self.assertEqual(set(answer["properties"]), {"format", "lab_id"}) + self.assertEqual(self.schemas["LabItemContent"]["properties"]["format"]["enum"], ["lab"]) + submission = operation_by_id(self.document, "SubmitMyAssessmentLab") + body = submission["requestBody"]["content"]["application/json"]["schema"] + self.assertEqual(body["$ref"], SCHEMA_PREFIX + "AssessmentLabSubmission") + + def test_busy_pool_is_a_retryable_503_that_changes_nothing(self) -> None: + create = operation_by_id(self.document, "CreateMyAssessmentLab") + reference = create["responses"]["503"]["$ref"] + self.assertEqual(reference, RESPONSE_PREFIX + "ServiceUnavailable") + busy = resolve_response(self.document, create["responses"]["503"]) + self.assertIn("Retry-After", busy["headers"]) + self.assertIn("application/problem+json", busy["content"]) + description = create["description"] + self.assertIn("answers 503 service_unavailable with Retry-After", description) + self.assertIn("Nothing was stored", description) + self.assertIn("the attempt is not consumed", description) + # The 503 is not replayed under the Idempotency-Key, so a retry is + # evaluated again once capacity is free. + self.assertIn("400, 429, and 503 are not", description) + for operation_id in ("CreateMyAssessmentLabConsoleSession", "SubmitMyAssessmentLab"): + with self.subTest(operation=operation_id): + operation = operation_by_id(self.document, operation_id) + self.assertEqual(operation["responses"]["503"]["$ref"], reference) + + def test_lab_is_an_item_format_answered_only_by_its_own_operation(self) -> None: + self.assertIn({"$ref": SCHEMA_PREFIX + "LabItemContent"}, self.schemas["ItemContent"]["oneOf"]) + answer_formats = set() + for variant in self.schemas["AssessmentAnswer"]["oneOf"]: + name = variant["$ref"][len(SCHEMA_PREFIX) :] + answer_formats.update(self.schemas[name]["properties"]["format"]["enum"]) + self.assertNotIn("lab", answer_formats) + users = [ + name + for name, schema in self.schemas.items() + if SCHEMA_PREFIX + "LabAnswer" in yaml.safe_dump(schema) + ] + self.assertEqual(users, ["AssessmentLabSubmission"]) + answers = operation_by_id(self.document, "SubmitMyAssessmentAnswer") + self.assertIn("SubmitMyAssessmentLab", answers["description"]) + self.assertIn("`/answer/format`", answers["description"]) + + def test_lab_problems_reuse_existing_codes(self) -> None: + codes = set(self.schemas["ProblemCode"]["enum"]) + self.assertFalse({code for code in codes if code.startswith("lab_") or "_lab" in code}) + for operation_id in CANDIDATE_LAB_OPERATIONS: + operation = operation_by_id(self.document, operation_id) + for status, response in operation["responses"].items(): + content = resolve_response(self.document, response).get("content", {}) + for example in content.get("application/problem+json", {}).get("examples", {}).values(): + reference = example.get("$ref") + if isinstance(reference, str): + self.assertTrue(reference.startswith(EXAMPLE_PREFIX), reference) + example = self.document["components"]["examples"][reference[len(EXAMPLE_PREFIX) :]] + value = example["value"] + with self.subTest(operation=operation_id, status=status): + self.assertIn(value["code"], codes) + + def test_problem_codes_stay_identical_to_the_ml_copy(self) -> None: + ml = load(ML_BUNDLE)["components"]["schemas"]["ProblemCode"]["enum"] + self.assertEqual(self.schemas["ProblemCode"]["enum"], ml) + + def test_mutating_lab_operations_require_csrf(self) -> None: + for operation_id in CANDIDATE_LAB_OPERATIONS - {"GetMyAssessmentLab"}: + with self.subTest(operation=operation_id): + operation = operation_by_id(self.document, operation_id) + self.assertEqual(operation["security"], [{"sessionCookie": [], "sessionCsrf": []}]) + + +class LabProvisionerContractTest(unittest.TestCase): + def setUp(self) -> None: + self.document = load(LABD_BUNDLE) + self.schemas = self.document["components"]["schemas"] + + def test_operations_cover_the_lab_lifecycle(self) -> None: + self.assertEqual( + labd_operation_ids(self.document) - LABD_HEALTH_OPERATIONS, + {"CreateLab", "GetLab", "DeleteLab", "CreateLabConsoleToken", "CheckLab"}, + ) + + def test_operations_require_the_bearer_token(self) -> None: + scheme = self.document["components"]["securitySchemes"]["bearerAuth"] + self.assertEqual((scheme["type"], scheme["scheme"]), ("http", "bearer")) + self.assertEqual(self.document["security"], [{"bearerAuth": []}]) + for path, method, _, operation in operations(self.document): + with self.subTest(operation=operation["operationId"]): + if operation["operationId"] in LABD_HEALTH_OPERATIONS: + self.assertEqual(operation.get("security"), []) + else: + self.assertNotIn("security", operation, f"{method} {path} must use the global bearer rule") + + def test_requests_carry_no_personal_or_product_identifiers(self) -> None: + self.assertEqual(labd_request_identifiers(self.document), []) + + def test_responses_carry_no_address_key_or_seed(self) -> None: + self.assertEqual(labd_leaks(self.document), []) + + def test_detector_finds_planted_leaks(self) -> None: + planted = copy.deepcopy(self.document) + planted["components"]["schemas"]["LabNode"]["properties"]["ipv4_address"] = {"type": "string"} + planted["components"]["schemas"]["LabCreateRequest"]["properties"]["candidate_id"] = {"type": "string"} + self.assertEqual( + [leak.rsplit(".", 1)[-1] for leak in labd_leaks(planted)], + ["ipv4_address"] * len(labd_leaks(planted)), + ) + self.assertTrue(labd_leaks(planted)) + self.assertEqual( + labd_request_identifiers(planted), + ["PUT /v1/labs/{lab_id} body.candidate_id"], + ) + + def test_request_objects_reject_unknown_fields(self) -> None: + for _, _, _, operation in operations(self.document): + for media in operation.get("requestBody", {}).get("content", {}).values(): + for location, schema in walk_schema(media["schema"], self.schemas, set(), operation["operationId"]): + with self.subTest(location=location): + self.assertIs(schema.get("additionalProperties"), False) + + def test_busy_pool_is_separate_from_an_infrastructure_failure(self) -> None: + codes = set(self.schemas["ProblemCode"]["enum"]) + self.assertTrue({"lab_pool_busy", "lab_unavailable", "unauthenticated", "idempotency_key_reused"} <= codes) + create = self.document["paths"]["/v1/labs/{lab_id}"]["put"] + busy = resolve_response(self.document, create["responses"]["503"]) + self.assertTrue(busy["headers"]["Retry-After"]["required"]) + example = busy["content"]["application/problem+json"]["examples"]["lab_pool_busy"]["value"] + self.assertEqual((example["status"], example["code"]), (503, "lab_pool_busy")) + self.assertTrue({"200", "202", "503", "default"} <= set(create["responses"])) + + def test_create_is_idempotent_by_lab_id(self) -> None: + item = self.document["paths"]["/v1/labs/{lab_id}"] + (reference,) = item["parameters"] + parameter = resolve_parameter(self.document, reference) + self.assertEqual((parameter["in"], parameter["schema"]["format"]), ("path", "uuid")) + self.assertNotIn("lab_id", self.schemas["LabCreateRequest"]["properties"]) + + +if __name__ == "__main__": + unittest.main()