feat(labs): describe the lab task contract and the provisioner port
This commit is contained in:
1 parent
3de226b16c
commit
9fdaa62b9b
91 files changed
+19262
-155
No files matched your search
+5
-1
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -511,6 +511,7 @@ schemas:
|
||||
- $ref: "#/schemas/FindErrorItemContent"
|
||||
- $ref: "#/schemas/ConfigurationItemContent"
|
||||
- $ref: "#/schemas/PracticeItemContent"
|
||||
- $ref: "./lab_schemas.yml#/schemas/LabItemContent"
|
||||
AssessmentItem:
|
||||
type: object
|
||||
description: >-
|
||||
|
||||
@@ -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"
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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:<code>` 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
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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:<code>` 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
|
||||
@@ -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 <token>`; 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 <token>` 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:<code>` 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
|
||||
@@ -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 <token>`; 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 <token>`
|
||||
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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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/
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
generator:
|
||||
features:
|
||||
disable:
|
||||
- paths/server
|
||||
- webhooks/server
|
||||
@@ -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 (
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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" {
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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{},
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
)
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 <token>` 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
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -128,5 +128,7 @@ function parseStoredDraft(raw: string, item: AssessmentItem): AnswerDraft | null
|
||||
sourceCode: value.sourceCode,
|
||||
};
|
||||
}
|
||||
case "lab":
|
||||
return { format: "lab" };
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
@@ -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: "Проверьте ответ и повторите отправку." };
|
||||
|
||||
@@ -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(
|
||||
<AnswerForm
|
||||
@@ -66,4 +80,12 @@ describe("answer form", () => {
|
||||
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("<form");
|
||||
});
|
||||
});
|
||||
@@ -74,6 +74,7 @@ export function AnswerForm({
|
||||
}
|
||||
|
||||
if (concealed) return null;
|
||||
if (item.content.format === "lab") return <LabPlaceholder nodes={item.content.nodes} />;
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={submit} onKeyDown={handleKeyDown}>
|
||||
@@ -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 (
|
||||
<section className={styles.form} aria-label="Практическая лаборатория">
|
||||
<p>Это задание выполняется в лаборатории из узлов:</p>
|
||||
<ul>
|
||||
{nodes.map((node) => (
|
||||
<li key={node.name}>
|
||||
{node.name} ({node.kind === "mikrotik" ? "MikroTik" : "Ubuntu"})
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className={styles.hint}>Открыть лабораторию из этой страницы пока нельзя.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type AnswerFieldsProps = {
|
||||
item: AssessmentItem;
|
||||
draft: AnswerDraft;
|
||||
@@ -339,5 +362,8 @@ function AnswerFields({ item, draft, setDraft }: AnswerFieldsProps) {
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
case "lab":
|
||||
// AnswerForm shows LabPlaceholder instead of the form.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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<Extract<AssessmentLab, object>> = {}): 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<Extract<AssessmentLab, object>> = {}): 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<Extract<AssessmentLabConsoleSession, object>> = {}): 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<Extract<AssessmentLab, object>> = {}): 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<Parameters<typeof http.get>[1]>[0]) => Promise<AssessmentAvailability> | AssessmentAvailability), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/me/assessment-availability', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
@@ -409,6 +430,54 @@ export const getGetMyAssessmentResultMockHandler = (overrideResponse?: Assessmen
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getCreateMyAssessmentLabMockHandler = (overrideResponse?: AssessmentLab | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentLab> | AssessmentLab), options?: RequestHandlerOptions) => {
|
||||
return http.post('*/api/v1/me/assessment-attempts/:attemptId/labs', async (info: Parameters<Parameters<typeof http.post>[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<Parameters<typeof http.get>[1]>[0]) => Promise<AssessmentLab> | AssessmentLab), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/me/assessment-attempts/:attemptId/labs/:labId', async (info: Parameters<Parameters<typeof http.get>[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<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentLabConsoleSession> | AssessmentLabConsoleSession), options?: RequestHandlerOptions) => {
|
||||
return http.post('*/api/v1/me/assessment-attempts/:attemptId/labs/:labId/console-sessions', async (info: Parameters<Parameters<typeof http.post>[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<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentLab> | AssessmentLab), options?: RequestHandlerOptions) => {
|
||||
return http.post('*/api/v1/me/assessment-attempts/:attemptId/labs/:labId/submission', async (info: Parameters<Parameters<typeof http.post>[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()
|
||||
]
|
||||
@@ -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 = <TError = ErrorType<Problem>,
|
||||
/**
|
||||
* 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<TData = Awaited<ReturnType<typeof getMy
|
||||
|
||||
|
||||
|
||||
export const getCreateMyAssessmentLabUrl = (attemptId: string,) => {
|
||||
|
||||
|
||||
|
||||
|
||||
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<typeof apiRequest>[1]): Promise<AssessmentLab> => {
|
||||
|
||||
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
|
||||
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<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
|
||||
);
|
||||
}
|
||||
const headers: Record<string, string | readonly string[]> = {};
|
||||
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
|
||||
if (value !== undefined) headers[name] = value;
|
||||
}
|
||||
return headers;
|
||||
};
|
||||
return apiRequest<AssessmentLab>(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 = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createMyAssessmentLab>>, TError,CreateMyAssessmentLabMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof createMyAssessmentLab>>, 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<Awaited<ReturnType<typeof createMyAssessmentLab>>, CreateMyAssessmentLabMutationVariables> = (props) => {
|
||||
const {attemptId,data,headers} = props ?? {};
|
||||
|
||||
return createMyAssessmentLab(attemptId,data,headers,requestOptions)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { mutationFn, ...mutationOptions }}
|
||||
|
||||
export type CreateMyAssessmentLabMutationResult = NonNullable<Awaited<ReturnType<typeof createMyAssessmentLab>>>
|
||||
export type CreateMyAssessmentLabMutationBody = AssessmentLabCreate
|
||||
export type CreateMyAssessmentLabMutationError = ErrorType<Problem>
|
||||
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 = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createMyAssessmentLab>>, TError,CreateMyAssessmentLabMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof createMyAssessmentLab>>,
|
||||
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<typeof apiRequest>[1]): Promise<AssessmentLab> => {
|
||||
|
||||
return apiRequest<AssessmentLab>(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 = <TData = Awaited<ReturnType<typeof getMyAssessmentLab>>, TError = ErrorType<Problem>>(attemptId: string,
|
||||
labId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentLab>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentLabQueryKey(attemptId,labId);
|
||||
|
||||
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getMyAssessmentLab>>> = ({ signal }) => getMyAssessmentLab(attemptId,labId, { signal, ...requestOptions });
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { queryKey, queryFn, enabled: attemptId !== null && attemptId !== undefined && labId !== null && labId !== undefined, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentLab>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
}
|
||||
|
||||
export type GetMyAssessmentLabQueryResult = NonNullable<Awaited<ReturnType<typeof getMyAssessmentLab>>>
|
||||
export type GetMyAssessmentLabQueryError = ErrorType<Problem>
|
||||
|
||||
|
||||
export function useGetMyAssessmentLab<TData = Awaited<ReturnType<typeof getMyAssessmentLab>>, TError = ErrorType<Problem>>(
|
||||
attemptId: string,
|
||||
labId: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentLab>>, TError, TData>> & Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getMyAssessmentLab>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getMyAssessmentLab>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetMyAssessmentLab<TData = Awaited<ReturnType<typeof getMyAssessmentLab>>, TError = ErrorType<Problem>>(
|
||||
attemptId: string,
|
||||
labId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentLab>>, TError, TData>> & Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getMyAssessmentLab>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getMyAssessmentLab>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetMyAssessmentLab<TData = Awaited<ReturnType<typeof getMyAssessmentLab>>, TError = ErrorType<Problem>>(
|
||||
attemptId: string,
|
||||
labId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentLab>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
/**
|
||||
* @summary Read the lab of an assessment attempt item.
|
||||
*/
|
||||
|
||||
export function useGetMyAssessmentLab<TData = Awaited<ReturnType<typeof getMyAssessmentLab>>, TError = ErrorType<Problem>>(
|
||||
attemptId: string,
|
||||
labId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentLab>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
||||
|
||||
const queryOptions = getGetMyAssessmentLabQueryOptions(attemptId,labId,options)
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
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<typeof apiRequest>[1]): Promise<AssessmentLabConsoleSession> => {
|
||||
|
||||
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
|
||||
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<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
|
||||
);
|
||||
}
|
||||
const headers: Record<string, string | readonly string[]> = {};
|
||||
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
|
||||
if (value !== undefined) headers[name] = value;
|
||||
}
|
||||
return headers;
|
||||
};
|
||||
return apiRequest<AssessmentLabConsoleSession>(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 = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createMyAssessmentLabConsoleSession>>, TError,CreateMyAssessmentLabConsoleSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof createMyAssessmentLabConsoleSession>>, 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<Awaited<ReturnType<typeof createMyAssessmentLabConsoleSession>>, CreateMyAssessmentLabConsoleSessionMutationVariables> = (props) => {
|
||||
const {attemptId,labId,data} = props ?? {};
|
||||
|
||||
return createMyAssessmentLabConsoleSession(attemptId,labId,data,requestOptions)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { mutationFn, ...mutationOptions }}
|
||||
|
||||
export type CreateMyAssessmentLabConsoleSessionMutationResult = NonNullable<Awaited<ReturnType<typeof createMyAssessmentLabConsoleSession>>>
|
||||
export type CreateMyAssessmentLabConsoleSessionMutationBody = AssessmentLabConsoleSessionCreate
|
||||
export type CreateMyAssessmentLabConsoleSessionMutationError = ErrorType<Problem>
|
||||
export type CreateMyAssessmentLabConsoleSessionMutationVariables = {attemptId: string;labId: string;data: AssessmentLabConsoleSessionCreate}
|
||||
|
||||
/**
|
||||
* @summary Open a console session of one node of a ready lab.
|
||||
*/
|
||||
export const useCreateMyAssessmentLabConsoleSession = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createMyAssessmentLabConsoleSession>>, TError,CreateMyAssessmentLabConsoleSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof createMyAssessmentLabConsoleSession>>,
|
||||
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<typeof apiRequest>[1]): Promise<AssessmentLab> => {
|
||||
|
||||
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
|
||||
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<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
|
||||
);
|
||||
}
|
||||
const headers: Record<string, string | readonly string[]> = {};
|
||||
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
|
||||
if (value !== undefined) headers[name] = value;
|
||||
}
|
||||
return headers;
|
||||
};
|
||||
return apiRequest<AssessmentLab>(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 = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof submitMyAssessmentLab>>, TError,SubmitMyAssessmentLabMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof submitMyAssessmentLab>>, 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<Awaited<ReturnType<typeof submitMyAssessmentLab>>, SubmitMyAssessmentLabMutationVariables> = (props) => {
|
||||
const {attemptId,labId,data,headers} = props ?? {};
|
||||
|
||||
return submitMyAssessmentLab(attemptId,labId,data,headers,requestOptions)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { mutationFn, ...mutationOptions }}
|
||||
|
||||
export type SubmitMyAssessmentLabMutationResult = NonNullable<Awaited<ReturnType<typeof submitMyAssessmentLab>>>
|
||||
export type SubmitMyAssessmentLabMutationBody = AssessmentLabSubmission
|
||||
export type SubmitMyAssessmentLabMutationError = ErrorType<Problem>
|
||||
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 = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof submitMyAssessmentLab>>, TError,SubmitMyAssessmentLabMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof submitMyAssessmentLab>>,
|
||||
TError,
|
||||
SubmitMyAssessmentLabMutationVariables,
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getSubmitMyAssessmentLabMutationOptions(options), queryClient);
|
||||
}
|
||||
@@ -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.'),
|
||||
|
||||
@@ -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.'),
|
||||
|
||||
@@ -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.'),
|
||||
|
||||
@@ -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.'),
|
||||
|
||||
@@ -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<typeof AssessmentItem>;
|
||||
|
||||
@@ -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<typeof AssessmentLab>;
|
||||
export type AssessmentLabOutput = zod.output<typeof AssessmentLab>;
|
||||
@@ -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<typeof AssessmentLabConsoleSession>;
|
||||
export type AssessmentLabConsoleSessionOutput = zod.output<typeof AssessmentLabConsoleSession>;
|
||||
@@ -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<typeof AssessmentLabConsoleSessionCreate>;
|
||||
export type AssessmentLabConsoleSessionCreateOutput = zod.output<typeof AssessmentLabConsoleSessionCreate>;
|
||||
@@ -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<typeof AssessmentLabCreate>;
|
||||
export type AssessmentLabCreateOutput = zod.output<typeof AssessmentLabCreate>;
|
||||
@@ -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<typeof AssessmentLabFailureReason>;
|
||||
export type AssessmentLabFailureReasonOutput = zod.output<typeof AssessmentLabFailureReason>;
|
||||
@@ -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<typeof AssessmentLabNode>;
|
||||
export type AssessmentLabNodeOutput = zod.output<typeof AssessmentLabNode>;
|
||||
@@ -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<typeof AssessmentLabNodeKind>;
|
||||
export type AssessmentLabNodeKindOutput = zod.output<typeof AssessmentLabNodeKind>;
|
||||
@@ -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<typeof AssessmentLabNodeName>;
|
||||
export type AssessmentLabNodeNameOutput = zod.output<typeof AssessmentLabNodeName>;
|
||||
@@ -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<typeof AssessmentLabState>;
|
||||
export type AssessmentLabStateOutput = zod.output<typeof AssessmentLabState>;
|
||||
@@ -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<typeof AssessmentLabSubmission>;
|
||||
export type AssessmentLabSubmissionOutput = zod.output<typeof AssessmentLabSubmission>;
|
||||
@@ -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.'),
|
||||
|
||||
@@ -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<typeof CreateMyAssessmentLabBody>;
|
||||
export type CreateMyAssessmentLabBodyOutput = zod.output<typeof CreateMyAssessmentLabBody>;
|
||||
+19
@@ -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<typeof CreateMyAssessmentLabConsoleSessionBody>;
|
||||
export type CreateMyAssessmentLabConsoleSessionBodyOutput = zod.output<typeof CreateMyAssessmentLabConsoleSessionBody>;
|
||||
@@ -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<typeof CreateMyAssessmentLabHeaders>;
|
||||
export type CreateMyAssessmentLabHeadersOutput = zod.output<typeof CreateMyAssessmentLabHeaders>;
|
||||
@@ -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';
|
||||
@@ -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<typeof ItemContent>;
|
||||
export type ItemContentOutput = zod.output<typeof ItemContent>;
|
||||
@@ -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<typeof LabAnswer>;
|
||||
export type LabAnswerOutput = zod.output<typeof LabAnswer>;
|
||||
@@ -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<typeof LabItemContent>;
|
||||
export type LabItemContentOutput = zod.output<typeof LabItemContent>;
|
||||
@@ -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<typeof SubmitMyAssessmentLabBody>;
|
||||
export type SubmitMyAssessmentLabBodyOutput = zod.output<typeof SubmitMyAssessmentLabBody>;
|
||||
@@ -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<typeof SubmitMyAssessmentLabHeaders>;
|
||||
export type SubmitMyAssessmentLabHeadersOutput = zod.output<typeof SubmitMyAssessmentLabHeaders>;
|
||||
@@ -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"}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user