diff --git a/.agents/sources-of-truth.md b/.agents/sources-of-truth.md index 18cde8d..1955501 100644 --- a/.agents/sources-of-truth.md +++ b/.agents/sources-of-truth.md @@ -4,7 +4,7 @@ Use the source that owns the fact being discussed. Read the relevant source befo - The user's request sets the authorized task scope and product choices for that task. - Source code shows behavior that exists in this checkout. A passing test gives evidence only for the behavior it exercises. -- api/core/openapi.yml and api/ml/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output. +- api/core/openapi.yml, api/ml/openapi.yml, and api/runner/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output. - Backend migrations define the database schema. sqlc query files define queries that sqlc generates. - Makefiles and checked-in tool configuration define supported project commands and options. Lockfiles preserve selected application dependency versions. Toolchain declarations define runtime versions; the Go backend uses exact version 1.26.9. Compose and Dockerfiles define image references, including intentionally moving `latest` or `alpine` tags. - Compose, Nginx, and observability configuration define the local deployment scaffold. They do not prove that a remote deployment or production security review occurred. diff --git a/.agents/standards/contracts.md b/.agents/standards/contracts.md index 33f3db0..44f85cd 100644 --- a/.agents/standards/contracts.md +++ b/.agents/standards/contracts.md @@ -4,10 +4,11 @@ The repository has separate public and internal OpenAPI contracts: - api/core/openapi.yml describes browser-to-Go operations. - api/ml/openapi.yml describes internal Go-to-ML operations. +- api/runner/openapi.yml describes internal operations between Go and the code runner. -Edit the split source files referenced by these roots. Use the API Makefile to merge schemas, bundle, and lint both specifications. Do not hand-edit bundled files. +Edit the split source files referenced by these roots. Use the API Makefile to merge schemas, bundle, and lint every specification. Do not hand-edit bundled files. -The selected Go server generator is ogen. The generated Go handler is mounted under chi. Orval generates the TypeScript client and related frontend artifacts. The Go ML client is configured in backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator uses ml/codegen/pyproject.toml to generate Pydantic v2 models in ml/src/lincodex_ml/api/models.py from the ML bundle. There are three code generation unit directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Each consumer owns the configuration for its generated code; contract sources remain shared under api/. +The selected Go server generator is ogen. The generated Go handler is mounted under chi. Orval generates the TypeScript client and related frontend artifacts. The Go ML client is configured in backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. The Go code runner client is configured in backend/codegen/ogen-code-runner.yml and generated into backend/internal/adapter/secondary/code_runner/api/. datamodel-code-generator uses ml/codegen/pyproject.toml to generate Pydantic v2 models in ml/src/lincodex_ml/api/models.py from the ML bundle. There are three code generation unit directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Each consumer owns the configuration for its generated code; contract sources remain shared under api/. OpenAPI 3.2.0 is the target contract version. Verify only the feature subset used by this repository through the pinned bundler, linter, ogen, Go runtime path, Orval, Python Pydantic models, and documentation pipeline. A passing fixture does not establish full support for every OpenAPI 3.2 feature. Record the exact checks run. diff --git a/Makefile b/Makefile index 54897ad..9c0f46d 100644 --- a/Makefile +++ b/Makefile @@ -13,44 +13,47 @@ install: ## Install project dependencies printf '\n==> %s install\n' "$$part"; \ $(MAKE) -C "$$part" install || status=1; \ done; \ - printf '\n==> backend deps\n'; \ - $(MAKE) -C backend deps || status=1; \ + for part in backend runner; do \ + printf '\n==> %s deps\n' "$$part"; \ + $(MAKE) -C "$$part" deps || status=1; \ + done; \ exit "$$status" generate: ## Generate shared contracts, Go and TypeScript code, and Python models $(MAKE) -C api bundle API_PREPARED=1 $(MAKE) -C backend generate + API_PREPARED=1 $(MAKE) -C runner generate API_PREPARED=1 $(MAKE) -C frontend generate API_PREPARED=1 $(MAKE) -C ml generate gen: generate ## Alias for generate fmt: ## Format all project parts - @status=0; for part in api backend frontend ml; do \ + @status=0; for part in api backend runner frontend ml; do \ printf '\n==> %s fmt\n' "$$part"; \ $(MAKE) -C "$$part" fmt || status=1; \ done; exit "$$status" fmt-check: ## Check formatting without changing files - @status=0; for part in api backend frontend ml; do \ + @status=0; for part in api backend runner frontend ml; do \ printf '\n==> %s fmt-check\n' "$$part"; \ $(MAKE) -C "$$part" fmt-check || status=1; \ done; exit "$$status" lint: ## Run configured linters - @status=0; for part in api backend frontend ml; do \ + @status=0; for part in api backend runner frontend ml; do \ printf '\n==> %s lint\n' "$$part"; \ $(MAKE) -C "$$part" lint || status=1; \ done; exit "$$status" test: ## Run unit and component tests - @status=0; for part in backend frontend ml; do \ + @status=0; for part in backend runner frontend ml; do \ printf '\n==> %s test\n' "$$part"; \ $(MAKE) -C "$$part" test || status=1; \ done; exit "$$status" check: ## Run local checks for code, docs, deployment, and observability - @status=0; for part in api backend frontend ml deploy observability; do \ + @status=0; for part in api backend runner frontend ml deploy observability; do \ printf '\n==> %s check\n' "$$part"; \ $(MAKE) -C "$$part" check || status=1; \ done; \ diff --git a/README.en.md b/README.en.md index 8863bf6..c6e4465 100644 --- a/README.en.md +++ b/README.en.md @@ -43,6 +43,7 @@ Short directory guides: | [backend/](backend/README.en.md) | Main Go service | | [frontend/](frontend/README.en.md) | React and TypeScript interface | | [ml/](ml/README.en.md) | Separate Python service for ML | +| [runner/](runner/README.en.md) | Go code runner with nsjail | | [deploy/](deploy/README.en.md) | Docker Compose, Nginx, and service startup | | [observability/](observability/README.en.md) | Metrics, logs, and dashboards | | [security/](security/README.en.md) | Security scanners and rules | diff --git a/README.md b/README.md index 28e8045..71e42d9 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ make -C deploy demo-seed DEMO_MODE=isolated | [backend/](backend/README.md) | Основной сервис на Go | | [frontend/](frontend/README.md) | Интерфейс на React и TypeScript | | [ml/](ml/README.md) | Отдельный Python-сервис для ML | +| [runner/](runner/README.md) | Исполнитель кода на Go с nsjail | | [deploy/](deploy/README.md) | Docker Compose, Nginx и запуск сервисов | | [observability/](observability/README.md) | Метрики, логи и дашборды | | [security/](security/README.md) | Сканеры и правила безопасности | diff --git a/api/Makefile b/api/Makefile index 529cbed..a1f217e 100644 --- a/api/Makefile +++ b/api/Makefile @@ -16,23 +16,27 @@ 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 and ML bundles +bundle: ## Merge split schemas and create public, ML, and code runner 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" "$(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" .PHONY: lint -lint: bundle ## Lint both bundled contracts +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" .PHONY: check -check: lint ## Build and lint both contract bundles +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_merge_schemas.py' PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_contract_copies.py' 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' .PHONY: check-compat check-compat: bundle ## Compare the public contract with API_BASE_REF diff --git a/api/README.en.md b/api/README.en.md index 47ffbb7..d2075e3 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -6,9 +6,10 @@ Shared OpenAPI contracts for Go, the frontend, and ML. Contract changes come fir - `core/` defines the main backend's public API. - `ml/` defines the ML service's internal HTTP API. +- `runner/` defines the internal HTTP API of the own code runner. - `testdata/` contains a specification for checking tool compatibility with OpenAPI 3.2.0. -Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`. +Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`; the code runner server code is generated from `runner/codegen/`. From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code. @@ -100,6 +101,17 @@ Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with t The ML service answers its errors with the same `Problem` schema. Its `ProblemCode` enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, and 501 to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback. +### Code runner contract + +`runner/openapi.yml` describes the internal API of the code runner, which only the Go backend calls. ogen generates the Go client from `backend/codegen/ogen-code-runner.yml` into `backend/internal/adapter/secondary/code_runner/api/`; no use case calls it yet. + +- Transport and sign-in. The runner listens on a private interface of its host over HTTPS (TLS 1.3). Every operation except `/healthz` and `/readyz` requires `Authorization: Bearer `; the token is a shared random secret of at least 32 characters from the deployment secret store. A wrong or missing token answers 401 `unauthenticated`. Plain HTTP is allowed only by an explicit switch of the local dev Compose file. +- Data. `RunRequest` carries only the language, the source code, the limits, and the test groups; each group has a label, a visibility (`public` or `hidden`), a checker kind, and tests with an input and an expected output. It has no candidate, account, attempt, task, or company field; `scripts/test_runner_contract.py` checks this for every request schema, together with `additionalProperties: false` on every request object. +- Idempotency. `PUT /v1/runs/{run_id}` (`SubmitRun`) takes a random UUID from the backend. A new ID with a free slot starts the run and answers 202, the same ID with the same body returns the current state with 200 without running again, and the same ID with a different body answers 422 `idempotency_key_reused`. Bodies are compared by a SHA-256 fingerprint of the decoded request. When every slot is busy or the process is stopping, the answer is 503 `runner_busy` with `Retry-After`; nothing is stored, and the backend keeps the queue. +- Result. `GetRun` returns `state` (`running` or `finished`) and, per group, the outcome `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error`, or `infrastructure_failure`, the number of passed tests, the CPU time, and the peak memory. `limit` names the limit that stopped a test (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Only public tests carry a stderr diagnostic; hidden tests never carry program output. +- Checker. The current kinds are `exact` (comparison after normalizing CRLF, trailing spaces of lines, and trailing empty lines) and `tokens` (token sequences split on ASCII whitespace). The `Checker` object grows with new `kind` values and optional parameters, such as a float tolerance. +- Errors use the api/core `Problem` shape with a runner-specific `ProblemCode` enum: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal`, and `runner_busy`. `scripts/test_runner_contract.py` checks that the shape matches api/core. + ### Identity: sessions, cookie, and CSRF The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders. diff --git a/api/README.md b/api/README.md index e46752e..97ef724 100644 --- a/api/README.md +++ b/api/README.md @@ -6,9 +6,10 @@ - `core/` - публичный API основного backend. - `ml/` - внутренний HTTP API ML-сервиса. +- `runner/` - внутренний HTTP API собственного исполнителя кода. - `testdata/` - спецификация для проверки совместимости инструментов с OpenAPI 3.2.0. -Маршруты лежат в `routes/`, схемы - в `components/`. Файлы `openapi.bundle.yml` собираются автоматически. Конфигурации генераторов находятся в `backend/codegen/`, `frontend/codegen/` и `ml/codegen/`. +Маршруты лежат в `routes/`, схемы - в `components/`. Файлы `openapi.bundle.yml` собираются автоматически. Конфигурации генераторов находятся в `backend/codegen/`, `frontend/codegen/` и `ml/codegen/`; серверный код исполнителя генерируется по `runner/codegen/`. Из корня: `make -C api check` проверяет контракты, `make generate` обновляет весь сгенерированный код. @@ -100,6 +101,17 @@ ML-сервис отвечает на ошибки той же схемой `Problem`. Его перечисление `ProblemCode` сохраняет публичные коды identity, чтобы оба контракта имели одну форму, но сервис их никогда не возвращает. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429 и 501 - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback. +### Контракт исполнителя кода + +`runner/openapi.yml` описывает внутренний API исполнителя кода, который вызывает только Go backend. Go-клиент генерируется ogen по `backend/codegen/ogen-code-runner.yml` в `backend/internal/adapter/secondary/code_runner/api/`; его пока не вызывает ни один usecase. + +- Транспорт и вход. Исполнитель слушает частный интерфейс своего хоста по HTTPS (TLS 1.3). Все операции, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer `; токен - общий случайный секрет не короче 32 символов из хранилища секретов развертывания. Неверный или отсутствующий токен дает 401 `unauthenticated`. Простой HTTP разрешен только явным переключателем локального dev Compose. +- Данные. `RunRequest` содержит только язык, исходный код, лимиты и группы тестов; у каждой группы есть метка, видимость (`public` или `hidden`), вид checker и тесты с входом и ожидаемым выводом. Полей кандидата, аккаунта, попытки, задания или компании нет; `scripts/test_runner_contract.py` проверяет это для всех схем запросов, а также `additionalProperties: false` у каждого объекта запроса. +- Идемпотентность. `PUT /v1/runs/{run_id}` (`SubmitRun`) принимает случайный UUID от backend. Новый ID при свободном слоте запускает прогон и отвечает 202, тот же ID с тем же телом возвращает текущее состояние с 200 без повторного запуска, тот же ID с другим телом дает 422 `idempotency_key_reused`. Тела сравниваются по SHA-256 отпечатку разобранного запроса. Когда все слоты заняты или процесс останавливается, ответ - 503 `runner_busy` с `Retry-After`; ничего не сохраняется, очередь держит backend. +- Результат. `GetRun` возвращает `state` (`running` или `finished`) и итог по каждой группе: `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` или `infrastructure_failure`, число пройденных тестов, время CPU и пиковую память. `limit` называет сработавший лимит (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Диагностика stderr есть только у публичных тестов; у скрытых тестов нет вывода программы. +- Checker. Сейчас есть `exact` (сравнение после нормализации CRLF, хвостовых пробелов строк и пустых строк в конце) и `tokens` (последовательности токенов по ASCII-пробелам). Объект `Checker` расширяется новыми `kind` и необязательными параметрами, например допуском для чисел. +- Ошибки используют форму `Problem` из api/core; перечисление `ProblemCode` свое: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal` и `runner_busy`. Совпадение формы с api/core проверяет `scripts/test_runner_contract.py`. + ### Identity: сессии, cookie и CSRF Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками. diff --git a/api/runner/components/responses.yml b/api/runner/components/responses.yml new file mode 100644 index 0000000..55781d6 --- /dev/null +++ b/api/runner/components/responses.yml @@ -0,0 +1,57 @@ +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: Request fields do not match the contract + 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: /groups/1/id + code: invalid + message: The value does not match the contract. + idempotency_key_reused: + summary: The run ID was used with a different payload + value: + type: urn:lincodex:problem:idempotency_key_reused + title: Run ID reused with a different payload + status: 422 + code: idempotency_key_reused + detail: A run with this ID exists with a different payload. +RunnerBusy: + description: >- + Every sandbox slot is busy or the runner is draining; code runner_busy. + Nothing was stored. Retry with the same run 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: 2 + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + runner_busy: + summary: No free sandbox slot + value: + type: urn:lincodex:problem:runner_busy + title: Runner busy + status: 503 + code: runner_busy + detail: Every sandbox slot is busy. Retry later with the same run ID. diff --git a/api/runner/components/schemas.yml b/api/runner/components/schemas.yml new file mode 100644 index 0000000..5814c64 --- /dev/null +++ b/api/runner/components/schemas.yml @@ -0,0 +1,452 @@ +RunnerHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok +RunnerReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready +Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the runner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/ProblemFieldError' +ProblemCode: + type: string + description: 'Stable error code of the runner 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 of SubmitRun; `errors` points at the fields. + + - unauthenticated (401): the bearer token is missing or wrong. + + - not_found (404): the route or the run does not exist. + + - method_not_allowed (405): the route does not support the method. + + - 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 run ID was already used with a different payload. + + - internal (500): unexpected server error. + + - runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After. + + + The Problem shape is the api/core shape; only this enum is specific to the runner.' + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - runner_busy +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 `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/run_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 +RunRequest: + type: object + description: One source and its test groups. The request has no field for a candidate, account, attempt, task, or company; the backend maps a run ID to its own records. + additionalProperties: false + required: + - language + - source + - limits + - groups + properties: + language: + $ref: '#/RunLanguage' + source: + type: string + minLength: 1 + maxLength: 65536 + description: Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and never logs it. + limits: + $ref: '#/RunLimits' + groups: + type: array + minItems: 1 + maxItems: 4 + description: Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are unique in a run. + items: + $ref: '#/TestGroup' +RunLanguage: + type: string + description: Language and runtime of the source. `python3` runs the Python 3 interpreter of the runner image with isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error. + enum: + - python3 +RunLimits: + type: object + description: Limits applied to every test of the run. + additionalProperties: false + required: + - time_limit_ms + - memory_limit_mb + - output_limit_kb + properties: + time_limit_ms: + type: integer + format: int32 + minimum: 100 + maximum: 10000 + description: CPU time per test, including interpreter startup, summed over every process of the test. The wall-clock limit is twice this value plus a fixed startup allowance. + memory_limit_mb: + type: integer + format: int32 + minimum: 32 + maximum: 512 + description: Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit also leaves a small fixed allowance for the sandbox supervisor process. + output_limit_kb: + type: integer + format: int32 + minimum: 1 + maximum: 1024 + description: Standard output per test in KiB. The test is stopped as soon as it writes more. +TestGroup: + type: object + additionalProperties: false + required: + - id + - visibility + - checker + - tests + properties: + id: + $ref: '#/TestKey' + visibility: + $ref: '#/TestVisibility' + checker: + $ref: '#/Checker' + tests: + type: array + minItems: 1 + maxItems: 50 + description: Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test. + items: + $ref: '#/TestCase' +TestKey: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9][a-z0-9_-]{0,31}$ + description: Opaque label chosen by the backend, for example `public` or `hidden-1`. It is not a database identifier. +TestVisibility: + type: string + description: '`public` tests may be shown to the person who wrote the source; their results may carry a diagnostic excerpt. `hidden` results never carry program output or diagnostics.' + enum: + - public + - hidden +Checker: + type: object + description: How the standard output of a test is compared with `expected_output`. Future kinds, such as a float tolerance or a custom checker, add a `kind` value and their own optional parameters to this object. + additionalProperties: false + required: + - kind + properties: + kind: + $ref: '#/CheckerKind' +CheckerKind: + type: string + description: '- exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at the end of each line, and removing trailing empty lines. + + - tokens: both texts split on ASCII whitespace give the same sequence of tokens.' + enum: + - exact + - tokens +TestCase: + type: object + additionalProperties: false + required: + - id + - input + - expected_output + properties: + id: + $ref: '#/TestKey' + input: + type: string + maxLength: 262144 + description: UTF-8 text written to the standard input of the program. + expected_output: + type: string + maxLength: 262144 + description: UTF-8 text the checker compares with the standard output. +RunState: + type: string + description: '`running` until every group was evaluated or the run failed; `finished` when `result` is final.' + enum: + - running + - finished +RunStatus: + type: object + additionalProperties: false + required: + - run_id + - state + properties: + run_id: + type: string + format: uuid + state: + $ref: '#/RunState' + result: + $ref: '#/RunResult' +RunOutcome: + type: string + description: 'Outcome of a test, a group, a compile step, or a whole run. + + + - accepted: the program exited with status 0 within every limit and the checker accepted the output. + + - wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output. + + - compile_error: the source was rejected before any test ran (for Python, a syntax error). + + - time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program. + + - memory_limit_exceeded: the cgroup memory limit stopped the program. + + - output_limit_exceeded: the program wrote more standard output than the limit. + + - runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit. + + - infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID. + + + A run''s outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group''s outcome is the outcome of its first failed test, otherwise accepted.' + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + - infrastructure_failure +TerminationLimit: + type: string + description: 'The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of processes and threads.' + enum: + - cpu_time + - wall_time + - memory + - output + - processes +RunResult: + type: object + additionalProperties: false + required: + - outcome + - groups + - duration_ms + properties: + outcome: + $ref: '#/RunOutcome' + compile: + $ref: '#/CompileResult' + groups: + type: array + maxItems: 4 + description: One result per requested group in request order. After compile_error or infrastructure_failure every group has that outcome and no tests. + items: + $ref: '#/GroupResult' + duration_ms: + type: integer + format: int64 + minimum: 0 + description: Wall-clock time of the whole run in the runner. +CompileResult: + type: object + additionalProperties: false + required: + - outcome + properties: + outcome: + $ref: '#/RunOutcome' + diagnostic: + type: string + maxLength: 4096 + description: Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the source, never test data. +GroupResult: + type: object + additionalProperties: false + required: + - id + - visibility + - outcome + - passed_tests + - total_tests + - tests + properties: + id: + $ref: '#/TestKey' + visibility: + $ref: '#/TestVisibility' + outcome: + $ref: '#/RunOutcome' + passed_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + total_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + max_time_ms: + type: integer + format: int64 + minimum: 0 + description: Largest CPU time of an evaluated test of the group. + max_memory_kb: + type: integer + format: int64 + minimum: 0 + description: Largest peak memory of an evaluated test of the group. + tests: + type: array + maxItems: 50 + description: Results of the evaluated tests in order. Tests after the first failed one are not run and not listed. + items: + $ref: '#/TestResult' +TestResult: + type: object + additionalProperties: false + required: + - id + - outcome + - time_ms + - wall_time_ms + - memory_kb + properties: + id: + $ref: '#/TestKey' + outcome: + $ref: '#/RunOutcome' + time_ms: + type: integer + format: int64 + minimum: 0 + description: CPU time of every process of the test. + wall_time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + description: 'Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including the sandbox supervisor process and file cache charged to the test.' + exit_code: + type: integer + format: int32 + description: Exit status when the program exited normally. + signal: + type: integer + format: int32 + minimum: 1 + maximum: 64 + description: Signal number when the program was killed by a signal. + limit: + $ref: '#/TerminationLimit' + diagnostic: + type: string + maxLength: 2048 + description: Truncated standard error of a failed public test. Hidden tests never carry it. diff --git a/api/runner/components/schemas/health_schemas.yml b/api/runner/components/schemas/health_schemas.yml new file mode 100644 index 0000000..64672f2 --- /dev/null +++ b/api/runner/components/schemas/health_schemas.yml @@ -0,0 +1,22 @@ +schemas: + RunnerHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok + RunnerReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready diff --git a/api/runner/components/schemas/problem_schemas.yml b/api/runner/components/schemas/problem_schemas.yml new file mode 100644 index 0000000..1dd5bfb --- /dev/null +++ b/api/runner/components/schemas/problem_schemas.yml @@ -0,0 +1,138 @@ +schemas: + Problem: + type: object + description: >- + Problem details (RFC 9457) returned with the application/problem+json + media type for every error response. This is the runner copy of the + public api/core Problem schema; keep both copies identical except for + descriptions and the ProblemCode enum. `code` is the stable, + machine-readable reason; clients branch on it rather than on `title`, + `detail`, or the HTTP status alone. The body never contains internal + error text, stack traces, SQL, file paths, credentials, contact data, or + echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: >- + URI that identifies the problem type. It has the form + `urn:lincodex:problem:` and is an identifier, not a link to + dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: >- + Short, fixed English summary of the problem type. It does not change + between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: >- + Safe English explanation of this occurrence. It never contains + internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Request identifier of the call when the caller propagated one; it is + not a secret. + errors: + type: array + maxItems: 100 + description: >- + Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: "#/schemas/ProblemFieldError" + ProblemCode: + type: string + description: |- + Stable error code of the runner 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 of SubmitRun; `errors` points at the fields. + - unauthenticated (401): the bearer token is missing or wrong. + - not_found (404): the route or the run does not exist. + - method_not_allowed (405): the route does not support the method. + - 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 run ID was already used with a different payload. + - internal (500): unexpected server error. + - runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After. + + The Problem shape is the api/core shape; only this enum is specific to the runner. + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - runner_busy + 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 `/limits/time_limit_ms`; an empty string means the whole + body. For a parameter it is `/` followed by the parameter name, for + example `/run_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z][a-z0-9_]*$" + description: >- + Stable field reason. Current values are `required` (missing value) + and `invalid` (malformed value or a value outside the schema). + Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/runner/components/schemas/run_schemas.yml b/api/runner/components/schemas/run_schemas.yml new file mode 100644 index 0000000..562af70 --- /dev/null +++ b/api/runner/components/schemas/run_schemas.yml @@ -0,0 +1,347 @@ +schemas: + RunRequest: + type: object + description: >- + One source and its test groups. The request has no field for a + candidate, account, attempt, task, or company; the backend maps a run ID + to its own records. + additionalProperties: false + required: + - language + - source + - limits + - groups + properties: + language: + $ref: "#/schemas/RunLanguage" + source: + type: string + minLength: 1 + maxLength: 65536 + description: >- + Complete program text in UTF-8. The runner writes it to a read-only + file inside the sandbox and never logs it. + limits: + $ref: "#/schemas/RunLimits" + groups: + type: array + minItems: 1 + maxItems: 4 + description: >- + Test groups in evaluation order, for example one public group and + three hidden groups. Group IDs are unique in a run. + items: + $ref: "#/schemas/TestGroup" + RunLanguage: + type: string + description: >- + Language and runtime of the source. `python3` runs the Python 3 + interpreter of the runner image with isolated mode and no bytecode + writes; a syntax check runs first and fails with compile_error. + enum: + - python3 + RunLimits: + type: object + description: Limits applied to every test of the run. + additionalProperties: false + required: + - time_limit_ms + - memory_limit_mb + - output_limit_kb + properties: + time_limit_ms: + type: integer + format: int32 + minimum: 100 + maximum: 10000 + description: >- + CPU time per test, including interpreter startup, summed over every + process of the test. The wall-clock limit is twice this value plus + a fixed startup allowance. + memory_limit_mb: + type: integer + format: int32 + minimum: 32 + maximum: 512 + description: >- + Memory of the test's processes in MiB, enforced by a cgroup v2 + memory limit without swap. The limit also leaves a small fixed + allowance for the sandbox supervisor process. + output_limit_kb: + type: integer + format: int32 + minimum: 1 + maximum: 1024 + description: >- + Standard output per test in KiB. The test is stopped as soon as it + writes more. + TestGroup: + type: object + additionalProperties: false + required: + - id + - visibility + - checker + - tests + properties: + id: + $ref: "#/schemas/TestKey" + visibility: + $ref: "#/schemas/TestVisibility" + checker: + $ref: "#/schemas/Checker" + tests: + type: array + minItems: 1 + maxItems: 50 + description: >- + Tests in evaluation order. Test IDs are unique in a group. A group + stops at its first failed test. + items: + $ref: "#/schemas/TestCase" + TestKey: + type: string + minLength: 1 + maxLength: 32 + pattern: "^[a-z0-9][a-z0-9_-]{0,31}$" + description: >- + Opaque label chosen by the backend, for example `public` or `hidden-1`. + It is not a database identifier. + TestVisibility: + type: string + description: >- + `public` tests may be shown to the person who wrote the source; their + results may carry a diagnostic excerpt. `hidden` results never carry + program output or diagnostics. + enum: + - public + - hidden + Checker: + type: object + description: >- + How the standard output of a test is compared with `expected_output`. + Future kinds, such as a float tolerance or a custom checker, add a + `kind` value and their own optional parameters to this object. + additionalProperties: false + required: + - kind + properties: + kind: + $ref: "#/schemas/CheckerKind" + CheckerKind: + type: string + description: |- + - exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at the end of each line, and removing trailing empty lines. + - tokens: both texts split on ASCII whitespace give the same sequence of tokens. + enum: + - exact + - tokens + TestCase: + type: object + additionalProperties: false + required: + - id + - input + - expected_output + properties: + id: + $ref: "#/schemas/TestKey" + input: + type: string + maxLength: 262144 + description: UTF-8 text written to the standard input of the program. + expected_output: + type: string + maxLength: 262144 + description: UTF-8 text the checker compares with the standard output. + RunState: + type: string + description: >- + `running` until every group was evaluated or the run failed; + `finished` when `result` is final. + enum: + - running + - finished + RunStatus: + type: object + additionalProperties: false + required: + - run_id + - state + properties: + run_id: + type: string + format: uuid + state: + $ref: "#/schemas/RunState" + result: + $ref: "#/schemas/RunResult" + RunOutcome: + type: string + description: |- + Outcome of a test, a group, a compile step, or a whole run. + + - accepted: the program exited with status 0 within every limit and the checker accepted the output. + - wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output. + - compile_error: the source was rejected before any test ran (for Python, a syntax error). + - time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program. + - memory_limit_exceeded: the cgroup memory limit stopped the program. + - output_limit_exceeded: the program wrote more standard output than the limit. + - runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit. + - infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID. + + A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of its first failed test, otherwise accepted. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + - infrastructure_failure + TerminationLimit: + type: string + description: >- + The limit that stopped a test: CPU time, wall-clock time, memory, + standard output, or the number of processes and threads. + enum: + - cpu_time + - wall_time + - memory + - output + - processes + RunResult: + type: object + additionalProperties: false + required: + - outcome + - groups + - duration_ms + properties: + outcome: + $ref: "#/schemas/RunOutcome" + compile: + $ref: "#/schemas/CompileResult" + groups: + type: array + maxItems: 4 + description: >- + One result per requested group in request order. After + compile_error or infrastructure_failure every group has that + outcome and no tests. + items: + $ref: "#/schemas/GroupResult" + duration_ms: + type: integer + format: int64 + minimum: 0 + description: Wall-clock time of the whole run in the runner. + CompileResult: + type: object + additionalProperties: false + required: + - outcome + properties: + outcome: + $ref: "#/schemas/RunOutcome" + diagnostic: + type: string + maxLength: 4096 + description: >- + Compiler or syntax checker message for compile_error, truncated to + the limit. It can quote the source, never test data. + GroupResult: + type: object + additionalProperties: false + required: + - id + - visibility + - outcome + - passed_tests + - total_tests + - tests + properties: + id: + $ref: "#/schemas/TestKey" + visibility: + $ref: "#/schemas/TestVisibility" + outcome: + $ref: "#/schemas/RunOutcome" + passed_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + total_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + max_time_ms: + type: integer + format: int64 + minimum: 0 + description: Largest CPU time of an evaluated test of the group. + max_memory_kb: + type: integer + format: int64 + minimum: 0 + description: Largest peak memory of an evaluated test of the group. + tests: + type: array + maxItems: 50 + description: >- + Results of the evaluated tests in order. Tests after the first + failed one are not run and not listed. + items: + $ref: "#/schemas/TestResult" + TestResult: + type: object + additionalProperties: false + required: + - id + - outcome + - time_ms + - wall_time_ms + - memory_kb + properties: + id: + $ref: "#/schemas/TestKey" + outcome: + $ref: "#/schemas/RunOutcome" + time_ms: + type: integer + format: int64 + minimum: 0 + description: CPU time of every process of the test. + wall_time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + description: >- + Peak memory of the test in KiB: the cgroup high-water mark of every + process of the test, including the sandbox supervisor process and + file cache charged to the test. + exit_code: + type: integer + format: int32 + description: Exit status when the program exited normally. + signal: + type: integer + format: int32 + minimum: 1 + maximum: 64 + description: Signal number when the program was killed by a signal. + limit: + $ref: "#/schemas/TerminationLimit" + diagnostic: + type: string + maxLength: 2048 + description: >- + Truncated standard error of a failed public test. Hidden tests + never carry it. diff --git a/api/runner/openapi.bundle.yml b/api/runner/openapi.bundle.yml new file mode 100644 index 0000000..f77ed50 --- /dev/null +++ b/api/runner/openapi.bundle.yml @@ -0,0 +1,633 @@ +openapi: 3.2.0 +info: + title: Lincodex Code Runner API + version: 0.1.0 + description: |- + Internal API of the own code runner. Only the Go backend calls it; it is + never exposed to browsers or to the public network. + + Transport and authentication: the runner listens on a private network + interface of its dedicated host and serves HTTPS (TLS 1.3). Every + operation except the health routes requires `Authorization: Bearer + `; the token is a shared random secret of at least 32 characters + that comes from the deployment secret store, never from this repository. + A missing or wrong token answers 401 `unauthenticated`. Plain HTTP exists + only behind an explicit development switch of the local Compose file. + + Data minimization: a run carries only the language, the source code, the + limits, and the test groups. It has no candidate, account, attempt, or + task identifiers, names, or contacts. The run ID is a random UUID chosen + by the backend for idempotency; the runner keeps it only in memory. + + Runs are asynchronous. SubmitRun accepts a run when a sandbox slot is free + and answers immediately; the caller polls GetRun until `state` is + `finished`. The runner does not queue runs: when every slot is busy it + answers 503 `runner_busy`, and the backend keeps the queue. +servers: + - url: / +security: + - bearerAuth: [] +paths: + /healthz: + get: + operationId: GetRunnerHealthz + summary: Check whether the runner process is responding. + security: [] + tags: + - health + responses: + '200': + description: The runner process is responding. + content: + application/json: + schema: + $ref: '#/components/schemas/RunnerHealthResponse' + default: + $ref: '#/components/responses/Problem' + /readyz: + get: + operationId: GetRunnerReadyz + summary: Check whether the sandbox is prepared to accept runs. + description: Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at startup and the process is not draining. A busy runner is still ready; busy is reported by SubmitRun. + security: [] + tags: + - health + responses: + '200': + description: The sandbox is prepared. + content: + application/json: + schema: + $ref: '#/components/schemas/RunnerReadinessResponse' + '503': + description: The sandbox is not prepared or the process is draining. + content: + application/json: + schema: + $ref: '#/components/schemas/RunnerReadinessResponse' + default: + $ref: '#/components/responses/Problem' + /v1/runs/{run_id}: + parameters: + - name: run_id + in: path + required: true + description: Random UUID chosen by the backend for one logical run. It is the idempotency key of SubmitRun and must not encode a candidate, attempt, or task identifier. + schema: + type: string + format: uuid + put: + operationId: SubmitRun + summary: Start a sandboxed run of one source against its test groups. + description: |- + Idempotent by `run_id`: + + - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`; + - the same ID with the same payload answers 200 with the current state of that run, including the finished result, without running it again; + - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_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. + The runner keeps runs only in memory for a bounded time after they + finish; an ID that was forgotten or lost in a restart starts a new run. + Requests above the configured body limit (8 MiB by default) answer 413 + `payload_too_large`. Semantic rules that the schema cannot express answer + 400 `validation_failed`: group IDs are unique in a run, test IDs are + unique in a group, and the number of tests multiplied by + `limits.time_limit_ms` does not exceed 300000. + tags: + - runs + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RunRequest' + responses: + '200': + description: A run with this ID and the same payload already exists. + content: + application/json: + schema: + $ref: '#/components/schemas/RunStatus' + '202': + description: The run was accepted and started. + content: + application/json: + schema: + $ref: '#/components/schemas/RunStatus' + '503': + $ref: '#/components/responses/RunnerBusy' + default: + $ref: '#/components/responses/Problem' + get: + operationId: GetRun + summary: Read the state and, when finished, the per-group result of a run. + description: Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its retention time or lost in a restart. + tags: + - runs + responses: + '200': + description: The current state of the run. + content: + application/json: + schema: + $ref: '#/components/schemas/RunStatus' + default: + $ref: '#/components/responses/Problem' +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: 'Shared random service token sent as `Authorization: Bearer ` over TLS. The runner 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: Request fields do not match the contract + 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: /groups/1/id + code: invalid + message: The value does not match the contract. + idempotency_key_reused: + summary: The run ID was used with a different payload + value: + type: urn:lincodex:problem:idempotency_key_reused + title: Run ID reused with a different payload + status: 422 + code: idempotency_key_reused + detail: A run with this ID exists with a different payload. + RunnerBusy: + description: Every sandbox slot is busy or the runner is draining; code runner_busy. Nothing was stored. Retry with the same run 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: 2 + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + runner_busy: + summary: No free sandbox slot + value: + type: urn:lincodex:problem:runner_busy + title: Runner busy + status: 503 + code: runner_busy + detail: Every sandbox slot is busy. Retry later with the same run ID. + schemas: + ProblemCode: + type: string + description: |- + Stable error code of the runner 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 of SubmitRun; `errors` points at the fields. + - unauthenticated (401): the bearer token is missing or wrong. + - not_found (404): the route or the run does not exist. + - method_not_allowed (405): the route does not support the method. + - 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 run ID was already used with a different payload. + - internal (500): unexpected server error. + - runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After. + + The Problem shape is the api/core shape; only this enum is specific to the runner. + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - runner_busy + 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 `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/run_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 runner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/components/schemas/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/components/schemas/ProblemFieldError' + RunnerHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok + RunnerReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready + RunState: + type: string + description: '`running` until every group was evaluated or the run failed; `finished` when `result` is final.' + enum: + - running + - finished + RunOutcome: + type: string + description: |- + Outcome of a test, a group, a compile step, or a whole run. + + - accepted: the program exited with status 0 within every limit and the checker accepted the output. + - wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output. + - compile_error: the source was rejected before any test ran (for Python, a syntax error). + - time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program. + - memory_limit_exceeded: the cgroup memory limit stopped the program. + - output_limit_exceeded: the program wrote more standard output than the limit. + - runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit. + - infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID. + + A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of its first failed test, otherwise accepted. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + - infrastructure_failure + CompileResult: + type: object + additionalProperties: false + required: + - outcome + properties: + outcome: + $ref: '#/components/schemas/RunOutcome' + diagnostic: + type: string + maxLength: 4096 + description: Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the source, never test data. + TestKey: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9][a-z0-9_-]{0,31}$ + description: Opaque label chosen by the backend, for example `public` or `hidden-1`. It is not a database identifier. + TestVisibility: + type: string + description: '`public` tests may be shown to the person who wrote the source; their results may carry a diagnostic excerpt. `hidden` results never carry program output or diagnostics.' + enum: + - public + - hidden + TerminationLimit: + type: string + description: 'The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of processes and threads.' + enum: + - cpu_time + - wall_time + - memory + - output + - processes + TestResult: + type: object + additionalProperties: false + required: + - id + - outcome + - time_ms + - wall_time_ms + - memory_kb + properties: + id: + $ref: '#/components/schemas/TestKey' + outcome: + $ref: '#/components/schemas/RunOutcome' + time_ms: + type: integer + format: int64 + minimum: 0 + description: CPU time of every process of the test. + wall_time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + description: 'Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including the sandbox supervisor process and file cache charged to the test.' + exit_code: + type: integer + format: int32 + description: Exit status when the program exited normally. + signal: + type: integer + format: int32 + minimum: 1 + maximum: 64 + description: Signal number when the program was killed by a signal. + limit: + $ref: '#/components/schemas/TerminationLimit' + diagnostic: + type: string + maxLength: 2048 + description: Truncated standard error of a failed public test. Hidden tests never carry it. + GroupResult: + type: object + additionalProperties: false + required: + - id + - visibility + - outcome + - passed_tests + - total_tests + - tests + properties: + id: + $ref: '#/components/schemas/TestKey' + visibility: + $ref: '#/components/schemas/TestVisibility' + outcome: + $ref: '#/components/schemas/RunOutcome' + passed_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + total_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + max_time_ms: + type: integer + format: int64 + minimum: 0 + description: Largest CPU time of an evaluated test of the group. + max_memory_kb: + type: integer + format: int64 + minimum: 0 + description: Largest peak memory of an evaluated test of the group. + tests: + type: array + maxItems: 50 + description: Results of the evaluated tests in order. Tests after the first failed one are not run and not listed. + items: + $ref: '#/components/schemas/TestResult' + RunResult: + type: object + additionalProperties: false + required: + - outcome + - groups + - duration_ms + properties: + outcome: + $ref: '#/components/schemas/RunOutcome' + compile: + $ref: '#/components/schemas/CompileResult' + groups: + type: array + maxItems: 4 + description: One result per requested group in request order. After compile_error or infrastructure_failure every group has that outcome and no tests. + items: + $ref: '#/components/schemas/GroupResult' + duration_ms: + type: integer + format: int64 + minimum: 0 + description: Wall-clock time of the whole run in the runner. + RunStatus: + type: object + additionalProperties: false + required: + - run_id + - state + properties: + run_id: + type: string + format: uuid + state: + $ref: '#/components/schemas/RunState' + result: + $ref: '#/components/schemas/RunResult' + RunLanguage: + type: string + description: Language and runtime of the source. `python3` runs the Python 3 interpreter of the runner image with isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error. + enum: + - python3 + RunLimits: + type: object + description: Limits applied to every test of the run. + additionalProperties: false + required: + - time_limit_ms + - memory_limit_mb + - output_limit_kb + properties: + time_limit_ms: + type: integer + format: int32 + minimum: 100 + maximum: 10000 + description: CPU time per test, including interpreter startup, summed over every process of the test. The wall-clock limit is twice this value plus a fixed startup allowance. + memory_limit_mb: + type: integer + format: int32 + minimum: 32 + maximum: 512 + description: Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit also leaves a small fixed allowance for the sandbox supervisor process. + output_limit_kb: + type: integer + format: int32 + minimum: 1 + maximum: 1024 + description: Standard output per test in KiB. The test is stopped as soon as it writes more. + CheckerKind: + type: string + description: |- + - exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at the end of each line, and removing trailing empty lines. + - tokens: both texts split on ASCII whitespace give the same sequence of tokens. + enum: + - exact + - tokens + Checker: + type: object + description: How the standard output of a test is compared with `expected_output`. Future kinds, such as a float tolerance or a custom checker, add a `kind` value and their own optional parameters to this object. + additionalProperties: false + required: + - kind + properties: + kind: + $ref: '#/components/schemas/CheckerKind' + TestCase: + type: object + additionalProperties: false + required: + - id + - input + - expected_output + properties: + id: + $ref: '#/components/schemas/TestKey' + input: + type: string + maxLength: 262144 + description: UTF-8 text written to the standard input of the program. + expected_output: + type: string + maxLength: 262144 + description: UTF-8 text the checker compares with the standard output. + TestGroup: + type: object + additionalProperties: false + required: + - id + - visibility + - checker + - tests + properties: + id: + $ref: '#/components/schemas/TestKey' + visibility: + $ref: '#/components/schemas/TestVisibility' + checker: + $ref: '#/components/schemas/Checker' + tests: + type: array + minItems: 1 + maxItems: 50 + description: Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test. + items: + $ref: '#/components/schemas/TestCase' + RunRequest: + type: object + description: One source and its test groups. The request has no field for a candidate, account, attempt, task, or company; the backend maps a run ID to its own records. + additionalProperties: false + required: + - language + - source + - limits + - groups + properties: + language: + $ref: '#/components/schemas/RunLanguage' + source: + type: string + minLength: 1 + maxLength: 65536 + description: Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and never logs it. + limits: + $ref: '#/components/schemas/RunLimits' + groups: + type: array + minItems: 1 + maxItems: 4 + description: Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are unique in a run. + items: + $ref: '#/components/schemas/TestGroup' diff --git a/api/runner/openapi.yml b/api/runner/openapi.yml new file mode 100644 index 0000000..6d05863 --- /dev/null +++ b/api/runner/openapi.yml @@ -0,0 +1,49 @@ +openapi: 3.2.0 +info: + title: Lincodex Code Runner API + version: 0.1.0 + description: |- + Internal API of the own code runner. Only the Go backend calls it; it is + never exposed to browsers or to the public network. + + Transport and authentication: the runner listens on a private network + interface of its dedicated host and serves HTTPS (TLS 1.3). Every + operation except the health routes requires `Authorization: Bearer + `; the token is a shared random secret of at least 32 characters + that comes from the deployment secret store, never from this repository. + A missing or wrong token answers 401 `unauthenticated`. Plain HTTP exists + only behind an explicit development switch of the local Compose file. + + Data minimization: a run carries only the language, the source code, the + limits, and the test groups. It has no candidate, account, attempt, or + task identifiers, names, or contacts. The run ID is a random UUID chosen + by the backend for idempotency; the runner keeps it only in memory. + + Runs are asynchronous. SubmitRun accepts a run when a sandbox slot is free + and answers immediately; the caller polls GetRun until `state` is + `finished`. The runner does not queue runs: when every slot is busy it + answers 503 `runner_busy`, and the backend keeps the queue. +servers: + - url: / +security: + - bearerAuth: [] +paths: + /healthz: + $ref: ./routes/healthz.yml + /readyz: + $ref: ./routes/readyz.yml + /v1/runs/{run_id}: + $ref: ./routes/runs.yml +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: >- + Shared random service token sent as `Authorization: Bearer ` + over TLS. The runner compares it in constant time and never logs it. + Rotation replaces the secret on both sides; there are no per-user + tokens. + responses: + Problem: + $ref: ./components/responses.yml#/Problem diff --git a/api/runner/routes/healthz.yml b/api/runner/routes/healthz.yml new file mode 100644 index 0000000..7ad5685 --- /dev/null +++ b/api/runner/routes/healthz.yml @@ -0,0 +1,15 @@ +get: + operationId: GetRunnerHealthz + summary: Check whether the runner process is responding. + security: [] + tags: + - health + responses: + "200": + description: The runner process is responding. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunnerHealthResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/runner/routes/readyz.yml b/api/runner/routes/readyz.yml new file mode 100644 index 0000000..931d4ec --- /dev/null +++ b/api/runner/routes/readyz.yml @@ -0,0 +1,25 @@ +get: + operationId: GetRunnerReadyz + summary: Check whether the sandbox is prepared to accept runs. + description: >- + Ready means that the cgroup hierarchy, the work directory, and the sandbox + binary were prepared at startup and the process is not draining. A busy + runner is still ready; busy is reported by SubmitRun. + security: [] + tags: + - health + responses: + "200": + description: The sandbox is prepared. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunnerReadinessResponse + "503": + description: The sandbox is not prepared or the process is draining. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunnerReadinessResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/runner/routes/runs.yml b/api/runner/routes/runs.yml new file mode 100644 index 0000000..6249553 --- /dev/null +++ b/api/runner/routes/runs.yml @@ -0,0 +1,72 @@ +parameters: + - name: run_id + in: path + required: true + description: >- + Random UUID chosen by the backend for one logical run. It is the + idempotency key of SubmitRun and must not encode a candidate, attempt, + or task identifier. + schema: + type: string + format: uuid +put: + operationId: SubmitRun + summary: Start a sandboxed run of one source against its test groups. + description: |- + Idempotent by `run_id`: + + - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`; + - the same ID with the same payload answers 200 with the current state of that run, including the finished result, without running it again; + - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_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. + The runner keeps runs only in memory for a bounded time after they + finish; an ID that was forgotten or lost in a restart starts a new run. + Requests above the configured body limit (8 MiB by default) answer 413 + `payload_too_large`. Semantic rules that the schema cannot express answer + 400 `validation_failed`: group IDs are unique in a run, test IDs are + unique in a group, and the number of tests multiplied by + `limits.time_limit_ms` does not exceed 300000. + tags: + - runs + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunRequest + responses: + "200": + description: A run with this ID and the same payload already exists. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunStatus + "202": + description: The run was accepted and started. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunStatus + "503": + $ref: ../components/responses.yml#/RunnerBusy + default: + $ref: ../components/responses.yml#/Problem +get: + operationId: GetRun + summary: Read the state and, when finished, the per-group result of a run. + description: >- + Answers 404 `not_found` for an ID the runner does not hold, including a + run forgotten after its retention time or lost in a restart. + tags: + - runs + responses: + "200": + description: The current state of the run. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunStatus + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/.golangci.yml b/backend/.golangci.yml index 50f4c64..4f080f6 100644 --- a/backend/.golangci.yml +++ b/backend/.golangci.yml @@ -125,6 +125,7 @@ linters: paths: - internal/adapter/primary/http/api/ - internal/adapter/secondary/ml/api/ + - internal/adapter/secondary/code_runner/api/ - internal/adapter/secondary/postgres/sqlc/ - internal/bootstrap/wire_gen\.go$ - (^|/)mocks/ @@ -160,6 +161,7 @@ formatters: paths: - internal/adapter/primary/http/api/ - internal/adapter/secondary/ml/api/ + - internal/adapter/secondary/code_runner/api/ - internal/adapter/secondary/postgres/sqlc/ - internal/bootstrap/wire_gen\.go$ - (^|/)mocks/ diff --git a/backend/Makefile b/backend/Makefile index dad117f..b9fb8cd 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -98,6 +98,7 @@ generate gen: ## Regenerate API, SQL, and dependency-injection code in dependenc @if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi $(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-sqlc $(MAKE) --no-print-directory gen-wire $(MAKE) --no-print-directory mocks @@ -112,6 +113,11 @@ gen-ml: ## Generate the internal ML service client @if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi $(GO_TOOL) ogen -config codegen/ogen-ml.yml --target internal/adapter/secondary/ml/api --package api --clean ../api/ml/openapi.bundle.yml +.PHONY: gen-code-runner +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-sqlc gen-sqlc: ## Generate PostgreSQL query code from migrations and queries $(GO_TOOL) sqlc generate -f codegen/sqlc.yml diff --git a/backend/codegen/ogen-code-runner.yml b/backend/codegen/ogen-code-runner.yml new file mode 100644 index 0000000..b2e7216 --- /dev/null +++ b/backend/codegen/ogen-code-runner.yml @@ -0,0 +1,5 @@ +generator: + features: + disable: + - paths/server + - webhooks/server diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_cfg_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_cfg_gen.go new file mode 100644 index 0000000..6cb819e --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_cfg_gen.go @@ -0,0 +1,151 @@ +// 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])*)*$"), + "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), + "^[a-z0-9][a-z0-9_-]{0,31}$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_-]{0,31}$"), + "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), +} +var ( + // Allocate option closure once. + clientSpanKind = trace.WithSpanKind(trace.SpanKindClient) +) + +type ( + optionFunc[C any] func(*C) + otelOptionFunc func(*otelConfig) +) + +type otelConfig struct { + TracerProvider trace.TracerProvider + Tracer trace.Tracer + MeterProvider metric.MeterProvider + Meter metric.Meter + Attributes []attribute.KeyValue +} + +func (cfg *otelConfig) initOTEL() { + if cfg.TracerProvider == nil { + cfg.TracerProvider = otel.GetTracerProvider() + } + if cfg.MeterProvider == nil { + cfg.MeterProvider = otel.GetMeterProvider() + } + cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name, + trace.WithInstrumentationVersion(otelogen.SemVersion()), + ) + cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name, + metric.WithInstrumentationVersion(otelogen.SemVersion()), + ) +} + +type clientConfig struct { + otelConfig + Client ht.Client +} + +// ClientOption is client config option. +type ClientOption interface { + applyClient(*clientConfig) +} + +var _ ClientOption = (optionFunc[clientConfig])(nil) + +func (o optionFunc[C]) applyClient(c *C) { + o(c) +} + +var _ ClientOption = (otelOptionFunc)(nil) + +func (o otelOptionFunc) applyClient(c *clientConfig) { + o(&c.otelConfig) +} + +func newClientConfig(opts ...ClientOption) clientConfig { + cfg := clientConfig{ + Client: http.DefaultClient, + } + for _, opt := range opts { + opt.applyClient(&cfg) + } + cfg.initOTEL() + return cfg +} + +type baseClient struct { + cfg clientConfig + requests metric.Int64Counter + errors metric.Int64Counter + duration metric.Float64Histogram +} + +func (cfg clientConfig) baseClient() (c baseClient, err error) { + c = baseClient{cfg: cfg} + if c.requests, err = otelogen.ClientRequestCountCounter(c.cfg.Meter); err != nil { + return c, err + } + if c.errors, err = otelogen.ClientErrorsCountCounter(c.cfg.Meter); err != nil { + return c, err + } + if c.duration, err = otelogen.ClientDurationHistogram(c.cfg.Meter); err != nil { + return c, err + } + return c, nil +} + +// Option is config option. +type Option interface { + ClientOption +} + +// WithTracerProvider specifies a tracer provider to use for creating a tracer. +// +// If none is specified, the global provider is used. +func WithTracerProvider(provider trace.TracerProvider) Option { + return otelOptionFunc(func(cfg *otelConfig) { + if provider != nil { + cfg.TracerProvider = provider + } + }) +} + +// WithMeterProvider specifies a meter provider to use for creating a meter. +// +// If none is specified, the otel.GetMeterProvider() is used. +func WithMeterProvider(provider metric.MeterProvider) Option { + return otelOptionFunc(func(cfg *otelConfig) { + if provider != nil { + cfg.MeterProvider = provider + } + }) +} + +// WithAttributes specifies default otel attributes. +func WithAttributes(attributes ...attribute.KeyValue) Option { + return otelOptionFunc(func(cfg *otelConfig) { + cfg.Attributes = attributes + }) +} + +// WithClient specifies http client to use. +func WithClient(client ht.Client) ClientOption { + return optionFunc[clientConfig](func(cfg *clientConfig) { + if client != nil { + cfg.Client = client + } + }) +} diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_client_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_client_gen.go new file mode 100644 index 0000000..dffd69f --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_client_gen.go @@ -0,0 +1,556 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" + "io" + "net/url" + "strings" + "time" + + "github.com/go-faster/errors" + "github.com/ogen-go/ogen/conv" + ht "github.com/ogen-go/ogen/http" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/otelogen" + "github.com/ogen-go/ogen/uri" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/metric" + semconv "go.opentelemetry.io/otel/semconv/v1.39.0" + "go.opentelemetry.io/otel/trace" +) + +func trimTrailingSlashes(u *url.URL) { + u.Path = strings.TrimRight(u.Path, "/") + u.RawPath = strings.TrimRight(u.RawPath, "/") +} + +// Invoker invokes operations described by OpenAPI v3 specification. +type Invoker interface { + // GetRun invokes GetRun operation. + // + // Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its + // retention time or lost in a restart. + // + // GET /v1/runs/{run_id} + GetRun(ctx context.Context, params GetRunParams) (*RunStatus, error) + // GetRunnerHealthz invokes GetRunnerHealthz operation. + // + // Check whether the runner process is responding. + // + // GET /healthz + GetRunnerHealthz(ctx context.Context) (*RunnerHealthResponse, error) + // GetRunnerReadyz invokes GetRunnerReadyz operation. + // + // Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at + // startup and the process is not draining. A busy runner is still ready; busy is reported by + // SubmitRun. + // + // GET /readyz + GetRunnerReadyz(ctx context.Context) (GetRunnerReadyzRes, error) + // SubmitRun invokes SubmitRun operation. + // + // Idempotent by `run_id`: + // + // - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`; + // - the same ID with the same payload answers 200 with the current state of that run, including the + // finished result, without running it again; + // - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + // - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_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. The runner keeps runs only in + // memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a + // new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`. + // Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique + // in a run, test IDs are unique in a group, and the number of tests multiplied by + // `limits.time_limit_ms` does not exceed 300000. + // + // PUT /v1/runs/{run_id} + SubmitRun(ctx context.Context, request *RunRequest, params SubmitRunParams) (SubmitRunRes, error) +} + +// Client implements OAS client. +type Client struct { + serverURL *url.URL + sec SecuritySource + baseClient +} + +// NewClient initializes new Client defined by OAS. +func NewClient(serverURL string, sec SecuritySource, opts ...ClientOption) (*Client, error) { + u, err := url.Parse(serverURL) + if err != nil { + return nil, err + } + trimTrailingSlashes(u) + + c, err := newClientConfig(opts...).baseClient() + if err != nil { + return nil, err + } + return &Client{ + serverURL: u, + sec: sec, + baseClient: c, + }, nil +} + +type serverURLKey struct{} + +// WithServerURL sets context key to override server URL. +func WithServerURL(ctx context.Context, u *url.URL) context.Context { + return context.WithValue(ctx, serverURLKey{}, u) +} + +func (c *Client) requestURL(ctx context.Context) *url.URL { + u, ok := ctx.Value(serverURLKey{}).(*url.URL) + if !ok { + return c.serverURL + } + return u +} + +// GetRun invokes GetRun operation. +// +// Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its +// retention time or lost in a restart. +// +// GET /v1/runs/{run_id} +func (c *Client) GetRun(ctx context.Context, params GetRunParams) (*RunStatus, error) { + res, err := c.sendGetRun(ctx, params) + return res, err +} + +func (c *Client) sendGetRun(ctx context.Context, params GetRunParams) (res *RunStatus, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetRun"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.URLTemplateKey.String("/v1/runs/{run_id}"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, GetRunOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [2]string + pathParts[0] = "/v1/runs/" + { + // Encode "run_id" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "run_id", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.UUIDToString(params.RunID)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[1] = encoded + } + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "GET", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + + { + type bitset = [1]uint8 + var satisfied bitset + { + stage = "Security:BearerAuth" + switch err := c.securityBearerAuth(ctx, GetRunOperation, r); { + case err == nil: // if NO error + satisfied[0] |= 1 << 0 + case errors.Is(err, ogenerrors.ErrSkipClientSecurity): + // Skip this security. + default: + return res, errors.Wrap(err, "security \"BearerAuth\"") + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied + } + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeGetRunResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// GetRunnerHealthz invokes GetRunnerHealthz operation. +// +// Check whether the runner process is responding. +// +// GET /healthz +func (c *Client) GetRunnerHealthz(ctx context.Context) (*RunnerHealthResponse, error) { + res, err := c.sendGetRunnerHealthz(ctx) + return res, err +} + +func (c *Client) sendGetRunnerHealthz(ctx context.Context) (res *RunnerHealthResponse, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetRunnerHealthz"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.URLTemplateKey.String("/healthz"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, GetRunnerHealthzOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [1]string + pathParts[0] = "/healthz" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "GET", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeGetRunnerHealthzResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// GetRunnerReadyz invokes GetRunnerReadyz operation. +// +// Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at +// startup and the process is not draining. A busy runner is still ready; busy is reported by +// SubmitRun. +// +// GET /readyz +func (c *Client) GetRunnerReadyz(ctx context.Context) (GetRunnerReadyzRes, error) { + res, err := c.sendGetRunnerReadyz(ctx) + return res, err +} + +func (c *Client) sendGetRunnerReadyz(ctx context.Context) (res GetRunnerReadyzRes, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetRunnerReadyz"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.URLTemplateKey.String("/readyz"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, GetRunnerReadyzOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [1]string + pathParts[0] = "/readyz" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "GET", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeGetRunnerReadyzResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + +// SubmitRun invokes SubmitRun operation. +// +// Idempotent by `run_id`: +// +// - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`; +// - the same ID with the same payload answers 200 with the current state of that run, including the +// finished result, without running it again; +// - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; +// - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_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. The runner keeps runs only in +// memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a +// new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`. +// Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique +// in a run, test IDs are unique in a group, and the number of tests multiplied by +// `limits.time_limit_ms` does not exceed 300000. +// +// PUT /v1/runs/{run_id} +func (c *Client) SubmitRun(ctx context.Context, request *RunRequest, params SubmitRunParams) (SubmitRunRes, error) { + res, err := c.sendSubmitRun(ctx, request, params) + return res, err +} + +func (c *Client) sendSubmitRun(ctx context.Context, request *RunRequest, params SubmitRunParams) (res SubmitRunRes, err error) { + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("SubmitRun"), + semconv.HTTPRequestMethodKey.String("PUT"), + semconv.URLTemplateKey.String("/v1/runs/{run_id}"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, SubmitRunOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [2]string + pathParts[0] = "/v1/runs/" + { + // Encode "run_id" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "run_id", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.UUIDToString(params.RunID)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[1] = encoded + } + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "PUT", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + if err := encodeSubmitRunRequest(request, r); err != nil { + return res, errors.Wrap(err, "encode request") + } + + { + type bitset = [1]uint8 + var satisfied bitset + { + stage = "Security:BearerAuth" + switch err := c.securityBearerAuth(ctx, SubmitRunOperation, r); { + case err == nil: // if NO error + satisfied[0] |= 1 << 0 + case errors.Is(err, ogenerrors.ErrSkipClientSecurity): + // Skip this security. + default: + return res, errors.Wrap(err, "security \"BearerAuth\"") + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied + } + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer func() { + // Drain the body to EOF before closing, so the underlying + // connection can be reused by the Transport regardless of the + // response status code. See https://github.com/ogen-go/ogen/issues/1670. + _, _ = io.Copy(io.Discard, body) + _ = body.Close() + }() + + stage = "DecodeResponse" + result, err := decodeSubmitRunResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_interfaces_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_interfaces_gen.go new file mode 100644 index 0000000..587330c --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_interfaces_gen.go @@ -0,0 +1,10 @@ +// Code generated by ogen, DO NOT EDIT. +package api + +type GetRunnerReadyzRes interface { + getRunnerReadyzRes() +} + +type SubmitRunRes interface { + submitRunRes() +} diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_json_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_json_gen.go new file mode 100644 index 0000000..1c39f15 --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_json_gen.go @@ -0,0 +1,2898 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "math/bits" + "strconv" + + "github.com/go-faster/errors" + "github.com/go-faster/jx" + "github.com/ogen-go/ogen/json" + "github.com/ogen-go/ogen/validate" +) + +// Encode implements json.Marshaler. +func (s *Checker) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Checker) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } +} + +var jsonFieldsNameOfChecker = [1]string{ + 0: "kind", +} + +// Decode decodes Checker from json. +func (s *Checker) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Checker to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Checker") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfChecker) { + name = jsonFieldsNameOfChecker[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *Checker) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Checker) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CheckerKind as json. +func (s CheckerKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CheckerKind from json. +func (s *CheckerKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CheckerKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CheckerKind(v) { + case CheckerKindExact: + *s = CheckerKindExact + case CheckerKindTokens: + *s = CheckerKindTokens + default: + *s = CheckerKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CheckerKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CheckerKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CompileResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CompileResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + if s.Diagnostic.Set { + e.FieldStart("diagnostic") + s.Diagnostic.Encode(e) + } + } +} + +var jsonFieldsNameOfCompileResult = [2]string{ + 0: "outcome", + 1: "diagnostic", +} + +// Decode decodes CompileResult from json. +func (s *CompileResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CompileResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "outcome": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "diagnostic": + if err := func() error { + s.Diagnostic.Reset() + if err := s.Diagnostic.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"diagnostic\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CompileResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCompileResult) { + name = jsonFieldsNameOfCompileResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CompileResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CompileResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetRunnerReadyzOK as json. +func (s *GetRunnerReadyzOK) Encode(e *jx.Encoder) { + unwrapped := (*RunnerReadinessResponse)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetRunnerReadyzOK from json. +func (s *GetRunnerReadyzOK) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetRunnerReadyzOK to nil") + } + var unwrapped RunnerReadinessResponse + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetRunnerReadyzOK(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetRunnerReadyzOK) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetRunnerReadyzOK) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetRunnerReadyzServiceUnavailable as json. +func (s *GetRunnerReadyzServiceUnavailable) Encode(e *jx.Encoder) { + unwrapped := (*RunnerReadinessResponse)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetRunnerReadyzServiceUnavailable from json. +func (s *GetRunnerReadyzServiceUnavailable) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetRunnerReadyzServiceUnavailable to nil") + } + var unwrapped RunnerReadinessResponse + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetRunnerReadyzServiceUnavailable(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetRunnerReadyzServiceUnavailable) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetRunnerReadyzServiceUnavailable) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *GroupResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *GroupResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("visibility") + s.Visibility.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("passed_tests") + e.Int32(s.PassedTests) + } + { + e.FieldStart("total_tests") + e.Int32(s.TotalTests) + } + { + if s.MaxTimeMs.Set { + e.FieldStart("max_time_ms") + s.MaxTimeMs.Encode(e) + } + } + { + if s.MaxMemoryKB.Set { + e.FieldStart("max_memory_kb") + s.MaxMemoryKB.Encode(e) + } + } + { + e.FieldStart("tests") + e.ArrStart() + for _, elem := range s.Tests { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfGroupResult = [8]string{ + 0: "id", + 1: "visibility", + 2: "outcome", + 3: "passed_tests", + 4: "total_tests", + 5: "max_time_ms", + 6: "max_memory_kb", + 7: "tests", +} + +// Decode decodes GroupResult from json. +func (s *GroupResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GroupResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "visibility": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Visibility.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"visibility\"") + } + case "outcome": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "passed_tests": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.PassedTests = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"passed_tests\"") + } + case "total_tests": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + v, err := d.Int32() + s.TotalTests = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"total_tests\"") + } + case "max_time_ms": + if err := func() error { + s.MaxTimeMs.Reset() + if err := s.MaxTimeMs.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_time_ms\"") + } + case "max_memory_kb": + if err := func() error { + s.MaxMemoryKB.Reset() + if err := s.MaxMemoryKB.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_memory_kb\"") + } + case "tests": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + s.Tests = make([]TestResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TestResult + if err := elem.Decode(d); err != nil { + return err + } + s.Tests = append(s.Tests, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tests\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode GroupResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b10011111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfGroupResult) { + name = jsonFieldsNameOfGroupResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GroupResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GroupResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CompileResult as json. +func (o OptCompileResult) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes CompileResult from json. +func (o *OptCompileResult) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptCompileResult to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptCompileResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptCompileResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes int32 as json. +func (o OptInt32) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Int32(int32(o.Value)) +} + +// Decode decodes int32 from json. +func (o *OptInt32) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptInt32 to nil") + } + o.Set = true + v, err := d.Int32() + if err != nil { + return err + } + o.Value = int32(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptInt32) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptInt32) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes int64 as json. +func (o OptInt64) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Int64(int64(o.Value)) +} + +// Decode decodes int64 from json. +func (o *OptInt64) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptInt64 to nil") + } + o.Set = true + v, err := d.Int64() + if err != nil { + return err + } + o.Value = int64(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptInt64) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptInt64) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunResult as json. +func (o OptRunResult) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes RunResult from json. +func (o *OptRunResult) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptRunResult to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptRunResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptRunResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes string as json. +func (o OptString) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Str(string(o.Value)) +} + +// Decode decodes string from json. +func (o *OptString) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptString to nil") + } + o.Set = true + v, err := d.Str() + if err != nil { + return err + } + o.Value = string(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptString) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptString) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TerminationLimit as json. +func (o OptTerminationLimit) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Str(string(o.Value)) +} + +// Decode decodes TerminationLimit from json. +func (o *OptTerminationLimit) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptTerminationLimit to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptTerminationLimit) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptTerminationLimit) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *Problem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Problem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + e.Str(s.Type) + } + { + e.FieldStart("title") + e.Str(s.Title) + } + { + e.FieldStart("status") + e.Int32(s.Status) + } + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + if s.Detail.Set { + e.FieldStart("detail") + s.Detail.Encode(e) + } + } + { + if s.Instance.Set { + e.FieldStart("instance") + s.Instance.Encode(e) + } + } + { + if s.TraceID.Set { + e.FieldStart("trace_id") + s.TraceID.Encode(e) + } + } + { + if s.Errors != nil { + e.FieldStart("errors") + e.ArrStart() + for _, elem := range s.Errors { + elem.Encode(e) + } + e.ArrEnd() + } + } +} + +var jsonFieldsNameOfProblem = [8]string{ + 0: "type", + 1: "title", + 2: "status", + 3: "code", + 4: "detail", + 5: "instance", + 6: "trace_id", + 7: "errors", +} + +// Decode decodes Problem from json. +func (s *Problem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Problem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Type = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.Status = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "code": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "detail": + if err := func() error { + s.Detail.Reset() + if err := s.Detail.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"detail\"") + } + case "instance": + if err := func() error { + s.Instance.Reset() + if err := s.Instance.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"instance\"") + } + case "trace_id": + if err := func() error { + s.TraceID.Reset() + if err := s.TraceID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"trace_id\"") + } + case "errors": + if err := func() error { + s.Errors = make([]ProblemFieldError, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProblemFieldError + if err := elem.Decode(d); err != nil { + return err + } + s.Errors = append(s.Errors, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"errors\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Problem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblem) { + name = jsonFieldsNameOfProblem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *Problem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Problem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemCode as json. +func (s ProblemCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemCode from json. +func (s *ProblemCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemCode(v) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + case ProblemCodeInternal: + *s = ProblemCodeInternal + case ProblemCodeRunnerBusy: + *s = ProblemCodeRunnerBusy + default: + *s = ProblemCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProblemFieldError) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProblemFieldError) encodeFields(e *jx.Encoder) { + { + e.FieldStart("in") + s.In.Encode(e) + } + { + e.FieldStart("pointer") + e.Str(s.Pointer) + } + { + e.FieldStart("code") + e.Str(s.Code) + } + { + e.FieldStart("message") + e.Str(s.Message) + } +} + +var jsonFieldsNameOfProblemFieldError = [4]string{ + 0: "in", + 1: "pointer", + 2: "code", + 3: "message", +} + +// Decode decodes ProblemFieldError from json. +func (s *ProblemFieldError) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldError to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "in": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.In.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"in\"") + } + case "pointer": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Pointer = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"pointer\"") + } + case "code": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Code = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "message": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Str() + s.Message = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"message\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProblemFieldError") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblemFieldError) { + name = jsonFieldsNameOfProblemFieldError[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProblemFieldError) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldError) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemFieldLocation as json. +func (s ProblemFieldLocation) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemFieldLocation from json. +func (s *ProblemFieldLocation) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldLocation to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemFieldLocation(v) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + default: + *s = ProblemFieldLocation(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemFieldLocation) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldLocation) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunLanguage as json. +func (s RunLanguage) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunLanguage from json. +func (s *RunLanguage) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunLanguage to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunLanguage(v) { + case RunLanguagePython3: + *s = RunLanguagePython3 + default: + *s = RunLanguage(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunLanguage) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunLanguage) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunLimits) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunLimits) encodeFields(e *jx.Encoder) { + { + e.FieldStart("time_limit_ms") + e.Int32(s.TimeLimitMs) + } + { + e.FieldStart("memory_limit_mb") + e.Int32(s.MemoryLimitMB) + } + { + e.FieldStart("output_limit_kb") + e.Int32(s.OutputLimitKB) + } +} + +var jsonFieldsNameOfRunLimits = [3]string{ + 0: "time_limit_ms", + 1: "memory_limit_mb", + 2: "output_limit_kb", +} + +// Decode decodes RunLimits from json. +func (s *RunLimits) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunLimits to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "time_limit_ms": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.TimeLimitMs = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"time_limit_ms\"") + } + case "memory_limit_mb": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.MemoryLimitMB = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"memory_limit_mb\"") + } + case "output_limit_kb": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.OutputLimitKB = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"output_limit_kb\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunLimits") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunLimits) { + name = jsonFieldsNameOfRunLimits[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunLimits) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunLimits) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunOutcome as json. +func (s RunOutcome) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunOutcome from json. +func (s *RunOutcome) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunOutcome to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunOutcome(v) { + case RunOutcomeAccepted: + *s = RunOutcomeAccepted + case RunOutcomeWrongAnswer: + *s = RunOutcomeWrongAnswer + case RunOutcomeCompileError: + *s = RunOutcomeCompileError + case RunOutcomeTimeLimitExceeded: + *s = RunOutcomeTimeLimitExceeded + case RunOutcomeMemoryLimitExceeded: + *s = RunOutcomeMemoryLimitExceeded + case RunOutcomeOutputLimitExceeded: + *s = RunOutcomeOutputLimitExceeded + case RunOutcomeRuntimeError: + *s = RunOutcomeRuntimeError + case RunOutcomeInfrastructureFailure: + *s = RunOutcomeInfrastructureFailure + default: + *s = RunOutcome(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunOutcome) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunOutcome) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("language") + s.Language.Encode(e) + } + { + e.FieldStart("source") + e.Str(s.Source) + } + { + e.FieldStart("limits") + s.Limits.Encode(e) + } + { + e.FieldStart("groups") + e.ArrStart() + for _, elem := range s.Groups { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfRunRequest = [4]string{ + 0: "language", + 1: "source", + 2: "limits", + 3: "groups", +} + +// Decode decodes RunRequest from json. +func (s *RunRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "language": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Language.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"language\"") + } + case "source": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Source = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + case "limits": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Limits.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"limits\"") + } + case "groups": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + s.Groups = make([]TestGroup, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TestGroup + if err := elem.Decode(d); err != nil { + return err + } + s.Groups = append(s.Groups, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"groups\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunRequest) { + name = jsonFieldsNameOfRunRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + if s.Compile.Set { + e.FieldStart("compile") + s.Compile.Encode(e) + } + } + { + e.FieldStart("groups") + e.ArrStart() + for _, elem := range s.Groups { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("duration_ms") + e.Int64(s.DurationMs) + } +} + +var jsonFieldsNameOfRunResult = [4]string{ + 0: "outcome", + 1: "compile", + 2: "groups", + 3: "duration_ms", +} + +// Decode decodes RunResult from json. +func (s *RunResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "outcome": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "compile": + if err := func() error { + s.Compile.Reset() + if err := s.Compile.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"compile\"") + } + case "groups": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.Groups = make([]GroupResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem GroupResult + if err := elem.Decode(d); err != nil { + return err + } + s.Groups = append(s.Groups, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"groups\"") + } + case "duration_ms": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int64() + s.DurationMs = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"duration_ms\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001101, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunResult) { + name = jsonFieldsNameOfRunResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunState as json. +func (s RunState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunState from json. +func (s *RunState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunState(v) { + case RunStateRunning: + *s = RunStateRunning + case RunStateFinished: + *s = RunStateFinished + default: + *s = RunState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunStatus) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunStatus) encodeFields(e *jx.Encoder) { + { + e.FieldStart("run_id") + json.EncodeUUID(e, s.RunID) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + if s.Result.Set { + e.FieldStart("result") + s.Result.Encode(e) + } + } +} + +var jsonFieldsNameOfRunStatus = [3]string{ + 0: "run_id", + 1: "state", + 2: "result", +} + +// Decode decodes RunStatus from json. +func (s *RunStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunStatus to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "run_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.RunID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"run_id\"") + } + case "state": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "result": + if err := func() error { + s.Result.Reset() + if err := s.Result.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"result\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunStatus") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunStatus) { + name = jsonFieldsNameOfRunStatus[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunnerHealthResponse) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunnerHealthResponse) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfRunnerHealthResponse = [1]string{ + 0: "status", +} + +// Decode decodes RunnerHealthResponse from json. +func (s *RunnerHealthResponse) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunnerHealthResponse to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunnerHealthResponse") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunnerHealthResponse) { + name = jsonFieldsNameOfRunnerHealthResponse[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunnerHealthResponse) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunnerHealthResponse) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunnerHealthResponseStatus as json. +func (s RunnerHealthResponseStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunnerHealthResponseStatus from json. +func (s *RunnerHealthResponseStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunnerHealthResponseStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunnerHealthResponseStatus(v) { + case RunnerHealthResponseStatusOk: + *s = RunnerHealthResponseStatusOk + default: + *s = RunnerHealthResponseStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunnerHealthResponseStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunnerHealthResponseStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunnerReadinessResponse) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunnerReadinessResponse) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfRunnerReadinessResponse = [1]string{ + 0: "status", +} + +// Decode decodes RunnerReadinessResponse from json. +func (s *RunnerReadinessResponse) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunnerReadinessResponse to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunnerReadinessResponse") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunnerReadinessResponse) { + name = jsonFieldsNameOfRunnerReadinessResponse[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunnerReadinessResponse) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunnerReadinessResponse) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunnerReadinessResponseStatus as json. +func (s RunnerReadinessResponseStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunnerReadinessResponseStatus from json. +func (s *RunnerReadinessResponseStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunnerReadinessResponseStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunnerReadinessResponseStatus(v) { + case RunnerReadinessResponseStatusReady: + *s = RunnerReadinessResponseStatusReady + case RunnerReadinessResponseStatusNotReady: + *s = RunnerReadinessResponseStatusNotReady + default: + *s = RunnerReadinessResponseStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunnerReadinessResponseStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunnerReadinessResponseStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitRunAccepted as json. +func (s *SubmitRunAccepted) Encode(e *jx.Encoder) { + unwrapped := (*RunStatus)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitRunAccepted from json. +func (s *SubmitRunAccepted) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitRunAccepted to nil") + } + var unwrapped RunStatus + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitRunAccepted(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitRunAccepted) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitRunAccepted) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitRunOK as json. +func (s *SubmitRunOK) Encode(e *jx.Encoder) { + unwrapped := (*RunStatus)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitRunOK from json. +func (s *SubmitRunOK) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitRunOK to nil") + } + var unwrapped RunStatus + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitRunOK(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitRunOK) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitRunOK) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TerminationLimit as json. +func (s TerminationLimit) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes TerminationLimit from json. +func (s *TerminationLimit) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TerminationLimit to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch TerminationLimit(v) { + case TerminationLimitCPUTime: + *s = TerminationLimitCPUTime + case TerminationLimitWallTime: + *s = TerminationLimitWallTime + case TerminationLimitMemory: + *s = TerminationLimitMemory + case TerminationLimitOutput: + *s = TerminationLimitOutput + case TerminationLimitProcesses: + *s = TerminationLimitProcesses + default: + *s = TerminationLimit(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TerminationLimit) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TerminationLimit) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *TestCase) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *TestCase) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("input") + e.Str(s.Input) + } + { + e.FieldStart("expected_output") + e.Str(s.ExpectedOutput) + } +} + +var jsonFieldsNameOfTestCase = [3]string{ + 0: "id", + 1: "input", + 2: "expected_output", +} + +// Decode decodes TestCase from json. +func (s *TestCase) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestCase to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "input": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Input = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"input\"") + } + case "expected_output": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.ExpectedOutput = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_output\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode TestCase") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfTestCase) { + name = jsonFieldsNameOfTestCase[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *TestCase) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestCase) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *TestGroup) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *TestGroup) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("visibility") + s.Visibility.Encode(e) + } + { + e.FieldStart("checker") + s.Checker.Encode(e) + } + { + e.FieldStart("tests") + e.ArrStart() + for _, elem := range s.Tests { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfTestGroup = [4]string{ + 0: "id", + 1: "visibility", + 2: "checker", + 3: "tests", +} + +// Decode decodes TestGroup from json. +func (s *TestGroup) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestGroup to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "visibility": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Visibility.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"visibility\"") + } + case "checker": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Checker.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"checker\"") + } + case "tests": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + s.Tests = make([]TestCase, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TestCase + if err := elem.Decode(d); err != nil { + return err + } + s.Tests = append(s.Tests, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tests\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode TestGroup") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfTestGroup) { + name = jsonFieldsNameOfTestGroup[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *TestGroup) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestGroup) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TestKey as json. +func (s TestKey) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes TestKey from json. +func (s *TestKey) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestKey to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = TestKey(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TestKey) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestKey) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *TestResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *TestResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("time_ms") + e.Int64(s.TimeMs) + } + { + e.FieldStart("wall_time_ms") + e.Int64(s.WallTimeMs) + } + { + e.FieldStart("memory_kb") + e.Int64(s.MemoryKB) + } + { + if s.ExitCode.Set { + e.FieldStart("exit_code") + s.ExitCode.Encode(e) + } + } + { + if s.Signal.Set { + e.FieldStart("signal") + s.Signal.Encode(e) + } + } + { + if s.Limit.Set { + e.FieldStart("limit") + s.Limit.Encode(e) + } + } + { + if s.Diagnostic.Set { + e.FieldStart("diagnostic") + s.Diagnostic.Encode(e) + } + } +} + +var jsonFieldsNameOfTestResult = [9]string{ + 0: "id", + 1: "outcome", + 2: "time_ms", + 3: "wall_time_ms", + 4: "memory_kb", + 5: "exit_code", + 6: "signal", + 7: "limit", + 8: "diagnostic", +} + +// Decode decodes TestResult from json. +func (s *TestResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestResult to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "outcome": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "time_ms": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int64() + s.TimeMs = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"time_ms\"") + } + case "wall_time_ms": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int64() + s.WallTimeMs = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"wall_time_ms\"") + } + case "memory_kb": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + v, err := d.Int64() + s.MemoryKB = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"memory_kb\"") + } + case "exit_code": + if err := func() error { + s.ExitCode.Reset() + if err := s.ExitCode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"exit_code\"") + } + case "signal": + if err := func() error { + s.Signal.Reset() + if err := s.Signal.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"signal\"") + } + case "limit": + if err := func() error { + s.Limit.Reset() + if err := s.Limit.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"limit\"") + } + case "diagnostic": + if err := func() error { + s.Diagnostic.Reset() + if err := s.Diagnostic.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"diagnostic\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode TestResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b00011111, + 0b00000000, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfTestResult) { + name = jsonFieldsNameOfTestResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *TestResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TestVisibility as json. +func (s TestVisibility) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes TestVisibility from json. +func (s *TestVisibility) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestVisibility to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch TestVisibility(v) { + case TestVisibilityPublic: + *s = TestVisibilityPublic + case TestVisibilityHidden: + *s = TestVisibilityHidden + default: + *s = TestVisibility(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TestVisibility) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestVisibility) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_operations_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_operations_gen.go new file mode 100644 index 0000000..b9f7be2 --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_operations_gen.go @@ -0,0 +1,13 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +// OperationName is the ogen operation name +type OperationName = string + +const ( + GetRunOperation OperationName = "GetRun" + GetRunnerHealthzOperation OperationName = "GetRunnerHealthz" + GetRunnerReadyzOperation OperationName = "GetRunnerReadyz" + SubmitRunOperation OperationName = "SubmitRun" +) diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_parameters_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_parameters_gen.go new file mode 100644 index 0000000..6f8b608 --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_parameters_gen.go @@ -0,0 +1,21 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "github.com/google/uuid" +) + +// GetRunParams is parameters of GetRun operation. +type GetRunParams struct { + // Random UUID chosen by the backend for one logical run. It is the idempotency key of SubmitRun and + // must not encode a candidate, attempt, or task identifier. + RunID uuid.UUID +} + +// SubmitRunParams is parameters of SubmitRun operation. +type SubmitRunParams struct { + // Random UUID chosen by the backend for one logical run. It is the idempotency key of SubmitRun and + // must not encode a candidate, attempt, or task identifier. + RunID uuid.UUID +} diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_request_encoders_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_request_encoders_gen.go new file mode 100644 index 0000000..2687425 --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_request_encoders_gen.go @@ -0,0 +1,25 @@ +// 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 encodeSubmitRunRequest( + req *RunRequest, + r *http.Request, +) error { + const contentType = "application/json" + e := new(jx.Encoder) + { + req.Encode(e) + } + encoded := e.Bytes() + ht.SetBody(r, bytes.NewReader(encoded), contentType) + return nil +} diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_response_decoders_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_response_decoders_gen.go new file mode 100644 index 0000000..072c1ce --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_response_decoders_gen.go @@ -0,0 +1,605 @@ +// 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 decodeGetRunResponse(resp *http.Response) (res *RunStatus, _ 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 RunStatus + 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 decodeGetRunnerHealthzResponse(resp *http.Response) (res *RunnerHealthResponse, _ 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 RunnerHealthResponse + 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 decodeGetRunnerReadyzResponse(resp *http.Response) (res GetRunnerReadyzRes, _ 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 GetRunnerReadyzOK + 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 GetRunnerReadyzServiceUnavailable + 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 decodeSubmitRunResponse(resp *http.Response) (res SubmitRunRes, _ 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 SubmitRunOK + 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 SubmitRunAccepted + 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 RunnerBusyHeaders + 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") +} diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_schemas_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_schemas_gen.go new file mode 100644 index 0000000..f4c89f0 --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_schemas_gen.go @@ -0,0 +1,1684 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "fmt" + + "github.com/go-faster/errors" + "github.com/google/uuid" +) + +func (s *ProblemStatusCode) Error() string { + return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response) +} + +type BearerAuth struct { + Token string + Roles []string +} + +// GetToken returns the value of Token. +func (s *BearerAuth) GetToken() string { + return s.Token +} + +// GetRoles returns the value of Roles. +func (s *BearerAuth) GetRoles() []string { + return s.Roles +} + +// SetToken sets the value of Token. +func (s *BearerAuth) SetToken(val string) { + s.Token = val +} + +// SetRoles sets the value of Roles. +func (s *BearerAuth) SetRoles(val []string) { + s.Roles = val +} + +// How the standard output of a test is compared with `expected_output`. Future kinds, such as a float +// tolerance or a custom checker, add a `kind` value and their own optional parameters to this object. +// Ref: #/components/schemas/Checker +type Checker struct { + Kind CheckerKind `json:"kind"` +} + +// GetKind returns the value of Kind. +func (s *Checker) GetKind() CheckerKind { + return s.Kind +} + +// SetKind sets the value of Kind. +func (s *Checker) SetKind(val CheckerKind) { + s.Kind = val +} + +// - exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at +// the end of each line, and removing trailing empty lines. +// - tokens: both texts split on ASCII whitespace give the same sequence of tokens. +// +// Ref: #/components/schemas/CheckerKind +type CheckerKind string + +const ( + CheckerKindExact CheckerKind = "exact" + CheckerKindTokens CheckerKind = "tokens" +) + +// AllValues returns all CheckerKind values. +func (CheckerKind) AllValues() []CheckerKind { + return []CheckerKind{ + CheckerKindExact, + CheckerKindTokens, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CheckerKind) MarshalText() ([]byte, error) { + switch s { + case CheckerKindExact: + return []byte(s), nil + case CheckerKindTokens: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CheckerKind) UnmarshalText(data []byte) error { + switch CheckerKind(data) { + case CheckerKindExact: + *s = CheckerKindExact + return nil + case CheckerKindTokens: + *s = CheckerKindTokens + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/CompileResult +type CompileResult struct { + Outcome RunOutcome `json:"outcome"` + // Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the + // source, never test data. + Diagnostic OptString `json:"diagnostic"` +} + +// GetOutcome returns the value of Outcome. +func (s *CompileResult) GetOutcome() RunOutcome { + return s.Outcome +} + +// GetDiagnostic returns the value of Diagnostic. +func (s *CompileResult) GetDiagnostic() OptString { + return s.Diagnostic +} + +// SetOutcome sets the value of Outcome. +func (s *CompileResult) SetOutcome(val RunOutcome) { + s.Outcome = val +} + +// SetDiagnostic sets the value of Diagnostic. +func (s *CompileResult) SetDiagnostic(val OptString) { + s.Diagnostic = val +} + +type GetRunnerReadyzOK RunnerReadinessResponse + +func (*GetRunnerReadyzOK) getRunnerReadyzRes() {} + +type GetRunnerReadyzServiceUnavailable RunnerReadinessResponse + +func (*GetRunnerReadyzServiceUnavailable) getRunnerReadyzRes() {} + +// Ref: #/components/schemas/GroupResult +type GroupResult struct { + ID TestKey `json:"id"` + Visibility TestVisibility `json:"visibility"` + Outcome RunOutcome `json:"outcome"` + PassedTests int32 `json:"passed_tests"` + TotalTests int32 `json:"total_tests"` + // Largest CPU time of an evaluated test of the group. + MaxTimeMs OptInt64 `json:"max_time_ms"` + // Largest peak memory of an evaluated test of the group. + MaxMemoryKB OptInt64 `json:"max_memory_kb"` + // Results of the evaluated tests in order. Tests after the first failed one are not run and not + // listed. + Tests []TestResult `json:"tests"` +} + +// GetID returns the value of ID. +func (s *GroupResult) GetID() TestKey { + return s.ID +} + +// GetVisibility returns the value of Visibility. +func (s *GroupResult) GetVisibility() TestVisibility { + return s.Visibility +} + +// GetOutcome returns the value of Outcome. +func (s *GroupResult) GetOutcome() RunOutcome { + return s.Outcome +} + +// GetPassedTests returns the value of PassedTests. +func (s *GroupResult) GetPassedTests() int32 { + return s.PassedTests +} + +// GetTotalTests returns the value of TotalTests. +func (s *GroupResult) GetTotalTests() int32 { + return s.TotalTests +} + +// GetMaxTimeMs returns the value of MaxTimeMs. +func (s *GroupResult) GetMaxTimeMs() OptInt64 { + return s.MaxTimeMs +} + +// GetMaxMemoryKB returns the value of MaxMemoryKB. +func (s *GroupResult) GetMaxMemoryKB() OptInt64 { + return s.MaxMemoryKB +} + +// GetTests returns the value of Tests. +func (s *GroupResult) GetTests() []TestResult { + return s.Tests +} + +// SetID sets the value of ID. +func (s *GroupResult) SetID(val TestKey) { + s.ID = val +} + +// SetVisibility sets the value of Visibility. +func (s *GroupResult) SetVisibility(val TestVisibility) { + s.Visibility = val +} + +// SetOutcome sets the value of Outcome. +func (s *GroupResult) SetOutcome(val RunOutcome) { + s.Outcome = val +} + +// SetPassedTests sets the value of PassedTests. +func (s *GroupResult) SetPassedTests(val int32) { + s.PassedTests = val +} + +// SetTotalTests sets the value of TotalTests. +func (s *GroupResult) SetTotalTests(val int32) { + s.TotalTests = val +} + +// SetMaxTimeMs sets the value of MaxTimeMs. +func (s *GroupResult) SetMaxTimeMs(val OptInt64) { + s.MaxTimeMs = val +} + +// SetMaxMemoryKB sets the value of MaxMemoryKB. +func (s *GroupResult) SetMaxMemoryKB(val OptInt64) { + s.MaxMemoryKB = val +} + +// SetTests sets the value of Tests. +func (s *GroupResult) SetTests(val []TestResult) { + s.Tests = val +} + +// NewOptCompileResult returns new OptCompileResult with value set to v. +func NewOptCompileResult(v CompileResult) OptCompileResult { + return OptCompileResult{ + Value: v, + Set: true, + } +} + +// OptCompileResult is optional CompileResult. +type OptCompileResult struct { + Value CompileResult + Set bool +} + +// IsSet returns true if OptCompileResult was set. +func (o OptCompileResult) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptCompileResult) Reset() { + var v CompileResult + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptCompileResult) SetTo(v CompileResult) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptCompileResult) Get() (v CompileResult, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptCompileResult) Or(d CompileResult) CompileResult { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptInt32 returns new OptInt32 with value set to v. +func NewOptInt32(v int32) OptInt32 { + return OptInt32{ + Value: v, + Set: true, + } +} + +// OptInt32 is optional int32. +type OptInt32 struct { + Value int32 + Set bool +} + +// IsSet returns true if OptInt32 was set. +func (o OptInt32) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptInt32) Reset() { + var v int32 + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptInt32) SetTo(v int32) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptInt32) Get() (v int32, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptInt32) Or(d int32) int32 { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptInt64 returns new OptInt64 with value set to v. +func NewOptInt64(v int64) OptInt64 { + return OptInt64{ + Value: v, + Set: true, + } +} + +// OptInt64 is optional int64. +type OptInt64 struct { + Value int64 + Set bool +} + +// IsSet returns true if OptInt64 was set. +func (o OptInt64) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptInt64) Reset() { + var v int64 + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptInt64) SetTo(v int64) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptInt64) Get() (v int64, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptInt64) Or(d int64) int64 { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptRunResult returns new OptRunResult with value set to v. +func NewOptRunResult(v RunResult) OptRunResult { + return OptRunResult{ + Value: v, + Set: true, + } +} + +// OptRunResult is optional RunResult. +type OptRunResult struct { + Value RunResult + Set bool +} + +// IsSet returns true if OptRunResult was set. +func (o OptRunResult) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptRunResult) Reset() { + var v RunResult + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptRunResult) SetTo(v RunResult) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptRunResult) Get() (v RunResult, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptRunResult) Or(d RunResult) RunResult { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptString returns new OptString with value set to v. +func NewOptString(v string) OptString { + return OptString{ + Value: v, + Set: true, + } +} + +// OptString is optional string. +type OptString struct { + Value string + Set bool +} + +// IsSet returns true if OptString was set. +func (o OptString) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptString) Reset() { + var v string + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptString) SetTo(v string) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptString) Get() (v string, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptString) Or(d string) string { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptTerminationLimit returns new OptTerminationLimit with value set to v. +func NewOptTerminationLimit(v TerminationLimit) OptTerminationLimit { + return OptTerminationLimit{ + Value: v, + Set: true, + } +} + +// OptTerminationLimit is optional TerminationLimit. +type OptTerminationLimit struct { + Value TerminationLimit + Set bool +} + +// IsSet returns true if OptTerminationLimit was set. +func (o OptTerminationLimit) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptTerminationLimit) Reset() { + var v TerminationLimit + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptTerminationLimit) SetTo(v TerminationLimit) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptTerminationLimit) Get() (v TerminationLimit, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptTerminationLimit) Or(d TerminationLimit) TerminationLimit { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// Problem details (RFC 9457) returned with the application/problem+json media type for every error +// response. This is the runner copy of the public api/core Problem schema; keep both copies identical +// except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; +// clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never +// contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed +// request values. +// Ref: #/components/schemas/Problem +type Problem struct { + // URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an + // identifier, not a link to dereference. + Type string `json:"type"` + // Short, fixed English summary of the problem type. It does not change between occurrences. + Title string `json:"title"` + // HTTP status code generated by the origin server. + Status int32 `json:"status"` + Code ProblemCode `json:"code"` + // Safe English explanation of this occurrence. It never contains internal error text or request + // values. + Detail OptString `json:"detail"` + // URI reference that identifies this occurrence, when one exists. + Instance OptString `json:"instance"` + // Request identifier of the call when the caller propagated one; it is not a secret. + TraceID OptString `json:"trace_id"` + // Field-level reasons for validation_failed. Other codes omit it. + Errors []ProblemFieldError `json:"errors"` +} + +// GetType returns the value of Type. +func (s *Problem) GetType() string { + return s.Type +} + +// GetTitle returns the value of Title. +func (s *Problem) GetTitle() string { + return s.Title +} + +// GetStatus returns the value of Status. +func (s *Problem) GetStatus() int32 { + return s.Status +} + +// GetCode returns the value of Code. +func (s *Problem) GetCode() ProblemCode { + return s.Code +} + +// GetDetail returns the value of Detail. +func (s *Problem) GetDetail() OptString { + return s.Detail +} + +// GetInstance returns the value of Instance. +func (s *Problem) GetInstance() OptString { + return s.Instance +} + +// GetTraceID returns the value of TraceID. +func (s *Problem) GetTraceID() OptString { + return s.TraceID +} + +// GetErrors returns the value of Errors. +func (s *Problem) GetErrors() []ProblemFieldError { + return s.Errors +} + +// SetType sets the value of Type. +func (s *Problem) SetType(val string) { + s.Type = val +} + +// SetTitle sets the value of Title. +func (s *Problem) SetTitle(val string) { + s.Title = val +} + +// SetStatus sets the value of Status. +func (s *Problem) SetStatus(val int32) { + s.Status = val +} + +// SetCode sets the value of Code. +func (s *Problem) SetCode(val ProblemCode) { + s.Code = val +} + +// SetDetail sets the value of Detail. +func (s *Problem) SetDetail(val OptString) { + s.Detail = val +} + +// SetInstance sets the value of Instance. +func (s *Problem) SetInstance(val OptString) { + s.Instance = val +} + +// SetTraceID sets the value of TraceID. +func (s *Problem) SetTraceID(val OptString) { + s.TraceID = val +} + +// SetErrors sets the value of Errors. +func (s *Problem) SetErrors(val []ProblemFieldError) { + s.Errors = val +} + +// Stable error code of the runner 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 of +// SubmitRun; `errors` points at the fields. +// - unauthenticated (401): the bearer token is missing or wrong. +// - not_found (404): the route or the run does not exist. +// - method_not_allowed (405): the route does not support the method. +// - 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 run ID was already used with a different payload. +// - internal (500): unexpected server error. +// - runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After. +// +// The Problem shape is the api/core shape; only this enum is specific to the runner. +// Ref: #/components/schemas/ProblemCode +type ProblemCode string + +const ( + ProblemCodeValidationFailed ProblemCode = "validation_failed" + ProblemCodeUnauthenticated ProblemCode = "unauthenticated" + ProblemCodeNotFound ProblemCode = "not_found" + ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed" + ProblemCodePayloadTooLarge ProblemCode = "payload_too_large" + ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type" + ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused" + ProblemCodeInternal ProblemCode = "internal" + ProblemCodeRunnerBusy ProblemCode = "runner_busy" +) + +// AllValues returns all ProblemCode values. +func (ProblemCode) AllValues() []ProblemCode { + return []ProblemCode{ + ProblemCodeValidationFailed, + ProblemCodeUnauthenticated, + ProblemCodeNotFound, + ProblemCodeMethodNotAllowed, + ProblemCodePayloadTooLarge, + ProblemCodeUnsupportedMediaType, + ProblemCodeIdempotencyKeyReused, + ProblemCodeInternal, + ProblemCodeRunnerBusy, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemCode) MarshalText() ([]byte, error) { + switch s { + case ProblemCodeValidationFailed: + return []byte(s), nil + case ProblemCodeUnauthenticated: + return []byte(s), nil + case ProblemCodeNotFound: + return []byte(s), nil + case ProblemCodeMethodNotAllowed: + return []byte(s), nil + case ProblemCodePayloadTooLarge: + return []byte(s), nil + case ProblemCodeUnsupportedMediaType: + return []byte(s), nil + case ProblemCodeIdempotencyKeyReused: + return []byte(s), nil + case ProblemCodeInternal: + return []byte(s), nil + case ProblemCodeRunnerBusy: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemCode) UnmarshalText(data []byte) error { + switch ProblemCode(data) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + return nil + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + return nil + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + return nil + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + return nil + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + return nil + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + return nil + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + return nil + case ProblemCodeInternal: + *s = ProblemCodeInternal + return nil + case ProblemCodeRunnerBusy: + *s = ProblemCodeRunnerBusy + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One reason why a request field or parameter is invalid. +// Ref: #/components/schemas/ProblemFieldError +type ProblemFieldError struct { + In ProblemFieldLocation `json:"in"` + // JSON Pointer (RFC 6901). For `body` it points into the request body document, for example + // `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by + // the parameter name, for example `/run_id`. + Pointer string `json:"pointer"` + // Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or + // a value outside the schema). Clients must tolerate new values. + Code string `json:"code"` + // Fixed English message that never echoes the submitted value. + Message string `json:"message"` +} + +// GetIn returns the value of In. +func (s *ProblemFieldError) GetIn() ProblemFieldLocation { + return s.In +} + +// GetPointer returns the value of Pointer. +func (s *ProblemFieldError) GetPointer() string { + return s.Pointer +} + +// GetCode returns the value of Code. +func (s *ProblemFieldError) GetCode() string { + return s.Code +} + +// GetMessage returns the value of Message. +func (s *ProblemFieldError) GetMessage() string { + return s.Message +} + +// SetIn sets the value of In. +func (s *ProblemFieldError) SetIn(val ProblemFieldLocation) { + s.In = val +} + +// SetPointer sets the value of Pointer. +func (s *ProblemFieldError) SetPointer(val string) { + s.Pointer = val +} + +// SetCode sets the value of Code. +func (s *ProblemFieldError) SetCode(val string) { + s.Code = val +} + +// SetMessage sets the value of Message. +func (s *ProblemFieldError) SetMessage(val string) { + s.Message = val +} + +// Part of the request that contains the invalid field. +// Ref: #/components/schemas/ProblemFieldLocation +type ProblemFieldLocation string + +const ( + ProblemFieldLocationBody ProblemFieldLocation = "body" + ProblemFieldLocationQuery ProblemFieldLocation = "query" + ProblemFieldLocationPath ProblemFieldLocation = "path" + ProblemFieldLocationHeader ProblemFieldLocation = "header" + ProblemFieldLocationCookie ProblemFieldLocation = "cookie" +) + +// AllValues returns all ProblemFieldLocation values. +func (ProblemFieldLocation) AllValues() []ProblemFieldLocation { + return []ProblemFieldLocation{ + ProblemFieldLocationBody, + ProblemFieldLocationQuery, + ProblemFieldLocationPath, + ProblemFieldLocationHeader, + ProblemFieldLocationCookie, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemFieldLocation) MarshalText() ([]byte, error) { + switch s { + case ProblemFieldLocationBody: + return []byte(s), nil + case ProblemFieldLocationQuery: + return []byte(s), nil + case ProblemFieldLocationPath: + return []byte(s), nil + case ProblemFieldLocationHeader: + return []byte(s), nil + case ProblemFieldLocationCookie: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemFieldLocation) UnmarshalText(data []byte) error { + switch ProblemFieldLocation(data) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + return nil + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + return nil + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + return nil + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + return nil + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// ProblemStatusCode wraps Problem with StatusCode. +type ProblemStatusCode struct { + StatusCode int + Response Problem +} + +// GetStatusCode returns the value of StatusCode. +func (s *ProblemStatusCode) GetStatusCode() int { + return s.StatusCode +} + +// GetResponse returns the value of Response. +func (s *ProblemStatusCode) GetResponse() Problem { + return s.Response +} + +// SetStatusCode sets the value of StatusCode. +func (s *ProblemStatusCode) SetStatusCode(val int) { + s.StatusCode = val +} + +// SetResponse sets the value of Response. +func (s *ProblemStatusCode) SetResponse(val Problem) { + s.Response = val +} + +// Language and runtime of the source. `python3` runs the Python 3 interpreter of the runner image with +// isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error. +// Ref: #/components/schemas/RunLanguage +type RunLanguage string + +const ( + RunLanguagePython3 RunLanguage = "python3" +) + +// AllValues returns all RunLanguage values. +func (RunLanguage) AllValues() []RunLanguage { + return []RunLanguage{ + RunLanguagePython3, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunLanguage) MarshalText() ([]byte, error) { + switch s { + case RunLanguagePython3: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunLanguage) UnmarshalText(data []byte) error { + switch RunLanguage(data) { + case RunLanguagePython3: + *s = RunLanguagePython3 + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Limits applied to every test of the run. +// Ref: #/components/schemas/RunLimits +type RunLimits struct { + // CPU time per test, including interpreter startup, summed over every process of the test. The + // wall-clock limit is twice this value plus a fixed startup allowance. + TimeLimitMs int32 `json:"time_limit_ms"` + // Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit + // also leaves a small fixed allowance for the sandbox supervisor process. + MemoryLimitMB int32 `json:"memory_limit_mb"` + // Standard output per test in KiB. The test is stopped as soon as it writes more. + OutputLimitKB int32 `json:"output_limit_kb"` +} + +// GetTimeLimitMs returns the value of TimeLimitMs. +func (s *RunLimits) GetTimeLimitMs() int32 { + return s.TimeLimitMs +} + +// GetMemoryLimitMB returns the value of MemoryLimitMB. +func (s *RunLimits) GetMemoryLimitMB() int32 { + return s.MemoryLimitMB +} + +// GetOutputLimitKB returns the value of OutputLimitKB. +func (s *RunLimits) GetOutputLimitKB() int32 { + return s.OutputLimitKB +} + +// SetTimeLimitMs sets the value of TimeLimitMs. +func (s *RunLimits) SetTimeLimitMs(val int32) { + s.TimeLimitMs = val +} + +// SetMemoryLimitMB sets the value of MemoryLimitMB. +func (s *RunLimits) SetMemoryLimitMB(val int32) { + s.MemoryLimitMB = val +} + +// SetOutputLimitKB sets the value of OutputLimitKB. +func (s *RunLimits) SetOutputLimitKB(val int32) { + s.OutputLimitKB = val +} + +// Outcome of a test, a group, a compile step, or a whole run. +// +// - accepted: the program exited with status 0 within every limit and the checker accepted the +// output. +// - wrong_answer: the program exited with status 0 within every limit, but the checker rejected the +// output. +// - compile_error: the source was rejected before any test ran (for Python, a syntax error). +// - time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program. +// - memory_limit_exceeded: the cgroup memory limit stopped the program. +// - output_limit_exceeded: the program wrote more standard output than the limit. +// - runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the +// process limit. +// - infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about +// the program, and the caller may retry with a new run ID. +// +// A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome +// of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of +// its first failed test, otherwise accepted. +// Ref: #/components/schemas/RunOutcome +type RunOutcome string + +const ( + RunOutcomeAccepted RunOutcome = "accepted" + RunOutcomeWrongAnswer RunOutcome = "wrong_answer" + RunOutcomeCompileError RunOutcome = "compile_error" + RunOutcomeTimeLimitExceeded RunOutcome = "time_limit_exceeded" + RunOutcomeMemoryLimitExceeded RunOutcome = "memory_limit_exceeded" + RunOutcomeOutputLimitExceeded RunOutcome = "output_limit_exceeded" + RunOutcomeRuntimeError RunOutcome = "runtime_error" + RunOutcomeInfrastructureFailure RunOutcome = "infrastructure_failure" +) + +// AllValues returns all RunOutcome values. +func (RunOutcome) AllValues() []RunOutcome { + return []RunOutcome{ + RunOutcomeAccepted, + RunOutcomeWrongAnswer, + RunOutcomeCompileError, + RunOutcomeTimeLimitExceeded, + RunOutcomeMemoryLimitExceeded, + RunOutcomeOutputLimitExceeded, + RunOutcomeRuntimeError, + RunOutcomeInfrastructureFailure, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunOutcome) MarshalText() ([]byte, error) { + switch s { + case RunOutcomeAccepted: + return []byte(s), nil + case RunOutcomeWrongAnswer: + return []byte(s), nil + case RunOutcomeCompileError: + return []byte(s), nil + case RunOutcomeTimeLimitExceeded: + return []byte(s), nil + case RunOutcomeMemoryLimitExceeded: + return []byte(s), nil + case RunOutcomeOutputLimitExceeded: + return []byte(s), nil + case RunOutcomeRuntimeError: + return []byte(s), nil + case RunOutcomeInfrastructureFailure: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunOutcome) UnmarshalText(data []byte) error { + switch RunOutcome(data) { + case RunOutcomeAccepted: + *s = RunOutcomeAccepted + return nil + case RunOutcomeWrongAnswer: + *s = RunOutcomeWrongAnswer + return nil + case RunOutcomeCompileError: + *s = RunOutcomeCompileError + return nil + case RunOutcomeTimeLimitExceeded: + *s = RunOutcomeTimeLimitExceeded + return nil + case RunOutcomeMemoryLimitExceeded: + *s = RunOutcomeMemoryLimitExceeded + return nil + case RunOutcomeOutputLimitExceeded: + *s = RunOutcomeOutputLimitExceeded + return nil + case RunOutcomeRuntimeError: + *s = RunOutcomeRuntimeError + return nil + case RunOutcomeInfrastructureFailure: + *s = RunOutcomeInfrastructureFailure + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One source and its test groups. The request has no field for a candidate, account, attempt, task, or +// company; the backend maps a run ID to its own records. +// Ref: #/components/schemas/RunRequest +type RunRequest struct { + Language RunLanguage `json:"language"` + // Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and + // never logs it. + Source string `json:"source"` + Limits RunLimits `json:"limits"` + // Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are + // unique in a run. + Groups []TestGroup `json:"groups"` +} + +// GetLanguage returns the value of Language. +func (s *RunRequest) GetLanguage() RunLanguage { + return s.Language +} + +// GetSource returns the value of Source. +func (s *RunRequest) GetSource() string { + return s.Source +} + +// GetLimits returns the value of Limits. +func (s *RunRequest) GetLimits() RunLimits { + return s.Limits +} + +// GetGroups returns the value of Groups. +func (s *RunRequest) GetGroups() []TestGroup { + return s.Groups +} + +// SetLanguage sets the value of Language. +func (s *RunRequest) SetLanguage(val RunLanguage) { + s.Language = val +} + +// SetSource sets the value of Source. +func (s *RunRequest) SetSource(val string) { + s.Source = val +} + +// SetLimits sets the value of Limits. +func (s *RunRequest) SetLimits(val RunLimits) { + s.Limits = val +} + +// SetGroups sets the value of Groups. +func (s *RunRequest) SetGroups(val []TestGroup) { + s.Groups = val +} + +// Ref: #/components/schemas/RunResult +type RunResult struct { + Outcome RunOutcome `json:"outcome"` + Compile OptCompileResult `json:"compile"` + // One result per requested group in request order. After compile_error or infrastructure_failure every + // group has that outcome and no tests. + Groups []GroupResult `json:"groups"` + // Wall-clock time of the whole run in the runner. + DurationMs int64 `json:"duration_ms"` +} + +// GetOutcome returns the value of Outcome. +func (s *RunResult) GetOutcome() RunOutcome { + return s.Outcome +} + +// GetCompile returns the value of Compile. +func (s *RunResult) GetCompile() OptCompileResult { + return s.Compile +} + +// GetGroups returns the value of Groups. +func (s *RunResult) GetGroups() []GroupResult { + return s.Groups +} + +// GetDurationMs returns the value of DurationMs. +func (s *RunResult) GetDurationMs() int64 { + return s.DurationMs +} + +// SetOutcome sets the value of Outcome. +func (s *RunResult) SetOutcome(val RunOutcome) { + s.Outcome = val +} + +// SetCompile sets the value of Compile. +func (s *RunResult) SetCompile(val OptCompileResult) { + s.Compile = val +} + +// SetGroups sets the value of Groups. +func (s *RunResult) SetGroups(val []GroupResult) { + s.Groups = val +} + +// SetDurationMs sets the value of DurationMs. +func (s *RunResult) SetDurationMs(val int64) { + s.DurationMs = val +} + +// `running` until every group was evaluated or the run failed; `finished` when `result` is final. +// Ref: #/components/schemas/RunState +type RunState string + +const ( + RunStateRunning RunState = "running" + RunStateFinished RunState = "finished" +) + +// AllValues returns all RunState values. +func (RunState) AllValues() []RunState { + return []RunState{ + RunStateRunning, + RunStateFinished, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunState) MarshalText() ([]byte, error) { + switch s { + case RunStateRunning: + return []byte(s), nil + case RunStateFinished: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunState) UnmarshalText(data []byte) error { + switch RunState(data) { + case RunStateRunning: + *s = RunStateRunning + return nil + case RunStateFinished: + *s = RunStateFinished + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/RunStatus +type RunStatus struct { + RunID uuid.UUID `json:"run_id"` + State RunState `json:"state"` + Result OptRunResult `json:"result"` +} + +// GetRunID returns the value of RunID. +func (s *RunStatus) GetRunID() uuid.UUID { + return s.RunID +} + +// GetState returns the value of State. +func (s *RunStatus) GetState() RunState { + return s.State +} + +// GetResult returns the value of Result. +func (s *RunStatus) GetResult() OptRunResult { + return s.Result +} + +// SetRunID sets the value of RunID. +func (s *RunStatus) SetRunID(val uuid.UUID) { + s.RunID = val +} + +// SetState sets the value of State. +func (s *RunStatus) SetState(val RunState) { + s.State = val +} + +// SetResult sets the value of Result. +func (s *RunStatus) SetResult(val OptRunResult) { + s.Result = val +} + +// RunnerBusyHeaders wraps Problem with response headers. +type RunnerBusyHeaders struct { + RetryAfter int32 + Response Problem +} + +// GetRetryAfter returns the value of RetryAfter. +func (s *RunnerBusyHeaders) GetRetryAfter() int32 { + return s.RetryAfter +} + +// GetResponse returns the value of Response. +func (s *RunnerBusyHeaders) GetResponse() Problem { + return s.Response +} + +// SetRetryAfter sets the value of RetryAfter. +func (s *RunnerBusyHeaders) SetRetryAfter(val int32) { + s.RetryAfter = val +} + +// SetResponse sets the value of Response. +func (s *RunnerBusyHeaders) SetResponse(val Problem) { + s.Response = val +} + +func (*RunnerBusyHeaders) submitRunRes() {} + +// Ref: #/components/schemas/RunnerHealthResponse +type RunnerHealthResponse struct { + Status RunnerHealthResponseStatus `json:"status"` +} + +// GetStatus returns the value of Status. +func (s *RunnerHealthResponse) GetStatus() RunnerHealthResponseStatus { + return s.Status +} + +// SetStatus sets the value of Status. +func (s *RunnerHealthResponse) SetStatus(val RunnerHealthResponseStatus) { + s.Status = val +} + +type RunnerHealthResponseStatus string + +const ( + RunnerHealthResponseStatusOk RunnerHealthResponseStatus = "ok" +) + +// AllValues returns all RunnerHealthResponseStatus values. +func (RunnerHealthResponseStatus) AllValues() []RunnerHealthResponseStatus { + return []RunnerHealthResponseStatus{ + RunnerHealthResponseStatusOk, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunnerHealthResponseStatus) MarshalText() ([]byte, error) { + switch s { + case RunnerHealthResponseStatusOk: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunnerHealthResponseStatus) UnmarshalText(data []byte) error { + switch RunnerHealthResponseStatus(data) { + case RunnerHealthResponseStatusOk: + *s = RunnerHealthResponseStatusOk + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/RunnerReadinessResponse +type RunnerReadinessResponse struct { + Status RunnerReadinessResponseStatus `json:"status"` +} + +// GetStatus returns the value of Status. +func (s *RunnerReadinessResponse) GetStatus() RunnerReadinessResponseStatus { + return s.Status +} + +// SetStatus sets the value of Status. +func (s *RunnerReadinessResponse) SetStatus(val RunnerReadinessResponseStatus) { + s.Status = val +} + +type RunnerReadinessResponseStatus string + +const ( + RunnerReadinessResponseStatusReady RunnerReadinessResponseStatus = "ready" + RunnerReadinessResponseStatusNotReady RunnerReadinessResponseStatus = "not_ready" +) + +// AllValues returns all RunnerReadinessResponseStatus values. +func (RunnerReadinessResponseStatus) AllValues() []RunnerReadinessResponseStatus { + return []RunnerReadinessResponseStatus{ + RunnerReadinessResponseStatusReady, + RunnerReadinessResponseStatusNotReady, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunnerReadinessResponseStatus) MarshalText() ([]byte, error) { + switch s { + case RunnerReadinessResponseStatusReady: + return []byte(s), nil + case RunnerReadinessResponseStatusNotReady: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunnerReadinessResponseStatus) UnmarshalText(data []byte) error { + switch RunnerReadinessResponseStatus(data) { + case RunnerReadinessResponseStatusReady: + *s = RunnerReadinessResponseStatusReady + return nil + case RunnerReadinessResponseStatusNotReady: + *s = RunnerReadinessResponseStatusNotReady + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type SubmitRunAccepted RunStatus + +func (*SubmitRunAccepted) submitRunRes() {} + +type SubmitRunOK RunStatus + +func (*SubmitRunOK) submitRunRes() {} + +// The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of +// processes and threads. +// Ref: #/components/schemas/TerminationLimit +type TerminationLimit string + +const ( + TerminationLimitCPUTime TerminationLimit = "cpu_time" + TerminationLimitWallTime TerminationLimit = "wall_time" + TerminationLimitMemory TerminationLimit = "memory" + TerminationLimitOutput TerminationLimit = "output" + TerminationLimitProcesses TerminationLimit = "processes" +) + +// AllValues returns all TerminationLimit values. +func (TerminationLimit) AllValues() []TerminationLimit { + return []TerminationLimit{ + TerminationLimitCPUTime, + TerminationLimitWallTime, + TerminationLimitMemory, + TerminationLimitOutput, + TerminationLimitProcesses, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s TerminationLimit) MarshalText() ([]byte, error) { + switch s { + case TerminationLimitCPUTime: + return []byte(s), nil + case TerminationLimitWallTime: + return []byte(s), nil + case TerminationLimitMemory: + return []byte(s), nil + case TerminationLimitOutput: + return []byte(s), nil + case TerminationLimitProcesses: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *TerminationLimit) UnmarshalText(data []byte) error { + switch TerminationLimit(data) { + case TerminationLimitCPUTime: + *s = TerminationLimitCPUTime + return nil + case TerminationLimitWallTime: + *s = TerminationLimitWallTime + return nil + case TerminationLimitMemory: + *s = TerminationLimitMemory + return nil + case TerminationLimitOutput: + *s = TerminationLimitOutput + return nil + case TerminationLimitProcesses: + *s = TerminationLimitProcesses + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/TestCase +type TestCase struct { + ID TestKey `json:"id"` + // UTF-8 text written to the standard input of the program. + Input string `json:"input"` + // UTF-8 text the checker compares with the standard output. + ExpectedOutput string `json:"expected_output"` +} + +// GetID returns the value of ID. +func (s *TestCase) GetID() TestKey { + return s.ID +} + +// GetInput returns the value of Input. +func (s *TestCase) GetInput() string { + return s.Input +} + +// GetExpectedOutput returns the value of ExpectedOutput. +func (s *TestCase) GetExpectedOutput() string { + return s.ExpectedOutput +} + +// SetID sets the value of ID. +func (s *TestCase) SetID(val TestKey) { + s.ID = val +} + +// SetInput sets the value of Input. +func (s *TestCase) SetInput(val string) { + s.Input = val +} + +// SetExpectedOutput sets the value of ExpectedOutput. +func (s *TestCase) SetExpectedOutput(val string) { + s.ExpectedOutput = val +} + +// Ref: #/components/schemas/TestGroup +type TestGroup struct { + ID TestKey `json:"id"` + Visibility TestVisibility `json:"visibility"` + Checker Checker `json:"checker"` + // Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test. + Tests []TestCase `json:"tests"` +} + +// GetID returns the value of ID. +func (s *TestGroup) GetID() TestKey { + return s.ID +} + +// GetVisibility returns the value of Visibility. +func (s *TestGroup) GetVisibility() TestVisibility { + return s.Visibility +} + +// GetChecker returns the value of Checker. +func (s *TestGroup) GetChecker() Checker { + return s.Checker +} + +// GetTests returns the value of Tests. +func (s *TestGroup) GetTests() []TestCase { + return s.Tests +} + +// SetID sets the value of ID. +func (s *TestGroup) SetID(val TestKey) { + s.ID = val +} + +// SetVisibility sets the value of Visibility. +func (s *TestGroup) SetVisibility(val TestVisibility) { + s.Visibility = val +} + +// SetChecker sets the value of Checker. +func (s *TestGroup) SetChecker(val Checker) { + s.Checker = val +} + +// SetTests sets the value of Tests. +func (s *TestGroup) SetTests(val []TestCase) { + s.Tests = val +} + +type TestKey string + +// Ref: #/components/schemas/TestResult +type TestResult struct { + ID TestKey `json:"id"` + Outcome RunOutcome `json:"outcome"` + // CPU time of every process of the test. + TimeMs int64 `json:"time_ms"` + WallTimeMs int64 `json:"wall_time_ms"` + // Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including + // the sandbox supervisor process and file cache charged to the test. + MemoryKB int64 `json:"memory_kb"` + // Exit status when the program exited normally. + ExitCode OptInt32 `json:"exit_code"` + // Signal number when the program was killed by a signal. + Signal OptInt32 `json:"signal"` + Limit OptTerminationLimit `json:"limit"` + // Truncated standard error of a failed public test. Hidden tests never carry it. + Diagnostic OptString `json:"diagnostic"` +} + +// GetID returns the value of ID. +func (s *TestResult) GetID() TestKey { + return s.ID +} + +// GetOutcome returns the value of Outcome. +func (s *TestResult) GetOutcome() RunOutcome { + return s.Outcome +} + +// GetTimeMs returns the value of TimeMs. +func (s *TestResult) GetTimeMs() int64 { + return s.TimeMs +} + +// GetWallTimeMs returns the value of WallTimeMs. +func (s *TestResult) GetWallTimeMs() int64 { + return s.WallTimeMs +} + +// GetMemoryKB returns the value of MemoryKB. +func (s *TestResult) GetMemoryKB() int64 { + return s.MemoryKB +} + +// GetExitCode returns the value of ExitCode. +func (s *TestResult) GetExitCode() OptInt32 { + return s.ExitCode +} + +// GetSignal returns the value of Signal. +func (s *TestResult) GetSignal() OptInt32 { + return s.Signal +} + +// GetLimit returns the value of Limit. +func (s *TestResult) GetLimit() OptTerminationLimit { + return s.Limit +} + +// GetDiagnostic returns the value of Diagnostic. +func (s *TestResult) GetDiagnostic() OptString { + return s.Diagnostic +} + +// SetID sets the value of ID. +func (s *TestResult) SetID(val TestKey) { + s.ID = val +} + +// SetOutcome sets the value of Outcome. +func (s *TestResult) SetOutcome(val RunOutcome) { + s.Outcome = val +} + +// SetTimeMs sets the value of TimeMs. +func (s *TestResult) SetTimeMs(val int64) { + s.TimeMs = val +} + +// SetWallTimeMs sets the value of WallTimeMs. +func (s *TestResult) SetWallTimeMs(val int64) { + s.WallTimeMs = val +} + +// SetMemoryKB sets the value of MemoryKB. +func (s *TestResult) SetMemoryKB(val int64) { + s.MemoryKB = val +} + +// SetExitCode sets the value of ExitCode. +func (s *TestResult) SetExitCode(val OptInt32) { + s.ExitCode = val +} + +// SetSignal sets the value of Signal. +func (s *TestResult) SetSignal(val OptInt32) { + s.Signal = val +} + +// SetLimit sets the value of Limit. +func (s *TestResult) SetLimit(val OptTerminationLimit) { + s.Limit = val +} + +// SetDiagnostic sets the value of Diagnostic. +func (s *TestResult) SetDiagnostic(val OptString) { + s.Diagnostic = val +} + +// `public` tests may be shown to the person who wrote the source; their results may carry a diagnostic +// excerpt. `hidden` results never carry program output or diagnostics. +// Ref: #/components/schemas/TestVisibility +type TestVisibility string + +const ( + TestVisibilityPublic TestVisibility = "public" + TestVisibilityHidden TestVisibility = "hidden" +) + +// AllValues returns all TestVisibility values. +func (TestVisibility) AllValues() []TestVisibility { + return []TestVisibility{ + TestVisibilityPublic, + TestVisibilityHidden, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s TestVisibility) MarshalText() ([]byte, error) { + switch s { + case TestVisibilityPublic: + return []byte(s), nil + case TestVisibilityHidden: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *TestVisibility) UnmarshalText(data []byte) error { + switch TestVisibility(data) { + case TestVisibilityPublic: + *s = TestVisibilityPublic + return nil + case TestVisibilityHidden: + *s = TestVisibilityHidden + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_security_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_security_gen.go new file mode 100644 index 0000000..f6217d0 --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_security_gen.go @@ -0,0 +1,55 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" + "net/http" + + "github.com/go-faster/errors" +) + +// SecuritySource is provider of security values (tokens, passwords, etc.). +type SecuritySource interface { + // BearerAuth provides bearerAuth security value. + // Shared random service token sent as `Authorization: Bearer ` over TLS. The runner 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{ + GetRunOperation: []string{}, + SubmitRunOperation: []string{}, +} + +// GetRolesForBearerAuth returns the required roles for the given operation. +// +// This is useful for authorization scenarios where you need to know which roles +// are required for an operation. +// +// Example: +// +// requiredRoles := GetRolesForBearerAuth(AddPetOperation) +// +// Returns nil if the operation has no role requirements or if the operation is unknown. +func GetRolesForBearerAuth(operation string) []string { + roles, ok := operationRolesBearerAuth[operation] + if !ok { + return nil + } + // Return a copy to prevent external modification + result := make([]string, len(roles)) + copy(result, roles) + return result +} + +func (s *Client) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) error { + t, err := s.sec.BearerAuth(ctx, operationName) + if err != nil { + return errors.Wrap(err, "security source \"BearerAuth\"") + } + req.Header.Set("Authorization", "Bearer "+t.Token) + return nil +} diff --git a/backend/internal/adapter/secondary/code_runner/api/oas_validators_gen.go b/backend/internal/adapter/secondary/code_runner/api/oas_validators_gen.go new file mode 100644 index 0000000..a84d549 --- /dev/null +++ b/backend/internal/adapter/secondary/code_runner/api/oas_validators_gen.go @@ -0,0 +1,1512 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "fmt" + + "github.com/go-faster/errors" + "github.com/ogen-go/ogen/validate" +) + +func (s *Checker) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s CheckerKind) Validate() error { + switch s { + case "exact": + return nil + case "tokens": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *CompileResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Diagnostic.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 4096, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "diagnostic", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *GetRunnerReadyzOK) Validate() error { + alias := (*RunnerReadinessResponse)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetRunnerReadyzServiceUnavailable) Validate() error { + alias := (*RunnerReadinessResponse)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GroupResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if err := func() error { + if err := s.Visibility.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "visibility", + Error: err, + }) + } + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 50, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.PassedTests)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "passed_tests", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 50, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TotalTests)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "total_tests", + Error: err, + }) + } + if err := func() error { + if value, ok := s.MaxTimeMs.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_time_ms", + Error: err, + }) + } + if err := func() error { + if value, ok := s.MaxMemoryKB.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_memory_kb", + Error: err, + }) + } + if err := func() error { + if s.Tests == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 50, + MaxLengthSet: true, + }).ValidateLength(len(s.Tests)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Tests { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "tests", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *Problem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 256, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Type)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 400, + MaxSet: true, + Max: 599, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Status)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Detail.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "detail", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Instance.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2048, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "instance", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TraceID.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "trace_id", + Error: err, + }) + } + if err := func() error { + if s.Errors == nil { + return nil // optional + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Errors)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Errors { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "errors", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemCode) Validate() error { + switch s { + case "validation_failed": + return nil + case "unauthenticated": + return nil + case "not_found": + return nil + case "method_not_allowed": + return nil + case "payload_too_large": + return nil + case "unsupported_media_type": + return nil + case "idempotency_key_reused": + return nil + case "internal": + return nil + case "runner_busy": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemFieldError) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.In.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "in", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1024, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^(/([^~/]|~[01])*)*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Pointer)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "pointer", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z][a-z0-9_]*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Code)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 500, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Message)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "message", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemFieldLocation) Validate() error { + switch s { + case "body": + return nil + case "query": + return nil + case "path": + return nil + case "header": + return nil + case "cookie": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemStatusCode) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunLanguage) Validate() error { + switch s { + case "python3": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *RunLimits) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 100, + MaxSet: true, + Max: 10000, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TimeLimitMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "time_limit_ms", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 32, + MaxSet: true, + Max: 512, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MemoryLimitMB)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "memory_limit_mb", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 1024, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.OutputLimitKB)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "output_limit_kb", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunOutcome) Validate() error { + switch s { + case "accepted": + return nil + case "wrong_answer": + return nil + case "compile_error": + return nil + case "time_limit_exceeded": + return nil + case "memory_limit_exceeded": + return nil + case "output_limit_exceeded": + return nil + case "runtime_error": + return nil + case "infrastructure_failure": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *RunRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Language.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "language", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 65536, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Source)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if err := func() error { + if err := s.Limits.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "limits", + Error: err, + }) + } + if err := func() error { + if s.Groups == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.Groups)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Groups { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "groups", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *RunResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Compile.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: "compile", + Error: err, + }) + } + if err := func() error { + if s.Groups == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.Groups)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Groups { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "groups", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.DurationMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "duration_ms", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunState) Validate() error { + switch s { + case "running": + return nil + case "finished": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *RunStatus) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Result.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "result", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *RunnerBusyHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 3600, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.RetryAfter)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "RetryAfter", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *RunnerHealthResponse) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunnerHealthResponseStatus) Validate() error { + switch s { + case "ok": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *RunnerReadinessResponse) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunnerReadinessResponseStatus) Validate() error { + switch s { + case "ready": + return nil + case "not_ready": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SubmitRunAccepted) Validate() error { + alias := (*RunStatus)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitRunOK) Validate() error { + alias := (*RunStatus)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s TerminationLimit) Validate() error { + switch s { + case "cpu_time": + return nil + case "wall_time": + return nil + case "memory": + return nil + case "output": + return nil + case "processes": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *TestCase) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 262144, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Input)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "input", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 262144, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.ExpectedOutput)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_output", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *TestGroup) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if err := func() error { + if err := s.Visibility.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "visibility", + Error: err, + }) + } + if err := func() error { + if err := s.Checker.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "checker", + Error: err, + }) + } + if err := func() error { + if s.Tests == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 50, + MaxLengthSet: true, + }).ValidateLength(len(s.Tests)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Tests { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "tests", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s TestKey) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 32, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z0-9][a-z0-9_-]{0,31}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *TestResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TimeMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "time_ms", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.WallTimeMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "wall_time_ms", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MemoryKB)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "memory_kb", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Signal.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 64, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "signal", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Limit.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: "limit", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Diagnostic.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2048, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "diagnostic", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s TestVisibility) Validate() error { + switch s { + case "public": + return nil + case "hidden": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} diff --git a/deploy/Makefile b/deploy/Makefile index 50f5da0..a137915 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -21,6 +21,12 @@ DEMO_FILE := $(ROOT)/deploy/docker/docker-compose.demo.yml DEMO_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.demo.release.yml RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.release.yml ML_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.ml.release.yml +# DEVELOPMENT ONLY: the privileged local code runner. It is never rendered +# together with a release overlay or started by a release target. +RUNNER_DEV_FILE := $(ROOT)/deploy/docker/docker-compose.runner.dev.yml +RUNNER_DEV_PROJECT ?= runner-dev +# Local random service token of the dev runner; runner/.gitignore keeps it out of Git. +RUNNER_DEV_TOKEN_FILE ?= $(ROOT)/runner/.dev/api-token RELEASE_SCRIPT := $(ROOT)/deploy/scripts/release_manifest.py RELEASE := PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)" # Pull policy of release-build for base and service images: missing or always. @@ -58,7 +64,7 @@ DEMO_SCRIPT_ENV = DOCKER="$(DOCKER)" DEMO_MODE="$(DEMO_MODE)" DEMO_PROJECT="$(DE DEMO_RELEASE_MANIFEST="$(DEMO_RELEASE_MANIFEST)" PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json") -.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down +.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs runner-dev-config runner-dev-build runner-dev-up runner-dev-down runner-dev-logs check-runner-dev check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down help: ## Show deployment commands @awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-24s %s\n", $$1, $$2}' $(MAKEFILE_LIST) @@ -76,6 +82,7 @@ config: ## Render all Compose files with safe example values APP_PROJECT=lincodex-demo-config APP_NETWORK=lincodex-demo-config_default DEMO_ACCOUNT_PASSWORD=render-only-demo-account-password IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-demo-config -f "$(CORE_FILE)" -f "$(DEMO_FILE)" --profile demo-seed config --quiet APP_PROJECT=lincodex-demo-config APP_NETWORK=lincodex-demo-config_default LINCODEX_RELEASE_TAG=000000000000 DEMO_ACCOUNT_PASSWORD=render-only-demo-account-password IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-demo-config -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" -f "$(DEMO_FILE)" -f "$(DEMO_RELEASE_FILE)" --profile demo-seed config --quiet E2E_COMPANY_FIXTURE_TOKEN=render-only-company-fixture-token-00000000000000000000000000000000 APP_PROJECT=lincodex-e2e-mail-config APP_NETWORK=lincodex-e2e-mail-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-mail-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" -f "$(E2E_MAIL_FILE)" --profile e2e config --quiet + RUNNER_DEV_TOKEN_FILE=/dev/null $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" config --quiet build: ## Build local frontend and backend images APP_PROJECT="$(APP_PROJECT)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" build @@ -125,6 +132,29 @@ ml-logs: ## Follow ML service logs @test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; } APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" logs -f +# DEVELOPMENT ONLY: the code runner in a privileged local container. See the +# header of docker-compose.runner.dev.yml; production runs the runner only on +# its dedicated VM. +runner-dev-config: ## Render the dev-only runner Compose file + RUNNER_DEV_TOKEN_FILE=/dev/null $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" config --quiet + +runner-dev-build: ## Build the runner image for the dev-only Compose project + RUNNER_DEV_TOKEN_FILE=/dev/null $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" build + +runner-dev-up: ## Start the dev-only privileged runner on 127.0.0.1 with a local random token + @if [ ! -s "$(RUNNER_DEV_TOKEN_FILE)" ]; then \ + mkdir -p "$$(dirname "$(RUNNER_DEV_TOKEN_FILE)")"; \ + (umask 077 && python3 -c 'import secrets; print(secrets.token_urlsafe(48))' > "$(RUNNER_DEV_TOKEN_FILE)"); \ + printf 'Created the dev runner token file %s\n' "$(RUNNER_DEV_TOKEN_FILE)"; \ + fi + RUNNER_DEV_TOKEN_FILE="$(RUNNER_DEV_TOKEN_FILE)" $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" up -d --build + +runner-dev-down: ## Stop the dev-only runner + RUNNER_DEV_TOKEN_FILE="$(RUNNER_DEV_TOKEN_FILE)" $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" down + +runner-dev-logs: ## Follow dev-only runner logs + RUNNER_DEV_TOKEN_FILE="$(RUNNER_DEV_TOKEN_FILE)" $(DOCKER) compose -p "$(RUNNER_DEV_PROJECT)" -f "$(RUNNER_DEV_FILE)" logs -f + # Edge proxy (TLS and tunnel templates under deploy/edge). edge.env is local; # the checked-in example is used when it does not exist. .PHONY: edge-render edge-config @@ -138,7 +168,7 @@ edge-render: ## Render the edge nginx config from deploy/edge/edge.env into depl edge-config: ## Render the edge templates and check the nginx config with nginx -t in a container @DOCKER="$(DOCKER)" EDGE_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" bash "$(EDGE_DIR)/scripts/check.sh" "$(EDGE_ENV)" -check: config check-workflows check-release check-perimeter check-e2e-mail check-demo ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services +check: config check-workflows check-release check-perimeter check-e2e-mail check-demo check-runner-dev ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services check-workflows: ## Check that each workflow aggregate job requires every other job PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/scripts" -p 'test_workflow_aggregate.py' @@ -152,6 +182,9 @@ check-perimeter: ## Check published ports, the app Nginx paths, limits, and the check-e2e-mail: ## Check that the mail fixture stays inside the explicit local E2E network PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_e2e_mail.py' +check-runner-dev: ## Check that the dev-only runner switches stay out of production files + PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_runner_dev.py' + check-demo: ## Check the guards of the demo targets and the demo overlay without starting services PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_demo.py' diff --git a/deploy/docker/docker-compose.runner.dev.yml b/deploy/docker/docker-compose.runner.dev.yml new file mode 100644 index 0000000..e52cf91 --- /dev/null +++ b/deploy/docker/docker-compose.runner.dev.yml @@ -0,0 +1,59 @@ +# DEVELOPMENT ONLY: the code runner on a developer machine (Docker Desktop). +# +# This file is never part of a release or a production deployment. It gives +# the container `privileged: true`, because nsjail needs namespaces and a +# writable cgroup v2 tree inside the Docker Desktop VM, and it serves plain +# HTTP on loopback. A privileged container on the core application host is +# forbidden; production runs the runner image only inside its dedicated VM +# with TLS and without these switches (see docs/en/DEPLOY.md). +# +# Use it through make -C deploy runner-dev-up, which creates the local token +# file named by RUNNER_DEV_TOKEN_FILE. +services: + runner: + build: + context: ../../runner + dockerfile: Dockerfile + image: lincodex-runner-dev:local + # DEV ONLY: see the header. + privileged: true + cgroup: private + # Reaps any orphan as a second line of defense; the runner itself lets + # nsjail reap every jailed process. + init: true + read_only: true + environment: + RUNNER_LISTEN_ADDRESS: ":8080" + # DEV ONLY: production requires RUNNER_TLS_CERT_FILE and RUNNER_TLS_KEY_FILE. + RUNNER_DEV_ALLOW_PLAINTEXT_HTTP: "true" + RUNNER_API_TOKEN_FILE: /run/secrets/runner_api_token + RUNNER_MAX_CONCURRENT_RUNS: "1" + secrets: + - runner_api_token + tmpfs: + - /var/lib/lincodex-runner/work:size=64m,mode=0711 + ports: + - "127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}:8080" + healthcheck: + test: ["CMD", "/opt/lincodex-runner/lincodex-runner", "healthcheck"] + interval: 10s + timeout: 3s + retries: 5 + start_period: 5s + restart: unless-stopped + logging: + driver: json-file + options: + max-size: 10m + max-file: "3" + # The planned runner VM has 2 vCPU and 3 GB. + deploy: + resources: + limits: + cpus: "2.0" + memory: 3G + pids: 512 + +secrets: + runner_api_token: + file: ${RUNNER_DEV_TOKEN_FILE:?Set RUNNER_DEV_TOKEN_FILE or use make -C deploy runner-dev-up} diff --git a/deploy/scripts/test_runner_dev.py b/deploy/scripts/test_runner_dev.py new file mode 100644 index 0000000..6e131e5 --- /dev/null +++ b/deploy/scripts/test_runner_dev.py @@ -0,0 +1,97 @@ +"""Check that the dev-only code runner switches stay out of production files. + +The local runner Compose file gives the container `privileged: true` and +serves plain HTTP, because nsjail needs namespaces and a writable cgroup tree +inside Docker Desktop. Production runs the runner only in its dedicated VM. +These tests read files; the render test also needs the docker CLI. +""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DOCKER_DIR = ROOT / "deploy" / "docker" +DEV_FILE = DOCKER_DIR / "docker-compose.runner.dev.yml" +DEPLOY_MAKEFILE = ROOT / "deploy" / "Makefile" +RUNNER_DOCKERFILE = ROOT / "runner" / "Dockerfile" +RELEASE_SCRIPT = ROOT / "deploy" / "scripts" / "release_manifest.py" +DOCKER = os.environ.get("DOCKER", "docker") +DEV_SWITCHES = ("privileged", "RUNNER_DEV_ALLOW_PLAINTEXT_HTTP", "docker-compose.runner.dev.yml") +# Make targets that may use the dev runner file. +DEV_TARGETS = {"config", "runner-dev-config", "runner-dev-build", "runner-dev-up", "runner-dev-down", "runner-dev-logs"} +TARGET = re.compile(r"^([A-Za-z0-9_-]+):") + + +class RunnerDevFilesTest(unittest.TestCase): + def test_the_dev_file_is_named_and_marked_as_development_only(self) -> None: + self.assertIn(".dev.", DEV_FILE.name) + header = DEV_FILE.read_text(encoding="utf-8").splitlines()[0] + self.assertTrue(header.startswith("# DEVELOPMENT ONLY"), header) + + def test_production_compose_files_have_no_dev_switch(self) -> None: + for path in sorted(DOCKER_DIR.glob("docker-compose*.yml")): + if path == DEV_FILE: + continue + text = path.read_text(encoding="utf-8") + for switch in DEV_SWITCHES: + with self.subTest(file=path.name, switch=switch): + self.assertNotIn(switch, text) + + def test_the_production_image_has_no_dev_switch(self) -> None: + text = RUNNER_DOCKERFILE.read_text(encoding="utf-8") + self.assertNotIn("RUNNER_DEV_", text) + self.assertNotIn("--privileged", text) + + def test_release_tooling_never_uses_the_dev_file(self) -> None: + self.assertNotIn(DEV_FILE.name, RELEASE_SCRIPT.read_text(encoding="utf-8")) + + def test_only_dev_targets_use_the_dev_file(self) -> None: + target = None + users = set() + for line in DEPLOY_MAKEFILE.read_text(encoding="utf-8").splitlines(): + match = TARGET.match(line) + if match and not line.startswith(("\t", " ")): + target = match.group(1) + if "$(RUNNER_DEV_FILE)" in line and line.startswith("\t"): + users.add(target) + self.assertTrue(users) + self.assertLessEqual(users, DEV_TARGETS) + + +class RunnerDevRenderTest(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + if shutil.which(DOCKER) is None: + raise unittest.SkipTest("docker CLI is not available") + result = subprocess.run( + [DOCKER, "compose", "-p", "runner-dev-check", "-f", str(DEV_FILE), "config", "--format", "json"], + env={**os.environ, "RUNNER_DEV_TOKEN_FILE": "/dev/null"}, + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0: + raise AssertionError(f"docker compose config failed: {result.stderr}") + cls.runner = json.loads(result.stdout)["services"]["runner"] + + def test_the_dev_runner_publishes_only_loopback(self) -> None: + ports = self.runner.get("ports") or [] + self.assertTrue(ports) + for port in ports: + self.assertEqual(port["host_ip"], "127.0.0.1") + + def test_the_dev_runner_reads_the_token_from_a_secret_file(self) -> None: + environment = self.runner["environment"] + self.assertEqual(environment["RUNNER_API_TOKEN_FILE"], "/run/secrets/runner_api_token") + self.assertNotIn("RUNNER_API_TOKEN", environment) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index fa0c12a..93a808d 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -26,9 +26,9 @@ The project brief assigns 35% of its score to matching, 25% to assessment and ca ## Contracts and code generation -The contract roots are split by boundary: api/core/ contains browser-to-Go operations, and api/ml/ contains internal Go-to-ML operations. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files. +The contract roots are split by boundary: api/core/ contains browser-to-Go operations, api/ml/ contains internal Go-to-ML operations, and api/runner/ contains internal operations between Go and the code runner. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files. -The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code. +The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/, and the code runner Go client is configured at backend/codegen/ogen-code-runner.yml and generated into backend/internal/adapter/secondary/code_runner/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code. OpenAPI 3.2.0 is the target version. Verify the subset used here across bundling and lint, ogen, the chi adapter, the API runtime path, Orval, Python Pydantic models, and documentation. A parser version or one fixture does not prove support for every OpenAPI 3.2.0 feature. @@ -537,6 +537,7 @@ The local release manifest separates core image verification from product data a ```text api/core/ public browser-to-Go contract and bundle api/ml/ internal Go-to-ML contract and bundle +api/runner/ internal Go-to-code-runner contract and bundle backend/cmd/app/main.go calls bootstrap.Run and reports errors backend/cmd/migrate/ local migration status, up, and down-one backend/config/ shared runtime configuration @@ -551,6 +552,7 @@ frontend/src/ app, pages, widgets, features, entities, shared frontend/codegen/ Orval configuration ml/src/ FastAPI service and operational checks ml/codegen/ Python datamodel-code-generator settings +runner/ Go code runner service: nsjail, cgroup v2, judge, and HTTP API deploy/ Compose, Nginx, and technical smoke checks observability/ Prometheus, Loki, Alloy, Grafana provisioning scripts/ shared documentation and schema tooling @@ -586,6 +588,7 @@ backend/ mail/resend/ mail transport that sends one request to the Resend HTTP API per message mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it ml/api/ generated client from backend/codegen/ogen-ml.yml + code_runner/api/ generated client from backend/codegen/ogen-code-runner.yml postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check postgres/sqlc/ generated SQL adapter redis/ cache adapter and Redis check @@ -720,6 +723,27 @@ A category changes only by a strict grade upgrade (the database trigger and the `basis` is the same value as the `source` of the category decision. Today it is always `synthetic_demo`: the database accepts only the demonstration source and `calibration_status = uncalibrated`. The candidate card and the organization search therefore show such a category as a demonstration, not as a validated measurement. The basis is required in every category object, so a category without a basis cannot look like a standard confirmation. +### Code runner + +Code practice runs in the own `runner/` service; Judge0 is not used (GPL license, owner decision). The service receives the source, the limits, and the test groups through the internal `api/runner/` contract, runs every test in nsjail, and returns the outcome of every group. The backend computes the 0-3 score from the three hidden groups; the runner only reports which groups passed. + +The A16 boundary. Untrusted code runs only on a separate runner host. The target production placement is a dedicated LXD VM on the app host (2 vCPU, 3 GB, one concurrent run) attached to a private bridge without internet access; the backend reaches it over TLS with a bearer token. A privileged container on the core host is forbidden, and a Docker network alone is not a boundary. The runner host holds no business secrets: only its TLS key and the API token. + +Isolation layers of one run (implemented): + +- nsjail in run-once mode: new network (empty, without loopback), PID, mount, IPC, UTS, user, and cgroup namespaces, `no_new_privs`, dropped capabilities, the user uid/gid 99999 inside and outside the user namespace, and no `/proc`. +- File system: the jail root is a read-only tmpfs; only `/usr` and `/lib` (the interpreter) are mounted read-only, the run directory with the source is mounted read-only as `/box`, plus `/dev/null` and `/dev/urandom`, and the working directory `/tmp` is a size-limited tmpfs. The run directory is removed after the run, and its root is emptied at startup. +- cgroup v2: the supervisor creates the cgroup of every run itself (`memory.max` with a small allowance for nsjail, `memory.swap.max=0`, `pids.max`, `cpu.max` for one CPU) and starts nsjail directly inside it with CLONE_INTO_CGROUP. The limits therefore cover the whole process tree, and the OOM, refused fork, and CPU counters are exact. +- rlimits: CPU, file size, open files, core 0, and address space. +- seccomp (kafel): the process is killed on ptrace, mount and namespace calls, keyrings, bpf, perf, userfaultfd, io_uring, kernel modules, and clock and swap administration; clone with namespace flags kills the process, clone3 answers ENOSYS, and sockets other than AF_UNIX answer EAFNOSUPPORT. +- The supervisor checks CPU, wall clock, OOM, and the process limit every 10 ms and, when a limit fires, kills the jailed processes but keeps nsjail so that it reaps its child; if nsjail does not exit within a second, the whole cgroup is killed. After a run the cgroup is removed only once it is empty. + +The service bounds concurrent runs (1 by default) and answers 503 `runner_busy` when no slot is free; the backend keeps the queue. The contract and the configuration bound the request body, the source, the inputs, and the output. Logs carry only the method, operation, status, duration, run ID, language, group and test counts, and outcome; the source, test data, program output, and token never reach a log. Runs live only in memory and are forgotten after their TTL; the backend resubmits a run lost in a restart. + +Outcomes distinguish `accepted`, `wrong_answer`, `compile_error` (for Python, a syntax check with `compile()` before the tests), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (including the process limit), and `infrastructure_failure`. Test time is the CPU time of every process of the test, including interpreter startup; memory is the cgroup peak of the test, including nsjail and file cache charged to the test. + +Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; Go (compile and run); a float tolerance checker and custom checkers; calls from the backend and the run queue; service metrics; the full A16 isolation suite built on `runner/testdata/hostile/`. + ## Matching and explanations Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 41590c0..4de2e1a 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -735,6 +735,44 @@ Verified on the app host (TASK-592): from a guest on `lxdbr-runner` the internet Cleanup before the rollout removed only the Docker build cache (`docker builder prune -af`, about 8 GB). `apt-get clean` and `journalctl --vacuum-size=100M` need sudo and are left to the operator. Docker volumes, the images of the running stack, `wg0`, `awg-lincodex` and the `ufw` rules are not touched. +## Code runner + +The `runner/Dockerfile` image holds the Go supervisor, nsjail, and Python from `python:alpine`; pip and ensurepip are removed. The base images are the `GO_IMAGE` and `RUNTIME_IMAGE` arguments, so a release build can pin their digests. The supervisor runs as root inside its own host or VM because it needs namespaces, user mapping, and writes to its delegated cgroup. Candidate programs run as uid 99999 without capabilities. + +### Local (development only) + +`deploy/docker/docker-compose.runner.dev.yml` is a separate dev project `runner-dev`. It gives the container `privileged: true`, because nsjail needs namespaces and a writable cgroup v2 tree inside the Docker Desktop VM, and it serves plain HTTP on 127.0.0.1 only. The file is never used by a release or in production; `make -C deploy check-runner-dev` checks that its switches stay out of the other Compose files, the production image, and the release tooling. + + make -C deploy runner-dev-config + make -C deploy runner-dev-up + make -C deploy runner-dev-logs + make -C deploy runner-dev-down + +`runner-dev-up` creates a local random token in `runner/.dev/api-token` (ignored by Git) when it is missing and starts the service on `127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}`. Call it with `Authorization: Bearer $(cat runner/.dev/api-token)` and `PUT /v1/runs/` from the `api/runner/` contract. + +### Production (planned) + +The runner runs only in the `lincodex-runner` VM on the `lxdbr-runner` bridge (see [the isolated runner host](#isolated-runner-and-lab-host-lxd)), never on the core host and never with the dev file. TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; the process does not start without them) and a token from a secret file (`RUNNER_API_TOKEN_FILE`) are required. Rolling out the VM, issuing the certificate, storing the token for the backend, and monitoring are not implemented yet. + +| Variable | Default | Purpose | +| --- | --- | --- | +| `RUNNER_LISTEN_ADDRESS` | `:8443` | HTTP(S) address | +| `RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE` | none | TLS 1.3 certificate and key; required outside dev | +| `RUNNER_API_TOKEN_FILE` or `RUNNER_API_TOKEN` | none | Token of at least 32 characters; prefer the file | +| `RUNNER_DEV_ALLOW_PLAINTEXT_HTTP` | `false` | Dev Compose only: HTTP without TLS | +| `RUNNER_MAX_CONCURRENT_RUNS` | `1` | Concurrent runs; more answer 503 `runner_busy` | +| `RUNNER_MAX_REQUEST_BYTES` | `8388608` | Request body limit | +| `RUNNER_RESULT_TTL`, `RUNNER_MAX_RETAINED_RUNS` | `15m`, `256` | In-memory result retention | +| `RUNNER_RETRY_AFTER`, `RUNNER_SHUTDOWN_TIMEOUT` | `2s`, `30s` | Retry-After when busy and the wait for runs at shutdown | +| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Run directories; emptied at startup, tmpfs recommended | +| `RUNNER_CGROUP_ROOT` | `/sys/fs/cgroup` | The service's delegated cgroup v2 | +| `RUNNER_NSJAIL_PATH`, `RUNNER_PYTHON_PATH` | `/usr/bin/nsjail`, `/usr/local/bin/python3` | Paths in the image | +| `RUNNER_SANDBOX_UID` | `99999` | Program user, never root | +| `RUNNER_SANDBOX_MAX_PROCESSES` | `16` | Processes and threads of a run | +| `RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES` | `4194304` | Memory allowance for nsjail above the task limit | +| `RUNNER_SANDBOX_TMPFS_BYTES`, `RUNNER_SANDBOX_FILE_SIZE_BYTES`, `RUNNER_SANDBOX_OPEN_FILES` | `16777216`, `8388608`, `64` | `/tmp` size, file size, and open files | +| `RUNNER_LOG_LEVEL` | `info` | JSON log level | + ## Services and images Container images use moving `latest` or `alpine` tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; the [release manifest](#release-manifest) records the actual image digests of a release. An SBOM is not produced yet. Application dependency lockfiles remain checked in separately. @@ -752,6 +790,7 @@ Container images use moving `latest` or `alpine` tags where the upstream publish | PostgreSQL exporter | prometheus-community/postgres_exporter | Apache-2.0 | | Docker socket proxy | Tecnativa/docker-socket-proxy | Apache-2.0 | | BusyBox | busybox | GPL-2.0-only | +| nsjail | Alpine `nsjail` package in the code runner image | [Apache-2.0](https://github.com/google/nsjail/blob/master/LICENSE) | Upstream references: [PostgreSQL image](https://github.com/docker-library/postgres), [Prometheus](https://github.com/prometheus/prometheus/blob/main/LICENSE), [Loki license details](https://github.com/grafana/loki/blob/main/LICENSING.md), [Alloy license details](https://github.com/grafana/alloy/blob/main/LICENSING.md), [Grafana license details](https://github.com/grafana/grafana/blob/main/LICENSING.md), [node_exporter](https://github.com/prometheus/node_exporter/blob/master/LICENSE), [postgres_exporter](https://github.com/prometheus-community/postgres_exporter/blob/master/LICENSE), [socket proxy](https://github.com/Tecnativa/docker-socket-proxy), [BusyBox license](https://busybox.net/license.html). diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index d387d21..9d20323 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -51,7 +51,7 @@ What exists now: - Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail. - Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and `identity.Credentials` are wired for registration and email confirmation. A generated Go client for the ML contract exists but is not wired into bootstrap. - Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). -- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders. +- OpenAPI contracts api/core/, api/ml/, and api/runner/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs two product handlers, the mail delivery consumer and the inbox consumer, and no product flow emits their events yet; see [Event consumers](#event-consumers). - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite. @@ -100,22 +100,24 @@ Each top-level directory except `.github/` has a short Russian `README.md` and a | --- | --- | | api/core/ | Public browser-to-Go OpenAPI contract | | api/ml/ | Internal Go-to-ML OpenAPI contract | +| api/runner/ | Internal OpenAPI contract between Go and the code runner | | scripts/ | Shared schema merge, generated drift, and docs-check | | backend/ | Go HTTP service, adapters, bootstrap, SQL, and consumer codegen | | backend/config/ | Shared Go configuration outside internal | | frontend/ | Vite SPA, Orval configuration, generated TypeScript | | ml/ | Python service, lockfile, and Pydantic model generator | +| runner/ | Go code runner service: nsjail, cgroup v2, judge, ogen server, and isolation tests | | deploy/ | Compose, Nginx, and smoke script | | observability/ | Prometheus, Loki, Alloy, provisioning, and dashboard JSON | | security/ | Scanner configuration, installation, Make targets, and local reports | | .agents/ | Canonical project instructions and working standards | | docs/ru/, docs/en/ | User documentation in Russian and English | -Codegen directories belong to the services that use the generated code: backend/codegen/, frontend/codegen/, and ml/codegen/. The Go client for the internal ML API is generated from backend/codegen/ogen-ml.yml and consumed at backend/internal/adapter/secondary/ml/api/. The public Go handler is generated from backend/codegen/ogen.yml and mounted in chi. sqlc configuration is backend/codegen/sqlc.yml, with generated SQL under backend/internal/adapter/secondary/postgres/sqlc/. Orval reads the public bundle from frontend/codegen/orval.config.ts. backend/cmd/app/main.go calls bootstrap.Run() and handles its error; startup, dependency wiring, and lifecycle logic live in backend/internal/bootstrap/app.go. +Codegen directories belong to the services that use the generated code: backend/codegen/, frontend/codegen/, and ml/codegen/. The Go client for the internal ML API is generated from backend/codegen/ogen-ml.yml and consumed at backend/internal/adapter/secondary/ml/api/. The Go client for the code runner is generated from backend/codegen/ogen-code-runner.yml into backend/internal/adapter/secondary/code_runner/api/. The public Go handler is generated from backend/codegen/ogen.yml and mounted in chi. sqlc configuration is backend/codegen/sqlc.yml, with generated SQL under backend/internal/adapter/secondary/postgres/sqlc/. Orval reads the public bundle from frontend/codegen/orval.config.ts. backend/cmd/app/main.go calls bootstrap.Run() and handles its error; startup, dependency wiring, and lifecycle logic live in backend/internal/bootstrap/app.go. ## Contracts and generation -Source YAML stays beside its contract. Run make -C api bundle to merge schemas separately for api/core/ and api/ml/ and then bundle both inputs. The public and internal APIs remain separate contracts. +Source YAML stays beside its contract. Run make -C api bundle to merge schemas separately for api/core/, api/ml/, and api/runner/ and then bundle each input. The public and internal APIs remain separate contracts. Root make generate prepares both bundles once, then runs Go, TypeScript, and Python consumers. Merged schemas, bundles, and generated clients are tracked derived files; change their sources and regenerate them. After changing a contract, regenerate every consumer and check drift. A service-local Make target can generate one consumer when its inputs are ready and the shared contract owner has agreed. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 9c854cc..4fc3d72 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -581,6 +581,20 @@ What these tests do not show: a real invitation event through Kafka and the rela The tests do not run the Make targets against a real stack. A manual check on a throwaway project: `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` twice with identical inventories, a sign-in of the prepared accounts with mail disabled, an express run and the start of the full test, then `demo-reset` refused after a visitor registered. Remove the project afterwards with `docker compose -p lincodex-demo-check down --volumes` and the same variables. The tests do not validate the content of the synthetic bank or any grade, and the browser route of the jury is not covered here. Integration tests need Docker. +## Code runner tests + +| Command | What it checks | +| --- | --- | +| make -C runner test | Unit tests with the race detector: checkers, configuration, judge outcomes on a scripted sandbox, idempotency and busy handling of the run manager, the HTTP API (token, 202/200/422/503, 400, 413, 404), and that logs carry no source, input, or token | +| make -C runner lint | golangci-lint for Linux, including the isolation tests | +| make -C runner check-generated | The generated ogen server matches the bundle | +| make -C runner test-sandbox | Isolation tests in a privileged dev container with real nsjail and cgroup v2 | +| make -C deploy check-runner-dev | Dev switches stay out of production files | + +`test-sandbox` runs every case of `runner/testdata/hostile/manifest.json` twice: a correct solution is accepted with its time and memory recorded; a syntax error gives `compile_error`; the CPU limit stops an infinite loop, the wall-clock limit a sleep, the cgroup memory limit a memory leak, the output limit endless output, and the process limit a fork bomb (`runtime_error`); network, file system, and privilege probes confirm that there is no network, the root and the source are read-only, runner files are not visible, and the program is not root. After every case and after the series the test checks that the run directory is empty, the run cgroups are gone, and no uid 99999 process is left. It runs without a separate init, so it also confirms that nsjail reaps every stopped process. + +What the tests do not prove: isolation in the production VM (they have not run there yet), protection against kernel, nsjail, or cgroup vulnerabilities, the absence of side channels, or behavior under load. The full A16 isolation suite is planned separately and will extend the same fixtures. + ## Future software validation Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 96c7b6e..53e57d0 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -26,15 +26,15 @@ Go владеет авторизацией, подтвержденными ка ## Контракты и генерация -Каталоги контрактов симметричны: api/core/ содержит публичный контракт браузер-Go, api/ml/ - внутренний контракт Go-ML. Общие Makefile, package.json и Redocly config находятся в api/; Python-скрипты сборки лежат в корневом scripts/. Обе спеки состоят из небольших исходных YAML-файлов, которые собираются в bundles. +Каталоги контрактов симметричны: api/core/ содержит публичный контракт браузер-Go, api/ml/ - внутренний контракт Go-ML, api/runner/ - внутренний контракт Go и исполнителя кода. Общие Makefile, package.json и Redocly config находятся в api/; Python-скрипты сборки лежат в корневом scripts/. Все спеки состоят из небольших исходных YAML-файлов, которые собираются в bundles. -Публичный Go handler генерируется ogen из backend/codegen/ogen.yml и монтируется в chi. Orval независимо генерирует TypeScript client, TanStack Query hooks, Zod schemas и MSW handlers. Go-клиент ML API генерируется по backend/codegen/ogen-ml.yml в backend/internal/adapter/secondary/ml/api/. Python-модели Pydantic v2 генерируются datamodel-code-generator из того же ML bundle в ml/src/lincodex_ml/api/models.py; их используют health/readiness handlers. Настройки Python-генератора находятся в ml/codegen/pyproject.toml, зависимости - в ml/pyproject.toml. Backend конфигурация sqlc находится в backend/codegen/sqlc.yml, generated SQL adapter - в backend/internal/adapter/secondary/postgres/sqlc/. Frontend config - в frontend/codegen/orval.config.ts. Всего три каталога codegen: backend/codegen/, frontend/codegen/ и ml/codegen/; конфигурация принадлежит сервису, который использует сгенерированный код. +Публичный Go handler генерируется ogen из backend/codegen/ogen.yml и монтируется в chi. Orval независимо генерирует TypeScript client, TanStack Query hooks, Zod schemas и MSW handlers. Go-клиент ML API генерируется по backend/codegen/ogen-ml.yml в backend/internal/adapter/secondary/ml/api/, Go-клиент исполнителя кода - по backend/codegen/ogen-code-runner.yml в backend/internal/adapter/secondary/code_runner/api/. Python-модели Pydantic v2 генерируются datamodel-code-generator из того же ML bundle в ml/src/lincodex_ml/api/models.py; их используют health/readiness handlers. Настройки Python-генератора находятся в ml/codegen/pyproject.toml, зависимости - в ml/pyproject.toml. Backend конфигурация sqlc находится в backend/codegen/sqlc.yml, generated SQL adapter - в backend/internal/adapter/secondary/postgres/sqlc/. Frontend config - в frontend/codegen/orval.config.ts. Всего три каталога codegen: backend/codegen/, frontend/codegen/ и ml/codegen/; конфигурация принадлежит сервису, который использует сгенерированный код. Целевая версия OpenAPI - 3.2.0. Проверяется только используемое подмножество: bundling/lint, ogen, chi adapter, runtime путь API, Orval, Python-модели Pydantic и документация. Проверка одной fixture или чтение версии parser не доказывает поддержку всех возможностей OpenAPI 3.2.0. В публичном API префикс /api/v1 применяется один раз. Служебный /metrics остается отдельным внутренним маршрутом. Health операции именуются с суффиксом z: healthz и readyz. DTO генераторов не заменяют проверку владельца, членства в компании, согласия или допустимости перехода бизнес-состояния. -Генерация идет из исходных контрактов. Core и ML bundles создаются отдельно; затем Go, TypeScript и Python потребители обновляются из своих Make targets. Изменения контракта включают regeneration и проверку generated drift для всех потребителей. Сгенерированные файлы не редактируются вручную. +Генерация идет из исходных контрактов. Core, ML и runner bundles создаются отдельно; затем Go, TypeScript и Python потребители обновляются из своих Make targets. Изменения контракта включают regeneration и проверку generated drift для всех потребителей. Сгенерированные файлы не редактируются вручную. ## Границы сервисов и данных @@ -537,6 +537,7 @@ Offsets и партиции. Каждый обработчик - один уча ```text api/core/ публичный контракт браузер-Go и bundle api/ml/ внутренний контракт Go-ML и bundle +api/runner/ внутренний контракт Go и исполнителя кода и bundle backend/cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку backend/cmd/migrate/ локальные status, up и down-one для миграций backend/config/ общая конфигурация runtime @@ -551,6 +552,7 @@ frontend/src/ app, pages, widgets, features, entities, shared frontend/codegen/ конфигурация Orval ml/src/ FastAPI сервис и operational checks ml/codegen/ настройки Python datamodel-code-generator +runner/ Go-сервис исполнителя кода: nsjail, cgroup v2, judge и HTTP API deploy/ Compose, Nginx и технические smoke checks observability/ Prometheus, Loki, Alloy и Grafana provisioning scripts/ общие инструменты для документации и схем @@ -586,6 +588,7 @@ backend/ mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend mail/resend/resendfixture/ локальная замена API Resend только для тестов; production ее не импортирует ml/api/ generated client из backend/codegen/ogen-ml.yml + code_runner/api/ generated client из backend/codegen/ogen-code-runner.yml postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий, организаций, членств и политики, health check postgres/sqlc/ generated SQL adapter redis/ адаптер кеша и проверка Redis @@ -720,6 +723,27 @@ contact_grant относится к паре кандидат-компания `basis` - то же значение, что `source` решения о категории. Сейчас оно всегда `synthetic_demo`: база принимает только демонстрационный источник и `calibration_status = uncalibrated`. Поэтому карточки кандидата и подбор организаций показывают такую категорию как демонстрационную, а не как проверенное измерение. Основание обязательно в каждом объекте категории, поэтому категория без основания не может выглядеть стандартным подтверждением. +### Исполнитель кода + +Практика с кодом исполняется собственным сервисом `runner/`; Judge0 не используется (лицензия GPL, решение владельца). Сервис принимает исходный код, лимиты и группы тестов по внутреннему контракту `api/runner/`, запускает каждый тест в nsjail и возвращает исход каждой группы. Балл 0-3 по трем скрытым группам считает backend; исполнитель только сообщает, какие группы пройдены. + +Граница A16. Недоверенный код запускается только на отдельном хосте исполнителя. Целевое production-размещение - выделенная LXD VM на app-хосте (2 vCPU, 3 GB, один параллельный прогон), подключенная к частному bridge без выхода в интернет; backend обращается к ней по TLS с bearer-токеном. Привилегированный контейнер на core-хосте запрещен, а сеть Docker сама по себе не считается границей. На хосте исполнителя нет бизнес-секретов: только его TLS-ключ и токен API. + +Слои изоляции одного прогона (реализовано): + +- nsjail в режиме одного запуска: новые пространства имен network (пустое, без loopback), PID, mount, IPC, UTS, user и cgroup, `no_new_privs`, сброс capabilities, пользователь uid/gid 99999 внутри и снаружи user namespace, без `/proc`. +- Файловая система: корень jail - tmpfs, смонтированный только для чтения; внутрь попадают только `/usr` и `/lib` (интерпретатор) только для чтения, каталог прогона с исходником как `/box` только для чтения, `/dev/null` и `/dev/urandom`, а рабочий каталог `/tmp` - tmpfs ограниченного размера. Каталог прогона удаляется после прогона, его корень очищается при старте. +- cgroup v2: супервизор сам создает cgroup каждого прогона (`memory.max` с небольшим запасом на nsjail, `memory.swap.max=0`, `pids.max`, `cpu.max` на один CPU) и запускает nsjail сразу внутри него через CLONE_INTO_CGROUP. Поэтому лимиты покрывают весь процессный tree, а счетчики OOM, отказов fork и CPU точные. +- rlimits: CPU, размер файла, открытые файлы, core 0, адресное пространство. +- seccomp (kafel): завершение процесса при ptrace, mount и namespace-вызовах, keyring, bpf, perf, userfaultfd, io_uring, модулях ядра и администрировании часов и swap; clone с флагами namespace завершает процесс, clone3 отвечает ENOSYS, сокеты кроме AF_UNIX отвечают EAFNOSUPPORT. +- Супервизор отслеживает CPU, стену, OOM и лимит процессов каждые 10 мс и при срабатывании убивает процессы jail, оставляя nsjail, чтобы тот забрал своего потомка; если nsjail не завершился за секунду, убивается вся cgroup. После прогона cgroup удаляется только пустой. + +Сервис ограничивает число параллельных прогонов (по умолчанию 1) и отвечает 503 `runner_busy` при занятом слоте; очередь держит backend. Размер тела запроса, исходника, входа и вывода ограничен контрактом и конфигурацией. Логи содержат только метод, операцию, статус, длительность, run ID, язык, число групп и тестов и исход; исходник, тестовые данные, вывод программы и токен в логи не попадают. Прогоны хранятся только в памяти и забываются после TTL; потерянный при рестарте прогон backend отправляет снова. + +Исходы различают `accepted`, `wrong_answer`, `compile_error` (для Python - проверка синтаксиса через `compile()` до тестов), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (включая лимит процессов) и `infrastructure_failure`. Время теста - CPU всех процессов теста вместе с запуском интерпретатора; память - пик cgroup теста, включая nsjail и файловый кеш, отнесенный к тесту. + +Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; Go (компиляция и запуск); checker с допуском для чисел и собственный checker; вызов исполнителя из backend и очередь прогонов; метрики сервиса; полный набор проверок изоляции A16 на базе `runner/testdata/hostile/`. + ## Подбор и объяснение Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 1924535..6f246b3 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -737,6 +737,44 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml Чистка перед раскаткой удалила только кеш сборки Docker (`docker builder prune -af`, около 8 ГБ). `apt-get clean` и `journalctl --vacuum-size=100M` требуют sudo и оставлены оператору. Тома Docker, образы работающего стека, `wg0`, `awg-lincodex` и правила `ufw` не затронуты. +## Исполнитель кода + +Образ `runner/Dockerfile` содержит Go-супервизор, nsjail и Python из `python:alpine`; pip и ensurepip удалены. Базовые образы - аргументы `GO_IMAGE` и `RUNTIME_IMAGE`, поэтому сборка выпуска может закрепить их digest. Супервизор работает root внутри своего хоста или VM: ему нужны namespaces, отображение пользователя и запись в делегированную cgroup. Программы кандидата работают как uid 99999 без capabilities. + +### Локально (только разработка) + +`deploy/docker/docker-compose.runner.dev.yml` - отдельный dev-проект `runner-dev`. Он дает контейнеру `privileged: true`, потому что nsjail внутри VM Docker Desktop нужны namespaces и записываемая cgroup v2, и обслуживает простой HTTP только на 127.0.0.1. Этот файл никогда не используется в выпуске или production; `make -C deploy check-runner-dev` проверяет, что его переключатели не попали в другие Compose-файлы, production-образ и инструменты выпуска. + + make -C deploy runner-dev-config + make -C deploy runner-dev-up + make -C deploy runner-dev-logs + make -C deploy runner-dev-down + +`runner-dev-up` создает локальный случайный токен в `runner/.dev/api-token` (игнорируется Git), если его нет, и запускает сервис на `127.0.0.1:${RUNNER_DEV_HTTP_PORT:-8070}`. Вызов: `Authorization: Bearer $(cat runner/.dev/api-token)` и `PUT /v1/runs/` по контракту `api/runner/`. + +### Production (запланировано) + +Исполнитель работает только в VM `lincodex-runner` на мосту `lxdbr-runner` (см. [изолированный хост раннера](#изолированный-хост-раннера-и-лабораторий-lxd)), никогда на core-хосте и никогда с dev-файлом. Обязательны TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; без них процесс не стартует) и токен из файла секрета (`RUNNER_API_TOKEN_FILE`). Раскатка VM, выпуск сертификата, хранение токена на стороне backend и мониторинг еще не реализованы. + +| Переменная | По умолчанию | Назначение | +| --- | --- | --- | +| `RUNNER_LISTEN_ADDRESS` | `:8443` | Адрес HTTP(S) | +| `RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE` | нет | Сертификат и ключ TLS 1.3; обязательны вне dev | +| `RUNNER_API_TOKEN_FILE` или `RUNNER_API_TOKEN` | нет | Токен не короче 32 символов; предпочтителен файл | +| `RUNNER_DEV_ALLOW_PLAINTEXT_HTTP` | `false` | Только dev Compose: HTTP без TLS | +| `RUNNER_MAX_CONCURRENT_RUNS` | `1` | Параллельные прогоны; сверх них 503 `runner_busy` | +| `RUNNER_MAX_REQUEST_BYTES` | `8388608` | Лимит тела запроса | +| `RUNNER_RESULT_TTL`, `RUNNER_MAX_RETAINED_RUNS` | `15m`, `256` | Хранение результатов в памяти | +| `RUNNER_RETRY_AFTER`, `RUNNER_SHUTDOWN_TIMEOUT` | `2s`, `30s` | Retry-After при занятости и ожидание прогонов при остановке | +| `RUNNER_WORK_DIR` | `/var/lib/lincodex-runner/work` | Каталоги прогонов; очищается при старте, рекомендуется tmpfs | +| `RUNNER_CGROUP_ROOT` | `/sys/fs/cgroup` | Делегированная cgroup v2 сервиса | +| `RUNNER_NSJAIL_PATH`, `RUNNER_PYTHON_PATH` | `/usr/bin/nsjail`, `/usr/local/bin/python3` | Пути в образе | +| `RUNNER_SANDBOX_UID` | `99999` | Пользователь программ, не root | +| `RUNNER_SANDBOX_MAX_PROCESSES` | `16` | Процессы и потоки прогона | +| `RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES` | `4194304` | Запас памяти на nsjail сверх лимита задания | +| `RUNNER_SANDBOX_TMPFS_BYTES`, `RUNNER_SANDBOX_FILE_SIZE_BYTES`, `RUNNER_SANDBOX_OPEN_FILES` | `16777216`, `8388608`, `64` | Размер `/tmp`, размер файла и открытые файлы | +| `RUNNER_LOG_LEVEL` | `info` | Уровень JSON-логов | + ## Сервисы и образы Для контейнерных образов выбраны moving tags `latest` или `alpine`, если upstream публикует такой вариант. При обновлении Compose сверяйте актуальные ссылки на образы. Теги `latest` и `alpine` могут перемещаться; фактические image digests выпуска фиксирует [манифест выпуска](#манифест-выпуска). SBOM пока не формируется. Lockfiles прикладных зависимостей сохраняются отдельно. @@ -754,6 +792,7 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml | PostgreSQL exporter | prometheus-community/postgres_exporter | Apache-2.0 | | Docker socket proxy | Tecnativa/docker-socket-proxy | Apache-2.0 | | BusyBox | busybox | GPL-2.0-only | +| nsjail | пакет Alpine `nsjail` в образе исполнителя кода | [Apache-2.0](https://github.com/google/nsjail/blob/master/LICENSE) | Ссылки на upstream: [PostgreSQL image](https://github.com/docker-library/postgres), [Prometheus](https://github.com/prometheus/prometheus/blob/main/LICENSE), [Loki license details](https://github.com/grafana/loki/blob/main/LICENSING.md), [Alloy license details](https://github.com/grafana/alloy/blob/main/LICENSING.md), [Grafana license details](https://github.com/grafana/grafana/blob/main/LICENSING.md), [node_exporter](https://github.com/prometheus/node_exporter/blob/master/LICENSE), [postgres_exporter](https://github.com/prometheus-community/postgres_exporter/blob/master/LICENSE), [socket proxy](https://github.com/Tecnativa/docker-socket-proxy), [BusyBox license](https://busybox.net/license.html). diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 89f7ac1..4103ae3 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -51,7 +51,7 @@ Frontend зависимости выбираются из актуальных s - Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет. - Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и `identity.Credentials` подключены для регистрации и подтверждения email. Generated Go client для ML контракта есть, но в bootstrap не подключен. - Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы продуктовых уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но отправка уведомлений еще не реализована. При `resend` backend запускает worker служебной почты identity: регистрация и повторная отправка создают письма подтверждения, привязанные к токенам; worker проверяет токен и аккаунт перед отправкой и использует шлюз квот и стабильный ключ идемпотентности. Сброс пароля пока не реализован. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). -- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки. +- OpenAPI контракты api/core/, api/ml/ и api/runner/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает два продуктовых обработчика - доставки писем и inbox, а продуктовые сценарии пока не создают их события; см. [Обработчики событий](#обработчики-событий). - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md). @@ -100,22 +100,24 @@ Cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `Same | --- | --- | | api/core/ | Публичный OpenAPI контракт браузер-Go | | api/ml/ | Внутренний OpenAPI контракт Go-ML | +| api/runner/ | Внутренний OpenAPI контракт Go и исполнителя кода | | scripts/ | Общее объединение схем, generated drift и docs-check | | backend/ | Go HTTP service, adapters, bootstrap, SQL и codegen потребителя | | backend/config/ | Общая конфигурация Go вне internal | | frontend/ | Vite SPA, Orval config и generated TypeScript | | ml/ | Python service, lockfile и генератор Pydantic-моделей | +| runner/ | Go-сервис исполнителя кода: nsjail, cgroup v2, judge, ogen-сервер и тесты изоляции | | deploy/ | Compose, Nginx и smoke | | observability/ | Prometheus, Loki, Alloy и provisioning/dashboard JSON | | security/ | Конфигурация сканеров, установка, Make targets и локальные отчеты | | .agents/ | Канонические проектные инструкции и рабочие стандарты | | docs/ru/, docs/en/ | Пользовательские документы на русском и английском | -Папки codegen принадлежат сервисам, которые используют сгенерированный код: backend/codegen/, frontend/codegen/ и ml/codegen/. Go client внутреннего ML API создается из backend/codegen/ogen-ml.yml и потребляется в backend/internal/adapter/secondary/ml/api/. Публичный generated Go handler создается из backend/codegen/ogen.yml и монтируется в chi. sqlc config находится в backend/codegen/sqlc.yml, generated SQL - в backend/internal/adapter/secondary/postgres/sqlc/. Orval читает публичный bundle через frontend/codegen/orval.config.ts. В backend/cmd/app/main.go остаются вызов bootstrap.Run() и обработка ошибки; запуск, сборка зависимостей и lifecycle находятся в backend/internal/bootstrap/app.go. +Папки codegen принадлежат сервисам, которые используют сгенерированный код: backend/codegen/, frontend/codegen/ и ml/codegen/. Go client внутреннего ML API создается из backend/codegen/ogen-ml.yml и потребляется в backend/internal/adapter/secondary/ml/api/. Go client исполнителя кода создается из backend/codegen/ogen-code-runner.yml в backend/internal/adapter/secondary/code_runner/api/. Публичный generated Go handler создается из backend/codegen/ogen.yml и монтируется в chi. sqlc config находится в backend/codegen/sqlc.yml, generated SQL - в backend/internal/adapter/secondary/postgres/sqlc/. Orval читает публичный bundle через frontend/codegen/orval.config.ts. В backend/cmd/app/main.go остаются вызов bootstrap.Run() и обработка ошибки; запуск, сборка зависимостей и lifecycle находятся в backend/internal/bootstrap/app.go. ## Контракты и генерация -Исходные YAML находятся рядом с соответствующим контрактом. Для общей сборки используйте make -C api bundle; он собирает схемы для api/core/ и api/ml/, затем bundles для обоих входов. Публичный и внутренний API не объединяются в одну спецификацию. +Исходные YAML находятся рядом с соответствующим контрактом. Для общей сборки используйте make -C api bundle; он собирает схемы для api/core/, api/ml/ и api/runner/, затем bundles для каждого входа. Публичный и внутренние API не объединяются в одну спецификацию. Корневой make generate подготавливает API bundles один раз, затем запускает потребителей Go, TypeScript и Python. Merged schemas, bundles и generated clients являются отслеживаемыми derived files; меняйте исходники и пересоздавайте их генератором. После контракта перегенерируйте всех потребителей и запустите drift check. Отдельный Make target можно использовать для генерации одной части, если ее вход готов и shared contract owner согласовал его. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 17c5207..eeba231 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -581,6 +581,20 @@ Vitest работает в Node без DOM, поэтому ограничени Тесты не запускают Make-цели против настоящего стека. Ручная проверка на одноразовом проекте: дважды `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` с одинаковыми перечнями, вход подготовленными аккаунтами при выключенной почте, экспресс-прохождение и начало полного теста, затем отказ `demo-reset` после регистрации посетителя. После проверки удалите проект командой `docker compose -p lincodex-demo-check down --volumes` с теми же переменными. Тесты не проверяют содержание синтетического банка или какой-либо грейд, а браузерный маршрут жюри здесь не покрыт. Интеграционным тестам нужен Docker. +## Тесты исполнителя кода + +| Команда | Что проверяет | +| --- | --- | +| make -C runner test | Unit-тесты с race detector: checker, конфигурация, исходы judge на сценарном sandbox, идемпотентность и занятость менеджера прогонов, HTTP API (токен, 202/200/422/503, 400, 413, 404) и отсутствие исходника, входа и токена в логах | +| make -C runner lint | golangci-lint для Linux, включая тесты изоляции | +| make -C runner check-generated | Сгенерированный ogen-сервер совпадает с bundle | +| make -C runner test-sandbox | Тесты изоляции в привилегированном dev-контейнере с настоящими nsjail и cgroup v2 | +| make -C deploy check-runner-dev | Dev-переключатели не попадают в production-файлы | + +`test-sandbox` прогоняет дважды все случаи `runner/testdata/hostile/manifest.json`: верное решение принимается с записанными временем и памятью; синтаксическая ошибка дает `compile_error`; бесконечный цикл останавливает лимит CPU, сон - лимит стены, утечка памяти - лимит памяти cgroup, бесконечный вывод - лимит вывода, fork bomb - лимит процессов (`runtime_error`); пробы сети, файловой системы и привилегий подтверждают, что сети нет, корень и исходник только для чтения, файлы runner не видны, а программа не root. После каждого случая и после серии проверяется, что каталог прогонов пуст, cgroup прогонов удалены и не осталось процессов uid 99999. Тест запускается без отдельного init, поэтому подтверждает, что nsjail забирает каждый остановленный процесс. + +Что тесты не доказывают: изоляцию в production VM (там они еще не запускались), защиту от уязвимостей ядра, nsjail или cgroup, отсутствие побочных каналов и устойчивость под нагрузкой. Полный набор проверок A16 запланирован отдельно и расширит те же fixtures. + ## Будущая программная валидация Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером. diff --git a/runner/.dockerignore b/runner/.dockerignore new file mode 100644 index 0000000..351f16a --- /dev/null +++ b/runner/.dockerignore @@ -0,0 +1,11 @@ +.git +.idea +.vscode +.DS_Store +.env +.env.* +.dev/ +bin/ +coverage.* +**/*.test +**/*.out diff --git a/runner/.gitignore b/runner/.gitignore new file mode 100644 index 0000000..16c2648 --- /dev/null +++ b/runner/.gitignore @@ -0,0 +1,11 @@ +/bin/ +/.dev/ + +# Go build and test output +*.exe +*.test +*.out +*.prof +*.cover +*.pprof +coverage.* diff --git a/runner/.golangci.yml b/runner/.golangci.yml new file mode 100644 index 0000000..5ad7b27 --- /dev/null +++ b/runner/.golangci.yml @@ -0,0 +1,136 @@ +version: "2" + +run: + timeout: 5m + tests: true + # Lint the isolation tests too; they compile only with this tag on Linux. + build-tags: + - sandbox + +linters: + default: standard + enable: + - asasalint + - asciicheck + - bidichk + - bodyclose + - contextcheck + - copyloopvar + - durationcheck + - embeddedstructfieldcheck + - errname + - errorlint + - exhaustive + - exptostd + - fatcontext + - gocheckcompilerdirectives + - gochecknoinits + - gochecksumtype + - gocritic + - gocyclo + - gosec + - goprintffuncname + - inamedparam + - iotamixing + - loggercheck + - makezero + - mirror + - misspell + - musttag + - nakedret + - nilerr + - nilnesserr + - noctx + - nolintlint + - prealloc + - predeclared + - reassign + - revive + - sloglint + - tagalign + - testableexamples + - testifylint + - thelper + - unconvert + - unparam + - wastedassign + - whitespace + + settings: + gocyclo: + min-complexity: 15 + govet: + enable-all: true + disable: + - fieldalignment + - shadow + revive: + rules: + - name: blank-imports + - name: context-as-argument + - name: context-keys-type + - name: error-return + - name: error-strings + - name: error-naming + - name: var-declaration + - name: range + - name: receiver-naming + - name: time-naming + - name: indent-error-flow + - name: errorf + - name: empty-block + - name: superfluous-else + - name: unused-parameter + - name: unreachable-code + - name: redefines-builtin-id + nolintlint: + allow-unused: false + require-explanation: true + require-specific: true + gosec: + excludes: + - G104 + staticcheck: + checks: + - all + testifylint: + enable-all: true + disable: + - go-require + + exclusions: + generated: strict + paths: + - internal/api/ + presets: + - comments + - common-false-positives + rules: + # Error locations use actual Go identifiers, including exported type names. + - linters: + - staticcheck + text: 'ST1005: error strings should not be capitalized' + source: '(fmt\.Errorf|errors\.New)\("[A-Z][A-Za-z0-9]*\.[A-Za-z0-9]+ - ' + - path: _test\.go + linters: + - gocyclo + - gosec + - errcheck + - dupl + - path: _test\.go + text: net/http/httptest\.NewRequest must not be called + linters: + - noctx + +formatters: + enable: + - gofmt + - goimports + exclusions: + generated: strict + paths: + - internal/api/ + +issues: + max-issues-per-linter: 0 + max-same-issues: 0 diff --git a/runner/Dockerfile b/runner/Dockerfile new file mode 100644 index 0000000..ae38304 --- /dev/null +++ b/runner/Dockerfile @@ -0,0 +1,45 @@ +# Production image of the code runner. It runs only on the dedicated runner +# host or VM, never on the core application host; see docs/en/DEPLOY.md. +# +# Base images are build arguments so that a release build can pin each one to +# the digest it resolved; the defaults keep the agreed tags. +ARG GO_IMAGE=golang:1.26.9-alpine +ARG RUNTIME_IMAGE=python:alpine + +FROM ${GO_IMAGE} AS build + +# Never download another Go toolchain: a go.mod that asks for a newer Go +# fails the build instead of silently replacing 1.26.9. +ENV GOTOOLCHAIN=local + +WORKDIR /src/runner +COPY go.mod go.sum ./ +RUN go mod download + +COPY . ./ +RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/lincodex-runner ./cmd/runner + +FROM ${RUNTIME_IMAGE} + +# The runtime is the Python base plus nsjail. Package installers are removed, +# so a jailed program finds no pip, and nothing is installed at run time. +RUN apk upgrade --no-cache \ + && apk add --no-cache nsjail \ + && python -m pip uninstall --yes pip \ + && python -c "import ensurepip, shutil; shutil.rmtree(ensurepip.__path__[0])" \ + && install -d -m 0711 /var/lib/lincodex-runner/work + +# The binary lives outside /usr and /lib, which are the only host paths +# mounted into a jail. +COPY --from=build /out/lincodex-runner /opt/lincodex-runner/lincodex-runner + +# The supervisor needs root on its dedicated host to create namespaces, map +# the sandbox user, and write its delegated cgroup. Jailed programs run as +# uid 99999 without capabilities, with no_new_privs and a seccomp policy. +USER 0:0 +EXPOSE 8443 + +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD ["/opt/lincodex-runner/lincodex-runner", "healthcheck"] + +ENTRYPOINT ["/opt/lincodex-runner/lincodex-runner"] diff --git a/runner/Dockerfile.sandbox-test b/runner/Dockerfile.sandbox-test new file mode 100644 index 0000000..ab147e4 --- /dev/null +++ b/runner/Dockerfile.sandbox-test @@ -0,0 +1,26 @@ +# DEVELOPMENT AND CI ONLY: the isolation test image. It adds the compiled +# isolation tests and the hostile fixtures to a locally built runner image and +# is started by make -C runner test-sandbox with the privileges that nsjail +# needs inside Docker. It is never a release or production image. +ARG GO_IMAGE=golang:1.26.9-alpine +ARG RUNNER_IMAGE=lincodex-runner-dev:local + +FROM ${GO_IMAGE} AS build + +ENV GOTOOLCHAIN=local + +WORKDIR /src/runner +COPY go.mod go.sum ./ +RUN go mod download + +COPY . ./ +RUN CGO_ENABLED=0 GOOS=linux go test -c -tags sandbox -o /out/isolation.test ./internal/isolationtest + +FROM ${RUNNER_IMAGE} + +COPY --from=build /out/isolation.test /opt/lincodex-runner-tests/isolation.test +COPY testdata/hostile /opt/lincodex-runner-tests/testdata/hostile +ENV RUNNER_HOSTILE_FIXTURES=/opt/lincodex-runner-tests/testdata/hostile + +HEALTHCHECK NONE +ENTRYPOINT ["/opt/lincodex-runner-tests/isolation.test", "-test.v", "-test.count=1"] diff --git a/runner/Makefile b/runner/Makefile new file mode 100644 index 0000000..03c845c --- /dev/null +++ b/runner/Makefile @@ -0,0 +1,107 @@ +SHELL := /usr/bin/env bash +.DEFAULT_GOAL := help + +GO ?= go +GO_TOOL := $(GO) tool +DOCKER ?= docker +API_DIR := $(abspath ../api) +API_PREPARED ?= 0 +# The runner and its sandbox are Linux-only, so lint analyzes Linux code. The +# linter binary is built for the host first; GOOS then selects only the +# analyzed packages. +LINT_GOOS ?= linux +GOLANGCI_LINT := bin/golangci-lint +RUNNER_IMAGE ?= lincodex-runner-dev:local +SANDBOX_TEST_IMAGE ?= lincodex-runner-sandbox-test:local +OGEN_ARGS := -config codegen/ogen.yml --package api --clean ../api/runner/openapi.bundle.yml + +##@ Build + +.PHONY: build +build: ## Build the runner binary for Linux + @mkdir -p bin + CGO_ENABLED=0 GOOS=linux $(GO) build -buildvcs=false -trimpath -o bin/lincodex-runner ./cmd/runner + +.PHONY: deps install +deps: ## Download pinned Go module dependencies + $(GO) mod download + +install: deps ## Install module-pinned Go tools without global changes + @$(GO) version + @$(GO_TOOL) ogen --version + @$(GO_TOOL) golangci-lint version + +.PHONY: tidy +tidy: ## Tidy application and tool dependencies + $(GO) mod tidy + +.PHONY: clean +clean: ## Remove local build and test artifacts + rm -rf bin coverage.out + +##@ Code generation + +.PHONY: generate gen +generate gen: ## Generate the ogen server from the code runner contract + @if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi + $(GO_TOOL) ogen --target internal/api $(OGEN_ARGS) + +.PHONY: check-generated +check-generated: ## Check the generated server against the bundled contract without rewriting it + @set -euo pipefail; mkdir -p bin; temporary_dir=$$(mktemp -d "$(CURDIR)/bin/ogen-check.XXXXXX"); trap 'rm -rf "$$temporary_dir"' EXIT; \ + $(GO_TOOL) ogen --target "$$temporary_dir" $(OGEN_ARGS) >/dev/null 2>&1; \ + diff -r internal/api "$$temporary_dir" + +##@ Format, lint, and test + +.PHONY: $(GOLANGCI_LINT) +$(GOLANGCI_LINT): + @mkdir -p bin + $(GO) build -o $(GOLANGCI_LINT) github.com/golangci/golangci-lint/v2/cmd/golangci-lint + +.PHONY: fmt +fmt: $(GOLANGCI_LINT) ## Format Go sources + GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) fmt ./... + +.PHONY: fmt-check +fmt-check: $(GOLANGCI_LINT) ## Check Go formatting without modifying files + @unformatted=$$(gofmt -l $$(find . -name '*.go' -type f -not -path './bin/*')); \ + if [ -n "$$unformatted" ]; then printf '%s\n' "$$unformatted"; exit 1; fi + @formatter_diff=$$(GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) fmt --diff ./...); \ + if [ -n "$$formatter_diff" ]; then printf '%s\n' "$$formatter_diff"; exit 1; fi + +.PHONY: lint +lint: $(GOLANGCI_LINT) ## Run golangci-lint for Linux, including the isolation tests + GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) run ./... + +.PHONY: test +test: ## Run unit tests with the race detector; they need no sandbox + $(GO) test -race -count=1 ./... + +.PHONY: image +image: ## Build the runner image for local development + $(DOCKER) build --file Dockerfile --tag "$(RUNNER_IMAGE)" . + +# DEVELOPMENT ONLY: --privileged gives nsjail namespaces and a writable +# cgroup v2 tree inside the Docker Desktop VM. Production runs the runner on +# its dedicated VM and never uses this target. +.PHONY: test-sandbox +test-sandbox: image ## Run the hostile-program isolation tests in a privileged dev container + $(DOCKER) build --file Dockerfile.sandbox-test --build-arg RUNNER_IMAGE="$(RUNNER_IMAGE)" --tag "$(SANDBOX_TEST_IMAGE)" . + $(DOCKER) run --rm --privileged --cgroupns=private --network=none \ + --tmpfs /var/lib/lincodex-runner/work:size=64m,mode=0711 \ + "$(SANDBOX_TEST_IMAGE)" + +.PHONY: check +check: ## Run formatting, build, unit, generated drift, and lint checks + $(MAKE) --no-print-directory fmt-check + $(MAKE) --no-print-directory build + $(MAKE) --no-print-directory test + $(MAKE) --no-print-directory check-generated + $(MAKE) --no-print-directory lint + +##@ Help + +.PHONY: help +help: ## Show available targets + @awk 'BEGIN{FS=":.*##"; printf "\nUsage:\n make -C runner \n"} /^[a-zA-Z0-9_-]+:.*##/ {printf " %-16s %s\n", $$1, $$2} /^##@/ {printf "\n%s\n", substr($$0, 5)}' $(MAKEFILE_LIST) diff --git a/runner/README.en.md b/runner/README.en.md new file mode 100644 index 0000000..b77b01b --- /dev/null +++ b/runner/README.en.md @@ -0,0 +1,17 @@ +# Code runner + +[Русский](README.md) | English + +A separate Go service that runs untrusted candidate code in nsjail and checks it against public and hidden tests. It currently supports Python 3 and the `exact` and `tokens` checkers. The backend calls it through the internal `api/runner/` contract over TLS with a bearer token; no backend use case calls it yet. + +- `cmd/runner/` is the entry point and the container `healthcheck`. +- `internal/sandbox/` holds nsjail, cgroup v2, seccomp, run directories, and stopping on limits. +- `internal/judge/` holds languages, the syntax check step, and test and group outcomes. +- `internal/checker/` holds the checker interface and the `exact` and `tokens` comparisons. +- `internal/jobs/` keeps runs in memory, makes them idempotent by run ID, and bounds concurrent runs. +- `internal/server/` is the HTTP API on the generated ogen server (`internal/api/`, from `codegen/ogen.yml`). +- `internal/isolationtest/` and `testdata/hostile/` are the isolation tests and the shared hostile programs. + +From the repository root, `make -C runner check` runs formatting, build, unit tests, the generated code check, and lint; `make -C runner test-sandbox` builds the image and runs the isolation tests in a privileged dev container. Local start: `make -C deploy runner-dev-up` (development only). + +Production: the service runs only in the dedicated runner VM, never on the core host. More: [deployment](../docs/en/DEPLOY.md#code-runner), [architecture](../docs/en/ARCHITECTURE.md#code-runner), and [checks](../docs/en/TESTING.md#code-runner-tests). diff --git a/runner/README.md b/runner/README.md new file mode 100644 index 0000000..dd998cd --- /dev/null +++ b/runner/README.md @@ -0,0 +1,17 @@ +# Исполнитель кода + +Русский | [English](README.en.md) + +Отдельный Go-сервис, который запускает недоверенный код кандидата в nsjail и проверяет его на публичных и скрытых тестах. Сейчас поддерживается Python 3; checker `exact` и `tokens`. Backend вызывает его по внутреннему контракту `api/runner/` с TLS и bearer-токеном; ни один usecase backend пока не использует его. + +- `cmd/runner/` - точка входа и `healthcheck` для контейнера. +- `internal/sandbox/` - nsjail, cgroup v2, seccomp, рабочие каталоги и остановка по лимитам. +- `internal/judge/` - языки, шаг проверки синтаксиса, исходы тестов и групп. +- `internal/checker/` - интерфейс checker и сравнения `exact` и `tokens`. +- `internal/jobs/` - прогоны в памяти, идемпотентность по run ID и лимит параллельных прогонов. +- `internal/server/` - HTTP API на сгенерированном ogen-сервере (`internal/api/`, из `codegen/ogen.yml`). +- `internal/isolationtest/` и `testdata/hostile/` - тесты изоляции и общие враждебные программы. + +Из корня: `make -C runner check` запускает форматирование, сборку, unit-тесты, проверку generated-кода и lint; `make -C runner test-sandbox` собирает образ и запускает тесты изоляции в привилегированном dev-контейнере. Локальный запуск: `make -C deploy runner-dev-up` (только для разработки). + +Production: сервис работает только в отдельной VM исполнителя, никогда на core-хосте. Подробнее: [развертывание](../docs/ru/DEPLOY.md#исполнитель-кода), [архитектура](../docs/ru/ARCHITECTURE.md#исполнитель-кода) и [проверки](../docs/ru/TESTING.md#тесты-исполнителя-кода). diff --git a/runner/cmd/runner/main.go b/runner/cmd/runner/main.go new file mode 100644 index 0000000..c921824 --- /dev/null +++ b/runner/cmd/runner/main.go @@ -0,0 +1,19 @@ +// Command runner serves the code runner API. +package main + +import ( + "fmt" + "os" + + "lincodex/runner/internal/app" +) + +func main() { + if len(os.Args) == 2 && os.Args[1] == "healthcheck" { + os.Exit(app.Healthcheck()) + } + if err := app.Run(); err != nil { + fmt.Fprintln(os.Stderr, "runner:", err) + os.Exit(1) + } +} diff --git a/runner/codegen/ogen.yml b/runner/codegen/ogen.yml new file mode 100644 index 0000000..a4dc9b8 --- /dev/null +++ b/runner/codegen/ogen.yml @@ -0,0 +1,5 @@ +generator: + features: + disable: + - paths/client + - webhooks/client diff --git a/runner/go.mod b/runner/go.mod new file mode 100644 index 0000000..b9adb8e --- /dev/null +++ b/runner/go.mod @@ -0,0 +1,243 @@ +module lincodex/runner + +go 1.26.9 + +tool ( + github.com/golangci/golangci-lint/v2/cmd/golangci-lint + github.com/ogen-go/ogen/cmd/ogen +) + +require ( + github.com/go-faster/errors v0.8.0 + github.com/go-faster/jx v1.2.0 + github.com/google/uuid v1.6.0 + github.com/ogen-go/ogen v1.24.0 + go.opentelemetry.io/otel v1.45.0 + go.opentelemetry.io/otel/metric v1.45.0 + go.opentelemetry.io/otel/trace v1.45.0 +) + +require ( + 4d63.com/gocheckcompilerdirectives v1.4.0 // indirect + 4d63.com/gochecknoglobals v0.2.2 // indirect + charm.land/lipgloss/v2 v2.0.6 // indirect + codeberg.org/chavacava/garif v0.2.1 // indirect + codeberg.org/polyfloyd/go-errorlint v1.9.0 // indirect + dev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect + dev.gaijin.team/go/exhaustruct/v5 v5.2.0 // indirect + dev.gaijin.team/go/golib v0.8.1 // indirect + github.com/4meepo/tagalign v1.4.4 // indirect + github.com/Abirdcfly/dupword v0.1.8 // indirect + github.com/AdminBenni/iota-mixing v1.0.0 // indirect + github.com/AlwxSin/noinlineerr v1.0.6 // indirect + github.com/Antonboom/errname v1.1.2 // indirect + github.com/Antonboom/nilnil v1.1.2 // indirect + github.com/Antonboom/testifylint v1.6.4 // indirect + github.com/BurntSushi/toml v1.6.0 // indirect + github.com/ClickHouse/clickhouse-go-linter v1.2.1 // indirect + github.com/Djarvur/go-err113 v0.1.1 // indirect + github.com/Masterminds/semver/v3 v3.5.0 // indirect + github.com/MirrexOne/unqueryvet v1.5.4 // indirect + github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect + github.com/alecthomas/chroma/v2 v2.27.0 // indirect + github.com/alecthomas/go-check-sumtype v0.5.1-0.20260828200218-ae6904d28606 // indirect + github.com/alexkohler/nakedret/v2 v2.0.6 // indirect + github.com/alexkohler/prealloc v1.1.0 // indirect + github.com/alfatraining/structtag v1.0.0 // indirect + github.com/alingse/asasalint v0.0.11 // indirect + github.com/alingse/nilnesserr v0.2.0 // indirect + github.com/ashanbrown/forbidigo/v2 v2.3.1 // indirect + github.com/ashanbrown/makezero/v2 v2.2.1 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/bkielbasa/cyclop v1.2.3 // indirect + github.com/blizzy78/varnamelen v0.8.0 // indirect + github.com/bombsimon/wsl/v4 v4.7.0 // indirect + github.com/bombsimon/wsl/v5 v5.9.0 // indirect + github.com/breml/bidichk v0.3.3 // indirect + github.com/breml/errchkjson v0.4.1 // indirect + github.com/butuzov/ireturn v0.4.1 // indirect + github.com/butuzov/mirror v1.3.3 // indirect + github.com/catenacyber/perfsprint v0.10.1 // indirect + github.com/ccojocar/zxcvbn-go v1.0.4 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/charithe/durationcheck v0.0.11 // indirect + github.com/charmbracelet/colorprofile v0.4.3 // indirect + github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect + github.com/charmbracelet/x/ansi v0.11.8 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/charmbracelet/x/termios v0.1.1 // indirect + github.com/charmbracelet/x/windows v0.2.2 // indirect + github.com/ckaznocha/intrange v0.3.1 // indirect + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/curioswitch/go-reassign v0.3.0 // indirect + github.com/daixiang0/gci v0.13.7 // indirect + github.com/dave/dst v0.27.3 // indirect + github.com/denis-tingaikin/go-header v0.5.0 // indirect + github.com/dlclark/regexp2 v1.12.0 // indirect + github.com/dlclark/regexp2/v2 v2.2.1 // indirect + github.com/ettle/strcase v0.2.0 // indirect + github.com/fatih/color v1.19.0 // indirect + github.com/fatih/structtag v1.2.0 // indirect + github.com/firefart/nonamedreturns v1.0.8 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/fzipp/gocyclo v0.6.0 // indirect + github.com/ghodss/yaml v1.0.0 // indirect + github.com/ghostiam/protogetter v1.0.1 // indirect + github.com/go-critic/go-critic v0.15.0 // indirect + github.com/go-faster/yaml v0.4.6 // indirect + github.com/go-logr/logr v1.4.4 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-toolsmith/astcast v1.1.0 // indirect + github.com/go-toolsmith/astcopy v1.1.0 // indirect + github.com/go-toolsmith/astequal v1.2.0 // indirect + github.com/go-toolsmith/astfmt v1.1.0 // indirect + github.com/go-toolsmith/astp v1.1.0 // indirect + github.com/go-toolsmith/strparse v1.1.0 // indirect + github.com/go-toolsmith/typep v1.1.0 // indirect + github.com/go-viper/mapstructure/v2 v2.5.0 // indirect + github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect + github.com/gobwas/glob v0.2.3 // indirect + github.com/godoc-lint/godoc-lint v0.11.4 // indirect + github.com/gofrs/flock v0.13.1 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/golangci/asciicheck v0.5.0 // indirect + github.com/golangci/canonicalheader v0.0.0-20260827115959-a25c71c521f6 // indirect + github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202 // indirect + github.com/golangci/go-printf-func-name v0.1.1 // indirect + github.com/golangci/gofmt v0.0.0-20260820135601-e84e05053792 // indirect + github.com/golangci/golangci-lint/v2 v2.14.0 // indirect + github.com/golangci/golines v0.15.0 // indirect + github.com/golangci/misspell v0.8.0 // indirect + github.com/golangci/plugin-module-register v0.1.2 // indirect + github.com/golangci/revgrep v0.8.0 // indirect + github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba // indirect + github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect + github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/gordonklaus/ineffassign v0.2.0 // indirect + github.com/gostaticanalysis/analysisutil v0.7.1 // indirect + github.com/gostaticanalysis/comment v1.5.0 // indirect + github.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect + github.com/gostaticanalysis/nilerr v0.1.2 // indirect + github.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect + github.com/hashicorp/go-version v1.9.0 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/hexops/gotextdiff v1.0.3 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/jgautheron/goconst v1.11.0 // indirect + github.com/jjti/go-spancheck v0.6.5 // indirect + github.com/julz/importas v0.2.0 // indirect + github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect + github.com/kisielk/errcheck v1.20.0 // indirect + github.com/kkHAIKE/contextcheck v1.1.6 // indirect + github.com/kulti/thelper v0.7.1 // indirect + github.com/kunwardeep/paralleltest v1.0.15 // indirect + github.com/ldez/exptostd v0.4.5 // indirect + github.com/ldez/gomoddirectives v0.10.0 // indirect + github.com/ldez/grignotin v0.10.1 // indirect + github.com/ldez/structtags v0.6.1 // indirect + github.com/ldez/tagliatelle v0.8.0 // indirect + github.com/ldez/usetesting v0.5.0 // indirect + github.com/leonklingele/grouper v1.1.2 // indirect + github.com/lucasb-eyer/go-colorful v1.4.1 // indirect + github.com/macabu/inamedparam v0.2.0 // indirect + github.com/magiconair/properties v1.8.6 // indirect + github.com/manuelarte/embeddedstructfieldcheck v0.4.0 // indirect + github.com/manuelarte/funcorder v0.6.0 // indirect + github.com/maratori/testableexamples v1.0.1 // indirect + github.com/maratori/testpackage v1.1.2 // indirect + github.com/matoous/godox v1.1.0 // indirect + github.com/mattn/go-colorable v0.1.15 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/mattn/go-runewidth v0.0.24 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/mgechev/revive v1.17.0 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/moricho/tparallel v0.3.2 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/nakabonne/nestif v0.3.1 // indirect + github.com/nishanths/exhaustive v0.13.0 // indirect + github.com/nishanths/predeclared v0.2.2 // indirect + github.com/nunnatsa/ginkgolinter v0.24.0 // indirect + github.com/pelletier/go-toml v1.9.5 // indirect + github.com/pelletier/go-toml/v2 v2.4.3 // indirect + github.com/prometheus/client_golang v1.12.1 // indirect + github.com/prometheus/client_model v0.2.0 // indirect + github.com/prometheus/common v0.32.1 // indirect + github.com/prometheus/procfs v0.7.3 // indirect + github.com/quasilyte/go-ruleguard v0.4.5 // indirect + github.com/quasilyte/go-ruleguard/dsl v0.3.23 // indirect + github.com/quasilyte/gogrep v0.5.0 // indirect + github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect + github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect + github.com/raeperd/recvcheck v0.3.1 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/rogpeppe/go-internal v1.16.0 // indirect + github.com/ryancurrah/gomodguard v1.4.1 // indirect + github.com/ryancurrah/gomodguard/v2 v2.1.3 // indirect + github.com/ryanrolds/sqlclosecheck v0.6.0 // indirect + github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect + github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect + github.com/sashamelentyev/interfacebloat v1.1.0 // indirect + github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect + github.com/securego/gosec/v2 v2.29.0 // indirect + github.com/segmentio/asm v1.2.1 // indirect + github.com/shopspring/decimal v1.4.0 // indirect + github.com/sirupsen/logrus v1.10.2 // indirect + github.com/sivchari/containedctx v1.0.3 // indirect + github.com/sonatard/noctx v0.5.1 // indirect + github.com/sourcegraph/go-diff v0.9.0 // indirect + github.com/spf13/afero v1.15.0 // indirect + github.com/spf13/cast v1.5.0 // indirect + github.com/spf13/cobra v1.10.2 // indirect + github.com/spf13/jwalterweatherman v1.1.0 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/spf13/viper v1.12.0 // indirect + github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect + github.com/stbenjam/no-sprintf-host-port v0.3.1 // indirect + github.com/stretchr/objx v0.5.3 // indirect + github.com/stretchr/testify v1.12.1 // indirect + github.com/subosito/gotenv v1.4.1 // indirect + github.com/tetafro/godot v1.5.6 // indirect + github.com/timakin/bodyclose v0.0.0-20260723120731-857993a2939c // indirect + github.com/timonwong/loggercheck v0.12.0 // indirect + github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect + github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect + github.com/ultraware/funlen v0.2.0 // indirect + github.com/ultraware/whitespace v0.2.0 // indirect + github.com/uudashr/gocognit v1.2.1 // indirect + github.com/uudashr/iface v1.5.1 // indirect + github.com/xen0n/gosmopolitan v1.3.0 // indirect + github.com/xo/terminfo v1.0.0 // indirect + github.com/yagipy/maintidx v1.0.0 // indirect + github.com/yeya24/promlinter v0.3.0 // indirect + github.com/ykadowak/zerologlint v0.1.5 // indirect + github.com/yuin/goldmark v1.8.2 // indirect + gitlab.com/bosi/decorder v0.4.2 // indirect + go-simpler.org/musttag v0.14.0 // indirect + go-simpler.org/sloglint v0.12.0 // indirect + go.augendre.info/arangolint v0.4.0 // indirect + go.augendre.info/fatcontext v0.10.1 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.28.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect + golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect + golang.org/x/mod v0.41.0 // indirect + golang.org/x/net v0.59.0 // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect + golang.org/x/tools v0.50.0 // indirect + google.golang.org/protobuf v1.36.12 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + honnef.co/go/tools v0.8.1 // indirect + mvdan.cc/gofumpt v0.12.0 // indirect + mvdan.cc/unparam v0.0.0-20260823230713-2fa3d841b0c8 // indirect +) diff --git a/runner/go.sum b/runner/go.sum new file mode 100644 index 0000000..c351a14 --- /dev/null +++ b/runner/go.sum @@ -0,0 +1,1007 @@ +4d63.com/gocheckcompilerdirectives v1.4.0 h1:ZLq62rbGWVmQhiZ8kuNVIT/M09xCSTdJz9K3xOdT/CY= +4d63.com/gocheckcompilerdirectives v1.4.0/go.mod h1:9ZOAiMOjqC/nRwci2fcUXVHUNLG/cH6r6rhUh+jTFtQ= +4d63.com/gochecknoglobals v0.2.2 h1:H1vdnwnMaZdQW/N+NrkT1SZMTBmcwHe9Vq8lJcYYTtU= +4d63.com/gochecknoglobals v0.2.2/go.mod h1:lLxwTQjL5eIesRbvnzIP3jZtG140FnTdz+AlMa+ogt0= +charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ= +charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +codeberg.org/chavacava/garif v0.2.1 h1:K9oYxSlvlXrHXyW26Z4q61bTpJDo1wbvXcYKar/F/LM= +codeberg.org/chavacava/garif v0.2.1/go.mod h1:oHnDSmc0f9K1MeE+MQD/yjkiIB5Xsn5y3S9Dg96Xk84= +codeberg.org/polyfloyd/go-errorlint v1.9.0 h1:VkdEEmA1VBpH6ecQoMR4LdphVI3fA4RrCh2an7YmodI= +codeberg.org/polyfloyd/go-errorlint v1.9.0/go.mod h1:GPRRu2LzVijNn4YkrZYJfatQIdS+TrcK8rL5Xs24qw8= +dev.gaijin.team/go/exhaustruct/v4 v4.0.0 h1:873r7aNneqoBB3IaFIzhvt2RFYTuHgmMjoKfwODoI1Y= +dev.gaijin.team/go/exhaustruct/v4 v4.0.0/go.mod h1:aZ/k2o4Y05aMJtiux15x8iXaumE88YdiB0Ai4fXOzPI= +dev.gaijin.team/go/exhaustruct/v5 v5.2.0 h1:HZB49Fshn8qHJCi9VzYtrcnR1jbLteRHXfnQz8Adams= +dev.gaijin.team/go/exhaustruct/v5 v5.2.0/go.mod h1:5IshpqhgGdKIrF8lBmi3M6YKmI7T3hMzAL9nrflko88= +dev.gaijin.team/go/golib v0.8.1 h1:JYju4x9BSo+QD/AYeHULVDcvEhiFg8wOi6pT0IaZF5E= +dev.gaijin.team/go/golib v0.8.1/go.mod h1:c5fu7t1RSGMxSQgcUYO1sODbzsYnOCXJLmHeNG1Eb+0= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/4meepo/tagalign v1.4.4 h1:052JDGj2pBORc6NkD30dDXpsUpoYszDeUwr9/5YZuVA= +github.com/4meepo/tagalign v1.4.4/go.mod h1:00WwRjiuSbrRJnSVeGWPLp2epS5Q/l4UEy0apLLS37c= +github.com/Abirdcfly/dupword v0.1.8 h1:SrhcUuGsROBuChFxHALRYzyyPODWn9zwghmzPvD9Cd8= +github.com/Abirdcfly/dupword v0.1.8/go.mod h1:XZrhVnI7YGpsTiWZANSQaBJ4QpL/Tq5vIEdKJJAs9WI= +github.com/AdminBenni/iota-mixing v1.0.0 h1:Os6lpjG2dp/AE5fYBPAA1zfa2qMdCAWwPMCgpwKq7wo= +github.com/AdminBenni/iota-mixing v1.0.0/go.mod h1:i4+tpAaB+qMVIV9OK3m4/DAynOd5bQFaOu+2AhtBCNY= +github.com/AlwxSin/noinlineerr v1.0.6 h1:KAvuxunTe9QxvqrFB7nZTdb/7Wzas4AvifslTnG0Ld8= +github.com/AlwxSin/noinlineerr v1.0.6/go.mod h1:+QgkkoYrMH7RHvcdxdlI7vYYEdgeoFOVjU9sUhw/rQc= +github.com/Antonboom/errname v1.1.2 h1:dxwONZJua3VB8Xh/VaCjqAcqF645sWWv7xj26zy7tdQ= +github.com/Antonboom/errname v1.1.2/go.mod h1:YeZIpgLMxT+SNkruGgYkLhzq/9vs3fsolTZegKaKDZI= +github.com/Antonboom/nilnil v1.1.2 h1:aNlFuJhaEseXe4fHO3xbjXlSeEiQVYa2lEkWD2s2hAY= +github.com/Antonboom/nilnil v1.1.2/go.mod h1:0ynwvphOLmAuMwTNDyBnDZmSwZoDpcFXmUHmzoHH2WA= +github.com/Antonboom/testifylint v1.6.4 h1:gs9fUEy+egzxkEbq9P4cpcMB6/G0DYdMeiFS87UiqmQ= +github.com/Antonboom/testifylint v1.6.4/go.mod h1:YO33FROXX2OoUfwjz8g+gUxQXio5i9qpVy7nXGbxDD4= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/ClickHouse/clickhouse-go-linter v1.2.1 h1:zGEKIyd5YL08ieWG/LOUmlau2DxbxPVOfAeo+4Jz3ck= +github.com/ClickHouse/clickhouse-go-linter v1.2.1/go.mod h1:pLorS7ffPTfuUV9M0SJgfHA/h/WQPQUk2FWG9x74cQ4= +github.com/Djarvur/go-err113 v0.1.1 h1:eHfopDqXRwAi+YmCUas75ZE0+hoBHJ2GQNLYRSxao4g= +github.com/Djarvur/go-err113 v0.1.1/go.mod h1:IaWJdYFLg76t2ihfflPZnM1LIQszWOsFDh2hhhAVF6k= +github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= +github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/MirrexOne/unqueryvet v1.5.4 h1:38QOxShO7JmMWT+eCdDMbcUgGCOeJphVkzzRgyLJgsQ= +github.com/MirrexOne/unqueryvet v1.5.4/go.mod h1:fs9Zq6eh1LRIhsDIsxf9PONVUjYdFHdtkHIgZdJnyPU= +github.com/OpenPeeDeeP/depguard/v2 v2.2.1 h1:vckeWVESWp6Qog7UZSARNqfu/cZqvki8zsuj3piCMx4= +github.com/OpenPeeDeeP/depguard/v2 v2.2.1/go.mod h1:q4DKzC4UcVaAvcfd41CZh0PWpGgzrVxUYBlgKNGquUo= +github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= +github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= +github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs= +github.com/alecthomas/chroma/v2 v2.27.0/go.mod h1:NjJ3ciIgrqBNeIkWZ4e46nseoLDslxU1LmfCoL+wcY8= +github.com/alecthomas/go-check-sumtype v0.5.1-0.20260828200218-ae6904d28606 h1:dXPJ+uOJLWb8rjlAuLX7JPiRJtZKw/53Ol+WxdDJ1Eo= +github.com/alecthomas/go-check-sumtype v0.5.1-0.20260828200218-ae6904d28606/go.mod h1:ZH31IJyNpxpStxP2ayCcPQz+3T2G/OnxIQqe4LWvSDw= +github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs= +github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/alexkohler/nakedret/v2 v2.0.6 h1:ME3Qef1/KIKr3kWX3nti3hhgNxw6aqN5pZmQiFSsuzQ= +github.com/alexkohler/nakedret/v2 v2.0.6/go.mod h1:l3RKju/IzOMQHmsEvXwkqMDzHHvurNQfAgE1eVmT40Q= +github.com/alexkohler/prealloc v1.1.0 h1:cKGRBqlXw5iyQGLYhrXrDlcHxugXpTq4tQ5c91wkf8M= +github.com/alexkohler/prealloc v1.1.0/go.mod h1:fT39Jge3bQrfA7nPMDngUfvUbQGQeJyGQnR+913SCig= +github.com/alfatraining/structtag v1.0.0 h1:2qmcUqNcCoyVJ0up879K614L9PazjBSFruTB0GOFjCc= +github.com/alfatraining/structtag v1.0.0/go.mod h1:p3Xi5SwzTi+Ryj64DqjLWz7XurHxbGsq6y3ubePJPus= +github.com/alingse/asasalint v0.0.11 h1:SFwnQXJ49Kx/1GghOFz1XGqHYKp21Kq1nHad/0WQRnw= +github.com/alingse/asasalint v0.0.11/go.mod h1:nCaoMhw7a9kSJObvQyVzNTPBDbNpdocqrSP7t/cW5+I= +github.com/alingse/nilnesserr v0.2.0 h1:raLem5KG7EFVb4UIDAXgrv3N2JIaffeKNtcEXkEWd/w= +github.com/alingse/nilnesserr v0.2.0/go.mod h1:1xJPrXonEtX7wyTq8Dytns5P2hNzoWymVUIaKm4HNFg= +github.com/ashanbrown/forbidigo/v2 v2.3.1 h1:KAZijvQ7zeIBKbhikT4jCm0TLYXC4u78bTiLh/8JROI= +github.com/ashanbrown/forbidigo/v2 v2.3.1/go.mod h1:2QDkLTzU6TV937eFROamXrW92M3paehdae4HCDCOZCM= +github.com/ashanbrown/makezero/v2 v2.2.1 h1:A7uU8dgB1PA9aelTxHMfHIQ8Qev8AB3JLxJUBUsejqM= +github.com/ashanbrown/makezero/v2 v2.2.1/go.mod h1:aEGT/9q3S8DHeE57C88z2a6xydvgx8J5hgXIGWgo0MY= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bkielbasa/cyclop v1.2.3 h1:faIVMIGDIANuGPWH031CZJTi2ymOQBULs9H21HSMa5w= +github.com/bkielbasa/cyclop v1.2.3/go.mod h1:kHTwA9Q0uZqOADdupvcFJQtp/ksSnytRMe8ztxG8Fuo= +github.com/blizzy78/varnamelen v0.8.0 h1:oqSblyuQvFsW1hbBHh1zfwrKe3kcSj0rnXkKzsQ089M= +github.com/blizzy78/varnamelen v0.8.0/go.mod h1:V9TzQZ4fLJ1DSrjVDfl89H7aMnTvKkApdHeyESmyR7k= +github.com/bombsimon/wsl/v4 v4.7.0 h1:1Ilm9JBPRczjyUs6hvOPKvd7VL1Q++PL8M0SXBDf+jQ= +github.com/bombsimon/wsl/v4 v4.7.0/go.mod h1:uV/+6BkffuzSAVYD+yGyld1AChO7/EuLrCF/8xTiapg= +github.com/bombsimon/wsl/v5 v5.9.0 h1:WCrgZ7RQnZO5oEwbVTlYgBdU3wL294kR1BSWV8vTfsU= +github.com/bombsimon/wsl/v5 v5.9.0/go.mod h1:kjo4HiAV5FDkHC8/uzJq9mBffEEd6WT/nvN7DoMovDM= +github.com/breml/bidichk v0.3.3 h1:WSM67ztRusf1sMoqH6/c4OBCUlRVTKq+CbSeo0R17sE= +github.com/breml/bidichk v0.3.3/go.mod h1:ISbsut8OnjB367j5NseXEGGgO/th206dVa427kR8YTE= +github.com/breml/errchkjson v0.4.1 h1:keFSS8D7A2T0haP9kzZTi7o26r7kE3vymjZNeNDRDwg= +github.com/breml/errchkjson v0.4.1/go.mod h1:a23OvR6Qvcl7DG/Z4o0el6BRAjKnaReoPQFciAl9U3s= +github.com/butuzov/ireturn v0.4.1 h1:vWb3NO4t77iku/sjCQ/2pHTQeOmxEhjIriJqRLg1Y+I= +github.com/butuzov/ireturn v0.4.1/go.mod h1:q+DXKzTDV5guNuXLnIab9fKXizTn2miZHLhxH7V/GB4= +github.com/butuzov/mirror v1.3.3 h1:v0RsWBhfFc1RQqE/f3sHpSttKDtodFn0gFmtYyD4/hA= +github.com/butuzov/mirror v1.3.3/go.mod h1:h9BzzwYnTiHO0GzgvaTqIg7VSsOUhdIv51cHFFBmX1w= +github.com/catenacyber/perfsprint v0.10.1 h1:u7Riei30bk46XsG8nknMhKLXG9BcXz3+3tl/WpKm0PQ= +github.com/catenacyber/perfsprint v0.10.1/go.mod h1:DJTGsi/Zufpuus6XPGJyKOTMELe347o6akPvWG9Zcsc= +github.com/ccojocar/zxcvbn-go v1.0.4 h1:FWnCIRMXPj43ukfX000kvBZvV6raSxakYr1nzyNrUcc= +github.com/ccojocar/zxcvbn-go v1.0.4/go.mod h1:3GxGX+rHmueTUMvm5ium7irpyjmm7ikxYFOSJB21Das= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/charithe/durationcheck v0.0.11 h1:g1/EX1eIiKS57NTWsYtHDZ/APfeXKhye1DidBcABctk= +github.com/charithe/durationcheck v0.0.11/go.mod h1:x5iZaixRNl8ctbM+3B2RrPG5t856TxRyVQEnbIEM2X4= +github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= +github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA= +github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro= +github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ= +github.com/charmbracelet/x/ansi v0.11.8/go.mod h1:ZNN+3mXny/516oTQPLMPIBeSINvNJJQ8uQXDgbeJxY0= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= +github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= +github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM= +github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/ckaznocha/intrange v0.3.1 h1:j1onQyXvHUsPWujDH6WIjhyH26gkRt/txNlV7LspvJs= +github.com/ckaznocha/intrange v0.3.1/go.mod h1:QVepyz1AkUoFQkpEqksSYpNpUo3c5W7nWh/s6SHIJJk= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/curioswitch/go-reassign v0.3.0 h1:dh3kpQHuADL3cobV/sSGETA8DOv457dwl+fbBAhrQPs= +github.com/curioswitch/go-reassign v0.3.0/go.mod h1:nApPCCTtqLJN/s8HfItCcKV0jIPwluBOvZP+dsJGA88= +github.com/daixiang0/gci v0.13.7 h1:+0bG5eK9vlI08J+J/NWGbWPTNiXPG4WhNLJOkSxWITQ= +github.com/daixiang0/gci v0.13.7/go.mod h1:812WVN6JLFY9S6Tv76twqmNqevN0pa3SX3nih0brVzQ= +github.com/dave/dst v0.27.3 h1:P1HPoMza3cMEquVf9kKy8yXsFirry4zEnWOdYPOoIzY= +github.com/dave/dst v0.27.3/go.mod h1:jHh6EOibnHgcUW3WjKHisiooEkYwqpHLBSX1iOBhEyc= +github.com/dave/jennifer v1.7.1 h1:B4jJJDHelWcDhlRQxWeo0Npa/pYKBLrirAQoTN45txo= +github.com/dave/jennifer v1.7.1/go.mod h1:nXbxhEmQfOZhWml3D1cDK5M1FLnMSozpbFN/m3RmGZc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denis-tingaikin/go-header v0.5.0 h1:SRdnP5ZKvcO9KKRP1KJrhFR3RrlGuD+42t4429eC9k8= +github.com/denis-tingaikin/go-header v0.5.0/go.mod h1:mMenU5bWrok6Wl2UsZjy+1okegmwQ3UgWl4V1D8gjlY= +github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8= +github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2/v2 v2.2.1 h1:mf4KkFUj0gJuarK8P+LgiS+Lit7m9N1yAwEfPbee7R0= +github.com/dlclark/regexp2/v2 v2.2.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q= +github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A= +github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= +github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= +github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4= +github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94= +github.com/firefart/nonamedreturns v1.0.8 h1:iB32Dl17zJl1zlVEj/WlUWgx0HiRyQ85OUw1WHa4/II= +github.com/firefart/nonamedreturns v1.0.8/go.mod h1:vxFNvm5AfP/8rgAKFzYmnqx0yp1HjrYsErZ9pHPTznA= +github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= +github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo= +github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/ghostiam/protogetter v1.0.1 h1:q4LLTx2KJHJpxrfO3BniUDWoFkoqWD/UlHhClBlUlLM= +github.com/ghostiam/protogetter v1.0.1/go.mod h1:50Fh5yZfs6SFGrd1FlmT04NcguyEOxyjNK5zGD6/EvM= +github.com/go-critic/go-critic v0.15.0 h1:MDUZIQKytIl+vPEc0Igw51m4uLTdi1ZGz2jatEqNs1g= +github.com/go-critic/go-critic v0.15.0/go.mod h1:3BPrw8nHATGm3o2n37cssOmJzpySGKCdY8JWkCzxgKQ= +github.com/go-faster/errors v0.8.0 h1:9T9eJrM+72dFk7n4DfhuaDDe6cyuFCSW2oNUkN77Yqc= +github.com/go-faster/errors v0.8.0/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo= +github.com/go-faster/jx v1.2.0 h1:T2YHJPrFaYu21fJtUxC9GzmluKu8rVIFDwwGBKTDseI= +github.com/go-faster/jx v1.2.0/go.mod h1:UWLOVDmMG597a5tBFPLIWJdUxz5/2emOpfsj9Neg0PE= +github.com/go-faster/yaml v0.4.6 h1:lOK/EhI04gCpPgPhgt0bChS6bvw7G3WwI8xxVe0sw9I= +github.com/go-faster/yaml v0.4.6/go.mod h1:390dRIvV4zbnO7qC9FGo6YYutc+wyyUSHBgbXL52eXk= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474= +github.com/go-quicktest/qt v1.102.0/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/go-toolsmith/astcast v1.1.0 h1:+JN9xZV1A+Re+95pgnMgDboWNVnIMMQXwfBwLRPgSC8= +github.com/go-toolsmith/astcast v1.1.0/go.mod h1:qdcuFWeGGS2xX5bLM/c3U9lewg7+Zu4mr+xPwZIB4ZU= +github.com/go-toolsmith/astcopy v1.1.0 h1:YGwBN0WM+ekI/6SS6+52zLDEf8Yvp3n2seZITCUBt5s= +github.com/go-toolsmith/astcopy v1.1.0/go.mod h1:hXM6gan18VA1T/daUEHCFcYiW8Ai1tIwIzHY6srfEAw= +github.com/go-toolsmith/astequal v1.0.3/go.mod h1:9Ai4UglvtR+4up+bAD4+hCj7iTo4m/OXVTSLnCyTAx4= +github.com/go-toolsmith/astequal v1.1.0/go.mod h1:sedf7VIdCL22LD8qIvv7Nn9MuWJruQA/ysswh64lffQ= +github.com/go-toolsmith/astequal v1.2.0 h1:3Fs3CYZ1k9Vo4FzFhwwewC3CHISHDnVUPC4x0bI2+Cw= +github.com/go-toolsmith/astequal v1.2.0/go.mod h1:c8NZ3+kSFtFY/8lPso4v8LuJjdJiUFVnSuU3s0qrrDY= +github.com/go-toolsmith/astfmt v1.1.0 h1:iJVPDPp6/7AaeLJEruMsBUlOYCmvg0MoCfJprsOmcco= +github.com/go-toolsmith/astfmt v1.1.0/go.mod h1:OrcLlRwu0CuiIBp/8b5PYF9ktGVZUjlNMV634mhwuQ4= +github.com/go-toolsmith/astp v1.1.0 h1:dXPuCl6u2llURjdPLLDxJeZInAeZ0/eZwFJmqZMnpQA= +github.com/go-toolsmith/astp v1.1.0/go.mod h1:0T1xFGz9hicKs8Z5MfAqSUitoUYS30pDMsRVIDHs8CA= +github.com/go-toolsmith/pkgload v1.2.2 h1:0CtmHq/02QhxcF7E9N5LIFcYFsMR5rdovfqTtRKkgIk= +github.com/go-toolsmith/pkgload v1.2.2/go.mod h1:R2hxLNRKuAsiXCo2i5J6ZQPhnPMOVtU+f0arbFPWCus= +github.com/go-toolsmith/strparse v1.0.0/go.mod h1:YI2nUKP9YGZnL/L1/DLFBfixrcjslWct4wyljWhSRy8= +github.com/go-toolsmith/strparse v1.1.0 h1:GAioeZUK9TGxnLS+qfdqNbA4z0SSm5zVNtCQiyP2Bvw= +github.com/go-toolsmith/strparse v1.1.0/go.mod h1:7ksGy58fsaQkGQlY8WVoBFNyEPMGuJin1rfoPS4lBSQ= +github.com/go-toolsmith/typep v1.1.0 h1:fIRYDyF+JywLfqzyhdiHzRop/GQDxxNhLGQ6gFUNHus= +github.com/go-toolsmith/typep v1.1.0/go.mod h1:fVIw+7zjdsMxDA3ITWnH1yOiw1rnTQKCsF/sk2H/qig= +github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= +github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/go-xmlfmt/xmlfmt v1.1.3 h1:t8Ey3Uy7jDSEisW2K3somuMKIpzktkWptA0iFCnRUWY= +github.com/go-xmlfmt/xmlfmt v1.1.3/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM= +github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= +github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= +github.com/godoc-lint/godoc-lint v0.11.4 h1:N9zUYVJ/OkznBbrBsU/zODvua64EUplMBLQWStO3+1M= +github.com/godoc-lint/godoc-lint v0.11.4/go.mod h1:7usTXoxS0QYIi5usTSCPwR0w/6xLjcz450shXjLn3t4= +github.com/gofrs/flock v0.13.1 h1:jjREztyBeSKBZYAC+mgc1laB+xsgy4kYMf3FbKF2UBo= +github.com/gofrs/flock v0.13.1/go.mod h1:sf4BFiHwnvgxa25DlQoDqXQnwRMEOwqxRq37P6MzzmE= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golangci/asciicheck v0.5.0 h1:jczN/BorERZwK8oiFBOGvlGPknhvq0bjnysTj4nUfo0= +github.com/golangci/asciicheck v0.5.0/go.mod h1:5RMNAInbNFw2krqN6ibBxN/zfRFa9S6tA1nPdM0l8qQ= +github.com/golangci/canonicalheader v0.0.0-20260827115959-a25c71c521f6 h1:fVLolA3dG6s0brGetsiDAtcnpMSwVa2LqXJEw/9RJG4= +github.com/golangci/canonicalheader v0.0.0-20260827115959-a25c71c521f6/go.mod h1:1xo+NFW5S+bEf2DKXhaxuzvcDN5AR6o/KMwvqC5Mkpo= +github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202 h1:CbTB8KpqnViI6lIXxp03Oclc4VFHi3K4BWC1TacsZ+A= +github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202/go.mod h1:NUw9Zr2Sy7+HxzdjIULge71wI6yEg1lWQr7Evcu8K0E= +github.com/golangci/go-printf-func-name v0.1.1 h1:hIYTFJqAGp1iwoIfsNTpoq1xZAarogrvjO9AfiW3B4U= +github.com/golangci/go-printf-func-name v0.1.1/go.mod h1:Es64MpWEZbh0UBtTAICOZiB+miW53w/K9Or/4QogJss= +github.com/golangci/gofmt v0.0.0-20260820135601-e84e05053792 h1:WL8YKrt3UbOBqSRU7GpP5BTtQTMWtVtj+mfPijgZeIg= +github.com/golangci/gofmt v0.0.0-20260820135601-e84e05053792/go.mod h1:te5hX0dW4C5r6YbXs+6ysNr8Q5UTmdIqGbb+mlFiYmA= +github.com/golangci/golangci-lint/v2 v2.14.0 h1:ot8QffRa4LzAAEgtvNYrVs9esxQ7xoTwoAv6uhp4ngA= +github.com/golangci/golangci-lint/v2 v2.14.0/go.mod h1:amHimCzNDP1GfVno3hIiNssjvqXmuW+CPZAHOdR4cIc= +github.com/golangci/golines v0.15.0 h1:Qnph25g8Y1c5fdo1X7GaRDGgnMHgnxh4Gk4VfPTtRx0= +github.com/golangci/golines v0.15.0/go.mod h1:AZjXd23tbHMpowhtnGlj9KCNsysj72aeZVVHnVcZx10= +github.com/golangci/misspell v0.8.0 h1:qvxQhiE2/5z+BVRo1kwYA8yGz+lOlu5Jfvtx2b04Jbg= +github.com/golangci/misspell v0.8.0/go.mod h1:WZyyI2P3hxPY2UVHs3cS8YcllAeyfquQcKfdeE9AFVg= +github.com/golangci/plugin-module-register v0.1.2 h1:e5WM6PO6NIAEcij3B053CohVp3HIYbzSuP53UAYgOpg= +github.com/golangci/plugin-module-register v0.1.2/go.mod h1:1+QGTsKBvAIvPvoY/os+G5eoqxWn70HYDm2uvUyGuVw= +github.com/golangci/revgrep v0.8.0 h1:EZBctwbVd0aMeRnNUsFogoyayvKHyxlV3CdUA46FX2s= +github.com/golangci/revgrep v0.8.0/go.mod h1:U4R/s9dlXZsg8uJmaR1GrloUr14D7qDl8gi2iPXJH8k= +github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba h1:lqtcnSMDuuJdu/LrKWi5RJzpSNLOJXYe/nzQutTI5kg= +github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba/go.mod h1:sCBNcpRmhJCtbFGz49+IM3ETTFf7QdJ30AeYCd43NKk= +github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e h1:ai0EfmVYE2bRA5htgAG9r7s3tHsfjIhN98WshBTJ9jM= +github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e/go.mod h1:Vrn4B5oR9qRwM+f54koyeH3yzphlecwERs0el27Fr/s= +github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e h1:gD6P7NEo7Eqtt0ssnqSJNNndxe69DOQ24A5h7+i3KpM= +github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e/go.mod h1:h+wZwLjUTJnm/P2rwlbJdRPZXOzaT36/FwnPnY2inzc= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/gordonklaus/ineffassign v0.2.0 h1:Uths4KnmwxNJNzq87fwQQDDnbNb7De00VOk9Nu0TySs= +github.com/gordonklaus/ineffassign v0.2.0/go.mod h1:TIpymnagPSexySzs7F9FnO1XFTy8IT3a59vmZp5Y9Lw= +github.com/gostaticanalysis/analysisutil v0.7.1 h1:ZMCjoue3DtDWQ5WyU16YbjbQEQ3VuzwxALrpYd+HeKk= +github.com/gostaticanalysis/analysisutil v0.7.1/go.mod h1:v21E3hY37WKMGSnbsw2S/ojApNWb6C1//mXO48CXbVc= +github.com/gostaticanalysis/comment v1.4.2/go.mod h1:KLUTGDv6HOCotCH8h2erHKmpci2ZoR8VPu34YA2uzdM= +github.com/gostaticanalysis/comment v1.5.0 h1:X82FLl+TswsUMpMh17srGRuKaaXprTaytmEpgnKIDu8= +github.com/gostaticanalysis/comment v1.5.0/go.mod h1:V6eb3gpCv9GNVqb6amXzEUX3jXLVK/AdA+IrAMSqvEc= +github.com/gostaticanalysis/forcetypeassert v0.2.0 h1:uSnWrrUEYDr86OCxWa4/Tp2jeYDlogZiZHzGkWFefTk= +github.com/gostaticanalysis/forcetypeassert v0.2.0/go.mod h1:M5iPavzE9pPqWyeiVXSFghQjljW1+l/Uke3PXHS6ILY= +github.com/gostaticanalysis/nilerr v0.1.2 h1:S6nk8a9N8g062nsx63kUkF6AzbHGw7zzyHMcpu52xQU= +github.com/gostaticanalysis/nilerr v0.1.2/go.mod h1:A19UHhoY3y8ahoL7YKz6sdjDtduwTSI4CsymaC2htPA= +github.com/gostaticanalysis/testutil v0.3.1-0.20210208050101-bfb5c8eec0e4/go.mod h1:D+FIZ+7OahH3ePw/izIEeH5I06eKs1IKI4Xr64/Am3M= +github.com/gostaticanalysis/testutil v0.5.0 h1:Dq4wT1DdTwTGCQQv3rl3IvD5Ld0E6HiY+3Zh0sUGqw8= +github.com/gostaticanalysis/testutil v0.5.0/go.mod h1:OLQSbuM6zw2EvCcXTz1lVq5unyoNft372msDY0nY5Hs= +github.com/hashicorp/go-immutable-radix/v2 v2.1.0 h1:CUW5RYIcysz+D3B+l1mDeXrQ7fUvGGCwJfdASSzbrfo= +github.com/hashicorp/go-immutable-radix/v2 v2.1.0/go.mod h1:hgdqLXA4f6NIjRVisM1TJ9aOJVNRqKZj+xDGF6m7PBw= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA= +github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jgautheron/goconst v1.11.0 h1:KgN90z5qXt5f0Uzf3cWXev3hfMMFUyNeKdpkSBRvLDk= +github.com/jgautheron/goconst v1.11.0/go.mod h1:0p+wv1lFOiUr0IlNNT1nrm6+8DB8u2sU6KHGzFRXHDc= +github.com/jjti/go-spancheck v0.6.5 h1:lmi7pKxa37oKYIMScialXUK6hP3iY5F1gu+mLBPgYB8= +github.com/jjti/go-spancheck v0.6.5/go.mod h1:aEogkeatBrbYsyW6y5TgDfihCulDYciL1B7rG2vSsrU= +github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/julz/importas v0.2.0 h1:y+MJN/UdL63QbFJHws9BVC5RpA2iq0kpjrFajTGivjQ= +github.com/julz/importas v0.2.0/go.mod h1:pThlt589EnCYtMnmhmRYY/qn9lCf/frPOK+WMx3xiJY= +github.com/karamaru-alpha/copyloopvar v1.2.2 h1:yfNQvP9YaGQR7VaWLYcfZUlRP2eo2vhExWKxD/fP6q0= +github.com/karamaru-alpha/copyloopvar v1.2.2/go.mod h1:oY4rGZqZ879JkJMtX3RRkcXRkmUvH0x35ykgaKgsgJY= +github.com/kisielk/errcheck v1.20.0 h1:9rwHBNKzd4wkDWcROy3DvFGNqEPlkxBg305rvk7HabI= +github.com/kisielk/errcheck v1.20.0/go.mod h1:O+f80MKNwX8Oor2jwgpeQ9An7uJm+hRSgT+h22knRJU= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kkHAIKE/contextcheck v1.1.6 h1:7HIyRcnyzxL9Lz06NGhiKvenXq7Zw6Q0UQu/ttjfJCE= +github.com/kkHAIKE/contextcheck v1.1.6/go.mod h1:3dDbMRNBFaq8HFXWC1JyvDSPm43CmE6IuHam8Wr0rkg= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kulti/thelper v0.7.1 h1:fI8QITAoFVLx+y+vSyuLBP+rcVIB8jKooNSCT2EiI98= +github.com/kulti/thelper v0.7.1/go.mod h1:NsMjfQEy6sd+9Kfw8kCP61W1I0nerGSYSFnGaxQkcbs= +github.com/kunwardeep/paralleltest v1.0.15 h1:ZMk4Qt306tHIgKISHWFJAO1IDQJLc6uDyJMLyncOb6w= +github.com/kunwardeep/paralleltest v1.0.15/go.mod h1:di4moFqtfz3ToSKxhNjhOZL+696QtJGCFe132CbBLGk= +github.com/ldez/exptostd v0.4.5 h1:kv2ZGUVI6VwRfp/+bcQ6Nbx0ghFWcGIKInkG/oFn1aQ= +github.com/ldez/exptostd v0.4.5/go.mod h1:QRjHRMXJrCTIm9WxVNH6VW7oN7KrGSht69bIRwvdFsM= +github.com/ldez/gomoddirectives v0.10.0 h1:Zb23rfMMkG21B6pZ9OfESzemByP5Qr7YvWcXQZE/S3Q= +github.com/ldez/gomoddirectives v0.10.0/go.mod h1:W9uh0721Vc7aaVoiMXTpKIveLmtHC9uaOSiHM4OK5a8= +github.com/ldez/grignotin v0.10.1 h1:keYi9rYsgbvqAZGI1liek5c+jv9UUjbvdj3Tbn5fn4o= +github.com/ldez/grignotin v0.10.1/go.mod h1:UlDbXFCARrXbWGNGP3S5vsysNXAPhnSuBufpTEbwOas= +github.com/ldez/structtags v0.6.1 h1:bUooFLbXx41tW8SvkfwfFkkjPYvFFs59AAMgVg6DUBk= +github.com/ldez/structtags v0.6.1/go.mod h1:YDxVSgDy/MON6ariaxLF2X09bh19qL7MtGBN5MrvbdY= +github.com/ldez/tagliatelle v0.8.0 h1:QczqVPa22JdT40p3m5JTTVmPMv5wDORqdomJn6/Pnn0= +github.com/ldez/tagliatelle v0.8.0/go.mod h1:K9n83Wv0wyVq3JYF9WI28BX8xXhDBVP3thHJ0ENuiEs= +github.com/ldez/usetesting v0.5.0 h1:3/QtzZObBKLy1F4F8jLuKJiKBjjVFi1IavpoWbmqLwc= +github.com/ldez/usetesting v0.5.0/go.mod h1:Spnb4Qppf8JTuRgblLrEWb7IE6rDmUpGvxY3iRrzvDQ= +github.com/leonklingele/grouper v1.1.2 h1:o1ARBDLOmmasUaNDesWqWCIFH3u7hoFlM84YrjT3mIY= +github.com/leonklingele/grouper v1.1.2/go.mod h1:6D0M/HVkhs2yRKRFZUoGjeDy7EZTfFBE9gl4kjmIGkA= +github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= +github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/macabu/inamedparam v0.2.0 h1:VyPYpOc10nkhI2qeNUdh3Zket4fcZjEWe35poddBCpE= +github.com/macabu/inamedparam v0.2.0/go.mod h1:+Pee9/YfGe5LJ62pYXqB89lJ+0k5bsR8Wgz/C0Zlq3U= +github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= +github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/manuelarte/embeddedstructfieldcheck v0.4.0 h1:3mAIyaGRtjK6EO9E73JlXLtiy7ha80b2ZVGyacxgfww= +github.com/manuelarte/embeddedstructfieldcheck v0.4.0/go.mod h1:z8dFSyXqp+fC6NLDSljRJeNQJJDWnY7RoWFzV3PC6UM= +github.com/manuelarte/funcorder v0.6.0 h1:0hBngc4fa1IgNiI65A7sFGkMvoMCc878RjqB5V7rWP0= +github.com/manuelarte/funcorder v0.6.0/go.mod h1:id3NDhXdQBmeqXH7eVC6Z89xS6JxvZ8kF9xUxpArU/g= +github.com/maratori/testableexamples v1.0.1 h1:HfOQXs+XgfeRBJ+Wz0XfH+FHnoY9TVqL6Fcevpzy4q8= +github.com/maratori/testableexamples v1.0.1/go.mod h1:XE2F/nQs7B9N08JgyRmdGjYVGqxWwClLPCGSQhXQSrQ= +github.com/maratori/testpackage v1.1.2 h1:ffDSh+AgqluCLMXhM19f/cpvQAKygKAJXFl9aUjmbqs= +github.com/maratori/testpackage v1.1.2/go.mod h1:8F24GdVDFW5Ew43Et02jamrVMNXLUNaOynhDssITGfc= +github.com/matoous/godox v1.1.0 h1:W5mqwbyWrwZv6OQ5Z1a/DHGMOvXYCBP3+Ht7KMoJhq4= +github.com/matoous/godox v1.1.0/go.mod h1:jgE/3fUXiTurkdHOLT5WEkThTSuE7yxHv5iWPa80afs= +github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE= +github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= +github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= +github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU= +github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mgechev/revive v1.17.0 h1:hwTTVC3svSv9X2FA2hiYT17Uws+lfxDWhPxzBZZCREg= +github.com/mgechev/revive v1.17.0/go.mod h1:uiVNUF8ruVh4WHm/aPs7kKEeuo+m6oO3tuOfniyzP/g= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/moricho/tparallel v0.3.2 h1:odr8aZVFA3NZrNybggMkYO3rgPRcqjeQUlBBFVxKHTI= +github.com/moricho/tparallel v0.3.2/go.mod h1:OQ+K3b4Ln3l2TZveGCywybl68glfLEwFGqvnjok8b+U= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/nakabonne/nestif v0.3.1 h1:wm28nZjhQY5HyYPx+weN3Q65k6ilSBxDb8v5S81B81U= +github.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE= +github.com/nishanths/exhaustive v0.13.0 h1:Rof0axOSNQaaPaPmLK5RxcRrJV2Vcv+vfUmuRy+2EAM= +github.com/nishanths/exhaustive v0.13.0/go.mod h1:3/adQjJgvD/UFHHSYBjpK9Wbz8DOvf0FBtzx+zI0Rlo= +github.com/nishanths/predeclared v0.2.2 h1:V2EPdZPliZymNAn79T8RkNApBjMmVKh5XRpLm/w98Vk= +github.com/nishanths/predeclared v0.2.2/go.mod h1:RROzoN6TnGQupbC+lqggsOlcgysk3LMK/HI84Mp280c= +github.com/nunnatsa/ginkgolinter v0.24.0 h1:Mp0EagluLFP98JatP6nqp/gGEoljNG97uf9AcxcBVy8= +github.com/nunnatsa/ginkgolinter v0.24.0/go.mod h1:2ZMRuzX6+3XXyY6UZOwb6n+MCocVGbkIsDBC4vuWz5c= +github.com/ogen-go/ogen v1.24.0 h1:NehBG/8s0JeM6jYHPJeFJntBG3cE/xQgZd1q8BchPNM= +github.com/ogen-go/ogen v1.24.0/go.mod h1:hcg4aTzLcu/MS1SGGahUriPBEOZB3c82RGIC6dYcdFU= +github.com/onsi/ginkgo/v2 v2.32.1 h1:6tlvcDm/3sE8lGJbZ4+d4mO3RLy24/tQWOFzVSQNIfw= +github.com/onsi/ginkgo/v2 v2.32.1/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= +github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I= +github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg= +github.com/otiai10/copy v1.2.0/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw= +github.com/otiai10/copy v1.14.0 h1:dCI/t1iTdYGtkvCuBG2BgR6KZa83PTclw4U5n2wAllU= +github.com/otiai10/copy v1.14.0/go.mod h1:ECfuL02W+/FkTWZWgQqXPWZgW9oeKCSQ5qVfSc4qc4w= +github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= +github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= +github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= +github.com/otiai10/mint v1.3.1/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= +github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= +github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= +github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= +github.com/prometheus/client_golang v1.12.1 h1:ZiaPsmm9uiBeaSMRznKsCDNtPCS0T3JVDGF+06gjBzk= +github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= +github.com/prometheus/common v0.32.1 h1:hWIdL3N2HoUx3B8j3YN9mWor0qhY/NlEKZEaXxuIRh4= +github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= +github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= +github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= +github.com/quasilyte/go-ruleguard v0.4.5 h1:AGY0tiOT5hJX9BTdx/xBdoCubQUAE2grkqY2lSwvZcA= +github.com/quasilyte/go-ruleguard v0.4.5/go.mod h1:Vl05zJ538vcEEwu16V/Hdu7IYZWyKSwIy4c88Ro1kRE= +github.com/quasilyte/go-ruleguard/dsl v0.3.23 h1:lxjt5B6ZCiBeeNO8/oQsegE6fLeCzuMRoVWSkXC4uvY= +github.com/quasilyte/go-ruleguard/dsl v0.3.23/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= +github.com/quasilyte/gogrep v0.5.0 h1:eTKODPXbI8ffJMN+W2aE0+oL0z/nh8/5eNdiO34SOAo= +github.com/quasilyte/gogrep v0.5.0/go.mod h1:Cm9lpz9NZjEoL1tgZ2OgeUKPIxL1meE7eo60Z6Sk+Ng= +github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 h1:TCg2WBOl980XxGFEZSS6KlBGIV0diGdySzxATTWoqaU= +github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727/go.mod h1:rlzQ04UMyJXu/aOvhd8qT+hvDrFpiwqp8MRXDY9szc0= +github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 h1:M8mH9eK4OUR4lu7Gd+PU1fV2/qnDNfzT635KRSObncs= +github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567/go.mod h1:DWNGW8A4Y+GyBgPuaQJuWiy0XYftx4Xm/y5Jqk9I6VQ= +github.com/raeperd/recvcheck v0.3.1 h1:p7nZMxiCWkdUtY2i3o+pv1h4fJCR5gpvqAXr9326hEY= +github.com/raeperd/recvcheck v0.3.1/go.mod h1:CbE7iRocQ4uc71JwpW/CPSh4BShnkre4A9Gb508RypU= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= +github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ryancurrah/gomodguard v1.4.1 h1:eWC8eUMNZ/wM/PWuZBv7JxxqT5fiIKSIyTvjb7Elr+g= +github.com/ryancurrah/gomodguard v1.4.1/go.mod h1:qnMJwV1hX9m+YJseXEBhd2s90+1Xn6x9dLz11ualI1I= +github.com/ryancurrah/gomodguard/v2 v2.1.3 h1:E7sz3PJwE9Ba1reVxSpF6XLCPJZ74Kfw/LabTNM4GIA= +github.com/ryancurrah/gomodguard/v2 v2.1.3/go.mod h1:CQicdLGatWMxLX53JzoBjYlsNZhHbmLv2AVa0s2aivU= +github.com/ryanrolds/sqlclosecheck v0.6.0 h1:pEyL9okISdg1F1SEpJNlrEotkTGerv5BMk7U4AG0eVg= +github.com/ryanrolds/sqlclosecheck v0.6.0/go.mod h1:xyX16hsDaCMXHrMJ3JMzGf5OpDfHTOTTQrT7HOFUmeU= +github.com/sanposhiho/wastedassign/v2 v2.1.0 h1:crurBF7fJKIORrV85u9UUpePDYGWnwvv3+A96WvwXT0= +github.com/sanposhiho/wastedassign/v2 v2.1.0/go.mod h1:+oSmSC+9bQ+VUAxA66nBb0Z7N8CK7mscKTDYC6aIek4= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= +github.com/sashamelentyev/interfacebloat v1.1.0 h1:xdRdJp0irL086OyW1H/RTZTr1h/tMEOsumirXcOJqAw= +github.com/sashamelentyev/interfacebloat v1.1.0/go.mod h1:+Y9yU5YdTkrNvoX0xHc84dxiN1iBi9+G8zZIhPVoNjQ= +github.com/sashamelentyev/usestdlibvars v1.29.0 h1:8J0MoRrw4/NAXtjQqTHrbW9NN+3iMf7Knkq057v4XOQ= +github.com/sashamelentyev/usestdlibvars v1.29.0/go.mod h1:8PpnjHMk5VdeWlVb4wCdrB8PNbLqZ3wBZTZWkrpZZL8= +github.com/securego/gosec/v2 v2.29.0 h1:pF2HSLcnY5voqpxQumEe0O5YAAbvF4Syu4qeIewpLyc= +github.com/securego/gosec/v2 v2.29.0/go.mod h1:47C7ej+L2bC1NOxteU2aCGnCi4cZaoKzRt5y9plIvuY= +github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0= +github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= +github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= +github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= +github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo= +github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q= +github.com/sivchari/containedctx v1.0.3 h1:x+etemjbsh2fB5ewm5FeLNi5bUjK0V8n0RB+Wwfd0XE= +github.com/sivchari/containedctx v1.0.3/go.mod h1:c1RDvCbnJLtH4lLcYD/GqwiBSSf4F5Qk0xld2rBqzJ4= +github.com/sonatard/noctx v0.5.1 h1:wklWg9c9ZYugOAk7qG4yP4PBrlQsmSLPTvW1K4PRQMs= +github.com/sonatard/noctx v0.5.1/go.mod h1:64XdbzFb18XL4LporKXp8poqZtPKbCrqQ402CV+kJas= +github.com/sourcegraph/go-diff v0.9.0 h1:7xcVsayWHhvxZGrqt1o89vvBApCa4nyCgO7tNxDHJ+Q= +github.com/sourcegraph/go-diff v0.9.0/go.mod h1:hWlcO7Al+UZStZAP8rBumHpCK5ZHQ5BXsMls8p4+F5E= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= +github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= +github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.12.0 h1:CZ7eSOd3kZoaYDLbXnmzgQI5RlciuXBMA+18HwHRfZQ= +github.com/spf13/viper v1.12.0/go.mod h1:b6COn30jlNxbm/V2IqWiNWkJ+vZNiMNksliPCiuKtSI= +github.com/ssgreg/nlreturn/v2 v2.2.1 h1:X4XDI7jstt3ySqGU86YGAURbxw3oTDPK9sPEi6YEwQ0= +github.com/ssgreg/nlreturn/v2 v2.2.1/go.mod h1:E/iiPB78hV7Szg2YfRgyIrk1AD6JVMTRkkxBiELzh2I= +github.com/stbenjam/no-sprintf-host-port v0.3.1 h1:AyX7+dxI4IdLBPtDbsGAyqiTSLpCP9hWRrXQDU4Cm/g= +github.com/stbenjam/no-sprintf-host-port v0.3.1/go.mod h1:ODbZesTCHMVKthBHskvUUexdcNHAQRXk9NpSsL8p/HQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs= +github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= +github.com/tenntenn/modver v1.0.1 h1:2klLppGhDgzJrScMpkj9Ujy3rXPUspSjAcev9tSEBgA= +github.com/tenntenn/modver v1.0.1/go.mod h1:bePIyQPb7UeioSRkw3Q0XeMhYZSMx9B8ePqg6SAMGH0= +github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3 h1:f+jULpRQGxTSkNYKJ51yaw6ChIqO+Je8UqsTKN/cDag= +github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3/go.mod h1:ON8b8w4BN/kE1EOhwT0o+d62W65a6aPw1nouo9LMgyY= +github.com/tetafro/godot v1.5.6 h1:IEkrFCwXaYHlOn4mGzGS3F3dkP6m9t0jpwqBFPIkKiA= +github.com/tetafro/godot v1.5.6/go.mod h1:eOkMrVQurDui411nBY2FA05EYH01r14LuWY/NrVDVcU= +github.com/timakin/bodyclose v0.0.0-20260723120731-857993a2939c h1:d/FUP8GD4QiY/rdFzZmBu3KqL9eBNVzMu7W/5pGkaMM= +github.com/timakin/bodyclose v0.0.0-20260723120731-857993a2939c/go.mod h1:sDHLK7rb/59v/ZxZ7KtymgcoxuUMxjXq8gtu9VMOK8M= +github.com/timonwong/loggercheck v0.12.0 h1:7Cb9XGLJZSWYNjgL459DIhpSiEHupD+MLQ6vaN2Pl3g= +github.com/timonwong/loggercheck v0.12.0/go.mod h1:Wa6Y+SJHQR01mViZlLLY5GAZVOWOLNMbkXddMjFWQCs= +github.com/tomarrell/wrapcheck/v2 v2.12.0 h1:H/qQ1aNWz/eeIhxKAFvkfIA+N7YDvq6TWVFL27Of9is= +github.com/tomarrell/wrapcheck/v2 v2.12.0/go.mod h1:AQhQuZd0p7b6rfW+vUwHm5OMCGgp63moQ9Qr/0BpIWo= +github.com/tommy-muehle/go-mnd/v2 v2.5.1 h1:NowYhSdyE/1zwK9QCLeRb6USWdoif80Ie+v+yU8u1Zw= +github.com/tommy-muehle/go-mnd/v2 v2.5.1/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= +github.com/ultraware/funlen v0.2.0 h1:gCHmCn+d2/1SemTdYMiKLAHFYxTYz7z9VIDRaTGyLkI= +github.com/ultraware/funlen v0.2.0/go.mod h1:ZE0q4TsJ8T1SQcjmkhN/w+MceuatI6pBFSxxyteHIJA= +github.com/ultraware/whitespace v0.2.0 h1:TYowo2m9Nfj1baEQBjuHzvMRbp19i+RCcRYrSWoFa+g= +github.com/ultraware/whitespace v0.2.0/go.mod h1:XcP1RLD81eV4BW8UhQlpaR+SDc2givTvyI8a586WjW8= +github.com/uudashr/gocognit v1.2.1 h1:CSJynt5txTnORn/DkhiB4mZjwPuifyASC8/6Q0I/QS4= +github.com/uudashr/gocognit v1.2.1/go.mod h1:acaubQc6xYlXFEMb9nWX2dYBzJ/bIjEkc1zzvyIZg5Q= +github.com/uudashr/iface v1.5.1 h1:BS3yrgaT55s3dAtJoxuTnsZNbsejq/mVuzp49YDyfBA= +github.com/uudashr/iface v1.5.1/go.mod h1:5UWoT6SvTdTww/KToRj6clO+n4Kg3/NrAQvgOB+5Ggw= +github.com/xen0n/gosmopolitan v1.3.0 h1:zAZI1zefvo7gcpbCOrPSHJZJYA9ZgLfJqtKzZ5pHqQM= +github.com/xen0n/gosmopolitan v1.3.0/go.mod h1:rckfr5T6o4lBtM1ga7mLGKZmLxswUoH1zxHgNXOsEt4= +github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY= +github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +github.com/yagipy/maintidx v1.0.0 h1:h5NvIsCz+nRDapQ0exNv4aJ0yXSI0420omVANTv3GJM= +github.com/yagipy/maintidx v1.0.0/go.mod h1:0qNf/I/CCZXSMhsRsrEPDZ+DkekpKLXAJfsTACwgXLk= +github.com/yeya24/promlinter v0.3.0 h1:JVDbMp08lVCP7Y6NP3qHroGAO6z2yGKQtS5JsjqtoFs= +github.com/yeya24/promlinter v0.3.0/go.mod h1:cDfJQQYv9uYciW60QT0eeHlFodotkYZlL+YcPQN+mW4= +github.com/ykadowak/zerologlint v0.1.5 h1:Gy/fMz1dFQN9JZTPjv1hxEk+sRWm05row04Yoolgdiw= +github.com/ykadowak/zerologlint v0.1.5/go.mod h1:KaUskqF3e/v59oPmdq1U1DnKcuHokl2/K1U4pmIELKg= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE= +github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= +gitlab.com/bosi/decorder v0.4.2 h1:qbQaV3zgwnBZ4zPMhGLW4KZe7A7NwxEhJx39R3shffo= +gitlab.com/bosi/decorder v0.4.2/go.mod h1:muuhHoaJkA9QLcYHq4Mj8FJUwDZ+EirSHRiaTcTf6T8= +go-simpler.org/assert v0.9.0 h1:PfpmcSvL7yAnWyChSjOz6Sp6m9j5lyK8Ok9pEL31YkQ= +go-simpler.org/assert v0.9.0/go.mod h1:74Eqh5eI6vCK6Y5l3PI8ZYFXG4Sa+tkr70OIPJAUr28= +go-simpler.org/musttag v0.14.0 h1:XGySZATqQYSEV3/YTy+iX+aofbZZllJaqwFWs+RTtSo= +go-simpler.org/musttag v0.14.0/go.mod h1:uP8EymctQjJ4Z1kUnjX0u2l60WfUdQxCwSNKzE1JEOE= +go-simpler.org/sloglint v0.12.0 h1:UzWDlLWNE5FLqsvyq3tWYHuQMbqrervOhT8qPl4Mmw4= +go-simpler.org/sloglint v0.12.0/go.mod h1:jBjjC2bm8rYrs88oTRlFX497kWjJsyZWYoNaXkGRI6I= +go.augendre.info/arangolint v0.4.0 h1:xSCZjRoS93nXazBSg5d0OGCi9APPLNMmmLrC995tR50= +go.augendre.info/arangolint v0.4.0/go.mod h1:l+f/b4plABuFISuKnTGD4RioXiCCgghv2xqst/xOvAA= +go.augendre.info/fatcontext v0.10.1 h1:HCS/+eob32cM0mEtmZM6NiXdqvS5KiZmsR+fCubTpbc= +go.augendre.info/fatcontext v0.10.1/go.mod h1:pqpGvA9GlrXy+aXkp8L2dKz12Zp4g2FhzcAtwToU+2w= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= +go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= +go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= +go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= +go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= +go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= +go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o= +golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= +golang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= +golang.org/x/exp/typeparams v0.0.0-20230203172020-98cc5a0785f9/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= +golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f h1:+lI8cDJ4uceLipg2f1ODay7fEuLkk0BIHXd6PB8icxo= +golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f/go.mod h1:PqrXSW65cXDZH0k4IeUbhmg/bcAZDbzNz3byBpKCsXo= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= +golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211105183446-c75c47738b0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200329025819-fd4102a86c65/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.1.1-0.20210205202024-ef80cdb6ec6d/go.mod h1:9bzcO0MWcOuT0tm1iBGzDVPshzfwoVvREIui8C+MHqU= +golang.org/x/tools v0.1.1-0.20210302220138-2ac05c832e1a/go.mod h1:9bzcO0MWcOuT0tm1iBGzDVPshzfwoVvREIui8C+MHqU= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= +golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= +golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM= +golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.8.1 h1:+JKf3xJ1ni4CwrhVg4/pqsfPGP6vNAXcKbMXJodYx3w= +honnef.co/go/tools v0.8.1/go.mod h1:XA+OnlRA9EDh/ukGvXMNSZNKGwFQJ+5dER0ioUkOxks= +mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho= +mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA= +mvdan.cc/unparam v0.0.0-20260823230713-2fa3d841b0c8 h1:Re1NRyLpiAt9kB+ImaaoapwWiQXrKwER4tY8fLOkDew= +mvdan.cc/unparam v0.0.0-20260823230713-2fa3d841b0c8/go.mod h1:MrS/+zJ1M2xvGXhKktiHbNQeQPyg3Qel+KkzT+f7/i4= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/runner/internal/api/oas_cfg_gen.go b/runner/internal/api/oas_cfg_gen.go new file mode 100644 index 0000000..b3cec3b --- /dev/null +++ b/runner/internal/api/oas_cfg_gen.go @@ -0,0 +1,258 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "net/http" + "strings" + + "github.com/ogen-go/ogen/middleware" + "github.com/ogen-go/ogen/ogenerrors" + "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])*)*$"), + "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), + "^[a-z0-9][a-z0-9_-]{0,31}$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_-]{0,31}$"), + "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), +} +var ( + // Allocate option closure once. + serverSpanKind = trace.WithSpanKind(trace.SpanKindServer) +) + +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()), + ) +} + +// ErrorHandler is error handler. +type ErrorHandler = ogenerrors.ErrorHandler + +type serverConfig struct { + otelConfig + NotFound http.HandlerFunc + MethodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string) + ErrorHandler ErrorHandler + Prefix string + Middleware Middleware + MaxMultipartMemory int64 +} + +// ServerOption is server config option. +type ServerOption interface { + applyServer(*serverConfig) +} + +var _ ServerOption = (optionFunc[serverConfig])(nil) + +func (o optionFunc[C]) applyServer(c *C) { + o(c) +} + +var _ ServerOption = (otelOptionFunc)(nil) + +func (o otelOptionFunc) applyServer(c *serverConfig) { + o(&c.otelConfig) +} + +func newServerConfig(opts ...ServerOption) serverConfig { + cfg := serverConfig{ + NotFound: http.NotFound, + MethodNotAllowed: nil, + ErrorHandler: ogenerrors.DefaultErrorHandler, + Middleware: nil, + MaxMultipartMemory: 32 << 20, // 32 MB + } + for _, opt := range opts { + opt.applyServer(&cfg) + } + cfg.initOTEL() + return cfg +} + +type baseServer struct { + cfg serverConfig + requests metric.Int64Counter + errors metric.Int64Counter + duration metric.Float64Histogram +} + +func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) { + s.cfg.NotFound(w, r) +} + +type notAllowedParams struct { + allowedMethods string + allowedHeaders map[string]string + acceptPost string + acceptPatch string +} + +func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, params notAllowedParams) { + h := w.Header() + isOptions := r.Method == "OPTIONS" + if isOptions { + h.Set("Access-Control-Allow-Methods", params.allowedMethods) + if params.allowedHeaders != nil { + m := r.Header.Get("Access-Control-Request-Method") + if m != "" { + allowedHeaders, ok := params.allowedHeaders[strings.ToUpper(m)] + if ok { + h.Set("Access-Control-Allow-Headers", allowedHeaders) + } + } + } + if params.acceptPost != "" { + h.Set("Accept-Post", params.acceptPost) + } + if params.acceptPatch != "" { + h.Set("Accept-Patch", params.acceptPatch) + } + } + if s.cfg.MethodNotAllowed != nil { + s.cfg.MethodNotAllowed(w, r, params.allowedMethods) + return + } + status := http.StatusNoContent + if !isOptions { + h.Set("Allow", params.allowedMethods) + status = http.StatusMethodNotAllowed + } + w.WriteHeader(status) +} + +func (cfg serverConfig) baseServer() (s baseServer, err error) { + s = baseServer{cfg: cfg} + if s.requests, err = otelogen.ServerRequestCountCounter(s.cfg.Meter); err != nil { + return s, err + } + if s.errors, err = otelogen.ServerErrorsCountCounter(s.cfg.Meter); err != nil { + return s, err + } + if s.duration, err = otelogen.ServerDurationHistogram(s.cfg.Meter); err != nil { + return s, err + } + return s, nil +} + +// Option is config option. +type Option interface { + ServerOption +} + +// 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 + }) +} + +// WithNotFound specifies Not Found handler to use. +func WithNotFound(notFound http.HandlerFunc) ServerOption { + return optionFunc[serverConfig](func(cfg *serverConfig) { + if notFound != nil { + cfg.NotFound = notFound + } + }) +} + +// WithMethodNotAllowed specifies Method Not Allowed handler to use. +func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption { + return optionFunc[serverConfig](func(cfg *serverConfig) { + if methodNotAllowed != nil { + cfg.MethodNotAllowed = methodNotAllowed + } + }) +} + +// WithErrorHandler specifies error handler to use. +func WithErrorHandler(h ErrorHandler) ServerOption { + return optionFunc[serverConfig](func(cfg *serverConfig) { + if h != nil { + cfg.ErrorHandler = h + } + }) +} + +// WithPathPrefix specifies server path prefix. +func WithPathPrefix(prefix string) ServerOption { + return optionFunc[serverConfig](func(cfg *serverConfig) { + cfg.Prefix = prefix + }) +} + +// WithMiddleware specifies middlewares to use. +func WithMiddleware(m ...Middleware) ServerOption { + return optionFunc[serverConfig](func(cfg *serverConfig) { + switch len(m) { + case 0: + cfg.Middleware = nil + case 1: + cfg.Middleware = m[0] + default: + cfg.Middleware = middleware.ChainMiddlewares(m...) + } + }) +} + +// WithMaxMultipartMemory specifies limit of memory for storing file parts. +// File parts which can't be stored in memory will be stored on disk in temporary files. +func WithMaxMultipartMemory(max int64) ServerOption { + return optionFunc[serverConfig](func(cfg *serverConfig) { + if max > 0 { + cfg.MaxMultipartMemory = max + } + }) +} diff --git a/runner/internal/api/oas_handlers_gen.go b/runner/internal/api/oas_handlers_gen.go new file mode 100644 index 0000000..d37cc60 --- /dev/null +++ b/runner/internal/api/oas_handlers_gen.go @@ -0,0 +1,736 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" + "net/http" + "time" + + "github.com/go-faster/errors" + ht "github.com/ogen-go/ogen/http" + "github.com/ogen-go/ogen/middleware" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/otelogen" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/metric" + semconv "go.opentelemetry.io/otel/semconv/v1.39.0" + "go.opentelemetry.io/otel/trace" +) + +type codeRecorder struct { + http.ResponseWriter + status int +} + +func (c *codeRecorder) WriteHeader(status int) { + c.status = status + c.ResponseWriter.WriteHeader(status) +} + +func (c *codeRecorder) Unwrap() http.ResponseWriter { + return c.ResponseWriter +} + +// handleGetRunRequest handles GetRun operation. +// +// Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its +// retention time or lost in a restart. +// +// GET /v1/runs/{run_id} +func (s *Server) handleGetRunRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetRun"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/v1/runs/{run_id}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetRunOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetRunOperation, + ID: "GetRun", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securityBearerAuth(ctx, GetRunOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "BearerAuth", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:BearerAuth", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeGetRunParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response *RunStatus + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetRunOperation, + OperationSummary: "Read the state and, when finished, the per-group result of a run.", + OperationID: "GetRun", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "run_id", + In: "path", + }: params.RunID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetRunParams + Response = *RunStatus + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetRunParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetRun(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetRun(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetRunResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetRunnerHealthzRequest handles GetRunnerHealthz operation. +// +// Check whether the runner process is responding. +// +// GET /healthz +func (s *Server) handleGetRunnerHealthzRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetRunnerHealthz"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/healthz"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetRunnerHealthzOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + ) + + var rawBody []byte + + var response *RunnerHealthResponse + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetRunnerHealthzOperation, + OperationSummary: "Check whether the runner process is responding.", + OperationID: "GetRunnerHealthz", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = *RunnerHealthResponse + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetRunnerHealthz(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetRunnerHealthz(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetRunnerHealthzResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetRunnerReadyzRequest handles GetRunnerReadyz operation. +// +// Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at +// startup and the process is not draining. A busy runner is still ready; busy is reported by +// SubmitRun. +// +// GET /readyz +func (s *Server) handleGetRunnerReadyzRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetRunnerReadyz"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/readyz"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetRunnerReadyzOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + ) + + var rawBody []byte + + var response GetRunnerReadyzRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetRunnerReadyzOperation, + OperationSummary: "Check whether the sandbox is prepared to accept runs.", + OperationID: "GetRunnerReadyz", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = GetRunnerReadyzRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetRunnerReadyz(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetRunnerReadyz(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetRunnerReadyzResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleSubmitRunRequest handles SubmitRun operation. +// +// Idempotent by `run_id`: +// +// - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`; +// - the same ID with the same payload answers 200 with the current state of that run, including the +// finished result, without running it again; +// - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; +// - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_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. The runner keeps runs only in +// memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a +// new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`. +// Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique +// in a run, test IDs are unique in a group, and the number of tests multiplied by +// `limits.time_limit_ms` does not exceed 300000. +// +// PUT /v1/runs/{run_id} +func (s *Server) handleSubmitRunRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("SubmitRun"), + semconv.HTTPRequestMethodKey.String("PUT"), + semconv.HTTPRouteKey.String("/v1/runs/{run_id}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), SubmitRunOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: SubmitRunOperation, + ID: "SubmitRun", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securityBearerAuth(ctx, SubmitRunOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "BearerAuth", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:BearerAuth", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeSubmitRunParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeSubmitRunRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response SubmitRunRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: SubmitRunOperation, + OperationSummary: "Start a sandboxed run of one source against its test groups.", + OperationID: "SubmitRun", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "run_id", + In: "path", + }: params.RunID, + }, + Raw: r, + } + + type ( + Request = *RunRequest + Params = SubmitRunParams + Response = SubmitRunRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackSubmitRunParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.SubmitRun(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.SubmitRun(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeSubmitRunResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} diff --git a/runner/internal/api/oas_interfaces_gen.go b/runner/internal/api/oas_interfaces_gen.go new file mode 100644 index 0000000..587330c --- /dev/null +++ b/runner/internal/api/oas_interfaces_gen.go @@ -0,0 +1,10 @@ +// Code generated by ogen, DO NOT EDIT. +package api + +type GetRunnerReadyzRes interface { + getRunnerReadyzRes() +} + +type SubmitRunRes interface { + submitRunRes() +} diff --git a/runner/internal/api/oas_json_gen.go b/runner/internal/api/oas_json_gen.go new file mode 100644 index 0000000..1c39f15 --- /dev/null +++ b/runner/internal/api/oas_json_gen.go @@ -0,0 +1,2898 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "math/bits" + "strconv" + + "github.com/go-faster/errors" + "github.com/go-faster/jx" + "github.com/ogen-go/ogen/json" + "github.com/ogen-go/ogen/validate" +) + +// Encode implements json.Marshaler. +func (s *Checker) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Checker) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } +} + +var jsonFieldsNameOfChecker = [1]string{ + 0: "kind", +} + +// Decode decodes Checker from json. +func (s *Checker) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Checker to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Checker") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfChecker) { + name = jsonFieldsNameOfChecker[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *Checker) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Checker) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CheckerKind as json. +func (s CheckerKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CheckerKind from json. +func (s *CheckerKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CheckerKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CheckerKind(v) { + case CheckerKindExact: + *s = CheckerKindExact + case CheckerKindTokens: + *s = CheckerKindTokens + default: + *s = CheckerKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CheckerKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CheckerKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CompileResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CompileResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + if s.Diagnostic.Set { + e.FieldStart("diagnostic") + s.Diagnostic.Encode(e) + } + } +} + +var jsonFieldsNameOfCompileResult = [2]string{ + 0: "outcome", + 1: "diagnostic", +} + +// Decode decodes CompileResult from json. +func (s *CompileResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CompileResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "outcome": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "diagnostic": + if err := func() error { + s.Diagnostic.Reset() + if err := s.Diagnostic.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"diagnostic\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CompileResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCompileResult) { + name = jsonFieldsNameOfCompileResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CompileResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CompileResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetRunnerReadyzOK as json. +func (s *GetRunnerReadyzOK) Encode(e *jx.Encoder) { + unwrapped := (*RunnerReadinessResponse)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetRunnerReadyzOK from json. +func (s *GetRunnerReadyzOK) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetRunnerReadyzOK to nil") + } + var unwrapped RunnerReadinessResponse + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetRunnerReadyzOK(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetRunnerReadyzOK) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetRunnerReadyzOK) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetRunnerReadyzServiceUnavailable as json. +func (s *GetRunnerReadyzServiceUnavailable) Encode(e *jx.Encoder) { + unwrapped := (*RunnerReadinessResponse)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetRunnerReadyzServiceUnavailable from json. +func (s *GetRunnerReadyzServiceUnavailable) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetRunnerReadyzServiceUnavailable to nil") + } + var unwrapped RunnerReadinessResponse + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetRunnerReadyzServiceUnavailable(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetRunnerReadyzServiceUnavailable) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetRunnerReadyzServiceUnavailable) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *GroupResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *GroupResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("visibility") + s.Visibility.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("passed_tests") + e.Int32(s.PassedTests) + } + { + e.FieldStart("total_tests") + e.Int32(s.TotalTests) + } + { + if s.MaxTimeMs.Set { + e.FieldStart("max_time_ms") + s.MaxTimeMs.Encode(e) + } + } + { + if s.MaxMemoryKB.Set { + e.FieldStart("max_memory_kb") + s.MaxMemoryKB.Encode(e) + } + } + { + e.FieldStart("tests") + e.ArrStart() + for _, elem := range s.Tests { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfGroupResult = [8]string{ + 0: "id", + 1: "visibility", + 2: "outcome", + 3: "passed_tests", + 4: "total_tests", + 5: "max_time_ms", + 6: "max_memory_kb", + 7: "tests", +} + +// Decode decodes GroupResult from json. +func (s *GroupResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GroupResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "visibility": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Visibility.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"visibility\"") + } + case "outcome": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "passed_tests": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.PassedTests = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"passed_tests\"") + } + case "total_tests": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + v, err := d.Int32() + s.TotalTests = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"total_tests\"") + } + case "max_time_ms": + if err := func() error { + s.MaxTimeMs.Reset() + if err := s.MaxTimeMs.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_time_ms\"") + } + case "max_memory_kb": + if err := func() error { + s.MaxMemoryKB.Reset() + if err := s.MaxMemoryKB.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"max_memory_kb\"") + } + case "tests": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + s.Tests = make([]TestResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TestResult + if err := elem.Decode(d); err != nil { + return err + } + s.Tests = append(s.Tests, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tests\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode GroupResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b10011111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfGroupResult) { + name = jsonFieldsNameOfGroupResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GroupResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GroupResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CompileResult as json. +func (o OptCompileResult) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes CompileResult from json. +func (o *OptCompileResult) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptCompileResult to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptCompileResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptCompileResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes int32 as json. +func (o OptInt32) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Int32(int32(o.Value)) +} + +// Decode decodes int32 from json. +func (o *OptInt32) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptInt32 to nil") + } + o.Set = true + v, err := d.Int32() + if err != nil { + return err + } + o.Value = int32(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptInt32) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptInt32) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes int64 as json. +func (o OptInt64) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Int64(int64(o.Value)) +} + +// Decode decodes int64 from json. +func (o *OptInt64) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptInt64 to nil") + } + o.Set = true + v, err := d.Int64() + if err != nil { + return err + } + o.Value = int64(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptInt64) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptInt64) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunResult as json. +func (o OptRunResult) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes RunResult from json. +func (o *OptRunResult) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptRunResult to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptRunResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptRunResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes string as json. +func (o OptString) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Str(string(o.Value)) +} + +// Decode decodes string from json. +func (o *OptString) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptString to nil") + } + o.Set = true + v, err := d.Str() + if err != nil { + return err + } + o.Value = string(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptString) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptString) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TerminationLimit as json. +func (o OptTerminationLimit) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Str(string(o.Value)) +} + +// Decode decodes TerminationLimit from json. +func (o *OptTerminationLimit) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptTerminationLimit to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptTerminationLimit) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptTerminationLimit) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *Problem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Problem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + e.Str(s.Type) + } + { + e.FieldStart("title") + e.Str(s.Title) + } + { + e.FieldStart("status") + e.Int32(s.Status) + } + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + if s.Detail.Set { + e.FieldStart("detail") + s.Detail.Encode(e) + } + } + { + if s.Instance.Set { + e.FieldStart("instance") + s.Instance.Encode(e) + } + } + { + if s.TraceID.Set { + e.FieldStart("trace_id") + s.TraceID.Encode(e) + } + } + { + if s.Errors != nil { + e.FieldStart("errors") + e.ArrStart() + for _, elem := range s.Errors { + elem.Encode(e) + } + e.ArrEnd() + } + } +} + +var jsonFieldsNameOfProblem = [8]string{ + 0: "type", + 1: "title", + 2: "status", + 3: "code", + 4: "detail", + 5: "instance", + 6: "trace_id", + 7: "errors", +} + +// Decode decodes Problem from json. +func (s *Problem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Problem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Type = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.Status = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "code": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "detail": + if err := func() error { + s.Detail.Reset() + if err := s.Detail.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"detail\"") + } + case "instance": + if err := func() error { + s.Instance.Reset() + if err := s.Instance.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"instance\"") + } + case "trace_id": + if err := func() error { + s.TraceID.Reset() + if err := s.TraceID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"trace_id\"") + } + case "errors": + if err := func() error { + s.Errors = make([]ProblemFieldError, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProblemFieldError + if err := elem.Decode(d); err != nil { + return err + } + s.Errors = append(s.Errors, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"errors\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Problem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblem) { + name = jsonFieldsNameOfProblem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *Problem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Problem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemCode as json. +func (s ProblemCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemCode from json. +func (s *ProblemCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemCode(v) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + case ProblemCodeInternal: + *s = ProblemCodeInternal + case ProblemCodeRunnerBusy: + *s = ProblemCodeRunnerBusy + default: + *s = ProblemCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProblemFieldError) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProblemFieldError) encodeFields(e *jx.Encoder) { + { + e.FieldStart("in") + s.In.Encode(e) + } + { + e.FieldStart("pointer") + e.Str(s.Pointer) + } + { + e.FieldStart("code") + e.Str(s.Code) + } + { + e.FieldStart("message") + e.Str(s.Message) + } +} + +var jsonFieldsNameOfProblemFieldError = [4]string{ + 0: "in", + 1: "pointer", + 2: "code", + 3: "message", +} + +// Decode decodes ProblemFieldError from json. +func (s *ProblemFieldError) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldError to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "in": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.In.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"in\"") + } + case "pointer": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Pointer = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"pointer\"") + } + case "code": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Code = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "message": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Str() + s.Message = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"message\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProblemFieldError") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblemFieldError) { + name = jsonFieldsNameOfProblemFieldError[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProblemFieldError) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldError) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemFieldLocation as json. +func (s ProblemFieldLocation) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemFieldLocation from json. +func (s *ProblemFieldLocation) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldLocation to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemFieldLocation(v) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + default: + *s = ProblemFieldLocation(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemFieldLocation) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldLocation) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunLanguage as json. +func (s RunLanguage) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunLanguage from json. +func (s *RunLanguage) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunLanguage to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunLanguage(v) { + case RunLanguagePython3: + *s = RunLanguagePython3 + default: + *s = RunLanguage(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunLanguage) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunLanguage) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunLimits) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunLimits) encodeFields(e *jx.Encoder) { + { + e.FieldStart("time_limit_ms") + e.Int32(s.TimeLimitMs) + } + { + e.FieldStart("memory_limit_mb") + e.Int32(s.MemoryLimitMB) + } + { + e.FieldStart("output_limit_kb") + e.Int32(s.OutputLimitKB) + } +} + +var jsonFieldsNameOfRunLimits = [3]string{ + 0: "time_limit_ms", + 1: "memory_limit_mb", + 2: "output_limit_kb", +} + +// Decode decodes RunLimits from json. +func (s *RunLimits) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunLimits to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "time_limit_ms": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.TimeLimitMs = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"time_limit_ms\"") + } + case "memory_limit_mb": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.MemoryLimitMB = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"memory_limit_mb\"") + } + case "output_limit_kb": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.OutputLimitKB = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"output_limit_kb\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunLimits") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunLimits) { + name = jsonFieldsNameOfRunLimits[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunLimits) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunLimits) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunOutcome as json. +func (s RunOutcome) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunOutcome from json. +func (s *RunOutcome) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunOutcome to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunOutcome(v) { + case RunOutcomeAccepted: + *s = RunOutcomeAccepted + case RunOutcomeWrongAnswer: + *s = RunOutcomeWrongAnswer + case RunOutcomeCompileError: + *s = RunOutcomeCompileError + case RunOutcomeTimeLimitExceeded: + *s = RunOutcomeTimeLimitExceeded + case RunOutcomeMemoryLimitExceeded: + *s = RunOutcomeMemoryLimitExceeded + case RunOutcomeOutputLimitExceeded: + *s = RunOutcomeOutputLimitExceeded + case RunOutcomeRuntimeError: + *s = RunOutcomeRuntimeError + case RunOutcomeInfrastructureFailure: + *s = RunOutcomeInfrastructureFailure + default: + *s = RunOutcome(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunOutcome) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunOutcome) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("language") + s.Language.Encode(e) + } + { + e.FieldStart("source") + e.Str(s.Source) + } + { + e.FieldStart("limits") + s.Limits.Encode(e) + } + { + e.FieldStart("groups") + e.ArrStart() + for _, elem := range s.Groups { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfRunRequest = [4]string{ + 0: "language", + 1: "source", + 2: "limits", + 3: "groups", +} + +// Decode decodes RunRequest from json. +func (s *RunRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "language": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Language.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"language\"") + } + case "source": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Source = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + case "limits": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Limits.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"limits\"") + } + case "groups": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + s.Groups = make([]TestGroup, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TestGroup + if err := elem.Decode(d); err != nil { + return err + } + s.Groups = append(s.Groups, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"groups\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunRequest) { + name = jsonFieldsNameOfRunRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + if s.Compile.Set { + e.FieldStart("compile") + s.Compile.Encode(e) + } + } + { + e.FieldStart("groups") + e.ArrStart() + for _, elem := range s.Groups { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("duration_ms") + e.Int64(s.DurationMs) + } +} + +var jsonFieldsNameOfRunResult = [4]string{ + 0: "outcome", + 1: "compile", + 2: "groups", + 3: "duration_ms", +} + +// Decode decodes RunResult from json. +func (s *RunResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "outcome": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "compile": + if err := func() error { + s.Compile.Reset() + if err := s.Compile.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"compile\"") + } + case "groups": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.Groups = make([]GroupResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem GroupResult + if err := elem.Decode(d); err != nil { + return err + } + s.Groups = append(s.Groups, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"groups\"") + } + case "duration_ms": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int64() + s.DurationMs = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"duration_ms\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001101, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunResult) { + name = jsonFieldsNameOfRunResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunState as json. +func (s RunState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunState from json. +func (s *RunState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunState(v) { + case RunStateRunning: + *s = RunStateRunning + case RunStateFinished: + *s = RunStateFinished + default: + *s = RunState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunStatus) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunStatus) encodeFields(e *jx.Encoder) { + { + e.FieldStart("run_id") + json.EncodeUUID(e, s.RunID) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + if s.Result.Set { + e.FieldStart("result") + s.Result.Encode(e) + } + } +} + +var jsonFieldsNameOfRunStatus = [3]string{ + 0: "run_id", + 1: "state", + 2: "result", +} + +// Decode decodes RunStatus from json. +func (s *RunStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunStatus to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "run_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.RunID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"run_id\"") + } + case "state": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "result": + if err := func() error { + s.Result.Reset() + if err := s.Result.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"result\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunStatus") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunStatus) { + name = jsonFieldsNameOfRunStatus[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunnerHealthResponse) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunnerHealthResponse) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfRunnerHealthResponse = [1]string{ + 0: "status", +} + +// Decode decodes RunnerHealthResponse from json. +func (s *RunnerHealthResponse) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunnerHealthResponse to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunnerHealthResponse") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunnerHealthResponse) { + name = jsonFieldsNameOfRunnerHealthResponse[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunnerHealthResponse) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunnerHealthResponse) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunnerHealthResponseStatus as json. +func (s RunnerHealthResponseStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunnerHealthResponseStatus from json. +func (s *RunnerHealthResponseStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunnerHealthResponseStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunnerHealthResponseStatus(v) { + case RunnerHealthResponseStatusOk: + *s = RunnerHealthResponseStatusOk + default: + *s = RunnerHealthResponseStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunnerHealthResponseStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunnerHealthResponseStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RunnerReadinessResponse) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RunnerReadinessResponse) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfRunnerReadinessResponse = [1]string{ + 0: "status", +} + +// Decode decodes RunnerReadinessResponse from json. +func (s *RunnerReadinessResponse) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunnerReadinessResponse to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RunnerReadinessResponse") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRunnerReadinessResponse) { + name = jsonFieldsNameOfRunnerReadinessResponse[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RunnerReadinessResponse) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunnerReadinessResponse) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RunnerReadinessResponseStatus as json. +func (s RunnerReadinessResponseStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes RunnerReadinessResponseStatus from json. +func (s *RunnerReadinessResponseStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RunnerReadinessResponseStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch RunnerReadinessResponseStatus(v) { + case RunnerReadinessResponseStatusReady: + *s = RunnerReadinessResponseStatusReady + case RunnerReadinessResponseStatusNotReady: + *s = RunnerReadinessResponseStatusNotReady + default: + *s = RunnerReadinessResponseStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s RunnerReadinessResponseStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RunnerReadinessResponseStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitRunAccepted as json. +func (s *SubmitRunAccepted) Encode(e *jx.Encoder) { + unwrapped := (*RunStatus)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitRunAccepted from json. +func (s *SubmitRunAccepted) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitRunAccepted to nil") + } + var unwrapped RunStatus + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitRunAccepted(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitRunAccepted) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitRunAccepted) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SubmitRunOK as json. +func (s *SubmitRunOK) Encode(e *jx.Encoder) { + unwrapped := (*RunStatus)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SubmitRunOK from json. +func (s *SubmitRunOK) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SubmitRunOK to nil") + } + var unwrapped RunStatus + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SubmitRunOK(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SubmitRunOK) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SubmitRunOK) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TerminationLimit as json. +func (s TerminationLimit) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes TerminationLimit from json. +func (s *TerminationLimit) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TerminationLimit to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch TerminationLimit(v) { + case TerminationLimitCPUTime: + *s = TerminationLimitCPUTime + case TerminationLimitWallTime: + *s = TerminationLimitWallTime + case TerminationLimitMemory: + *s = TerminationLimitMemory + case TerminationLimitOutput: + *s = TerminationLimitOutput + case TerminationLimitProcesses: + *s = TerminationLimitProcesses + default: + *s = TerminationLimit(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TerminationLimit) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TerminationLimit) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *TestCase) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *TestCase) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("input") + e.Str(s.Input) + } + { + e.FieldStart("expected_output") + e.Str(s.ExpectedOutput) + } +} + +var jsonFieldsNameOfTestCase = [3]string{ + 0: "id", + 1: "input", + 2: "expected_output", +} + +// Decode decodes TestCase from json. +func (s *TestCase) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestCase to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "input": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Input = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"input\"") + } + case "expected_output": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.ExpectedOutput = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_output\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode TestCase") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfTestCase) { + name = jsonFieldsNameOfTestCase[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *TestCase) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestCase) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *TestGroup) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *TestGroup) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("visibility") + s.Visibility.Encode(e) + } + { + e.FieldStart("checker") + s.Checker.Encode(e) + } + { + e.FieldStart("tests") + e.ArrStart() + for _, elem := range s.Tests { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfTestGroup = [4]string{ + 0: "id", + 1: "visibility", + 2: "checker", + 3: "tests", +} + +// Decode decodes TestGroup from json. +func (s *TestGroup) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestGroup to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "visibility": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Visibility.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"visibility\"") + } + case "checker": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Checker.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"checker\"") + } + case "tests": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + s.Tests = make([]TestCase, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TestCase + if err := elem.Decode(d); err != nil { + return err + } + s.Tests = append(s.Tests, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tests\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode TestGroup") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfTestGroup) { + name = jsonFieldsNameOfTestGroup[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *TestGroup) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestGroup) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TestKey as json. +func (s TestKey) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes TestKey from json. +func (s *TestKey) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestKey to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = TestKey(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TestKey) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestKey) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *TestResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *TestResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + s.ID.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("time_ms") + e.Int64(s.TimeMs) + } + { + e.FieldStart("wall_time_ms") + e.Int64(s.WallTimeMs) + } + { + e.FieldStart("memory_kb") + e.Int64(s.MemoryKB) + } + { + if s.ExitCode.Set { + e.FieldStart("exit_code") + s.ExitCode.Encode(e) + } + } + { + if s.Signal.Set { + e.FieldStart("signal") + s.Signal.Encode(e) + } + } + { + if s.Limit.Set { + e.FieldStart("limit") + s.Limit.Encode(e) + } + } + { + if s.Diagnostic.Set { + e.FieldStart("diagnostic") + s.Diagnostic.Encode(e) + } + } +} + +var jsonFieldsNameOfTestResult = [9]string{ + 0: "id", + 1: "outcome", + 2: "time_ms", + 3: "wall_time_ms", + 4: "memory_kb", + 5: "exit_code", + 6: "signal", + 7: "limit", + 8: "diagnostic", +} + +// Decode decodes TestResult from json. +func (s *TestResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestResult to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "outcome": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "time_ms": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int64() + s.TimeMs = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"time_ms\"") + } + case "wall_time_ms": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int64() + s.WallTimeMs = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"wall_time_ms\"") + } + case "memory_kb": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + v, err := d.Int64() + s.MemoryKB = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"memory_kb\"") + } + case "exit_code": + if err := func() error { + s.ExitCode.Reset() + if err := s.ExitCode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"exit_code\"") + } + case "signal": + if err := func() error { + s.Signal.Reset() + if err := s.Signal.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"signal\"") + } + case "limit": + if err := func() error { + s.Limit.Reset() + if err := s.Limit.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"limit\"") + } + case "diagnostic": + if err := func() error { + s.Diagnostic.Reset() + if err := s.Diagnostic.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"diagnostic\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode TestResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b00011111, + 0b00000000, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfTestResult) { + name = jsonFieldsNameOfTestResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *TestResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TestVisibility as json. +func (s TestVisibility) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes TestVisibility from json. +func (s *TestVisibility) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestVisibility to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch TestVisibility(v) { + case TestVisibilityPublic: + *s = TestVisibilityPublic + case TestVisibilityHidden: + *s = TestVisibilityHidden + default: + *s = TestVisibility(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TestVisibility) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestVisibility) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} diff --git a/runner/internal/api/oas_labeler_gen.go b/runner/internal/api/oas_labeler_gen.go new file mode 100644 index 0000000..7e519e8 --- /dev/null +++ b/runner/internal/api/oas_labeler_gen.go @@ -0,0 +1,42 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" + + "go.opentelemetry.io/otel/attribute" +) + +// Labeler is used to allow adding custom attributes to the server request metrics. +type Labeler struct { + attrs []attribute.KeyValue +} + +// Add attributes to the Labeler. +func (l *Labeler) Add(attrs ...attribute.KeyValue) { + l.attrs = append(l.attrs, attrs...) +} + +// AttributeSet returns the attributes added to the Labeler as an attribute.Set. +func (l *Labeler) AttributeSet() attribute.Set { + return attribute.NewSet(l.attrs...) +} + +type labelerContextKey struct{} + +// LabelerFromContext retrieves the Labeler from the provided context, if present. +// +// If no Labeler was found in the provided context a new, empty Labeler is returned and the second +// return value is false. In this case it is safe to use the Labeler but any attributes added to +// it will not be used. +func LabelerFromContext(ctx context.Context) (*Labeler, bool) { + if l, ok := ctx.Value(labelerContextKey{}).(*Labeler); ok { + return l, true + } + return &Labeler{}, false +} + +func contextWithLabeler(ctx context.Context, l *Labeler) context.Context { + return context.WithValue(ctx, labelerContextKey{}, l) +} diff --git a/runner/internal/api/oas_middleware_gen.go b/runner/internal/api/oas_middleware_gen.go new file mode 100644 index 0000000..6f58a1a --- /dev/null +++ b/runner/internal/api/oas_middleware_gen.go @@ -0,0 +1,10 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "github.com/ogen-go/ogen/middleware" +) + +// Middleware is middleware type. +type Middleware = middleware.Middleware diff --git a/runner/internal/api/oas_operations_gen.go b/runner/internal/api/oas_operations_gen.go new file mode 100644 index 0000000..b9f7be2 --- /dev/null +++ b/runner/internal/api/oas_operations_gen.go @@ -0,0 +1,13 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +// OperationName is the ogen operation name +type OperationName = string + +const ( + GetRunOperation OperationName = "GetRun" + GetRunnerHealthzOperation OperationName = "GetRunnerHealthz" + GetRunnerReadyzOperation OperationName = "GetRunnerReadyz" + SubmitRunOperation OperationName = "SubmitRun" +) diff --git a/runner/internal/api/oas_parameters_gen.go b/runner/internal/api/oas_parameters_gen.go new file mode 100644 index 0000000..b376605 --- /dev/null +++ b/runner/internal/api/oas_parameters_gen.go @@ -0,0 +1,150 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "net/http" + "net/url" + + "github.com/go-faster/errors" + "github.com/google/uuid" + "github.com/ogen-go/ogen/conv" + "github.com/ogen-go/ogen/middleware" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/uri" + "github.com/ogen-go/ogen/validate" +) + +// GetRunParams is parameters of GetRun operation. +type GetRunParams struct { + // Random UUID chosen by the backend for one logical run. It is the idempotency key of SubmitRun and + // must not encode a candidate, attempt, or task identifier. + RunID uuid.UUID +} + +func unpackGetRunParams(packed middleware.Parameters) (params GetRunParams) { + { + key := middleware.ParameterKey{ + Name: "run_id", + In: "path", + } + params.RunID = packed[key].(uuid.UUID) + } + return params +} + +func decodeGetRunParams(args [1]string, argsEscaped bool, r *http.Request) (params GetRunParams, _ error) { + // Decode path: run_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: "run_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.RunID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "run_id", + In: "path", + Err: err, + } + } + return params, nil +} + +// SubmitRunParams is parameters of SubmitRun operation. +type SubmitRunParams struct { + // Random UUID chosen by the backend for one logical run. It is the idempotency key of SubmitRun and + // must not encode a candidate, attempt, or task identifier. + RunID uuid.UUID +} + +func unpackSubmitRunParams(packed middleware.Parameters) (params SubmitRunParams) { + { + key := middleware.ParameterKey{ + Name: "run_id", + In: "path", + } + params.RunID = packed[key].(uuid.UUID) + } + return params +} + +func decodeSubmitRunParams(args [1]string, argsEscaped bool, r *http.Request) (params SubmitRunParams, _ error) { + // Decode path: run_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: "run_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.RunID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "run_id", + In: "path", + Err: err, + } + } + return params, nil +} diff --git a/runner/internal/api/oas_request_decoders_gen.go b/runner/internal/api/oas_request_decoders_gen.go new file mode 100644 index 0000000..f6ba76f --- /dev/null +++ b/runner/internal/api/oas_request_decoders_gen.go @@ -0,0 +1,94 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "bytes" + "io" + "mime" + "net/http" + + "github.com/go-faster/errors" + "github.com/go-faster/jx" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/validate" +) + +func (s *Server) decodeSubmitRunRequest(r *http.Request) ( + req *RunRequest, + 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 RunRequest + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} diff --git a/runner/internal/api/oas_response_encoders_gen.go b/runner/internal/api/oas_response_encoders_gen.go new file mode 100644 index 0000000..0cf5850 --- /dev/null +++ b/runner/internal/api/oas_response_encoders_gen.go @@ -0,0 +1,159 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "net/http" + + "github.com/go-faster/errors" + "github.com/go-faster/jx" + "github.com/ogen-go/ogen/conv" + ht "github.com/ogen-go/ogen/http" + "github.com/ogen-go/ogen/uri" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/trace" +) + +func encodeGetRunResponse(response *RunStatus, w http.ResponseWriter, span trace.Span) error { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil +} + +func encodeGetRunnerHealthzResponse(response *RunnerHealthResponse, w http.ResponseWriter, span trace.Span) error { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil +} + +func encodeGetRunnerReadyzResponse(response GetRunnerReadyzRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *GetRunnerReadyzOK: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetRunnerReadyzServiceUnavailable: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(503) + span.SetStatus(codes.Error, http.StatusText(503)) + + 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 encodeSubmitRunResponse(response SubmitRunRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *SubmitRunOK: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SubmitRunAccepted: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(202) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RunnerBusyHeaders: + 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 { + return e.EncodeValue(conv.Int32ToString(response.RetryAfter)) + }); 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 encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error { + w.Header().Set("Content-Type", "application/problem+json") + code := response.StatusCode + if code == 0 { + // Set default status code. + code = http.StatusOK + } + w.WriteHeader(code) + if code >= http.StatusInternalServerError { + span.SetStatus(codes.Error, http.StatusText(code)) + } + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + if code >= http.StatusInternalServerError { + return errors.Wrapf(ht.ErrInternalServerErrorResponse, "code: %d, message: %s", code, http.StatusText(code)) + } + return nil + +} diff --git a/runner/internal/api/oas_router_gen.go b/runner/internal/api/oas_router_gen.go new file mode 100644 index 0000000..37b50c2 --- /dev/null +++ b/runner/internal/api/oas_router_gen.go @@ -0,0 +1,359 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "net/http" + "net/url" + "strings" + + "github.com/ogen-go/ogen/uri" +) + +var ( + rn2AllowedHeaders = map[string]string{ + "GET": "Authorization", + "PUT": "Authorization,Content-Type", + } +) + +func (s *Server) cutPrefix(path string) (string, bool) { + prefix := s.cfg.Prefix + if prefix == "" { + return path, true + } + if !strings.HasPrefix(path, prefix) { + // Prefix doesn't match. + return "", false + } + // Cut prefix from the path. + return strings.TrimPrefix(path, prefix), true +} + +// ServeHTTP serves http request as defined by OpenAPI v3 specification, +// calling handler that matches the path or returning not found error. +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + elem := r.URL.Path + elemIsEscaped := false + if rawPath := r.URL.RawPath; rawPath != "" { + if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok { + elem = normalized + elemIsEscaped = strings.ContainsRune(elem, '%') + } + } + + elem, ok := s.cutPrefix(elem) + if !ok || len(elem) == 0 { + s.notFound(w, r) + return + } + args := [1]string{} + + // Static code generated router with unwrapped path search. + switch { + default: + if len(elem) == 0 { + break + } + 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 'h': // Prefix: "healthz" + + if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetRunnerHealthzRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 'r': // Prefix: "readyz" + + if l := len("readyz"); len(elem) >= l && elem[0:l] == "readyz" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetRunnerReadyzRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 'v': // Prefix: "v1/runs/" + + if l := len("v1/runs/"); len(elem) >= l && elem[0:l] == "v1/runs/" { + elem = elem[l:] + } else { + break + } + + // Param: "run_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetRunRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + case "PUT": + s.handleSubmitRunRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,PUT", + allowedHeaders: rn2AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + } + } + s.notFound(w, r) +} + +// Route is route object. +type Route struct { + name string + summary string + operationID string + operationGroup string + pathPattern string + count int + args [1]string +} + +// Name returns ogen operation name. +// +// It is guaranteed to be unique and not empty. +func (r Route) Name() string { + return r.name +} + +// Summary returns OpenAPI summary. +func (r Route) Summary() string { + return r.summary +} + +// OperationID returns OpenAPI operationId. +func (r Route) OperationID() string { + return r.operationID +} + +// OperationGroup returns the x-ogen-operation-group value. +func (r Route) OperationGroup() string { + return r.operationGroup +} + +// PathPattern returns OpenAPI path. +func (r Route) PathPattern() string { + return r.pathPattern +} + +// Args returns parsed arguments. +func (r Route) Args() []string { + return r.args[:r.count] +} + +// FindRoute finds Route for given method and path. +// +// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead. +func (s *Server) FindRoute(method, path string) (Route, bool) { + return s.FindPath(method, &url.URL{Path: path}) +} + +// FindPath finds Route for given method and URL. +func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { + var ( + elem = u.Path + args = r.args + ) + if rawPath := u.RawPath; rawPath != "" { + if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok { + elem = normalized + } + defer func() { + for i, arg := range r.args[:r.count] { + if unescaped, err := url.PathUnescape(arg); err == nil { + r.args[i] = unescaped + } + } + }() + } + + elem, ok := s.cutPrefix(elem) + if !ok { + return r, false + } + + // Static code generated router with unwrapped path search. + switch { + default: + if len(elem) == 0 { + break + } + 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 'h': // Prefix: "healthz" + + if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetRunnerHealthzOperation + r.summary = "Check whether the runner process is responding." + r.operationID = "GetRunnerHealthz" + r.operationGroup = "" + r.pathPattern = "/healthz" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 'r': // Prefix: "readyz" + + if l := len("readyz"); len(elem) >= l && elem[0:l] == "readyz" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetRunnerReadyzOperation + r.summary = "Check whether the sandbox is prepared to accept runs." + r.operationID = "GetRunnerReadyz" + r.operationGroup = "" + r.pathPattern = "/readyz" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 'v': // Prefix: "v1/runs/" + + if l := len("v1/runs/"); len(elem) >= l && elem[0:l] == "v1/runs/" { + elem = elem[l:] + } else { + break + } + + // Param: "run_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetRunOperation + r.summary = "Read the state and, when finished, the per-group result of a run." + r.operationID = "GetRun" + r.operationGroup = "" + r.pathPattern = "/v1/runs/{run_id}" + r.args = args + r.count = 1 + return r, true + case "PUT": + r.name = SubmitRunOperation + r.summary = "Start a sandboxed run of one source against its test groups." + r.operationID = "SubmitRun" + r.operationGroup = "" + r.pathPattern = "/v1/runs/{run_id}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + } + + } + } + return r, false +} diff --git a/runner/internal/api/oas_schemas_gen.go b/runner/internal/api/oas_schemas_gen.go new file mode 100644 index 0000000..f4c89f0 --- /dev/null +++ b/runner/internal/api/oas_schemas_gen.go @@ -0,0 +1,1684 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "fmt" + + "github.com/go-faster/errors" + "github.com/google/uuid" +) + +func (s *ProblemStatusCode) Error() string { + return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response) +} + +type BearerAuth struct { + Token string + Roles []string +} + +// GetToken returns the value of Token. +func (s *BearerAuth) GetToken() string { + return s.Token +} + +// GetRoles returns the value of Roles. +func (s *BearerAuth) GetRoles() []string { + return s.Roles +} + +// SetToken sets the value of Token. +func (s *BearerAuth) SetToken(val string) { + s.Token = val +} + +// SetRoles sets the value of Roles. +func (s *BearerAuth) SetRoles(val []string) { + s.Roles = val +} + +// How the standard output of a test is compared with `expected_output`. Future kinds, such as a float +// tolerance or a custom checker, add a `kind` value and their own optional parameters to this object. +// Ref: #/components/schemas/Checker +type Checker struct { + Kind CheckerKind `json:"kind"` +} + +// GetKind returns the value of Kind. +func (s *Checker) GetKind() CheckerKind { + return s.Kind +} + +// SetKind sets the value of Kind. +func (s *Checker) SetKind(val CheckerKind) { + s.Kind = val +} + +// - exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at +// the end of each line, and removing trailing empty lines. +// - tokens: both texts split on ASCII whitespace give the same sequence of tokens. +// +// Ref: #/components/schemas/CheckerKind +type CheckerKind string + +const ( + CheckerKindExact CheckerKind = "exact" + CheckerKindTokens CheckerKind = "tokens" +) + +// AllValues returns all CheckerKind values. +func (CheckerKind) AllValues() []CheckerKind { + return []CheckerKind{ + CheckerKindExact, + CheckerKindTokens, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CheckerKind) MarshalText() ([]byte, error) { + switch s { + case CheckerKindExact: + return []byte(s), nil + case CheckerKindTokens: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CheckerKind) UnmarshalText(data []byte) error { + switch CheckerKind(data) { + case CheckerKindExact: + *s = CheckerKindExact + return nil + case CheckerKindTokens: + *s = CheckerKindTokens + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/CompileResult +type CompileResult struct { + Outcome RunOutcome `json:"outcome"` + // Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the + // source, never test data. + Diagnostic OptString `json:"diagnostic"` +} + +// GetOutcome returns the value of Outcome. +func (s *CompileResult) GetOutcome() RunOutcome { + return s.Outcome +} + +// GetDiagnostic returns the value of Diagnostic. +func (s *CompileResult) GetDiagnostic() OptString { + return s.Diagnostic +} + +// SetOutcome sets the value of Outcome. +func (s *CompileResult) SetOutcome(val RunOutcome) { + s.Outcome = val +} + +// SetDiagnostic sets the value of Diagnostic. +func (s *CompileResult) SetDiagnostic(val OptString) { + s.Diagnostic = val +} + +type GetRunnerReadyzOK RunnerReadinessResponse + +func (*GetRunnerReadyzOK) getRunnerReadyzRes() {} + +type GetRunnerReadyzServiceUnavailable RunnerReadinessResponse + +func (*GetRunnerReadyzServiceUnavailable) getRunnerReadyzRes() {} + +// Ref: #/components/schemas/GroupResult +type GroupResult struct { + ID TestKey `json:"id"` + Visibility TestVisibility `json:"visibility"` + Outcome RunOutcome `json:"outcome"` + PassedTests int32 `json:"passed_tests"` + TotalTests int32 `json:"total_tests"` + // Largest CPU time of an evaluated test of the group. + MaxTimeMs OptInt64 `json:"max_time_ms"` + // Largest peak memory of an evaluated test of the group. + MaxMemoryKB OptInt64 `json:"max_memory_kb"` + // Results of the evaluated tests in order. Tests after the first failed one are not run and not + // listed. + Tests []TestResult `json:"tests"` +} + +// GetID returns the value of ID. +func (s *GroupResult) GetID() TestKey { + return s.ID +} + +// GetVisibility returns the value of Visibility. +func (s *GroupResult) GetVisibility() TestVisibility { + return s.Visibility +} + +// GetOutcome returns the value of Outcome. +func (s *GroupResult) GetOutcome() RunOutcome { + return s.Outcome +} + +// GetPassedTests returns the value of PassedTests. +func (s *GroupResult) GetPassedTests() int32 { + return s.PassedTests +} + +// GetTotalTests returns the value of TotalTests. +func (s *GroupResult) GetTotalTests() int32 { + return s.TotalTests +} + +// GetMaxTimeMs returns the value of MaxTimeMs. +func (s *GroupResult) GetMaxTimeMs() OptInt64 { + return s.MaxTimeMs +} + +// GetMaxMemoryKB returns the value of MaxMemoryKB. +func (s *GroupResult) GetMaxMemoryKB() OptInt64 { + return s.MaxMemoryKB +} + +// GetTests returns the value of Tests. +func (s *GroupResult) GetTests() []TestResult { + return s.Tests +} + +// SetID sets the value of ID. +func (s *GroupResult) SetID(val TestKey) { + s.ID = val +} + +// SetVisibility sets the value of Visibility. +func (s *GroupResult) SetVisibility(val TestVisibility) { + s.Visibility = val +} + +// SetOutcome sets the value of Outcome. +func (s *GroupResult) SetOutcome(val RunOutcome) { + s.Outcome = val +} + +// SetPassedTests sets the value of PassedTests. +func (s *GroupResult) SetPassedTests(val int32) { + s.PassedTests = val +} + +// SetTotalTests sets the value of TotalTests. +func (s *GroupResult) SetTotalTests(val int32) { + s.TotalTests = val +} + +// SetMaxTimeMs sets the value of MaxTimeMs. +func (s *GroupResult) SetMaxTimeMs(val OptInt64) { + s.MaxTimeMs = val +} + +// SetMaxMemoryKB sets the value of MaxMemoryKB. +func (s *GroupResult) SetMaxMemoryKB(val OptInt64) { + s.MaxMemoryKB = val +} + +// SetTests sets the value of Tests. +func (s *GroupResult) SetTests(val []TestResult) { + s.Tests = val +} + +// NewOptCompileResult returns new OptCompileResult with value set to v. +func NewOptCompileResult(v CompileResult) OptCompileResult { + return OptCompileResult{ + Value: v, + Set: true, + } +} + +// OptCompileResult is optional CompileResult. +type OptCompileResult struct { + Value CompileResult + Set bool +} + +// IsSet returns true if OptCompileResult was set. +func (o OptCompileResult) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptCompileResult) Reset() { + var v CompileResult + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptCompileResult) SetTo(v CompileResult) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptCompileResult) Get() (v CompileResult, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptCompileResult) Or(d CompileResult) CompileResult { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptInt32 returns new OptInt32 with value set to v. +func NewOptInt32(v int32) OptInt32 { + return OptInt32{ + Value: v, + Set: true, + } +} + +// OptInt32 is optional int32. +type OptInt32 struct { + Value int32 + Set bool +} + +// IsSet returns true if OptInt32 was set. +func (o OptInt32) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptInt32) Reset() { + var v int32 + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptInt32) SetTo(v int32) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptInt32) Get() (v int32, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptInt32) Or(d int32) int32 { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptInt64 returns new OptInt64 with value set to v. +func NewOptInt64(v int64) OptInt64 { + return OptInt64{ + Value: v, + Set: true, + } +} + +// OptInt64 is optional int64. +type OptInt64 struct { + Value int64 + Set bool +} + +// IsSet returns true if OptInt64 was set. +func (o OptInt64) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptInt64) Reset() { + var v int64 + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptInt64) SetTo(v int64) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptInt64) Get() (v int64, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptInt64) Or(d int64) int64 { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptRunResult returns new OptRunResult with value set to v. +func NewOptRunResult(v RunResult) OptRunResult { + return OptRunResult{ + Value: v, + Set: true, + } +} + +// OptRunResult is optional RunResult. +type OptRunResult struct { + Value RunResult + Set bool +} + +// IsSet returns true if OptRunResult was set. +func (o OptRunResult) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptRunResult) Reset() { + var v RunResult + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptRunResult) SetTo(v RunResult) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptRunResult) Get() (v RunResult, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptRunResult) Or(d RunResult) RunResult { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptString returns new OptString with value set to v. +func NewOptString(v string) OptString { + return OptString{ + Value: v, + Set: true, + } +} + +// OptString is optional string. +type OptString struct { + Value string + Set bool +} + +// IsSet returns true if OptString was set. +func (o OptString) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptString) Reset() { + var v string + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptString) SetTo(v string) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptString) Get() (v string, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptString) Or(d string) string { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptTerminationLimit returns new OptTerminationLimit with value set to v. +func NewOptTerminationLimit(v TerminationLimit) OptTerminationLimit { + return OptTerminationLimit{ + Value: v, + Set: true, + } +} + +// OptTerminationLimit is optional TerminationLimit. +type OptTerminationLimit struct { + Value TerminationLimit + Set bool +} + +// IsSet returns true if OptTerminationLimit was set. +func (o OptTerminationLimit) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptTerminationLimit) Reset() { + var v TerminationLimit + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptTerminationLimit) SetTo(v TerminationLimit) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptTerminationLimit) Get() (v TerminationLimit, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptTerminationLimit) Or(d TerminationLimit) TerminationLimit { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// Problem details (RFC 9457) returned with the application/problem+json media type for every error +// response. This is the runner copy of the public api/core Problem schema; keep both copies identical +// except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; +// clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never +// contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed +// request values. +// Ref: #/components/schemas/Problem +type Problem struct { + // URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an + // identifier, not a link to dereference. + Type string `json:"type"` + // Short, fixed English summary of the problem type. It does not change between occurrences. + Title string `json:"title"` + // HTTP status code generated by the origin server. + Status int32 `json:"status"` + Code ProblemCode `json:"code"` + // Safe English explanation of this occurrence. It never contains internal error text or request + // values. + Detail OptString `json:"detail"` + // URI reference that identifies this occurrence, when one exists. + Instance OptString `json:"instance"` + // Request identifier of the call when the caller propagated one; it is not a secret. + TraceID OptString `json:"trace_id"` + // Field-level reasons for validation_failed. Other codes omit it. + Errors []ProblemFieldError `json:"errors"` +} + +// GetType returns the value of Type. +func (s *Problem) GetType() string { + return s.Type +} + +// GetTitle returns the value of Title. +func (s *Problem) GetTitle() string { + return s.Title +} + +// GetStatus returns the value of Status. +func (s *Problem) GetStatus() int32 { + return s.Status +} + +// GetCode returns the value of Code. +func (s *Problem) GetCode() ProblemCode { + return s.Code +} + +// GetDetail returns the value of Detail. +func (s *Problem) GetDetail() OptString { + return s.Detail +} + +// GetInstance returns the value of Instance. +func (s *Problem) GetInstance() OptString { + return s.Instance +} + +// GetTraceID returns the value of TraceID. +func (s *Problem) GetTraceID() OptString { + return s.TraceID +} + +// GetErrors returns the value of Errors. +func (s *Problem) GetErrors() []ProblemFieldError { + return s.Errors +} + +// SetType sets the value of Type. +func (s *Problem) SetType(val string) { + s.Type = val +} + +// SetTitle sets the value of Title. +func (s *Problem) SetTitle(val string) { + s.Title = val +} + +// SetStatus sets the value of Status. +func (s *Problem) SetStatus(val int32) { + s.Status = val +} + +// SetCode sets the value of Code. +func (s *Problem) SetCode(val ProblemCode) { + s.Code = val +} + +// SetDetail sets the value of Detail. +func (s *Problem) SetDetail(val OptString) { + s.Detail = val +} + +// SetInstance sets the value of Instance. +func (s *Problem) SetInstance(val OptString) { + s.Instance = val +} + +// SetTraceID sets the value of TraceID. +func (s *Problem) SetTraceID(val OptString) { + s.TraceID = val +} + +// SetErrors sets the value of Errors. +func (s *Problem) SetErrors(val []ProblemFieldError) { + s.Errors = val +} + +// Stable error code of the runner 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 of +// SubmitRun; `errors` points at the fields. +// - unauthenticated (401): the bearer token is missing or wrong. +// - not_found (404): the route or the run does not exist. +// - method_not_allowed (405): the route does not support the method. +// - 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 run ID was already used with a different payload. +// - internal (500): unexpected server error. +// - runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After. +// +// The Problem shape is the api/core shape; only this enum is specific to the runner. +// Ref: #/components/schemas/ProblemCode +type ProblemCode string + +const ( + ProblemCodeValidationFailed ProblemCode = "validation_failed" + ProblemCodeUnauthenticated ProblemCode = "unauthenticated" + ProblemCodeNotFound ProblemCode = "not_found" + ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed" + ProblemCodePayloadTooLarge ProblemCode = "payload_too_large" + ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type" + ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused" + ProblemCodeInternal ProblemCode = "internal" + ProblemCodeRunnerBusy ProblemCode = "runner_busy" +) + +// AllValues returns all ProblemCode values. +func (ProblemCode) AllValues() []ProblemCode { + return []ProblemCode{ + ProblemCodeValidationFailed, + ProblemCodeUnauthenticated, + ProblemCodeNotFound, + ProblemCodeMethodNotAllowed, + ProblemCodePayloadTooLarge, + ProblemCodeUnsupportedMediaType, + ProblemCodeIdempotencyKeyReused, + ProblemCodeInternal, + ProblemCodeRunnerBusy, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemCode) MarshalText() ([]byte, error) { + switch s { + case ProblemCodeValidationFailed: + return []byte(s), nil + case ProblemCodeUnauthenticated: + return []byte(s), nil + case ProblemCodeNotFound: + return []byte(s), nil + case ProblemCodeMethodNotAllowed: + return []byte(s), nil + case ProblemCodePayloadTooLarge: + return []byte(s), nil + case ProblemCodeUnsupportedMediaType: + return []byte(s), nil + case ProblemCodeIdempotencyKeyReused: + return []byte(s), nil + case ProblemCodeInternal: + return []byte(s), nil + case ProblemCodeRunnerBusy: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemCode) UnmarshalText(data []byte) error { + switch ProblemCode(data) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + return nil + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + return nil + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + return nil + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + return nil + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + return nil + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + return nil + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + return nil + case ProblemCodeInternal: + *s = ProblemCodeInternal + return nil + case ProblemCodeRunnerBusy: + *s = ProblemCodeRunnerBusy + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One reason why a request field or parameter is invalid. +// Ref: #/components/schemas/ProblemFieldError +type ProblemFieldError struct { + In ProblemFieldLocation `json:"in"` + // JSON Pointer (RFC 6901). For `body` it points into the request body document, for example + // `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by + // the parameter name, for example `/run_id`. + Pointer string `json:"pointer"` + // Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or + // a value outside the schema). Clients must tolerate new values. + Code string `json:"code"` + // Fixed English message that never echoes the submitted value. + Message string `json:"message"` +} + +// GetIn returns the value of In. +func (s *ProblemFieldError) GetIn() ProblemFieldLocation { + return s.In +} + +// GetPointer returns the value of Pointer. +func (s *ProblemFieldError) GetPointer() string { + return s.Pointer +} + +// GetCode returns the value of Code. +func (s *ProblemFieldError) GetCode() string { + return s.Code +} + +// GetMessage returns the value of Message. +func (s *ProblemFieldError) GetMessage() string { + return s.Message +} + +// SetIn sets the value of In. +func (s *ProblemFieldError) SetIn(val ProblemFieldLocation) { + s.In = val +} + +// SetPointer sets the value of Pointer. +func (s *ProblemFieldError) SetPointer(val string) { + s.Pointer = val +} + +// SetCode sets the value of Code. +func (s *ProblemFieldError) SetCode(val string) { + s.Code = val +} + +// SetMessage sets the value of Message. +func (s *ProblemFieldError) SetMessage(val string) { + s.Message = val +} + +// Part of the request that contains the invalid field. +// Ref: #/components/schemas/ProblemFieldLocation +type ProblemFieldLocation string + +const ( + ProblemFieldLocationBody ProblemFieldLocation = "body" + ProblemFieldLocationQuery ProblemFieldLocation = "query" + ProblemFieldLocationPath ProblemFieldLocation = "path" + ProblemFieldLocationHeader ProblemFieldLocation = "header" + ProblemFieldLocationCookie ProblemFieldLocation = "cookie" +) + +// AllValues returns all ProblemFieldLocation values. +func (ProblemFieldLocation) AllValues() []ProblemFieldLocation { + return []ProblemFieldLocation{ + ProblemFieldLocationBody, + ProblemFieldLocationQuery, + ProblemFieldLocationPath, + ProblemFieldLocationHeader, + ProblemFieldLocationCookie, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemFieldLocation) MarshalText() ([]byte, error) { + switch s { + case ProblemFieldLocationBody: + return []byte(s), nil + case ProblemFieldLocationQuery: + return []byte(s), nil + case ProblemFieldLocationPath: + return []byte(s), nil + case ProblemFieldLocationHeader: + return []byte(s), nil + case ProblemFieldLocationCookie: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemFieldLocation) UnmarshalText(data []byte) error { + switch ProblemFieldLocation(data) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + return nil + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + return nil + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + return nil + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + return nil + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// ProblemStatusCode wraps Problem with StatusCode. +type ProblemStatusCode struct { + StatusCode int + Response Problem +} + +// GetStatusCode returns the value of StatusCode. +func (s *ProblemStatusCode) GetStatusCode() int { + return s.StatusCode +} + +// GetResponse returns the value of Response. +func (s *ProblemStatusCode) GetResponse() Problem { + return s.Response +} + +// SetStatusCode sets the value of StatusCode. +func (s *ProblemStatusCode) SetStatusCode(val int) { + s.StatusCode = val +} + +// SetResponse sets the value of Response. +func (s *ProblemStatusCode) SetResponse(val Problem) { + s.Response = val +} + +// Language and runtime of the source. `python3` runs the Python 3 interpreter of the runner image with +// isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error. +// Ref: #/components/schemas/RunLanguage +type RunLanguage string + +const ( + RunLanguagePython3 RunLanguage = "python3" +) + +// AllValues returns all RunLanguage values. +func (RunLanguage) AllValues() []RunLanguage { + return []RunLanguage{ + RunLanguagePython3, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunLanguage) MarshalText() ([]byte, error) { + switch s { + case RunLanguagePython3: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunLanguage) UnmarshalText(data []byte) error { + switch RunLanguage(data) { + case RunLanguagePython3: + *s = RunLanguagePython3 + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Limits applied to every test of the run. +// Ref: #/components/schemas/RunLimits +type RunLimits struct { + // CPU time per test, including interpreter startup, summed over every process of the test. The + // wall-clock limit is twice this value plus a fixed startup allowance. + TimeLimitMs int32 `json:"time_limit_ms"` + // Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit + // also leaves a small fixed allowance for the sandbox supervisor process. + MemoryLimitMB int32 `json:"memory_limit_mb"` + // Standard output per test in KiB. The test is stopped as soon as it writes more. + OutputLimitKB int32 `json:"output_limit_kb"` +} + +// GetTimeLimitMs returns the value of TimeLimitMs. +func (s *RunLimits) GetTimeLimitMs() int32 { + return s.TimeLimitMs +} + +// GetMemoryLimitMB returns the value of MemoryLimitMB. +func (s *RunLimits) GetMemoryLimitMB() int32 { + return s.MemoryLimitMB +} + +// GetOutputLimitKB returns the value of OutputLimitKB. +func (s *RunLimits) GetOutputLimitKB() int32 { + return s.OutputLimitKB +} + +// SetTimeLimitMs sets the value of TimeLimitMs. +func (s *RunLimits) SetTimeLimitMs(val int32) { + s.TimeLimitMs = val +} + +// SetMemoryLimitMB sets the value of MemoryLimitMB. +func (s *RunLimits) SetMemoryLimitMB(val int32) { + s.MemoryLimitMB = val +} + +// SetOutputLimitKB sets the value of OutputLimitKB. +func (s *RunLimits) SetOutputLimitKB(val int32) { + s.OutputLimitKB = val +} + +// Outcome of a test, a group, a compile step, or a whole run. +// +// - accepted: the program exited with status 0 within every limit and the checker accepted the +// output. +// - wrong_answer: the program exited with status 0 within every limit, but the checker rejected the +// output. +// - compile_error: the source was rejected before any test ran (for Python, a syntax error). +// - time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program. +// - memory_limit_exceeded: the cgroup memory limit stopped the program. +// - output_limit_exceeded: the program wrote more standard output than the limit. +// - runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the +// process limit. +// - infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about +// the program, and the caller may retry with a new run ID. +// +// A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome +// of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of +// its first failed test, otherwise accepted. +// Ref: #/components/schemas/RunOutcome +type RunOutcome string + +const ( + RunOutcomeAccepted RunOutcome = "accepted" + RunOutcomeWrongAnswer RunOutcome = "wrong_answer" + RunOutcomeCompileError RunOutcome = "compile_error" + RunOutcomeTimeLimitExceeded RunOutcome = "time_limit_exceeded" + RunOutcomeMemoryLimitExceeded RunOutcome = "memory_limit_exceeded" + RunOutcomeOutputLimitExceeded RunOutcome = "output_limit_exceeded" + RunOutcomeRuntimeError RunOutcome = "runtime_error" + RunOutcomeInfrastructureFailure RunOutcome = "infrastructure_failure" +) + +// AllValues returns all RunOutcome values. +func (RunOutcome) AllValues() []RunOutcome { + return []RunOutcome{ + RunOutcomeAccepted, + RunOutcomeWrongAnswer, + RunOutcomeCompileError, + RunOutcomeTimeLimitExceeded, + RunOutcomeMemoryLimitExceeded, + RunOutcomeOutputLimitExceeded, + RunOutcomeRuntimeError, + RunOutcomeInfrastructureFailure, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunOutcome) MarshalText() ([]byte, error) { + switch s { + case RunOutcomeAccepted: + return []byte(s), nil + case RunOutcomeWrongAnswer: + return []byte(s), nil + case RunOutcomeCompileError: + return []byte(s), nil + case RunOutcomeTimeLimitExceeded: + return []byte(s), nil + case RunOutcomeMemoryLimitExceeded: + return []byte(s), nil + case RunOutcomeOutputLimitExceeded: + return []byte(s), nil + case RunOutcomeRuntimeError: + return []byte(s), nil + case RunOutcomeInfrastructureFailure: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunOutcome) UnmarshalText(data []byte) error { + switch RunOutcome(data) { + case RunOutcomeAccepted: + *s = RunOutcomeAccepted + return nil + case RunOutcomeWrongAnswer: + *s = RunOutcomeWrongAnswer + return nil + case RunOutcomeCompileError: + *s = RunOutcomeCompileError + return nil + case RunOutcomeTimeLimitExceeded: + *s = RunOutcomeTimeLimitExceeded + return nil + case RunOutcomeMemoryLimitExceeded: + *s = RunOutcomeMemoryLimitExceeded + return nil + case RunOutcomeOutputLimitExceeded: + *s = RunOutcomeOutputLimitExceeded + return nil + case RunOutcomeRuntimeError: + *s = RunOutcomeRuntimeError + return nil + case RunOutcomeInfrastructureFailure: + *s = RunOutcomeInfrastructureFailure + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One source and its test groups. The request has no field for a candidate, account, attempt, task, or +// company; the backend maps a run ID to its own records. +// Ref: #/components/schemas/RunRequest +type RunRequest struct { + Language RunLanguage `json:"language"` + // Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and + // never logs it. + Source string `json:"source"` + Limits RunLimits `json:"limits"` + // Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are + // unique in a run. + Groups []TestGroup `json:"groups"` +} + +// GetLanguage returns the value of Language. +func (s *RunRequest) GetLanguage() RunLanguage { + return s.Language +} + +// GetSource returns the value of Source. +func (s *RunRequest) GetSource() string { + return s.Source +} + +// GetLimits returns the value of Limits. +func (s *RunRequest) GetLimits() RunLimits { + return s.Limits +} + +// GetGroups returns the value of Groups. +func (s *RunRequest) GetGroups() []TestGroup { + return s.Groups +} + +// SetLanguage sets the value of Language. +func (s *RunRequest) SetLanguage(val RunLanguage) { + s.Language = val +} + +// SetSource sets the value of Source. +func (s *RunRequest) SetSource(val string) { + s.Source = val +} + +// SetLimits sets the value of Limits. +func (s *RunRequest) SetLimits(val RunLimits) { + s.Limits = val +} + +// SetGroups sets the value of Groups. +func (s *RunRequest) SetGroups(val []TestGroup) { + s.Groups = val +} + +// Ref: #/components/schemas/RunResult +type RunResult struct { + Outcome RunOutcome `json:"outcome"` + Compile OptCompileResult `json:"compile"` + // One result per requested group in request order. After compile_error or infrastructure_failure every + // group has that outcome and no tests. + Groups []GroupResult `json:"groups"` + // Wall-clock time of the whole run in the runner. + DurationMs int64 `json:"duration_ms"` +} + +// GetOutcome returns the value of Outcome. +func (s *RunResult) GetOutcome() RunOutcome { + return s.Outcome +} + +// GetCompile returns the value of Compile. +func (s *RunResult) GetCompile() OptCompileResult { + return s.Compile +} + +// GetGroups returns the value of Groups. +func (s *RunResult) GetGroups() []GroupResult { + return s.Groups +} + +// GetDurationMs returns the value of DurationMs. +func (s *RunResult) GetDurationMs() int64 { + return s.DurationMs +} + +// SetOutcome sets the value of Outcome. +func (s *RunResult) SetOutcome(val RunOutcome) { + s.Outcome = val +} + +// SetCompile sets the value of Compile. +func (s *RunResult) SetCompile(val OptCompileResult) { + s.Compile = val +} + +// SetGroups sets the value of Groups. +func (s *RunResult) SetGroups(val []GroupResult) { + s.Groups = val +} + +// SetDurationMs sets the value of DurationMs. +func (s *RunResult) SetDurationMs(val int64) { + s.DurationMs = val +} + +// `running` until every group was evaluated or the run failed; `finished` when `result` is final. +// Ref: #/components/schemas/RunState +type RunState string + +const ( + RunStateRunning RunState = "running" + RunStateFinished RunState = "finished" +) + +// AllValues returns all RunState values. +func (RunState) AllValues() []RunState { + return []RunState{ + RunStateRunning, + RunStateFinished, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunState) MarshalText() ([]byte, error) { + switch s { + case RunStateRunning: + return []byte(s), nil + case RunStateFinished: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunState) UnmarshalText(data []byte) error { + switch RunState(data) { + case RunStateRunning: + *s = RunStateRunning + return nil + case RunStateFinished: + *s = RunStateFinished + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/RunStatus +type RunStatus struct { + RunID uuid.UUID `json:"run_id"` + State RunState `json:"state"` + Result OptRunResult `json:"result"` +} + +// GetRunID returns the value of RunID. +func (s *RunStatus) GetRunID() uuid.UUID { + return s.RunID +} + +// GetState returns the value of State. +func (s *RunStatus) GetState() RunState { + return s.State +} + +// GetResult returns the value of Result. +func (s *RunStatus) GetResult() OptRunResult { + return s.Result +} + +// SetRunID sets the value of RunID. +func (s *RunStatus) SetRunID(val uuid.UUID) { + s.RunID = val +} + +// SetState sets the value of State. +func (s *RunStatus) SetState(val RunState) { + s.State = val +} + +// SetResult sets the value of Result. +func (s *RunStatus) SetResult(val OptRunResult) { + s.Result = val +} + +// RunnerBusyHeaders wraps Problem with response headers. +type RunnerBusyHeaders struct { + RetryAfter int32 + Response Problem +} + +// GetRetryAfter returns the value of RetryAfter. +func (s *RunnerBusyHeaders) GetRetryAfter() int32 { + return s.RetryAfter +} + +// GetResponse returns the value of Response. +func (s *RunnerBusyHeaders) GetResponse() Problem { + return s.Response +} + +// SetRetryAfter sets the value of RetryAfter. +func (s *RunnerBusyHeaders) SetRetryAfter(val int32) { + s.RetryAfter = val +} + +// SetResponse sets the value of Response. +func (s *RunnerBusyHeaders) SetResponse(val Problem) { + s.Response = val +} + +func (*RunnerBusyHeaders) submitRunRes() {} + +// Ref: #/components/schemas/RunnerHealthResponse +type RunnerHealthResponse struct { + Status RunnerHealthResponseStatus `json:"status"` +} + +// GetStatus returns the value of Status. +func (s *RunnerHealthResponse) GetStatus() RunnerHealthResponseStatus { + return s.Status +} + +// SetStatus sets the value of Status. +func (s *RunnerHealthResponse) SetStatus(val RunnerHealthResponseStatus) { + s.Status = val +} + +type RunnerHealthResponseStatus string + +const ( + RunnerHealthResponseStatusOk RunnerHealthResponseStatus = "ok" +) + +// AllValues returns all RunnerHealthResponseStatus values. +func (RunnerHealthResponseStatus) AllValues() []RunnerHealthResponseStatus { + return []RunnerHealthResponseStatus{ + RunnerHealthResponseStatusOk, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunnerHealthResponseStatus) MarshalText() ([]byte, error) { + switch s { + case RunnerHealthResponseStatusOk: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunnerHealthResponseStatus) UnmarshalText(data []byte) error { + switch RunnerHealthResponseStatus(data) { + case RunnerHealthResponseStatusOk: + *s = RunnerHealthResponseStatusOk + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/RunnerReadinessResponse +type RunnerReadinessResponse struct { + Status RunnerReadinessResponseStatus `json:"status"` +} + +// GetStatus returns the value of Status. +func (s *RunnerReadinessResponse) GetStatus() RunnerReadinessResponseStatus { + return s.Status +} + +// SetStatus sets the value of Status. +func (s *RunnerReadinessResponse) SetStatus(val RunnerReadinessResponseStatus) { + s.Status = val +} + +type RunnerReadinessResponseStatus string + +const ( + RunnerReadinessResponseStatusReady RunnerReadinessResponseStatus = "ready" + RunnerReadinessResponseStatusNotReady RunnerReadinessResponseStatus = "not_ready" +) + +// AllValues returns all RunnerReadinessResponseStatus values. +func (RunnerReadinessResponseStatus) AllValues() []RunnerReadinessResponseStatus { + return []RunnerReadinessResponseStatus{ + RunnerReadinessResponseStatusReady, + RunnerReadinessResponseStatusNotReady, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s RunnerReadinessResponseStatus) MarshalText() ([]byte, error) { + switch s { + case RunnerReadinessResponseStatusReady: + return []byte(s), nil + case RunnerReadinessResponseStatusNotReady: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *RunnerReadinessResponseStatus) UnmarshalText(data []byte) error { + switch RunnerReadinessResponseStatus(data) { + case RunnerReadinessResponseStatusReady: + *s = RunnerReadinessResponseStatusReady + return nil + case RunnerReadinessResponseStatusNotReady: + *s = RunnerReadinessResponseStatusNotReady + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type SubmitRunAccepted RunStatus + +func (*SubmitRunAccepted) submitRunRes() {} + +type SubmitRunOK RunStatus + +func (*SubmitRunOK) submitRunRes() {} + +// The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of +// processes and threads. +// Ref: #/components/schemas/TerminationLimit +type TerminationLimit string + +const ( + TerminationLimitCPUTime TerminationLimit = "cpu_time" + TerminationLimitWallTime TerminationLimit = "wall_time" + TerminationLimitMemory TerminationLimit = "memory" + TerminationLimitOutput TerminationLimit = "output" + TerminationLimitProcesses TerminationLimit = "processes" +) + +// AllValues returns all TerminationLimit values. +func (TerminationLimit) AllValues() []TerminationLimit { + return []TerminationLimit{ + TerminationLimitCPUTime, + TerminationLimitWallTime, + TerminationLimitMemory, + TerminationLimitOutput, + TerminationLimitProcesses, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s TerminationLimit) MarshalText() ([]byte, error) { + switch s { + case TerminationLimitCPUTime: + return []byte(s), nil + case TerminationLimitWallTime: + return []byte(s), nil + case TerminationLimitMemory: + return []byte(s), nil + case TerminationLimitOutput: + return []byte(s), nil + case TerminationLimitProcesses: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *TerminationLimit) UnmarshalText(data []byte) error { + switch TerminationLimit(data) { + case TerminationLimitCPUTime: + *s = TerminationLimitCPUTime + return nil + case TerminationLimitWallTime: + *s = TerminationLimitWallTime + return nil + case TerminationLimitMemory: + *s = TerminationLimitMemory + return nil + case TerminationLimitOutput: + *s = TerminationLimitOutput + return nil + case TerminationLimitProcesses: + *s = TerminationLimitProcesses + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/TestCase +type TestCase struct { + ID TestKey `json:"id"` + // UTF-8 text written to the standard input of the program. + Input string `json:"input"` + // UTF-8 text the checker compares with the standard output. + ExpectedOutput string `json:"expected_output"` +} + +// GetID returns the value of ID. +func (s *TestCase) GetID() TestKey { + return s.ID +} + +// GetInput returns the value of Input. +func (s *TestCase) GetInput() string { + return s.Input +} + +// GetExpectedOutput returns the value of ExpectedOutput. +func (s *TestCase) GetExpectedOutput() string { + return s.ExpectedOutput +} + +// SetID sets the value of ID. +func (s *TestCase) SetID(val TestKey) { + s.ID = val +} + +// SetInput sets the value of Input. +func (s *TestCase) SetInput(val string) { + s.Input = val +} + +// SetExpectedOutput sets the value of ExpectedOutput. +func (s *TestCase) SetExpectedOutput(val string) { + s.ExpectedOutput = val +} + +// Ref: #/components/schemas/TestGroup +type TestGroup struct { + ID TestKey `json:"id"` + Visibility TestVisibility `json:"visibility"` + Checker Checker `json:"checker"` + // Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test. + Tests []TestCase `json:"tests"` +} + +// GetID returns the value of ID. +func (s *TestGroup) GetID() TestKey { + return s.ID +} + +// GetVisibility returns the value of Visibility. +func (s *TestGroup) GetVisibility() TestVisibility { + return s.Visibility +} + +// GetChecker returns the value of Checker. +func (s *TestGroup) GetChecker() Checker { + return s.Checker +} + +// GetTests returns the value of Tests. +func (s *TestGroup) GetTests() []TestCase { + return s.Tests +} + +// SetID sets the value of ID. +func (s *TestGroup) SetID(val TestKey) { + s.ID = val +} + +// SetVisibility sets the value of Visibility. +func (s *TestGroup) SetVisibility(val TestVisibility) { + s.Visibility = val +} + +// SetChecker sets the value of Checker. +func (s *TestGroup) SetChecker(val Checker) { + s.Checker = val +} + +// SetTests sets the value of Tests. +func (s *TestGroup) SetTests(val []TestCase) { + s.Tests = val +} + +type TestKey string + +// Ref: #/components/schemas/TestResult +type TestResult struct { + ID TestKey `json:"id"` + Outcome RunOutcome `json:"outcome"` + // CPU time of every process of the test. + TimeMs int64 `json:"time_ms"` + WallTimeMs int64 `json:"wall_time_ms"` + // Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including + // the sandbox supervisor process and file cache charged to the test. + MemoryKB int64 `json:"memory_kb"` + // Exit status when the program exited normally. + ExitCode OptInt32 `json:"exit_code"` + // Signal number when the program was killed by a signal. + Signal OptInt32 `json:"signal"` + Limit OptTerminationLimit `json:"limit"` + // Truncated standard error of a failed public test. Hidden tests never carry it. + Diagnostic OptString `json:"diagnostic"` +} + +// GetID returns the value of ID. +func (s *TestResult) GetID() TestKey { + return s.ID +} + +// GetOutcome returns the value of Outcome. +func (s *TestResult) GetOutcome() RunOutcome { + return s.Outcome +} + +// GetTimeMs returns the value of TimeMs. +func (s *TestResult) GetTimeMs() int64 { + return s.TimeMs +} + +// GetWallTimeMs returns the value of WallTimeMs. +func (s *TestResult) GetWallTimeMs() int64 { + return s.WallTimeMs +} + +// GetMemoryKB returns the value of MemoryKB. +func (s *TestResult) GetMemoryKB() int64 { + return s.MemoryKB +} + +// GetExitCode returns the value of ExitCode. +func (s *TestResult) GetExitCode() OptInt32 { + return s.ExitCode +} + +// GetSignal returns the value of Signal. +func (s *TestResult) GetSignal() OptInt32 { + return s.Signal +} + +// GetLimit returns the value of Limit. +func (s *TestResult) GetLimit() OptTerminationLimit { + return s.Limit +} + +// GetDiagnostic returns the value of Diagnostic. +func (s *TestResult) GetDiagnostic() OptString { + return s.Diagnostic +} + +// SetID sets the value of ID. +func (s *TestResult) SetID(val TestKey) { + s.ID = val +} + +// SetOutcome sets the value of Outcome. +func (s *TestResult) SetOutcome(val RunOutcome) { + s.Outcome = val +} + +// SetTimeMs sets the value of TimeMs. +func (s *TestResult) SetTimeMs(val int64) { + s.TimeMs = val +} + +// SetWallTimeMs sets the value of WallTimeMs. +func (s *TestResult) SetWallTimeMs(val int64) { + s.WallTimeMs = val +} + +// SetMemoryKB sets the value of MemoryKB. +func (s *TestResult) SetMemoryKB(val int64) { + s.MemoryKB = val +} + +// SetExitCode sets the value of ExitCode. +func (s *TestResult) SetExitCode(val OptInt32) { + s.ExitCode = val +} + +// SetSignal sets the value of Signal. +func (s *TestResult) SetSignal(val OptInt32) { + s.Signal = val +} + +// SetLimit sets the value of Limit. +func (s *TestResult) SetLimit(val OptTerminationLimit) { + s.Limit = val +} + +// SetDiagnostic sets the value of Diagnostic. +func (s *TestResult) SetDiagnostic(val OptString) { + s.Diagnostic = val +} + +// `public` tests may be shown to the person who wrote the source; their results may carry a diagnostic +// excerpt. `hidden` results never carry program output or diagnostics. +// Ref: #/components/schemas/TestVisibility +type TestVisibility string + +const ( + TestVisibilityPublic TestVisibility = "public" + TestVisibilityHidden TestVisibility = "hidden" +) + +// AllValues returns all TestVisibility values. +func (TestVisibility) AllValues() []TestVisibility { + return []TestVisibility{ + TestVisibilityPublic, + TestVisibilityHidden, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s TestVisibility) MarshalText() ([]byte, error) { + switch s { + case TestVisibilityPublic: + return []byte(s), nil + case TestVisibilityHidden: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *TestVisibility) UnmarshalText(data []byte) error { + switch TestVisibility(data) { + case TestVisibilityPublic: + *s = TestVisibilityPublic + return nil + case TestVisibilityHidden: + *s = TestVisibilityHidden + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} diff --git a/runner/internal/api/oas_security_gen.go b/runner/internal/api/oas_security_gen.go new file mode 100644 index 0000000..63ffd59 --- /dev/null +++ b/runner/internal/api/oas_security_gen.go @@ -0,0 +1,80 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" + "net/http" + "strings" + + "github.com/go-faster/errors" + "github.com/ogen-go/ogen/ogenerrors" +) + +// SecurityHandler is handler for security parameters. +type SecurityHandler interface { + // HandleBearerAuth handles bearerAuth security. + // Shared random service token sent as `Authorization: Bearer ` over TLS. The runner compares it + // in constant time and never logs it. Rotation replaces the secret on both sides; there are no + // per-user tokens. + HandleBearerAuth(ctx context.Context, operationName OperationName, t BearerAuth) (context.Context, error) +} + +func findAuthorization(h http.Header, prefix string) (string, bool) { + v, ok := h["Authorization"] + if !ok { + return "", false + } + for _, vv := range v { + scheme, value, ok := strings.Cut(vv, " ") + if !ok || !strings.EqualFold(scheme, prefix) { + continue + } + return value, true + } + return "", false +} + +// operationRolesBearerAuth is a private map storing roles per operation. +var operationRolesBearerAuth = map[string][]string{ + GetRunOperation: []string{}, + SubmitRunOperation: []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 *Server) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) { + var t BearerAuth + token, ok := findAuthorization(req.Header, "Bearer") + if !ok { + return ctx, false, nil + } + t.Token = token + t.Roles = operationRolesBearerAuth[operationName] + rctx, err := s.sec.HandleBearerAuth(ctx, operationName, t) + if errors.Is(err, ogenerrors.ErrSkipServerSecurity) { + return nil, false, nil + } else if err != nil { + return nil, false, err + } + return rctx, true, err +} diff --git a/runner/internal/api/oas_server_gen.go b/runner/internal/api/oas_server_gen.go new file mode 100644 index 0000000..87d0791 --- /dev/null +++ b/runner/internal/api/oas_server_gen.go @@ -0,0 +1,77 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" +) + +// Handler handles operations described by OpenAPI v3 specification. +type Handler interface { + // GetRun implements GetRun operation. + // + // Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its + // retention time or lost in a restart. + // + // GET /v1/runs/{run_id} + GetRun(ctx context.Context, params GetRunParams) (*RunStatus, error) + // GetRunnerHealthz implements GetRunnerHealthz operation. + // + // Check whether the runner process is responding. + // + // GET /healthz + GetRunnerHealthz(ctx context.Context) (*RunnerHealthResponse, error) + // GetRunnerReadyz implements GetRunnerReadyz operation. + // + // Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at + // startup and the process is not draining. A busy runner is still ready; busy is reported by + // SubmitRun. + // + // GET /readyz + GetRunnerReadyz(ctx context.Context) (GetRunnerReadyzRes, error) + // SubmitRun implements SubmitRun operation. + // + // Idempotent by `run_id`: + // + // - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`; + // - the same ID with the same payload answers 200 with the current state of that run, including the + // finished result, without running it again; + // - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + // - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_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. The runner keeps runs only in + // memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a + // new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`. + // Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique + // in a run, test IDs are unique in a group, and the number of tests multiplied by + // `limits.time_limit_ms` does not exceed 300000. + // + // PUT /v1/runs/{run_id} + SubmitRun(ctx context.Context, req *RunRequest, params SubmitRunParams) (SubmitRunRes, error) + // NewError creates *ProblemStatusCode from error returned by handler. + // + // Used for common default response. + NewError(ctx context.Context, err error) *ProblemStatusCode +} + +// Server implements http server based on OpenAPI v3 specification and +// calls Handler to handle requests. +type Server struct { + h Handler + sec SecurityHandler + baseServer +} + +// NewServer creates new Server. +func NewServer(h Handler, sec SecurityHandler, opts ...ServerOption) (*Server, error) { + s, err := newServerConfig(opts...).baseServer() + if err != nil { + return nil, err + } + return &Server{ + h: h, + sec: sec, + baseServer: s, + }, nil +} diff --git a/runner/internal/api/oas_unimplemented_gen.go b/runner/internal/api/oas_unimplemented_gen.go new file mode 100644 index 0000000..7946562 --- /dev/null +++ b/runner/internal/api/oas_unimplemented_gen.go @@ -0,0 +1,75 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" + + ht "github.com/ogen-go/ogen/http" +) + +// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented. +type UnimplementedHandler struct{} + +var _ Handler = UnimplementedHandler{} + +// GetRun implements GetRun operation. +// +// Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its +// retention time or lost in a restart. +// +// GET /v1/runs/{run_id} +func (UnimplementedHandler) GetRun(ctx context.Context, params GetRunParams) (r *RunStatus, _ error) { + return r, ht.ErrNotImplemented +} + +// GetRunnerHealthz implements GetRunnerHealthz operation. +// +// Check whether the runner process is responding. +// +// GET /healthz +func (UnimplementedHandler) GetRunnerHealthz(ctx context.Context) (r *RunnerHealthResponse, _ error) { + return r, ht.ErrNotImplemented +} + +// GetRunnerReadyz implements GetRunnerReadyz operation. +// +// Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at +// startup and the process is not draining. A busy runner is still ready; busy is reported by +// SubmitRun. +// +// GET /readyz +func (UnimplementedHandler) GetRunnerReadyz(ctx context.Context) (r GetRunnerReadyzRes, _ error) { + return r, ht.ErrNotImplemented +} + +// SubmitRun implements SubmitRun operation. +// +// Idempotent by `run_id`: +// +// - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`; +// - the same ID with the same payload answers 200 with the current state of that run, including the +// finished result, without running it again; +// - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; +// - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_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. The runner keeps runs only in +// memory for a bounded time after they finish; an ID that was forgotten or lost in a restart starts a +// new run. Requests above the configured body limit (8 MiB by default) answer 413 `payload_too_large`. +// Semantic rules that the schema cannot express answer 400 `validation_failed`: group IDs are unique +// in a run, test IDs are unique in a group, and the number of tests multiplied by +// `limits.time_limit_ms` does not exceed 300000. +// +// PUT /v1/runs/{run_id} +func (UnimplementedHandler) SubmitRun(ctx context.Context, req *RunRequest, params SubmitRunParams) (r SubmitRunRes, _ error) { + return r, ht.ErrNotImplemented +} + +// NewError creates *ProblemStatusCode from error returned by handler. +// +// Used for common default response. +func (UnimplementedHandler) NewError(ctx context.Context, err error) (r *ProblemStatusCode) { + r = new(ProblemStatusCode) + return r +} diff --git a/runner/internal/api/oas_validators_gen.go b/runner/internal/api/oas_validators_gen.go new file mode 100644 index 0000000..a84d549 --- /dev/null +++ b/runner/internal/api/oas_validators_gen.go @@ -0,0 +1,1512 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "fmt" + + "github.com/go-faster/errors" + "github.com/ogen-go/ogen/validate" +) + +func (s *Checker) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s CheckerKind) Validate() error { + switch s { + case "exact": + return nil + case "tokens": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *CompileResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Diagnostic.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 4096, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "diagnostic", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *GetRunnerReadyzOK) Validate() error { + alias := (*RunnerReadinessResponse)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetRunnerReadyzServiceUnavailable) Validate() error { + alias := (*RunnerReadinessResponse)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GroupResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if err := func() error { + if err := s.Visibility.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "visibility", + Error: err, + }) + } + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 50, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.PassedTests)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "passed_tests", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 50, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TotalTests)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "total_tests", + Error: err, + }) + } + if err := func() error { + if value, ok := s.MaxTimeMs.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_time_ms", + Error: err, + }) + } + if err := func() error { + if value, ok := s.MaxMemoryKB.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "max_memory_kb", + Error: err, + }) + } + if err := func() error { + if s.Tests == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 50, + MaxLengthSet: true, + }).ValidateLength(len(s.Tests)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Tests { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "tests", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *Problem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 256, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Type)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 400, + MaxSet: true, + Max: 599, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Status)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Detail.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "detail", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Instance.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2048, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "instance", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TraceID.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "trace_id", + Error: err, + }) + } + if err := func() error { + if s.Errors == nil { + return nil // optional + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Errors)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Errors { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "errors", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemCode) Validate() error { + switch s { + case "validation_failed": + return nil + case "unauthenticated": + return nil + case "not_found": + return nil + case "method_not_allowed": + return nil + case "payload_too_large": + return nil + case "unsupported_media_type": + return nil + case "idempotency_key_reused": + return nil + case "internal": + return nil + case "runner_busy": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemFieldError) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.In.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "in", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1024, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^(/([^~/]|~[01])*)*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Pointer)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "pointer", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z][a-z0-9_]*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Code)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 500, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Message)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "message", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemFieldLocation) Validate() error { + switch s { + case "body": + return nil + case "query": + return nil + case "path": + return nil + case "header": + return nil + case "cookie": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemStatusCode) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunLanguage) Validate() error { + switch s { + case "python3": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *RunLimits) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 100, + MaxSet: true, + Max: 10000, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TimeLimitMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "time_limit_ms", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 32, + MaxSet: true, + Max: 512, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MemoryLimitMB)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "memory_limit_mb", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 1024, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.OutputLimitKB)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "output_limit_kb", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunOutcome) Validate() error { + switch s { + case "accepted": + return nil + case "wrong_answer": + return nil + case "compile_error": + return nil + case "time_limit_exceeded": + return nil + case "memory_limit_exceeded": + return nil + case "output_limit_exceeded": + return nil + case "runtime_error": + return nil + case "infrastructure_failure": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *RunRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Language.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "language", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 65536, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Source)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if err := func() error { + if err := s.Limits.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "limits", + Error: err, + }) + } + if err := func() error { + if s.Groups == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.Groups)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Groups { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "groups", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *RunResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Compile.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: "compile", + Error: err, + }) + } + if err := func() error { + if s.Groups == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.Groups)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Groups { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "groups", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.DurationMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "duration_ms", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunState) Validate() error { + switch s { + case "running": + return nil + case "finished": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *RunStatus) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Result.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "result", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *RunnerBusyHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 3600, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.RetryAfter)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "RetryAfter", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *RunnerHealthResponse) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunnerHealthResponseStatus) Validate() error { + switch s { + case "ok": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *RunnerReadinessResponse) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s RunnerReadinessResponseStatus) Validate() error { + switch s { + case "ready": + return nil + case "not_ready": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SubmitRunAccepted) Validate() error { + alias := (*RunStatus)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SubmitRunOK) Validate() error { + alias := (*RunStatus)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s TerminationLimit) Validate() error { + switch s { + case "cpu_time": + return nil + case "wall_time": + return nil + case "memory": + return nil + case "output": + return nil + case "processes": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *TestCase) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 262144, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Input)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "input", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 262144, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.ExpectedOutput)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_output", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *TestGroup) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if err := func() error { + if err := s.Visibility.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "visibility", + Error: err, + }) + } + if err := func() error { + if err := s.Checker.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "checker", + Error: err, + }) + } + if err := func() error { + if s.Tests == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 50, + MaxLengthSet: true, + }).ValidateLength(len(s.Tests)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Tests { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "tests", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s TestKey) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 32, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z0-9][a-z0-9_-]{0,31}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *TestResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ID.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "id", + Error: err, + }) + } + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.TimeMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "time_ms", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.WallTimeMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "wall_time_ms", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.MemoryKB)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "memory_kb", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Signal.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 64, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "signal", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Limit.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: "limit", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Diagnostic.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2048, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "diagnostic", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s TestVisibility) Validate() error { + switch s { + case "public": + return nil + case "hidden": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} diff --git a/runner/internal/app/app.go b/runner/internal/app/app.go new file mode 100644 index 0000000..3f710ab --- /dev/null +++ b/runner/internal/app/app.go @@ -0,0 +1,189 @@ +// Package app wires the runner and controls its lifecycle. +package app + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/runner/internal/config" + "lincodex/runner/internal/jobs" + "lincodex/runner/internal/judge" + "lincodex/runner/internal/sandbox" + "lincodex/runner/internal/server" +) + +// HTTP server bounds. Request bodies are bounded separately by +// RUNNER_MAX_REQUEST_BYTES. +const ( + readHeaderTimeout = 5 * time.Second + readTimeout = 30 * time.Second + writeTimeout = 30 * time.Second + idleTimeout = 60 * time.Second + maxHeaderBytes = 16 << 10 + healthcheckWait = 2 * time.Second +) + +// Sandbox settings that belong to the runner image rather than to a +// deployment. +const ( + stderrCaptureBytes = 16 << 10 + pollInterval = 10 * time.Millisecond +) + +// sandboxMounts are the read-only host paths the interpreter needs: the +// Python installation under /usr/local and the musl loader and libraries. +var sandboxMounts = []string{"/usr", "/lib"} + +// sandboxEnv is the whole environment of a jailed program. +var sandboxEnv = []string{ + "PATH=/usr/local/bin:/usr/bin:/bin", + "HOME=" + sandbox.ScratchPath, + "LANG=C.UTF-8", + "PYTHONIOENCODING=utf-8", + "PYTHONDONTWRITEBYTECODE=1", +} + +// Run starts the runner and blocks until SIGINT or SIGTERM. +func Run() error { + cfg, err := config.Load() + if err != nil { + return err + } + logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel})) + + executor, err := sandbox.New(SandboxConfig(cfg)) + if err != nil { + return fmt.Errorf("app.Run - prepare sandbox: %w", err) + } + evaluator := judge.New(executor, logger, judge.Python3(cfg.PythonPath)) + manager, err := jobs.NewManager(jobs.Config{ + MaxConcurrent: cfg.MaxConcurrentRuns, + ResultTTL: cfg.ResultTTL, + MaxRetained: cfg.MaxRetainedRuns, + }, evaluator, logger) + if err != nil { + return err + } + handler := server.NewHandler(manager, evaluator.Supports, func() bool { return !manager.Draining() }, cfg.RetryAfter, logger) + httpHandler, err := server.New(handler, cfg.APIToken, cfg.MaxRequestBytes, logger) + if err != nil { + return err + } + + httpServer := &http.Server{ + Addr: cfg.ListenAddress, + Handler: httpHandler, + ReadHeaderTimeout: readHeaderTimeout, + ReadTimeout: readTimeout, + WriteTimeout: writeTimeout, + IdleTimeout: idleTimeout, + MaxHeaderBytes: maxHeaderBytes, + TLSConfig: &tls.Config{MinVersion: tls.VersionTLS13}, + ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn), + } + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + serveErr := make(chan error, 1) + go func() { + serveErr <- serve(httpServer, cfg, logger) + }() + logger.InfoContext(ctx, "runner started", + slog.String("address", cfg.ListenAddress), + slog.Bool("tls", !cfg.AllowPlaintextHTTP), + slog.Int("max_concurrent_runs", cfg.MaxConcurrentRuns), + ) + + select { + case err := <-serveErr: + return errors.Join(err, manager.Close(context.Background())) + case <-ctx.Done(): + } + logger.InfoContext(ctx, "runner stopping") + shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) + defer cancel() + return errors.Join(httpServer.Shutdown(shutdownCtx), manager.Close(shutdownCtx)) +} + +func serve(httpServer *http.Server, cfg config.Config, logger *slog.Logger) error { + var err error + if cfg.AllowPlaintextHTTP { + logger.Warn("serving plaintext HTTP; this switch is for local development only") + err = httpServer.ListenAndServe() + } else { + err = httpServer.ListenAndServeTLS(cfg.TLSCertFile, cfg.TLSKeyFile) + } + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return fmt.Errorf("app.serve - listen: %w", err) +} + +// SandboxConfig returns the sandbox settings of the runner for cfg. +func SandboxConfig(cfg config.Config) sandbox.Config { + return sandbox.Config{ + NsjailPath: cfg.NsjailPath, + CgroupRoot: cfg.CgroupRoot, + WorkRoot: cfg.WorkDir, + SandboxUID: cfg.SandboxUID, + SandboxGID: cfg.SandboxUID, + MaxProcesses: cfg.MaxProcesses, + MemoryOverheadBytes: cfg.MemoryOverheadBytes, + TmpfsBytes: cfg.TmpfsBytes, + FileSizeBytes: cfg.FileSizeBytes, + OpenFiles: cfg.OpenFiles, + StderrCaptureBytes: stderrCaptureBytes, + ReadOnlyMounts: sandboxMounts, + Env: sandboxEnv, + PollInterval: pollInterval, + } +} + +// Healthcheck requests /healthz of the local process and returns the exit +// status for a container health check. It sends no token. +func Healthcheck() int { + cfg, err := config.Load() + if err != nil { + return 1 + } + _, port, err := net.SplitHostPort(cfg.ListenAddress) + if err != nil { + return 1 + } + scheme := "https" + if cfg.AllowPlaintextHTTP { + scheme = "http" + } + client := &http.Client{ + Timeout: healthcheckWait, + Transport: &http.Transport{ + // The probe talks to its own process over loopback and sends no + // secret; the certificate names the private host, not 127.0.0.1. + TLSClientConfig: &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS13}, //nolint:gosec // Loopback liveness probe only. + }, + } + ctx, cancel := context.WithTimeout(context.Background(), healthcheckWait) + defer cancel() + request, err := http.NewRequestWithContext(ctx, http.MethodGet, scheme+"://"+net.JoinHostPort("127.0.0.1", port)+"/healthz", http.NoBody) + if err != nil { + return 1 + } + response, err := client.Do(request) + if err != nil { + return 1 + } + _ = response.Body.Close() // Only the status matters. + if response.StatusCode != http.StatusOK { + return 1 + } + return 0 +} diff --git a/runner/internal/checker/checker.go b/runner/internal/checker/checker.go new file mode 100644 index 0000000..3c71f90 --- /dev/null +++ b/runner/internal/checker/checker.go @@ -0,0 +1,93 @@ +// Package checker compares the output of a sandboxed program with the expected +// output of a test. +// +// A checker is selected by a Spec. Kinds that need parameters, such as a float +// tolerance, add fields to Spec; kinds that need to run code, such as a custom +// checker program, implement Checker with their own sandbox and use the +// context and the error result for cancellation and infrastructure failures. +package checker + +import ( + "bytes" + "context" + "fmt" +) + +// Kind names a comparison rule of the runner contract. +type Kind string + +const ( + // Exact accepts texts that are equal after line-ending and trailing + // whitespace normalization. + Exact Kind = "exact" + // Tokens accepts texts with the same sequence of whitespace-separated + // tokens. + Tokens Kind = "tokens" +) + +// Spec selects and parameterizes a checker. +type Spec struct { + Kind Kind `json:"kind"` +} + +// Input is everything a checker may look at for one test. +type Input struct { + TestInput []byte + Expected []byte + Actual []byte +} + +// Checker decides whether the actual output of a test is accepted. +type Checker interface { + // Check reports whether the output is accepted. An error means that the + // checker itself failed, not that the output is wrong. + Check(ctx context.Context, input Input) (bool, error) +} + +// New returns the checker for spec. +func New(spec Spec) (Checker, error) { + switch spec.Kind { + case Exact: + return exactChecker{}, nil + case Tokens: + return tokensChecker{}, nil + default: + return nil, fmt.Errorf("checker.New - unknown kind %q", spec.Kind) + } +} + +type exactChecker struct{} + +func (exactChecker) Check(_ context.Context, input Input) (bool, error) { + return bytes.Equal(normalizeLines(input.Expected), normalizeLines(input.Actual)), nil +} + +type tokensChecker struct{} + +func (tokensChecker) Check(_ context.Context, input Input) (bool, error) { + expected := bytes.Fields(input.Expected) + actual := bytes.Fields(input.Actual) + if len(expected) != len(actual) { + return false, nil + } + for index := range expected { + if !bytes.Equal(expected[index], actual[index]) { + return false, nil + } + } + return true, nil +} + +// normalizeLines replaces CRLF with LF, removes spaces and tabs at the end of +// every line, and removes trailing empty lines. +func normalizeLines(text []byte) []byte { + lines := bytes.Split(bytes.ReplaceAll(text, []byte("\r\n"), []byte("\n")), []byte("\n")) + for index, line := range lines { + lines[index] = bytes.TrimRight(line, " \t") + } + last := len(lines) + for last > 0 && len(lines[last-1]) == 0 { + last-- + } + return bytes.Join(lines[:last], []byte("\n")) +} diff --git a/runner/internal/checker/checker_test.go b/runner/internal/checker/checker_test.go new file mode 100644 index 0000000..45bae4c --- /dev/null +++ b/runner/internal/checker/checker_test.go @@ -0,0 +1,53 @@ +package checker + +import ( + "testing" +) + +func TestCheckersCompareOutput(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + kind Kind + expected string + actual string + accepted bool + }{ + {"exact equal", Exact, "6\n", "6\n", true}, + {"exact missing final newline", Exact, "6\n", "6", true}, + {"exact CRLF and trailing spaces", Exact, "1 2\n3\n", "1 2 \r\n3\t\r\n\r\n", true}, + {"exact inner spaces matter", Exact, "1 2\n", "1 2\n", false}, + {"exact leading empty line matters", Exact, "1\n", "\n1\n", false}, + {"exact different value", Exact, "6\n", "7\n", false}, + {"exact empty output", Exact, "", "\n\n", true}, + {"tokens ignore layout", Tokens, "1 2\n3\n", "1\n2 3", true}, + {"tokens different count", Tokens, "1 2 3", "1 2", false}, + {"tokens different token", Tokens, "1 2 3", "1 2 4", false}, + {"tokens are case sensitive", Tokens, "Yes", "yes", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + check, err := New(Spec{Kind: tc.kind}) + if err != nil { + t.Fatalf("New: %v", err) + } + accepted, err := check.Check(t.Context(), Input{Expected: []byte(tc.expected), Actual: []byte(tc.actual)}) + if err != nil { + t.Fatalf("Check: %v", err) + } + if accepted != tc.accepted { + t.Fatalf("Check(%q, %q) = %v, want %v", tc.expected, tc.actual, accepted, tc.accepted) + } + }) + } +} + +func TestNewRejectsUnknownKind(t *testing.T) { + t.Parallel() + + if _, err := New(Spec{Kind: "float"}); err == nil { + t.Fatal("New accepted an unknown checker kind") + } +} diff --git a/runner/internal/config/config.go b/runner/internal/config/config.go new file mode 100644 index 0000000..2f0b13a --- /dev/null +++ b/runner/internal/config/config.go @@ -0,0 +1,266 @@ +// Package config reads the runner configuration from the environment. +package config + +import ( + "errors" + "fmt" + "log/slog" + "os" + "strconv" + "strings" + "time" +) + +// Defaults of the runner settings. +const ( + DefaultListenAddress = ":8443" + DefaultMaxConcurrentRuns = 1 + DefaultMaxRequestBytes = 8 << 20 + DefaultResultTTL = 15 * time.Minute + DefaultMaxRetainedRuns = 256 + DefaultWorkDir = "/var/lib/lincodex-runner/work" + DefaultCgroupRoot = "/sys/fs/cgroup" + DefaultNsjailPath = "/usr/bin/nsjail" + DefaultPythonPath = "/usr/local/bin/python3" + DefaultSandboxUID = 99999 + DefaultMaxProcesses = 16 + DefaultMemoryOverheadBytes = 4 << 20 + DefaultTmpfsBytes = 16 << 20 + DefaultFileSizeBytes = 8 << 20 + DefaultOpenFiles = 64 + DefaultShutdownTimeout = 30 * time.Second + DefaultRetryAfter = 2 * time.Second + // MinTokenLength is the shortest accepted service token. + MinTokenLength = 32 +) + +// Config is the validated runner configuration. +type Config struct { + ListenAddress string + TLSCertFile string + TLSKeyFile string + // AllowPlaintextHTTP serves HTTP without TLS. Only the local dev + // Compose file sets it. + AllowPlaintextHTTP bool + APIToken string + + MaxConcurrentRuns int + MaxRequestBytes int64 + ResultTTL time.Duration + MaxRetainedRuns int + RetryAfter time.Duration + ShutdownTimeout time.Duration + + WorkDir string + CgroupRoot string + NsjailPath string + PythonPath string + SandboxUID int + MaxProcesses int + MemoryOverheadBytes int64 + TmpfsBytes int64 + FileSizeBytes int64 + OpenFiles int + + LogLevel slog.Level +} + +// Load reads the configuration from the process environment. +func Load() (Config, error) { + return parse(os.LookupEnv, os.ReadFile) +} + +type ( + lookupFunc func(string) (string, bool) + readFileFunc func(string) ([]byte, error) +) + +func parse(lookup lookupFunc, readFile readFileFunc) (Config, error) { + r := reader{lookup: lookup} + cfg := Config{ + ListenAddress: r.text("RUNNER_LISTEN_ADDRESS", DefaultListenAddress), + TLSCertFile: r.text("RUNNER_TLS_CERT_FILE", ""), + TLSKeyFile: r.text("RUNNER_TLS_KEY_FILE", ""), + AllowPlaintextHTTP: r.boolean("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP"), + MaxConcurrentRuns: r.integer("RUNNER_MAX_CONCURRENT_RUNS", DefaultMaxConcurrentRuns), + MaxRequestBytes: r.int64("RUNNER_MAX_REQUEST_BYTES", DefaultMaxRequestBytes), + ResultTTL: r.duration("RUNNER_RESULT_TTL", DefaultResultTTL), + MaxRetainedRuns: r.integer("RUNNER_MAX_RETAINED_RUNS", DefaultMaxRetainedRuns), + RetryAfter: r.duration("RUNNER_RETRY_AFTER", DefaultRetryAfter), + ShutdownTimeout: r.duration("RUNNER_SHUTDOWN_TIMEOUT", DefaultShutdownTimeout), + WorkDir: r.text("RUNNER_WORK_DIR", DefaultWorkDir), + CgroupRoot: r.text("RUNNER_CGROUP_ROOT", DefaultCgroupRoot), + NsjailPath: r.text("RUNNER_NSJAIL_PATH", DefaultNsjailPath), + PythonPath: r.text("RUNNER_PYTHON_PATH", DefaultPythonPath), + SandboxUID: r.integer("RUNNER_SANDBOX_UID", DefaultSandboxUID), + MaxProcesses: r.integer("RUNNER_SANDBOX_MAX_PROCESSES", DefaultMaxProcesses), + MemoryOverheadBytes: r.int64("RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES", DefaultMemoryOverheadBytes), + TmpfsBytes: r.int64("RUNNER_SANDBOX_TMPFS_BYTES", DefaultTmpfsBytes), + FileSizeBytes: r.int64("RUNNER_SANDBOX_FILE_SIZE_BYTES", DefaultFileSizeBytes), + OpenFiles: r.integer("RUNNER_SANDBOX_OPEN_FILES", DefaultOpenFiles), + LogLevel: r.logLevel("RUNNER_LOG_LEVEL"), + } + cfg.APIToken = r.token(readFile) + // Report parse and validation errors together, so one start names + // every setting to fix. + if err := errors.Join(append(r.errs, cfg.validate())...); err != nil { + return Config{}, err + } + return cfg, nil +} + +func (c Config) validate() error { + return errors.Join(c.validateTransport(), c.validateLimits(), c.validatePaths()) +} + +func (c Config) validateTransport() error { + tlsSet := c.TLSCertFile != "" || c.TLSKeyFile != "" + switch { + case tlsSet && (c.TLSCertFile == "" || c.TLSKeyFile == ""): + return errors.New("config.validate - RUNNER_TLS_CERT_FILE and RUNNER_TLS_KEY_FILE must be set together") + case tlsSet && c.AllowPlaintextHTTP: + return errors.New("config.validate - RUNNER_DEV_ALLOW_PLAINTEXT_HTTP conflicts with TLS settings") + case !tlsSet && !c.AllowPlaintextHTTP: + return errors.New("config.validate - TLS is required: set RUNNER_TLS_CERT_FILE and RUNNER_TLS_KEY_FILE") + } + return nil +} + +func (c Config) validateLimits() error { + var errs []error + positive := map[string]int64{ + "RUNNER_MAX_CONCURRENT_RUNS": int64(c.MaxConcurrentRuns), + "RUNNER_MAX_REQUEST_BYTES": c.MaxRequestBytes, + "RUNNER_MAX_RETAINED_RUNS": int64(c.MaxRetainedRuns), + "RUNNER_SANDBOX_MAX_PROCESSES": int64(c.MaxProcesses), + "RUNNER_SANDBOX_TMPFS_BYTES": c.TmpfsBytes, + "RUNNER_SANDBOX_FILE_SIZE_BYTES": c.FileSizeBytes, + "RUNNER_SANDBOX_OPEN_FILES": int64(c.OpenFiles), + "RUNNER_RESULT_TTL": int64(c.ResultTTL), + "RUNNER_RETRY_AFTER": int64(c.RetryAfter), + "RUNNER_SHUTDOWN_TIMEOUT": int64(c.ShutdownTimeout), + } + for name, value := range positive { + if value <= 0 { + errs = append(errs, fmt.Errorf("config.validate - %s must be positive", name)) + } + } + if c.MaxRetainedRuns < c.MaxConcurrentRuns { + errs = append(errs, errors.New("config.validate - RUNNER_MAX_RETAINED_RUNS must not be below RUNNER_MAX_CONCURRENT_RUNS")) + } + if c.SandboxUID <= 0 { + errs = append(errs, errors.New("config.validate - RUNNER_SANDBOX_UID must not be root")) + } + if c.MemoryOverheadBytes < 0 { + errs = append(errs, errors.New("config.validate - RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES must not be negative")) + } + return errors.Join(errs...) +} + +func (c Config) validatePaths() error { + var errs []error + for name, path := range map[string]string{ + "RUNNER_WORK_DIR": c.WorkDir, + "RUNNER_CGROUP_ROOT": c.CgroupRoot, + "RUNNER_NSJAIL_PATH": c.NsjailPath, + "RUNNER_PYTHON_PATH": c.PythonPath, + } { + if !strings.HasPrefix(path, "/") { + errs = append(errs, fmt.Errorf("config.validate - %s must be an absolute path", name)) + } + } + return errors.Join(errs...) +} + +// reader collects parse errors so that one start reports every bad value. +type reader struct { + lookup lookupFunc + errs []error +} + +func (r *reader) text(name, fallback string) string { + value, ok := r.lookup(name) + if !ok || value == "" { + return fallback + } + return value +} + +func (r *reader) boolean(name string) bool { + value, ok := r.lookup(name) + if !ok || value == "" { + return false + } + parsed, err := strconv.ParseBool(value) + if err != nil { + r.errs = append(r.errs, fmt.Errorf("config.reader.boolean - %s is not a boolean", name)) + } + return parsed +} + +func (r *reader) integer(name string, fallback int) int { + return int(r.int64(name, int64(fallback))) +} + +func (r *reader) int64(name string, fallback int64) int64 { + value, ok := r.lookup(name) + if !ok || value == "" { + return fallback + } + parsed, err := strconv.ParseInt(value, 10, 64) + if err != nil { + r.errs = append(r.errs, fmt.Errorf("config.reader.int64 - %s is not an integer", name)) + } + return parsed +} + +func (r *reader) duration(name string, fallback time.Duration) time.Duration { + value, ok := r.lookup(name) + if !ok || value == "" { + return fallback + } + parsed, err := time.ParseDuration(value) + if err != nil { + r.errs = append(r.errs, fmt.Errorf("config.reader.duration - %s is not a duration", name)) + } + return parsed +} + +func (r *reader) logLevel(name string) slog.Level { + value, ok := r.lookup(name) + if !ok || value == "" { + return slog.LevelInfo + } + var level slog.Level + if err := level.UnmarshalText([]byte(value)); err != nil { + r.errs = append(r.errs, fmt.Errorf("config.reader.logLevel - %s is not a log level", name)) + } + return level +} + +// token reads the service token from RUNNER_API_TOKEN_FILE or, failing +// that, RUNNER_API_TOKEN. The value never appears in an error. +func (r *reader) token(readFile readFileFunc) string { + file := r.text("RUNNER_API_TOKEN_FILE", "") + direct := r.text("RUNNER_API_TOKEN", "") + var token string + switch { + case file != "" && direct != "": + r.errs = append(r.errs, errors.New("config.reader.token - set RUNNER_API_TOKEN_FILE or RUNNER_API_TOKEN, not both")) + return "" + case file != "": + content, err := readFile(file) + if err != nil { + r.errs = append(r.errs, fmt.Errorf("config.reader.token - read RUNNER_API_TOKEN_FILE: %w", err)) + return "" + } + token = strings.TrimSpace(string(content)) + default: + token = direct + } + if len(token) < MinTokenLength { + r.errs = append(r.errs, fmt.Errorf("config.reader.token - the service token must have at least %d characters", MinTokenLength)) + return "" + } + return token +} diff --git a/runner/internal/config/config_test.go b/runner/internal/config/config_test.go new file mode 100644 index 0000000..43f0fcc --- /dev/null +++ b/runner/internal/config/config_test.go @@ -0,0 +1,116 @@ +package config + +import ( + "io/fs" + "strings" + "testing" + "time" +) + +const testToken = "test-token-0123456789abcdefghijklmnop" + +func env(values map[string]string) lookupFunc { + return func(name string) (string, bool) { + value, ok := values[name] + return value, ok + } +} + +func noFiles(string) ([]byte, error) { + return nil, fs.ErrNotExist +} + +func TestParseDefaultsWithTLS(t *testing.T) { + t.Parallel() + + cfg, err := parse(env(map[string]string{ + "RUNNER_TLS_CERT_FILE": "/run/secrets/tls.crt", + "RUNNER_TLS_KEY_FILE": "/run/secrets/tls.key", + "RUNNER_API_TOKEN": testToken, + }), noFiles) + if err != nil { + t.Fatalf("parse: %v", err) + } + if cfg.MaxConcurrentRuns != DefaultMaxConcurrentRuns || cfg.ResultTTL != DefaultResultTTL || cfg.AllowPlaintextHTTP { + t.Fatalf("unexpected defaults: %+v", cfg) + } +} + +func TestParseRequiresTLSUnlessTheDevSwitchIsSet(t *testing.T) { + t.Parallel() + + _, err := parse(env(map[string]string{"RUNNER_API_TOKEN": testToken}), noFiles) + if err == nil || !strings.Contains(err.Error(), "TLS is required") { + t.Fatalf("parse without TLS = %v, want a TLS error", err) + } + cfg, err := parse(env(map[string]string{ + "RUNNER_API_TOKEN": testToken, + "RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "true", + }), noFiles) + if err != nil || !cfg.AllowPlaintextHTTP { + t.Fatalf("parse with the dev switch = %+v, %v", cfg, err) + } +} + +func TestParseReadsTheTokenFileAndHidesTheValue(t *testing.T) { + t.Parallel() + + files := func(path string) ([]byte, error) { + if path == "/run/secrets/token" { + return []byte(testToken + "\n"), nil + } + return nil, fs.ErrNotExist + } + cfg, err := parse(env(map[string]string{ + "RUNNER_API_TOKEN_FILE": "/run/secrets/token", + "RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "1", + }), files) + if err != nil || cfg.APIToken != testToken { + t.Fatalf("parse token file = %q, %v", cfg.APIToken, err) + } + + short := "short-secret" + _, err = parse(env(map[string]string{ + "RUNNER_API_TOKEN": short, + "RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "1", + }), noFiles) + if err == nil || strings.Contains(err.Error(), short) { + t.Fatalf("parse short token = %v, want an error without the value", err) + } +} + +func TestParseReportsEveryInvalidValue(t *testing.T) { + t.Parallel() + + _, err := parse(env(map[string]string{ + "RUNNER_API_TOKEN": testToken, + "RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "true", + "RUNNER_MAX_CONCURRENT_RUNS": "many", + "RUNNER_RESULT_TTL": "soon", + "RUNNER_SANDBOX_UID": "0", + "RUNNER_WORK_DIR": "relative/work", + }), noFiles) + if err == nil { + t.Fatal("parse accepted invalid values") + } + for _, name := range []string{"RUNNER_MAX_CONCURRENT_RUNS", "RUNNER_RESULT_TTL", "RUNNER_SANDBOX_UID", "RUNNER_WORK_DIR"} { + if !strings.Contains(err.Error(), name) { + t.Errorf("error %q does not name %s", err, name) + } + } +} + +func TestParseRejectsConflictingTLSAndPlaintext(t *testing.T) { + t.Parallel() + + _, err := parse(env(map[string]string{ + "RUNNER_API_TOKEN": testToken, + "RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "true", + "RUNNER_TLS_CERT_FILE": "/tls.crt", + "RUNNER_TLS_KEY_FILE": "/tls.key", + "RUNNER_SHUTDOWN_TIMEOUT": time.Second.String(), + }), noFiles) + if err == nil || !strings.Contains(err.Error(), "conflicts") { + t.Fatalf("parse = %v, want a conflict error", err) + } +} diff --git a/runner/internal/isolationtest/doc.go b/runner/internal/isolationtest/doc.go new file mode 100644 index 0000000..1a8a7f9 --- /dev/null +++ b/runner/internal/isolationtest/doc.go @@ -0,0 +1,6 @@ +// Package isolationtest holds the sandbox isolation tests. They need Linux +// with nsjail and a writable cgroup v2 hierarchy, so they are built only with +// the sandbox tag and run in the dev-only test container +// (make -C runner test-sandbox). The fixtures under testdata/hostile are +// shared with later isolation suites. +package isolationtest diff --git a/runner/internal/isolationtest/isolation_test.go b/runner/internal/isolationtest/isolation_test.go new file mode 100644 index 0000000..5ea1c16 --- /dev/null +++ b/runner/internal/isolationtest/isolation_test.go @@ -0,0 +1,195 @@ +//go:build sandbox && linux + +package isolationtest + +import ( + "bufio" + "encoding/json" + "fmt" + "log/slog" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "lincodex/runner/internal/app" + "lincodex/runner/internal/checker" + "lincodex/runner/internal/config" + "lincodex/runner/internal/judge" + "lincodex/runner/internal/sandbox" +) + +const ( + fixturesEnv = "RUNNER_HOSTILE_FIXTURES" + defaultFixtures = "../../testdata/hostile" + // seriesRepeats runs the whole manifest this many times before the final + // cleanup check. + seriesRepeats = 2 +) + +type manifest struct { + Schema string `json:"schema"` + DefaultLimits limits `json:"default_limits"` + Cases []struct { + Name string `json:"name"` + Language string `json:"language"` + Source string `json:"source"` + Input string `json:"input"` + ExpectedOutput string `json:"expected_output"` + Limits *limits `json:"limits"` + Expect struct { + Outcome judge.Outcome `json:"outcome"` + Limit sandbox.Termination `json:"limit"` + } `json:"expect"` + } `json:"cases"` +} + +type limits struct { + TimeLimitMs int64 `json:"time_limit_ms"` + MemoryLimitMB int64 `json:"memory_limit_mb"` + OutputLimitKB int64 `json:"output_limit_kb"` +} + +func fixturesDir() string { + if dir := os.Getenv(fixturesEnv); dir != "" { + return dir + } + return defaultFixtures +} + +func loadManifest(t *testing.T) manifest { + t.Helper() + content, err := os.ReadFile(filepath.Join(fixturesDir(), "manifest.json")) + if err != nil { + t.Fatalf("read manifest: %v", err) + } + var loaded manifest + if err := json.Unmarshal(content, &loaded); err != nil { + t.Fatalf("decode manifest: %v", err) + } + if loaded.Schema != "lincodex.runner-hostile-fixtures/v1" || len(loaded.Cases) == 0 { + t.Fatalf("unexpected manifest %q with %d cases", loaded.Schema, len(loaded.Cases)) + } + return loaded +} + +// newRunner builds the sandbox from the production configuration path. +func newRunner(t *testing.T) (*sandbox.Executor, *judge.Judge) { + t.Helper() + t.Setenv("RUNNER_API_TOKEN", strings.Repeat("t", config.MinTokenLength)) + t.Setenv("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP", "true") + cfg, err := config.Load() + if err != nil { + t.Fatalf("config: %v", err) + } + executor, err := sandbox.New(app.SandboxConfig(cfg)) + if err != nil { + t.Fatalf("sandbox: %v", err) + } + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})) + return executor, judge.New(executor, logger, judge.Python3(cfg.PythonPath)) +} + +func TestHostileProgramsAreStoppedByTheRightLimit(t *testing.T) { + loaded := loadManifest(t) + executor, evaluator := newRunner(t) + + for round := range seriesRepeats { + for _, tc := range loaded.Cases { + source, err := os.ReadFile(filepath.Join(fixturesDir(), tc.Source)) + if err != nil { + t.Fatalf("read %s: %v", tc.Source, err) + } + caseLimits := loaded.DefaultLimits + if tc.Limits != nil { + caseLimits = *tc.Limits + } + request := judge.Request{ + Language: tc.Language, + Source: string(source), + Limits: judge.Limits{ + TimeLimit: time.Duration(caseLimits.TimeLimitMs) * time.Millisecond, + MemoryBytes: caseLimits.MemoryLimitMB << 20, + OutputBytes: caseLimits.OutputLimitKB << 10, + }, + Groups: []judge.Group{{ + ID: "public", + Visibility: judge.Public, + Checker: checker.Spec{Kind: checker.Exact}, + Tests: []judge.Test{{ID: "t1", Input: tc.Input, ExpectedOutput: tc.ExpectedOutput}}, + }}, + } + result := evaluator.Run(t.Context(), request) + if result.Outcome != tc.Expect.Outcome { + t.Errorf("round %d %s: outcome %s, want %s (%s)", round, tc.Name, result.Outcome, tc.Expect.Outcome, describe(result)) + continue + } + if tc.Expect.Outcome == judge.CompileError { + if result.Compile == nil || result.Compile.Diagnostic == "" { + t.Errorf("round %d %s: compile error without a diagnostic", round, tc.Name) + } + continue + } + test := result.Groups[0].Tests[0] + if test.Limit != tc.Expect.Limit { + t.Errorf("round %d %s: limit %q, want %q (%s)", round, tc.Name, test.Limit, tc.Expect.Limit, describe(result)) + } + if test.CPUTime <= 0 || test.WallTime <= 0 || test.MemoryKB <= 0 { + t.Errorf("round %d %s: usage not recorded: cpu %v wall %v memory %d KiB", round, tc.Name, test.CPUTime, test.WallTime, test.MemoryKB) + } + t.Logf("round %d %-16s %-22s limit=%-9q cpu=%v wall=%v memory=%dKiB", round, tc.Name, test.Outcome, test.Limit, test.CPUTime, test.WallTime, test.MemoryKB) + assertNothingLeft(t, executor, tc.Name) + } + } + assertNothingLeft(t, executor, "series") +} + +func describe(result judge.Result) string { + return fmt.Sprintf("%+v", result) +} + +// assertNothingLeft checks that the work directory and the run cgroups are +// gone and that no process of the sandbox user is alive. +func assertNothingLeft(t *testing.T, executor *sandbox.Executor, label string) { + t.Helper() + boxes, cgroups, err := executor.Leftovers() + if err != nil { + t.Fatalf("%s: leftovers: %v", label, err) + } + if len(boxes) != 0 || len(cgroups) != 0 { + t.Fatalf("%s: left boxes %q and cgroups %q", label, boxes, cgroups) + } + if pids := sandboxUserProcesses(t, config.DefaultSandboxUID); len(pids) != 0 { + t.Fatalf("%s: sandbox user processes still alive: %v", label, pids) + } +} + +func sandboxUserProcesses(t *testing.T, uid int) []string { + t.Helper() + entries, err := os.ReadDir("/proc") + if err != nil { + t.Fatalf("list /proc: %v", err) + } + wanted := "\t" + strconv.Itoa(uid) + "\t" + var pids []string + for _, entry := range entries { + if !entry.IsDir() || strings.Trim(entry.Name(), "0123456789") != "" { + continue + } + file, err := os.Open(filepath.Join("/proc", entry.Name(), "status")) + if err != nil { + continue // The process exited meanwhile. + } + scanner := bufio.NewScanner(file) + for scanner.Scan() { + line := scanner.Text() + if strings.HasPrefix(line, "Uid:") && strings.Contains(line+"\t", wanted) { + pids = append(pids, entry.Name()) + } + } + _ = file.Close() + } + return pids +} diff --git a/runner/internal/jobs/manager.go b/runner/internal/jobs/manager.go new file mode 100644 index 0000000..7127470 --- /dev/null +++ b/runner/internal/jobs/manager.go @@ -0,0 +1,240 @@ +// Package jobs keeps runs in memory, enforces the number of concurrent +// sandbox runs, and makes submissions idempotent by run ID. +package jobs + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "log/slog" + "sync" + "time" + + "github.com/google/uuid" + + "lincodex/runner/internal/judge" +) + +// State of a run. +type State string + +const ( + Running State = "running" + Finished State = "finished" +) + +var ( + // ErrBusy means that every slot is taken or the manager is draining. + ErrBusy = errors.New("every sandbox slot is busy") + // ErrPayloadMismatch means that the run ID exists with another payload. + ErrPayloadMismatch = errors.New("run ID reused with a different payload") + // ErrNotFound means that the manager does not hold the run. + ErrNotFound = errors.New("run not found") +) + +// Runner evaluates one request. +type Runner interface { + Run(ctx context.Context, request judge.Request) judge.Result +} + +// Snapshot is a copy of a run's state. +type Snapshot struct { + ID uuid.UUID + State State + Result *judge.Result +} + +// Config bounds the manager. +type Config struct { + MaxConcurrent int + // ResultTTL is how long a finished run stays readable. + ResultTTL time.Duration + // MaxRetained bounds stored runs, running ones included. + MaxRetained int +} + +type job struct { + fingerprint [sha256.Size]byte + state State + result *judge.Result + finishedAt time.Time +} + +// Manager owns the runs. Request payloads live only while a run executes; +// a stored run keeps its fingerprint and result. +type Manager struct { + cfg Config + runner Runner + logger *slog.Logger + now func() time.Time + + ctx context.Context + cancel context.CancelFunc + running sync.WaitGroup + + mu sync.Mutex + jobs map[uuid.UUID]*job + active int + draining bool +} + +// NewManager returns a manager. Runs use a context that Close cancels. +func NewManager(cfg Config, runner Runner, logger *slog.Logger) (*Manager, error) { + if cfg.MaxConcurrent <= 0 || cfg.MaxRetained < cfg.MaxConcurrent || cfg.ResultTTL <= 0 { + return nil, errors.New("jobs.NewManager - invalid limits") + } + ctx, cancel := context.WithCancel(context.Background()) + return &Manager{ + cfg: cfg, + runner: runner, + logger: logger, + now: time.Now, + ctx: ctx, + cancel: cancel, + jobs: make(map[uuid.UUID]*job), + }, nil +} + +// Fingerprint is the SHA-256 of the canonical JSON encoding of a request. +// Struct fields encode in declaration order and the request has no maps, so +// equal requests always give equal fingerprints. +func Fingerprint(request judge.Request) ([sha256.Size]byte, error) { + encoded, err := json.Marshal(request) + if err != nil { + return [sha256.Size]byte{}, fmt.Errorf("jobs.Fingerprint - encode: %w", err) + } + return sha256.Sum256(encoded), nil +} + +// Submit starts a run or returns the existing run with the same ID and +// payload. created is true when a new run started. +func (m *Manager) Submit(id uuid.UUID, request judge.Request) (snapshot Snapshot, created bool, err error) { + fingerprint, err := Fingerprint(request) + if err != nil { + return Snapshot{}, false, err + } + m.mu.Lock() + defer m.mu.Unlock() + m.forgetExpiredLocked() + if existing, ok := m.jobs[id]; ok { + if existing.fingerprint != fingerprint { + return Snapshot{}, false, ErrPayloadMismatch + } + return existing.snapshot(id), false, nil + } + if m.draining || m.active >= m.cfg.MaxConcurrent { + return Snapshot{}, false, ErrBusy + } + if len(m.jobs) >= m.cfg.MaxRetained && !m.forgetOldestFinishedLocked() { + return Snapshot{}, false, ErrBusy + } + current := &job{fingerprint: fingerprint, state: Running} + m.jobs[id] = current + m.active++ + m.running.Go(func() { m.execute(id, current, request) }) + return current.snapshot(id), true, nil +} + +// Get returns the state of a run. +func (m *Manager) Get(id uuid.UUID) (Snapshot, error) { + m.mu.Lock() + defer m.mu.Unlock() + m.forgetExpiredLocked() + existing, ok := m.jobs[id] + if !ok { + return Snapshot{}, ErrNotFound + } + return existing.snapshot(id), nil +} + +// Draining reports whether the manager refuses new runs. +func (m *Manager) Draining() bool { + m.mu.Lock() + defer m.mu.Unlock() + return m.draining +} + +// Close refuses new runs, waits for running ones until ctx ends, and then +// cancels them, which kills their sandboxes. +func (m *Manager) Close(ctx context.Context) error { + m.mu.Lock() + m.draining = true + m.mu.Unlock() + + done := make(chan struct{}) + go func() { + m.running.Wait() + close(done) + }() + select { + case <-done: + m.cancel() + return nil + case <-ctx.Done(): + m.cancel() + <-done + return fmt.Errorf("jobs.Manager.Close - canceled running runs: %w", ctx.Err()) + } +} + +func (m *Manager) execute(id uuid.UUID, current *job, request judge.Request) { + m.logger.InfoContext(m.ctx, "run started", + slog.String("run_id", id.String()), + slog.String("language", request.Language), + slog.Int("groups", len(request.Groups)), + slog.Int("tests", countTests(request)), + ) + result := m.runner.Run(m.ctx, request) + m.mu.Lock() + current.state = Finished + current.result = &result + current.finishedAt = m.now() + m.active-- + m.mu.Unlock() + m.logger.InfoContext(m.ctx, "run finished", + slog.String("run_id", id.String()), + slog.String("outcome", string(result.Outcome)), + slog.Int64("duration_ms", result.Duration.Milliseconds()), + ) +} + +func (m *Manager) forgetExpiredLocked() { + now := m.now() + for id, existing := range m.jobs { + if existing.state == Finished && now.Sub(existing.finishedAt) > m.cfg.ResultTTL { + delete(m.jobs, id) + } + } +} + +func (m *Manager) forgetOldestFinishedLocked() bool { + var oldestID uuid.UUID + var oldest *job + for id, existing := range m.jobs { + if existing.state != Finished { + continue + } + if oldest == nil || existing.finishedAt.Before(oldest.finishedAt) { + oldestID, oldest = id, existing + } + } + if oldest == nil { + return false + } + delete(m.jobs, oldestID) + return true +} + +func (j *job) snapshot(id uuid.UUID) Snapshot { + return Snapshot{ID: id, State: j.state, Result: j.result} +} + +func countTests(request judge.Request) int { + total := 0 + for _, group := range request.Groups { + total += len(group.Tests) + } + return total +} diff --git a/runner/internal/jobs/manager_test.go b/runner/internal/jobs/manager_test.go new file mode 100644 index 0000000..914e45e --- /dev/null +++ b/runner/internal/jobs/manager_test.go @@ -0,0 +1,223 @@ +package jobs + +import ( + "context" + "errors" + "log/slog" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/runner/internal/judge" +) + +// gatedRunner blocks every run until release is closed or the run context +// ends, and counts the runs it saw. +type gatedRunner struct { + release chan struct{} + mu sync.Mutex + runs int +} + +func newGatedRunner() *gatedRunner { + return &gatedRunner{release: make(chan struct{})} +} + +func (r *gatedRunner) Run(ctx context.Context, _ judge.Request) judge.Result { + r.mu.Lock() + r.runs++ + r.mu.Unlock() + select { + case <-r.release: + return judge.Result{Outcome: judge.Accepted} + case <-ctx.Done(): + return judge.Result{Outcome: judge.InfrastructureFailure} + } +} + +func (r *gatedRunner) count() int { + r.mu.Lock() + defer r.mu.Unlock() + return r.runs +} + +func newTestManager(t *testing.T, runner Runner, cfg Config) *Manager { + t.Helper() + manager, err := NewManager(cfg, runner, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("NewManager: %v", err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _ = manager.Close(ctx) + }) + return manager +} + +func request(source string) judge.Request { + return judge.Request{Language: "python3", Source: source, Limits: judge.Limits{TimeLimit: time.Second}} +} + +func waitFinished(t *testing.T, manager *Manager, id uuid.UUID) Snapshot { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + snapshot, err := manager.Get(id) + if err != nil { + t.Fatalf("Get: %v", err) + } + if snapshot.State == Finished { + return snapshot + } + time.Sleep(time.Millisecond) + } + t.Fatal("run did not finish") + return Snapshot{} +} + +func TestSubmitIsIdempotentByRunIDAndPayload(t *testing.T) { + t.Parallel() + + runner := newGatedRunner() + manager := newTestManager(t, runner, Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 8}) + id := uuid.New() + + first, created, err := manager.Submit(id, request("print(1)")) + if err != nil || !created || first.State != Running { + t.Fatalf("first Submit = %+v, %v, %v", first, created, err) + } + again, created, err := manager.Submit(id, request("print(1)")) + if err != nil || created || again.State != Running { + t.Fatalf("repeated Submit = %+v, %v, %v; want the same running run", again, created, err) + } + if _, _, err := manager.Submit(id, request("print(2)")); !errors.Is(err, ErrPayloadMismatch) { + t.Fatalf("Submit with another payload = %v, want ErrPayloadMismatch", err) + } + + close(runner.release) + finished := waitFinished(t, manager, id) + replay, created, err := manager.Submit(id, request("print(1)")) + if err != nil || created || replay.State != Finished || replay.Result != finished.Result { + t.Fatalf("Submit after finish = %+v, %v, %v; want the stored result", replay, created, err) + } + if runner.count() != 1 { + t.Fatalf("runner ran %d times, want 1", runner.count()) + } +} + +func TestSubmitAnswersBusyWhenEverySlotIsTaken(t *testing.T) { + t.Parallel() + + runner := newGatedRunner() + manager := newTestManager(t, runner, Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 8}) + busyID := uuid.New() + + if _, _, err := manager.Submit(uuid.New(), request("a")); err != nil { + t.Fatalf("Submit: %v", err) + } + if _, _, err := manager.Submit(busyID, request("b")); !errors.Is(err, ErrBusy) { + t.Fatalf("second Submit = %v, want ErrBusy", err) + } + if _, err := manager.Get(busyID); !errors.Is(err, ErrNotFound) { + t.Fatalf("Get of a refused run = %v, want ErrNotFound", err) + } + + close(runner.release) + deadline := time.Now().Add(5 * time.Second) + for { + _, _, err := manager.Submit(busyID, request("b")) + if err == nil { + break + } + if !errors.Is(err, ErrBusy) || time.Now().After(deadline) { + t.Fatalf("Submit after the slot freed = %v", err) + } + time.Sleep(time.Millisecond) + } +} + +func TestFinishedRunsExpireAfterTheirTTL(t *testing.T) { + t.Parallel() + + runner := newGatedRunner() + close(runner.release) + manager := newTestManager(t, runner, Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 1}) + clock := time.Now() + var clockMu sync.Mutex + manager.now = func() time.Time { + clockMu.Lock() + defer clockMu.Unlock() + return clock + } + id := uuid.New() + if _, _, err := manager.Submit(id, request("a")); err != nil { + t.Fatalf("Submit: %v", err) + } + waitFinished(t, manager, id) + + // A full store forgets the oldest finished run for a new one. + other := uuid.New() + if _, _, err := manager.Submit(other, request("b")); err != nil { + t.Fatalf("Submit into a full store: %v", err) + } + if _, err := manager.Get(id); !errors.Is(err, ErrNotFound) { + t.Fatalf("Get of the evicted run = %v, want ErrNotFound", err) + } + waitFinished(t, manager, other) + + clockMu.Lock() + clock = clock.Add(2 * time.Minute) + clockMu.Unlock() + if _, err := manager.Get(other); !errors.Is(err, ErrNotFound) { + t.Fatalf("Get after the TTL = %v, want ErrNotFound", err) + } +} + +func TestCloseRefusesNewRunsAndCancelsRunningOnes(t *testing.T) { + t.Parallel() + + runner := newGatedRunner() + manager := newTestManager(t, runner, Config{MaxConcurrent: 2, ResultTTL: time.Minute, MaxRetained: 8}) + id := uuid.New() + if _, _, err := manager.Submit(id, request("a")); err != nil { + t.Fatalf("Submit: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + if err := manager.Close(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Close = %v, want the deadline after canceling the run", err) + } + snapshot, err := manager.Get(id) + if err != nil || snapshot.State != Finished || snapshot.Result.Outcome != judge.InfrastructureFailure { + t.Fatalf("canceled run = %+v, %v", snapshot, err) + } + if _, _, err := manager.Submit(uuid.New(), request("b")); !errors.Is(err, ErrBusy) { + t.Fatalf("Submit while draining = %v, want ErrBusy", err) + } +} + +func TestFingerprintDependsOnEveryField(t *testing.T) { + t.Parallel() + + base := judge.Request{Language: "python3", Source: "x", Groups: []judge.Group{{ID: "g", Tests: []judge.Test{{ID: "t", Input: "1", ExpectedOutput: "1"}}}}} + changed := base + changed.Groups = []judge.Group{{ID: "g", Tests: []judge.Test{{ID: "t", Input: "1", ExpectedOutput: "2"}}}} + first, err := Fingerprint(base) + if err != nil { + t.Fatalf("Fingerprint: %v", err) + } + second, err := Fingerprint(changed) + if err != nil { + t.Fatalf("Fingerprint: %v", err) + } + same, err := Fingerprint(base) + if err != nil { + t.Fatalf("Fingerprint: %v", err) + } + if first == second || first != same { + t.Fatal("fingerprints must differ for different payloads and match for equal ones") + } +} diff --git a/runner/internal/judge/judge.go b/runner/internal/judge/judge.go new file mode 100644 index 0000000..f601018 --- /dev/null +++ b/runner/internal/judge/judge.go @@ -0,0 +1,347 @@ +// Package judge evaluates one source against its test groups in the sandbox +// and turns sandbox results into contract outcomes. +package judge + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "strings" + "time" + "unicode/utf8" + + "lincodex/runner/internal/checker" + "lincodex/runner/internal/sandbox" +) + +// Outcome is the result of a test, a group, a compile step, or a run. +type Outcome string + +const ( + Accepted Outcome = "accepted" + WrongAnswer Outcome = "wrong_answer" + CompileError Outcome = "compile_error" + TimeLimitExceeded Outcome = "time_limit_exceeded" + MemoryLimitExceeded Outcome = "memory_limit_exceeded" + OutputLimitExceeded Outcome = "output_limit_exceeded" + RuntimeError Outcome = "runtime_error" + InfrastructureFailure Outcome = "infrastructure_failure" +) + +// Visibility tells whether results may carry program diagnostics. +type Visibility string + +const ( + Public Visibility = "public" + Hidden Visibility = "hidden" +) + +// Contract limits of a test result. +const ( + maxCompileDiagnostic = 4096 + maxTestDiagnostic = 2048 +) + +// Request is one run. It holds no identifiers of people or product records. +// The JSON tags define the encoding of the idempotency fingerprint. +type Request struct { + Language string `json:"language"` + Source string `json:"source"` + Limits Limits `json:"limits"` + Groups []Group `json:"groups"` +} + +// Limits apply to every test of a run. +type Limits struct { + TimeLimit time.Duration `json:"time_limit"` + MemoryBytes int64 `json:"memory_bytes"` + OutputBytes int64 `json:"output_bytes"` +} + +// Group is a set of tests with one checker. +type Group struct { + ID string `json:"id"` + Visibility Visibility `json:"visibility"` + Checker checker.Spec `json:"checker"` + Tests []Test `json:"tests"` +} + +// Test is one input and its expected output. +type Test struct { + ID string `json:"id"` + Input string `json:"input"` + ExpectedOutput string `json:"expected_output"` +} + +// Result is the evaluation of a run. +type Result struct { + Outcome Outcome + Compile *CompileResult + Groups []GroupResult + Duration time.Duration +} + +// CompileResult is the outcome of the compile or syntax check step. +type CompileResult struct { + Outcome Outcome + Diagnostic string +} + +// GroupResult is the evaluation of one group. +type GroupResult struct { + ID string + Visibility Visibility + Outcome Outcome + Passed int + Total int + MaxCPUTime time.Duration + MaxMemoryKB int64 + Tests []TestResult +} + +// TestResult is the evaluation of one test. +type TestResult struct { + ID string + Outcome Outcome + CPUTime time.Duration + WallTime time.Duration + MemoryKB int64 + ExitCode *int + Signal *int + Limit sandbox.Termination + Diagnostic string +} + +// Executor is the sandbox used by the judge. +type Executor interface { + NewBox(fileName string, content []byte) (*sandbox.Box, error) + Run(ctx context.Context, spec sandbox.Spec, limits sandbox.Limits) (sandbox.Result, error) +} + +// Judge evaluates requests with one executor and a set of languages. +type Judge struct { + executor Executor + languages map[string]Language + logger *slog.Logger +} + +// New returns a judge for the given languages. +func New(executor Executor, logger *slog.Logger, languages ...Language) *Judge { + byID := make(map[string]Language, len(languages)) + for _, language := range languages { + byID[language.ID] = language + } + return &Judge{executor: executor, languages: byID, logger: logger} +} + +// Supports reports whether the judge knows the language. +func (j *Judge) Supports(language string) bool { + _, ok := j.languages[language] + return ok +} + +// Run evaluates a request. Failures of the runner become +// infrastructure_failure; they never look like an outcome of the program. +func (j *Judge) Run(ctx context.Context, request Request) Result { + started := time.Now() + result := j.evaluate(ctx, request) + result.Duration = time.Since(started) + return result +} + +func (j *Judge) evaluate(ctx context.Context, request Request) Result { + language, ok := j.languages[request.Language] + if !ok { + j.logger.ErrorContext(ctx, "run has an unsupported language") + return failedRun(request, InfrastructureFailure, nil) + } + box, err := j.executor.NewBox(language.SourceFile, []byte(request.Source)) + if err != nil { + j.logger.ErrorContext(ctx, "cannot create the run directory", slog.Any("error", err)) + return failedRun(request, InfrastructureFailure, nil) + } + defer func() { + if err := box.Remove(); err != nil { + j.logger.ErrorContext(ctx, "cannot remove the run directory", slog.Any("error", err)) + } + }() + + compile, ok := j.compile(ctx, language, box) + if !ok { + return failedRun(request, compile.Outcome, compile) + } + result := Result{Outcome: Accepted, Compile: compile, Groups: make([]GroupResult, 0, len(request.Groups))} + for _, group := range request.Groups { + groupResult := j.evaluateGroup(ctx, language, box, request.Limits, group) + if groupResult.Outcome == InfrastructureFailure { + return failedRun(request, InfrastructureFailure, compile) + } + if result.Outcome == Accepted && groupResult.Outcome != Accepted { + result.Outcome = groupResult.Outcome + } + result.Groups = append(result.Groups, groupResult) + } + return result +} + +// compile runs the language's compile step. ok is false when no test may run. +func (j *Judge) compile(ctx context.Context, language Language, box *sandbox.Box) (*CompileResult, bool) { + if len(language.Compile) == 0 { + return nil, true + } + run, err := j.executor.Run(ctx, sandbox.Spec{Argv: language.Compile, BoxDir: box.Dir()}, language.CompileLimits) + if err != nil { + j.logger.ErrorContext(ctx, "compile step failed in the sandbox", slog.Any("error", err)) + return &CompileResult{Outcome: InfrastructureFailure}, false + } + if run.Termination == sandbox.TerminationNone && run.ExitCode == 0 && run.Signal == 0 { + return &CompileResult{Outcome: Accepted}, true + } + diagnostic := compileDiagnostic(run) + return &CompileResult{Outcome: CompileError, Diagnostic: diagnostic}, false +} + +func compileDiagnostic(run sandbox.Result) string { + if run.Termination != sandbox.TerminationNone { + return "The compile step exceeded its " + strings.ReplaceAll(string(run.Termination), "_", " ") + " limit." + } + return excerpt(run.Stderr, maxCompileDiagnostic) +} + +func (j *Judge) evaluateGroup(ctx context.Context, language Language, box *sandbox.Box, limits Limits, group Group) GroupResult { + result := GroupResult{ + ID: group.ID, + Visibility: group.Visibility, + Outcome: Accepted, + Total: len(group.Tests), + Tests: make([]TestResult, 0, len(group.Tests)), + } + check, err := checker.New(group.Checker) + if err != nil { + j.logger.ErrorContext(ctx, "group has an unknown checker", slog.Any("error", err)) + result.Outcome = InfrastructureFailure + return result + } + for _, test := range group.Tests { + testResult, err := j.evaluateTest(ctx, language, box, limits, group.Visibility, check, test) + if err != nil { + j.logger.ErrorContext(ctx, "test failed in the sandbox", slog.Any("error", err)) + result.Outcome = InfrastructureFailure + return result + } + result.Tests = append(result.Tests, testResult) + result.MaxCPUTime = max(result.MaxCPUTime, testResult.CPUTime) + result.MaxMemoryKB = max(result.MaxMemoryKB, testResult.MemoryKB) + if testResult.Outcome != Accepted { + result.Outcome = testResult.Outcome + return result + } + result.Passed++ + } + return result +} + +func (j *Judge) evaluateTest( + ctx context.Context, + language Language, + box *sandbox.Box, + limits Limits, + visibility Visibility, + check checker.Checker, + test Test, +) (TestResult, error) { + run, err := j.executor.Run(ctx, sandbox.Spec{ + Argv: language.Run, + Stdin: []byte(test.Input), + BoxDir: box.Dir(), + }, sandbox.Limits{ + CPUTime: limits.TimeLimit, + WallTime: wallTimeLimit(limits.TimeLimit), + MemoryBytes: limits.MemoryBytes, + OutputBytes: limits.OutputBytes, + }) + if err != nil { + return TestResult{}, err + } + result := TestResult{ + ID: test.ID, + Outcome: outcomeOf(run), + CPUTime: run.CPUTime, + WallTime: run.WallTime, + MemoryKB: run.PeakMemoryKB, + Limit: run.Termination, + } + if run.Signal != 0 { + result.Signal = &run.Signal + } else { + result.ExitCode = &run.ExitCode + } + if result.Outcome == Accepted { + accepted, err := check.Check(ctx, checker.Input{ + TestInput: []byte(test.Input), + Expected: []byte(test.ExpectedOutput), + Actual: run.Stdout, + }) + if err != nil { + return TestResult{}, fmt.Errorf("judge.Judge.evaluateTest - checker: %w", err) + } + if !accepted { + result.Outcome = WrongAnswer + } + } + if visibility == Public && result.Outcome != Accepted && result.Outcome != WrongAnswer { + result.Diagnostic = excerpt(run.Stderr, maxTestDiagnostic) + } + return result, nil +} + +// wallTimeLimit allows blocking and startup on top of the CPU limit. +func wallTimeLimit(cpu time.Duration) time.Duration { + const startupAllowance = 500 * time.Millisecond + return 2*cpu + startupAllowance +} + +// outcomeOf maps how a program ended to an outcome before checking output. +func outcomeOf(run sandbox.Result) Outcome { + switch run.Termination { + case sandbox.TerminationMemory: + return MemoryLimitExceeded + case sandbox.TerminationOutput: + return OutputLimitExceeded + case sandbox.TerminationCPUTime, sandbox.TerminationWallTime: + return TimeLimitExceeded + case sandbox.TerminationProcesses: + return RuntimeError + case sandbox.TerminationNone: + } + if run.Signal != 0 || run.ExitCode != 0 { + return RuntimeError + } + return Accepted +} + +// failedRun gives every group the outcome of a run that stopped early. +func failedRun(request Request, outcome Outcome, compile *CompileResult) Result { + result := Result{Outcome: outcome, Compile: compile, Groups: make([]GroupResult, 0, len(request.Groups))} + for _, group := range request.Groups { + result.Groups = append(result.Groups, GroupResult{ + ID: group.ID, + Visibility: group.Visibility, + Outcome: outcome, + Total: len(group.Tests), + Tests: []TestResult{}, + }) + } + return result +} + +// excerpt returns the last limit bytes of text as valid UTF-8. +func excerpt(text []byte, limit int) string { + text = bytes.ToValidUTF8(text, []byte("�")) + for len(text) > limit { + _, size := utf8.DecodeRune(text) + text = text[size:] + } + return string(text) +} diff --git a/runner/internal/judge/judge_test.go b/runner/internal/judge/judge_test.go new file mode 100644 index 0000000..bccdb7e --- /dev/null +++ b/runner/internal/judge/judge_test.go @@ -0,0 +1,212 @@ +package judge + +import ( + "bytes" + "context" + "errors" + "log/slog" + "os" + "slices" + "testing" + "time" + + "lincodex/runner/internal/checker" + "lincodex/runner/internal/sandbox" +) + +// scriptedExecutor answers runs from a script keyed by the stdin of a test; +// the compile step has no stdin. +type scriptedExecutor struct { + root string + results map[string]sandbox.Result + errs map[string]error + runs []string + boxes []string +} + +func (e *scriptedExecutor) NewBox(fileName string, content []byte) (*sandbox.Box, error) { + box, err := sandbox.CreateBox(e.root, fileName, content) + if err == nil { + e.boxes = append(e.boxes, box.Dir()) + } + return box, err +} + +func (e *scriptedExecutor) Run(_ context.Context, spec sandbox.Spec, _ sandbox.Limits) (sandbox.Result, error) { + key := string(spec.Stdin) + e.runs = append(e.runs, key) + if err := e.errs[key]; err != nil { + return sandbox.Result{}, err + } + if result, ok := e.results[key]; ok { + return result, nil + } + return sandbox.Result{}, nil +} + +func newScripted(t *testing.T) *scriptedExecutor { + t.Helper() + return &scriptedExecutor{root: t.TempDir(), results: map[string]sandbox.Result{}, errs: map[string]error{}} +} + +func output(text string) sandbox.Result { + return sandbox.Result{Stdout: []byte(text), CPUTime: 20 * time.Millisecond, WallTime: 30 * time.Millisecond, PeakMemoryKB: 9000} +} + +func discardLogger() *slog.Logger { + return slog.New(slog.DiscardHandler) +} + +func twoGroupRequest() Request { + return Request{ + Language: "python3", + Source: "print(sum(map(int, input().split())))", + Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10}, + Groups: []Group{ + {ID: "public", Visibility: Public, Checker: checker.Spec{Kind: checker.Exact}, Tests: []Test{ + {ID: "t1", Input: "1 2", ExpectedOutput: "3\n"}, + {ID: "t2", Input: "2 2", ExpectedOutput: "4\n"}, + }}, + {ID: "hidden-1", Visibility: Hidden, Checker: checker.Spec{Kind: checker.Tokens}, Tests: []Test{ + {ID: "t1", Input: "5 5", ExpectedOutput: "10"}, + {ID: "t2", Input: "6 6", ExpectedOutput: "12"}, + }}, + }, + } +} + +func TestRunAcceptsCorrectOutputAndRecordsUsage(t *testing.T) { + t.Parallel() + + executor := newScripted(t) + executor.results["1 2"] = output("3\n") + executor.results["2 2"] = output("4") + executor.results["5 5"] = output("10\n") + executor.results["6 6"] = output(" 12 ") + result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest()) + + if result.Outcome != Accepted || result.Compile == nil || result.Compile.Outcome != Accepted { + t.Fatalf("result = %+v, want accepted with a passed compile step", result) + } + for _, group := range result.Groups { + if group.Outcome != Accepted || group.Passed != 2 || group.Total != 2 { + t.Fatalf("group %+v, want 2 of 2 accepted", group) + } + if group.MaxCPUTime != 20*time.Millisecond || group.MaxMemoryKB != 9000 { + t.Fatalf("group usage %v %d, want the recorded usage", group.MaxCPUTime, group.MaxMemoryKB) + } + } + assertBoxesRemoved(t, executor) +} + +func TestRunStopsAGroupAtItsFirstFailureAndKeepsDiagnosticsPublicOnly(t *testing.T) { + t.Parallel() + + executor := newScripted(t) + crash := sandbox.Result{ExitCode: 1, Stderr: []byte("Traceback: ValueError")} + executor.results["1 2"] = crash + executor.results["5 5"] = crash + result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest()) + + if result.Outcome != RuntimeError { + t.Fatalf("outcome = %s, want runtime_error", result.Outcome) + } + public, hidden := result.Groups[0], result.Groups[1] + if len(public.Tests) != 1 || public.Passed != 0 || public.Tests[0].Diagnostic != "Traceback: ValueError" { + t.Fatalf("public group %+v, want one failed test with its diagnostic", public) + } + if len(hidden.Tests) != 1 || hidden.Tests[0].Diagnostic != "" { + t.Fatalf("hidden group %+v, want one failed test without a diagnostic", hidden) + } + if slices.Contains(executor.runs, "2 2") || slices.Contains(executor.runs, "6 6") { + t.Fatalf("runs %q include tests after a failure", executor.runs) + } +} + +func TestRunMapsSandboxTerminationsToOutcomes(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + result sandbox.Result + outcome Outcome + }{ + {"cpu time", sandbox.Result{Termination: sandbox.TerminationCPUTime, Signal: 9}, TimeLimitExceeded}, + {"wall time", sandbox.Result{Termination: sandbox.TerminationWallTime, Signal: 9}, TimeLimitExceeded}, + {"memory", sandbox.Result{Termination: sandbox.TerminationMemory, Signal: 9}, MemoryLimitExceeded}, + {"output", sandbox.Result{Termination: sandbox.TerminationOutput, Signal: 9, Stdout: []byte("3\n")}, OutputLimitExceeded}, + {"processes", sandbox.Result{Termination: sandbox.TerminationProcesses, ExitCode: 1}, RuntimeError}, + {"signal", sandbox.Result{Signal: 31, ExitCode: -1}, RuntimeError}, + {"wrong answer", output("4\n"), WrongAnswer}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + executor := newScripted(t) + executor.results["1 2"] = tc.result + result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest()) + got := result.Groups[0].Tests[0] + if got.Outcome != tc.outcome || got.Limit != tc.result.Termination { + t.Fatalf("test result %+v, want %s with limit %q", got, tc.outcome, tc.result.Termination) + } + }) + } +} + +func TestRunReportsCompileErrorsWithoutRunningTests(t *testing.T) { + t.Parallel() + + executor := newScripted(t) + executor.results[""] = sandbox.Result{ExitCode: 1, Stderr: []byte("SyntaxError: invalid syntax\n")} + result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest()) + + if result.Outcome != CompileError || result.Compile.Diagnostic != "SyntaxError: invalid syntax\n" { + t.Fatalf("result = %+v, want compile_error with the diagnostic", result) + } + if len(executor.runs) != 1 { + t.Fatalf("runs = %q, want only the compile step", executor.runs) + } + for _, group := range result.Groups { + if group.Outcome != CompileError || len(group.Tests) != 0 || group.Total != 2 { + t.Fatalf("group %+v, want compile_error without tests", group) + } + } + assertBoxesRemoved(t, executor) +} + +func TestRunTurnsSandboxFailuresIntoInfrastructureFailure(t *testing.T) { + t.Parallel() + + executor := newScripted(t) + executor.results["1 2"] = output("3\n") + executor.errs["2 2"] = errors.New("nsjail failed") + result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest()) + + if result.Outcome != InfrastructureFailure { + t.Fatalf("outcome = %s, want infrastructure_failure", result.Outcome) + } + for _, group := range result.Groups { + if group.Outcome != InfrastructureFailure || len(group.Tests) != 0 { + t.Fatalf("group %+v, want infrastructure_failure without partial tests", group) + } + } + assertBoxesRemoved(t, executor) +} + +func TestExcerptKeepsTheTailAsValidUTF8(t *testing.T) { + t.Parallel() + + text := append(bytes.Repeat([]byte("ж"), 10), 0xff, 'x') + if got := excerpt(text, 7); got != "ж\uFFFDx" { + t.Fatalf("excerpt = %q, want the last whole runes within 7 bytes", got) + } +} + +func assertBoxesRemoved(t *testing.T, executor *scriptedExecutor) { + t.Helper() + for _, dir := range executor.boxes { + if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("box %s still exists: %v", dir, err) + } + } +} diff --git a/runner/internal/judge/language.go b/runner/internal/judge/language.go new file mode 100644 index 0000000..9c30234 --- /dev/null +++ b/runner/internal/judge/language.go @@ -0,0 +1,62 @@ +package judge + +import ( + "time" + + "lincodex/runner/internal/sandbox" +) + +// Language describes how the sandbox checks and runs a source file. +type Language struct { + ID string + // SourceFile is the file name of the source inside sandbox.BoxPath. + SourceFile string + // Compile is the optional compile or syntax check command. + Compile []string + // CompileLimits bound the compile step; they do not depend on the run. + CompileLimits sandbox.Limits + // Run is the command of every test; the test input is its stdin. + Run []string +} + +// pythonSyntaxCheck compiles the source without running it and prints only +// the exception line, so that a syntax error is a compile_error with a short +// message. compile() never executes the program. +const pythonSyntaxCheck = `import sys, traceback +path = sys.argv[1] +try: + with open(path, "rb") as stream: + compile(stream.read(), "main.py", "exec", dont_inherit=True) +except (SyntaxError, ValueError) as error: + sys.stderr.write("".join(traceback.format_exception_only(type(error), error))) + sys.exit(1) +` + +// Limits of the Python syntax check. A 64 KiB source compiles far below +// them; a pathological source fails with compile_error. +const ( + pythonCompileCPU = 5 * time.Second + pythonCompileWall = 10 * time.Second + pythonCompileMemory = 256 << 20 + pythonCompileOutput = 64 << 10 +) + +// Python3 returns the Python 3 language for the interpreter at path. The +// interpreter runs in isolated mode (-I: no environment variables, no user +// site directory, no script directory on sys.path) and never writes +// bytecode (-B). +func Python3(interpreter string) Language { + source := sandbox.BoxPath + "/main.py" + return Language{ + ID: "python3", + SourceFile: "main.py", + Compile: []string{interpreter, "-I", "-B", "-c", pythonSyntaxCheck, source}, + CompileLimits: sandbox.Limits{ + CPUTime: pythonCompileCPU, + WallTime: pythonCompileWall, + MemoryBytes: pythonCompileMemory, + OutputBytes: pythonCompileOutput, + }, + Run: []string{interpreter, "-I", "-B", source}, + } +} diff --git a/runner/internal/sandbox/cgroup.go b/runner/internal/sandbox/cgroup.go new file mode 100644 index 0000000..20ddf14 --- /dev/null +++ b/runner/internal/sandbox/cgroup.go @@ -0,0 +1,353 @@ +package sandbox + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "syscall" + "time" +) + +const ( + supervisorCgroup = "supervisor" + jailsCgroup = "jails" + // cpuQuota allows one CPU per run: quota and period in microseconds. + cpuQuota = "100000 100000" + // cgroupDrainTimeout bounds the wait for a killed cgroup to empty. + cgroupDrainTimeout = 5 * time.Second + cgroupDrainPoll = 5 * time.Millisecond + // moveAttempts bounds retries while processes appear in the root cgroup. + moveAttempts = 10 + cgroupFileMode = 0o644 + cgroupDirMode = 0o755 + bytesPerKB = 1 << 10 +) + +var requiredControllers = []string{"cpu", "memory", "pids"} + +// cgroupTree is the cgroup hierarchy owned by the runner: +// +// /supervisor the runner process itself +// /jails/ one cgroup per sandboxed run +// +// cgroup v2 forbids processes in a cgroup that delegates controllers to its +// children, so the runner first moves itself out of the root. +type cgroupTree struct { + root string + jails string +} + +// prepareCgroups creates the hierarchy below root, enables the controllers, +// and removes run cgroups left by an earlier process. +func prepareCgroups(root string) (*cgroupTree, error) { + controllers, err := os.ReadFile(filepath.Join(root, "cgroup.controllers")) + if err != nil { + return nil, fmt.Errorf("sandbox.prepareCgroups - read controllers: %w", err) + } + available := strings.Fields(string(controllers)) + for _, controller := range requiredControllers { + if !slices.Contains(available, controller) { + return nil, fmt.Errorf("sandbox.prepareCgroups - controller %s is not delegated", controller) + } + } + supervisor := filepath.Join(root, supervisorCgroup) + if err := mkdirCgroup(supervisor); err != nil { + return nil, err + } + if err := moveProcesses(root, supervisor); err != nil { + return nil, err + } + enable := "+" + strings.Join(requiredControllers, " +") + if err := writeCgroupFile(root, "cgroup.subtree_control", enable); err != nil { + return nil, err + } + tree := &cgroupTree{root: root, jails: filepath.Join(root, jailsCgroup)} + if err := mkdirCgroup(tree.jails); err != nil { + return nil, err + } + if err := writeCgroupFile(tree.jails, "cgroup.subtree_control", enable); err != nil { + return nil, err + } + if err := tree.removeLeftovers(); err != nil { + return nil, err + } + return tree, nil +} + +func mkdirCgroup(path string) error { + if err := os.Mkdir(path, cgroupDirMode); err != nil && !errors.Is(err, fs.ErrExist) { + return fmt.Errorf("sandbox.mkdirCgroup - create %s: %w", filepath.Base(path), err) + } + return nil +} + +// moveProcesses moves every process of the from cgroup into the to cgroup. +func moveProcesses(from, to string) error { + for range moveAttempts { + pids, err := readPIDs(from) + if err != nil { + return err + } + if len(pids) == 0 { + return nil + } + for _, pid := range pids { + err := writeCgroupFile(to, "cgroup.procs", strconv.Itoa(pid)) + if err != nil && !errors.Is(err, syscall.ESRCH) { + return err + } + } + } + return errors.New("sandbox.moveProcesses - processes keep appearing in the root cgroup") +} + +func readPIDs(cgroup string) ([]int, error) { + content, err := os.ReadFile(filepath.Join(cgroup, "cgroup.procs")) + if err != nil { + return nil, fmt.Errorf("sandbox.readPIDs - read procs: %w", err) + } + var pids []int + for field := range strings.FieldsSeq(string(content)) { + pid, err := strconv.Atoi(field) + if err != nil { + return nil, fmt.Errorf("sandbox.readPIDs - parse pid: %w", err) + } + pids = append(pids, pid) + } + return pids, nil +} + +// removeLeftovers kills and removes run cgroups of an earlier process. +func (t *cgroupTree) removeLeftovers() error { + entries, err := os.ReadDir(t.jails) + if err != nil { + return fmt.Errorf("sandbox.cgroupTree.removeLeftovers - list: %w", err) + } + for _, entry := range entries { + if !entry.IsDir() { + continue + } + run := &runCgroup{path: filepath.Join(t.jails, entry.Name())} + if err := run.remove(context.Background()); err != nil { + return err + } + } + return nil +} + +// leftoverRuns returns the names of run cgroups that still exist. +func (t *cgroupTree) leftoverRuns() ([]string, error) { + entries, err := os.ReadDir(t.jails) + if err != nil { + return nil, fmt.Errorf("sandbox.cgroupTree.leftoverRuns - list: %w", err) + } + var names []string + for _, entry := range entries { + if entry.IsDir() { + names = append(names, entry.Name()) + } + } + return names, nil +} + +// cgroupLimits are the controller values of one run cgroup. +type cgroupLimits struct { + memoryBytes int64 + processes int +} + +// runCgroup is the cgroup of one run. dir is an open descriptor of the +// directory for CLONE_INTO_CGROUP. +type runCgroup struct { + path string + dir *os.File +} + +func (t *cgroupTree) create(ctx context.Context, name string, limits cgroupLimits) (*runCgroup, error) { + cleanupCtx := context.WithoutCancel(ctx) + path := filepath.Join(t.jails, name) + if err := os.Mkdir(path, cgroupDirMode); err != nil { + return nil, fmt.Errorf("sandbox.cgroupTree.create - create: %w", err) + } + run := &runCgroup{path: path} + settings := []struct{ file, value string }{ + {"memory.max", strconv.FormatInt(limits.memoryBytes, 10)}, + {"memory.swap.max", "0"}, + {"pids.max", strconv.Itoa(limits.processes)}, + {"cpu.max", cpuQuota}, + } + for _, setting := range settings { + err := writeCgroupFile(path, setting.file, setting.value) + if errors.Is(err, fs.ErrNotExist) && setting.file == "memory.swap.max" { + // A kernel without swap accounting has no swap to limit. + continue + } + if err != nil { + return nil, errors.Join(err, run.remove(cleanupCtx)) + } + } + dir, err := os.Open(path) + if err != nil { + return nil, errors.Join(fmt.Errorf("sandbox.cgroupTree.create - open: %w", err), run.remove(cleanupCtx)) + } + run.dir = dir + return run, nil +} + +// cgroupStats are the counters the supervisor reads during and after a run. +type cgroupStats struct { + cpuUsage time.Duration + oomKills int64 + pidsLimits int64 +} + +func (c *runCgroup) stats() (cgroupStats, error) { + var stats cgroupStats + cpu, err := readKeyedFile(c.path, "cpu.stat") + if err != nil { + return stats, err + } + stats.cpuUsage = time.Duration(cpu["usage_usec"]) * time.Microsecond + memory, err := readKeyedFile(c.path, "memory.events") + if err != nil { + return stats, err + } + stats.oomKills = memory["oom_kill"] + memory["oom_group_kill"] + pids, err := readKeyedFile(c.path, "pids.events") + if err != nil { + return stats, err + } + stats.pidsLimits = pids["max"] + return stats, nil +} + +// kill stops every process of the cgroup. +func (c *runCgroup) kill() error { + err := writeCgroupFile(c.path, "cgroup.kill", "1") + if !errors.Is(err, fs.ErrNotExist) { + return err + } + // Kernels before 5.14 have no cgroup.kill; signal each process instead. + pids, err := readPIDs(c.path) + if err != nil { + return err + } + for _, pid := range pids { + if err := syscall.Kill(pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) { + return fmt.Errorf("sandbox.runCgroup.kill - signal: %w", err) + } + } + return nil +} + +// killExcept kills every process of the cgroup except keep. Killing the +// jailed processes but not nsjail lets nsjail reap its child and report how it +// ended; once the namespace's first process dies, the kernel kills the rest +// of the PID namespace. +func (c *runCgroup) killExcept(keep int) error { + pids, err := readPIDs(c.path) + if err != nil { + return err + } + for _, pid := range pids { + if pid == keep { + continue + } + if err := syscall.Kill(pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) { + return fmt.Errorf("sandbox.runCgroup.killExcept - signal: %w", err) + } + } + return nil +} + +// remove kills what is left, waits until the cgroup is empty, and deletes it. +func (c *runCgroup) remove(ctx context.Context) error { + if c.dir != nil { + _ = c.dir.Close() // The descriptor only served CLONE_INTO_CGROUP. + c.dir = nil + } + if err := c.kill(); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + ctx, cancel := context.WithTimeout(ctx, cgroupDrainTimeout) + defer cancel() + for { + err := os.Remove(c.path) + if err == nil || errors.Is(err, fs.ErrNotExist) { + return nil + } + if !errors.Is(err, syscall.EBUSY) { + return fmt.Errorf("sandbox.runCgroup.remove - remove: %w", err) + } + select { + case <-ctx.Done(): + return fmt.Errorf("sandbox.runCgroup.remove - processes did not exit: %w", ctx.Err()) + case <-time.After(cgroupDrainPoll): + } + } +} + +func writeCgroupFile(dir, name, value string) error { + path := filepath.Join(dir, name) + // O_TRUNC is not allowed on cgroup files; each write is one operation. + file, err := os.OpenFile(path, os.O_WRONLY, cgroupFileMode) + if err != nil { + return fmt.Errorf("sandbox.writeCgroupFile - open %s: %w", name, err) + } + _, writeErr := file.WriteString(value) + closeErr := file.Close() + if writeErr != nil { + return fmt.Errorf("sandbox.writeCgroupFile - write %s: %w", name, writeErr) + } + if closeErr != nil { + return fmt.Errorf("sandbox.writeCgroupFile - close %s: %w", name, closeErr) + } + return nil +} + +// readKeyedFile parses a flat "key value" cgroup file. +func readKeyedFile(dir, name string) (map[string]int64, error) { + content, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + return nil, fmt.Errorf("sandbox.readKeyedFile - read %s: %w", name, err) + } + values := make(map[string]int64) + scanner := bufio.NewScanner(bytes.NewReader(content)) + for scanner.Scan() { + key, value, found := strings.Cut(scanner.Text(), " ") + if !found { + continue + } + number, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64) + if err != nil { + continue + } + values[key] = number + } + return values, nil +} + +// peakMemoryKB returns memory.peak in KiB, or 0 when the kernel has no +// such file. It is the exact high-water mark of every process of the run, +// nsjail included, plus file cache charged to the run. Unlike ru_maxrss it +// never includes the runner itself: Go starts nsjail through vfork, so the +// rusage of nsjail inherits the runner's resident set at exec. +func (c *runCgroup) peakMemoryKB() int64 { + content, err := os.ReadFile(filepath.Join(c.path, "memory.peak")) + if err != nil { + return 0 + } + peak, err := strconv.ParseInt(strings.TrimSpace(string(content)), 10, 64) + if err != nil { + return 0 + } + return peak / bytesPerKB +} diff --git a/runner/internal/sandbox/executor.go b/runner/internal/sandbox/executor.go new file mode 100644 index 0000000..5c17b4e --- /dev/null +++ b/runner/internal/sandbox/executor.go @@ -0,0 +1,384 @@ +package sandbox + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "os/exec" + "sync" + "time" +) + +const ( + // nsjailProcesses is the supervising nsjail process inside the run + // cgroup; it is added to the process limit of the program. + nsjailProcesses = 1 + // maxNsjailLog bounds the nsjail log kept for one run. + maxNsjailLog = 64 << 10 + runNameBytes = 8 + readChunk = 32 << 10 +) + +// terminationCanceled marks a run stopped because its context ended. +const terminationCanceled Termination = "canceled" + +// Executor runs commands in nsjail. It is safe for concurrent use. +type Executor struct { + cfg Config + cgroups *cgroupTree + policy string +} + +// New checks the host and prepares the cgroup hierarchy and the work root. +func New(cfg Config) (*Executor, error) { + if err := platformSupported(); err != nil { + return nil, err + } + if err := validateConfig(cfg); err != nil { + return nil, err + } + info, err := os.Stat(cfg.NsjailPath) + if err != nil { + return nil, fmt.Errorf("sandbox.New - stat nsjail: %w", err) + } + if info.IsDir() || info.Mode().Perm()&0o111 == 0 { + return nil, errors.New("sandbox.New - nsjail is not an executable file") + } + if err := emptyWorkRoot(cfg.WorkRoot); err != nil { + return nil, err + } + tree, err := prepareCgroups(cfg.CgroupRoot) + if err != nil { + return nil, err + } + return &Executor{cfg: cfg, cgroups: tree, policy: seccompPolicy()}, nil +} + +func validateConfig(cfg Config) error { + switch { + case cfg.SandboxUID <= 0 || cfg.SandboxGID <= 0: + return errors.New("sandbox.validateConfig - the sandbox user must not be root") + case cfg.MaxProcesses <= 0: + return errors.New("sandbox.validateConfig - the process limit must be positive") + case cfg.TmpfsBytes <= 0 || cfg.FileSizeBytes <= 0 || cfg.OpenFiles <= 0: + return errors.New("sandbox.validateConfig - tmpfs, file size, and open file limits must be positive") + case cfg.StderrCaptureBytes <= 0 || cfg.PollInterval <= 0: + return errors.New("sandbox.validateConfig - stderr capture and poll interval must be positive") + case cfg.MemoryOverheadBytes < 0: + return errors.New("sandbox.validateConfig - the memory overhead must not be negative") + } + return nil +} + +// NewBox creates the read-only file directory of a run. +func (e *Executor) NewBox(fileName string, content []byte) (*Box, error) { + return CreateBox(e.cfg.WorkRoot, fileName, content) +} + +// Leftovers lists boxes and run cgroups that still exist. After every run +// has finished both lists are empty. +func (e *Executor) Leftovers() (boxes, cgroups []string, err error) { + entries, err := os.ReadDir(e.cfg.WorkRoot) + if err != nil { + return nil, nil, fmt.Errorf("sandbox.Executor.Leftovers - list work root: %w", err) + } + for _, entry := range entries { + boxes = append(boxes, entry.Name()) + } + cgroups, err = e.cgroups.leftoverRuns() + return boxes, cgroups, err +} + +// Run executes spec under limits. It returns an error only when the sandbox +// itself failed or ctx ended; every outcome caused by the program, including +// a limit, is a Result. +func (e *Executor) Run(ctx context.Context, spec Spec, limits Limits) (result Result, err error) { + cgroup, err := e.cgroups.create(ctx, newRunName(), cgroupLimits{ + memoryBytes: limits.MemoryBytes + e.cfg.MemoryOverheadBytes, + processes: e.cfg.MaxProcesses + nsjailProcesses, + }) + if err != nil { + return Result{}, err + } + defer func() { + // A cgroup that cannot be removed may still hold processes, so the + // run is not trustworthy. + if removeErr := cgroup.remove(context.WithoutCancel(ctx)); removeErr != nil { + err = errors.Join(err, removeErr) + } + }() + + pipes, err := openPipes() + if err != nil { + return Result{}, err + } + defer pipes.closeAll() + + // The watchdog stops a canceled run by killing its whole cgroup; + // CommandContext would kill only nsjail. The binary path comes from + // configuration and the arguments are built above. + cmd := exec.Command(e.cfg.NsjailPath, nsjailArgs(e.cfg, spec, limits, e.policy)...) //nolint:noctx,gosec // See the comment above. + // The runner environment, including any secret, never reaches nsjail. + cmd.Env = []string{} + cmd.Stdin = bytes.NewReader(spec.Stdin) + cmd.Stdout = pipes.stdoutWrite + cmd.Stderr = pipes.stderrWrite + cmd.ExtraFiles = []*os.File{pipes.logWrite} + attachToCgroup(cmd, cgroup) + + started := time.Now() + if err := cmd.Start(); err != nil { + return Result{}, fmt.Errorf("sandbox.Executor.Run - start nsjail: %w", err) + } + pipes.closeWriteEnds() + + stopper := &stopper{cgroup: cgroup, nsjailPID: cmd.Process.Pid} + var readers sync.WaitGroup + var stdout, stderr, nsjailLog []byte + readers.Go(func() { + stdout = readLimited(pipes.stdoutRead, limits.OutputBytes, func() { stopper.stop(TerminationOutput) }) + }) + readers.Go(func() { stderr = readTail(pipes.stderrRead, e.cfg.StderrCaptureBytes) }) + readers.Go(func() { nsjailLog = readLimited(pipes.logRead, maxNsjailLog, func() {}) }) + + watchdogDone := make(chan struct{}) + var watchdog sync.WaitGroup + watchdog.Go(func() { e.watch(ctx, cgroup, limits, stopper, watchdogDone) }) + + readers.Wait() + waitErr := cmd.Wait() + wallTime := time.Since(started) + close(watchdogDone) + watchdog.Wait() + + var exitErr *exec.ExitError + if waitErr != nil && !errors.As(waitErr, &exitErr) { + return Result{}, fmt.Errorf("sandbox.Executor.Run - wait for nsjail: %w", waitErr) + } + stats, err := cgroup.stats() + if err != nil { + return Result{}, err + } + reason := stopper.reason() + if reason == terminationCanceled { + return Result{}, fmt.Errorf("sandbox.Executor.Run - run stopped: %w", context.Cause(ctx)) + } + if reason == TerminationNone { + reason = terminationFromStats(stats, limits) + } + result = Result{ + Stdout: stdout, + Stderr: stderr, + CPUTime: stats.cpuUsage, + WallTime: wallTime, + PeakMemoryKB: cgroup.peakMemoryKB(), + Termination: reason, + } + if result.PeakMemoryKB == 0 { + // Kernels before 5.19 have no memory.peak. + result.PeakMemoryKB = peakMemoryKB(cmd.ProcessState) + } + return result, applyExitStatus(&result, parseNsjailLog(nsjailLog), cmd.ProcessState) +} + +// terminationFromStats finds a limit that stopped the run between two polls +// or that the program reached without being stopped. +func terminationFromStats(stats cgroupStats, limits Limits) Termination { + switch { + case stats.oomKills > 0: + return TerminationMemory + case stats.pidsLimits > 0: + return TerminationProcesses + case stats.cpuUsage > limits.CPUTime: + return TerminationCPUTime + default: + return TerminationNone + } +} + +// applyExitStatus fills the exit code and signal from the nsjail log. +func applyExitStatus(result *Result, report nsjailReport, state *os.ProcessState) error { + stoppedBySupervisor := result.Termination != TerminationNone + switch { + case report.failure != "" && !stoppedBySupervisor: + return fmt.Errorf("sandbox.applyExitStatus - nsjail failed: %s", report.failure) + case report.reported: + result.ExitCode = report.exitCode + result.Signal = report.signal + case stoppedBySupervisor: + // nsjail was killed together with the program. + result.ExitCode = -1 + result.Signal = signalKill + default: + return fmt.Errorf("sandbox.applyExitStatus - nsjail ended without a report: %s", state.String()) + } + return nil +} + +// watch enforces the CPU and wall-clock limits and stops a run as soon as +// the cgroup reports an OOM kill or a refused fork. +func (e *Executor) watch(ctx context.Context, cgroup *runCgroup, limits Limits, stopper *stopper, done <-chan struct{}) { + ticker := time.NewTicker(e.cfg.PollInterval) + defer ticker.Stop() + wall := time.NewTimer(limits.WallTime) + defer wall.Stop() + for { + select { + case <-done: + return + case <-ctx.Done(): + stopper.stop(terminationCanceled) + case <-wall.C: + stopper.stop(TerminationWallTime) + case <-ticker.C: + stopper.enforceGrace() + stats, err := cgroup.stats() + if err != nil { + // The cgroup is gone only after the run ended. + continue + } + if reason := terminationFromStats(stats, limits); reason != TerminationNone { + stopper.stop(reason) + } + } + } +} + +// stopper records the first reason a run was stopped and kills the jailed +// processes. nsjail stays alive to reap its child, so no orphan is left to +// the init process; if nsjail does not exit within stopGrace, the watchdog +// kills the whole cgroup. +type stopper struct { + cgroup *runCgroup + nsjailPID int + mu sync.Mutex + first Termination + stoppedAt time.Time +} + +// stopGrace is how long nsjail may take to reap a killed program. +const stopGrace = time.Second + +func (s *stopper) stop(reason Termination) { + s.mu.Lock() + defer s.mu.Unlock() + if s.first == TerminationNone { + s.first = reason + s.stoppedAt = time.Now() + } + // Killing again is harmless and covers processes forked meanwhile. + _ = s.cgroup.killExcept(s.nsjailPID) // A failure surfaces when the cgroup is removed. +} + +// enforceGrace kills nsjail too when it outlives the grace period. +func (s *stopper) enforceGrace() { + s.mu.Lock() + defer s.mu.Unlock() + if s.first != TerminationNone && time.Since(s.stoppedAt) > stopGrace { + _ = s.cgroup.kill() // A failure surfaces when the cgroup is removed. + } +} + +func (s *stopper) reason() Termination { + s.mu.Lock() + defer s.mu.Unlock() + return s.first +} + +// readLimited reads r to the end and keeps at most limit bytes; onExceeded +// runs once when more arrives. Reading continues so the writer never blocks. +func readLimited(r io.Reader, limit int64, onExceeded func()) []byte { + var kept bytes.Buffer + var exceeded bool + chunk := make([]byte, readChunk) + for { + n, err := r.Read(chunk) + if n > 0 { + room := limit - int64(kept.Len()) + if int64(n) > room { + kept.Write(chunk[:max(room, 0)]) + if !exceeded { + exceeded = true + onExceeded() + } + } else { + kept.Write(chunk[:n]) + } + } + if err != nil { + return kept.Bytes() + } + } +} + +// readTail reads r to the end and keeps its last limit bytes. +func readTail(r io.Reader, limit int) []byte { + var kept []byte + chunk := make([]byte, readChunk) + for { + n, err := r.Read(chunk) + kept = append(kept, chunk[:n]...) + if len(kept) > 2*limit { + kept = append([]byte(nil), kept[len(kept)-limit:]...) + } + if err != nil { + if len(kept) > limit { + kept = kept[len(kept)-limit:] + } + return kept + } + } +} + +type runPipes struct { + stdoutRead, stdoutWrite *os.File + stderrRead, stderrWrite *os.File + logRead, logWrite *os.File +} + +func openPipes() (*runPipes, error) { + pipes := &runPipes{} + var err error + if pipes.stdoutRead, pipes.stdoutWrite, err = os.Pipe(); err != nil { + return nil, fmt.Errorf("sandbox.openPipes - stdout: %w", err) + } + if pipes.stderrRead, pipes.stderrWrite, err = os.Pipe(); err != nil { + pipes.closeAll() + return nil, fmt.Errorf("sandbox.openPipes - stderr: %w", err) + } + if pipes.logRead, pipes.logWrite, err = os.Pipe(); err != nil { + pipes.closeAll() + return nil, fmt.Errorf("sandbox.openPipes - log: %w", err) + } + return pipes, nil +} + +func (p *runPipes) closeWriteEnds() { + for _, file := range []**os.File{&p.stdoutWrite, &p.stderrWrite, &p.logWrite} { + if *file != nil { + _ = (*file).Close() // The child holds its own copy. + *file = nil + } + } +} + +func (p *runPipes) closeAll() { + p.closeWriteEnds() + for _, file := range []**os.File{&p.stdoutRead, &p.stderrRead, &p.logRead} { + if *file != nil { + _ = (*file).Close() // Reading has finished. + *file = nil + } + } +} + +func newRunName() string { + name := make([]byte, runNameBytes) + _, _ = rand.Read(name) // crypto/rand.Read never fails on supported platforms. + return "run-" + hex.EncodeToString(name) +} diff --git a/runner/internal/sandbox/nsjail.go b/runner/internal/sandbox/nsjail.go new file mode 100644 index 0000000..0faba83 --- /dev/null +++ b/runner/internal/sandbox/nsjail.go @@ -0,0 +1,132 @@ +package sandbox + +import ( + "bufio" + "bytes" + "math" + "regexp" + "strconv" + "time" +) + +const ( + // nsjailLogFD is the descriptor of the nsjail log pipe in the child. + nsjailLogFD = 3 + // addressSpaceLimitMB stays far above the cgroup memory limit, so that + // memory pressure ends in a cgroup OOM kill (memory_limit_exceeded) + // instead of an allocation failure inside the program; it still stops + // absurd reservations. + addressSpaceLimitMB = 4096 + // nsjailTimeBackstop is added to the wall-clock limit for nsjail's own + // time limit, which only matters if the supervisor fails to stop a run. + nsjailTimeBackstop = 2 * time.Second + // cpuRlimitBackstop is added to the CPU limit for RLIMIT_CPU; the + // supervisor's cgroup watchdog normally stops a run first. + cpuRlimitBackstop = time.Second + sandboxHostname = "sandbox" + bytesPerMB = 1 << 20 +) + +// nsjailArgs returns the nsjail command line for one run. Every isolation +// switch is explicit so that a change in nsjail defaults cannot weaken it. +func nsjailArgs(cfg Config, spec Spec, limits Limits, seccompPolicy string) []string { + args := []string{ + "--mode", "o", + "--log_fd", strconv.Itoa(nsjailLogFD), + "--hostname", sandboxHostname, + "--cwd", ScratchPath, + // Inside and outside the user namespace the program is the same + // unprivileged ID, never root. + "--user", idMapping(cfg.SandboxUID), + "--group", idMapping(cfg.SandboxGID), + "--time_limit", strconv.Itoa(ceilSeconds(limits.WallTime + nsjailTimeBackstop)), + "--rlimit_as", strconv.Itoa(addressSpaceLimitMB), + "--rlimit_cpu", strconv.Itoa(ceilSeconds(limits.CPUTime + cpuRlimitBackstop)), + "--rlimit_fsize", strconv.Itoa(ceilMB(cfg.FileSizeBytes)), + "--rlimit_nofile", strconv.Itoa(cfg.OpenFiles), + "--rlimit_core", "0", + "--disable_proc", + // A new network namespace is nsjail's default; the empty namespace + // also has no loopback interface. + "--iface_no_lo", + "--seccomp_string", seccompPolicy, + } + for _, mount := range cfg.ReadOnlyMounts { + args = append(args, "--bindmount_ro", mount) + } + args = append(args, + "--bindmount_ro", spec.BoxDir+":"+BoxPath, + "--bindmount", "/dev/null", + "--bindmount_ro", "/dev/urandom", + "--mount", "none:"+ScratchPath+":tmpfs:size="+strconv.FormatInt(cfg.TmpfsBytes, 10), + ) + for _, variable := range cfg.Env { + args = append(args, "--env", variable) + } + args = append(args, "--") + return append(args, spec.Argv...) +} + +func idMapping(id int) string { + value := strconv.Itoa(id) + return value + ":" + value + ":1" +} + +func ceilSeconds(duration time.Duration) int { + return int(math.Ceil(duration.Seconds())) +} + +func ceilMB(size int64) int { + return max(1, int((size+bytesPerMB-1)/bytesPerMB)) +} + +var ( + childExited = regexp.MustCompile(`\) exited with status: (\d+)`) + childSignaled = regexp.MustCompile(`\) terminated with signal: [^(]*\((\d+)\)`) +) + +// nsjailReport is what the nsjail log says about the jailed command. +type nsjailReport struct { + exitCode int + signal int + // reported is true when the log names how the command ended. + reported bool + // failure is the first error line of nsjail itself, without timestamps. + failure string +} + +const maxFailureExcerpt = 200 + +// parseNsjailLog reads the nsjail log. A launch failure is reported by error +// ([E]) or fatal ([F]) lines; the log never contains program input or output. +func parseNsjailLog(log []byte) nsjailReport { + var report nsjailReport + scanner := bufio.NewScanner(bytes.NewReader(log)) + for scanner.Scan() { + line := scanner.Bytes() + if report.failure == "" && (bytes.HasPrefix(line, []byte("[E]")) || bytes.HasPrefix(line, []byte("[F]"))) { + report.failure = failureExcerpt(line) + } + if match := childExited.FindSubmatch(line); match != nil { + report.exitCode, _ = strconv.Atoi(string(match[1])) + report.reported = true + } + if match := childSignaled.FindSubmatch(line); match != nil { + report.signal, _ = strconv.Atoi(string(match[1])) + report.exitCode = -1 + report.reported = true + } + } + return report +} + +func failureExcerpt(line []byte) string { + // Drop the "[E][timestamp][pid] " prefix; keep the function and message. + if index := bytes.LastIndexByte(line, ']'); index >= 0 && index+1 < len(line) { + line = bytes.TrimSpace(line[index+1:]) + } + if len(line) > maxFailureExcerpt { + line = line[:maxFailureExcerpt] + } + return string(bytes.ToValidUTF8(line, []byte("?"))) +} diff --git a/runner/internal/sandbox/process_linux.go b/runner/internal/sandbox/process_linux.go new file mode 100644 index 0000000..e61a867 --- /dev/null +++ b/runner/internal/sandbox/process_linux.go @@ -0,0 +1,38 @@ +//go:build linux + +package sandbox + +import ( + "os" + "os/exec" + "syscall" +) + +const signalKill = int(syscall.SIGKILL) + +func platformSupported() error { + return nil +} + +// attachToCgroup starts nsjail directly inside the run cgroup, so no +// instruction of nsjail or of the program runs outside its limits, and kills +// nsjail if the runner dies. +func attachToCgroup(cmd *exec.Cmd, cgroup *runCgroup) { + cmd.SysProcAttr = &syscall.SysProcAttr{ + UseCgroupFD: true, + CgroupFD: int(cgroup.dir.Fd()), + Setpgid: true, + Pdeathsig: syscall.SIGKILL, + } +} + +// peakMemoryKB returns ru_maxrss of nsjail in KiB, the fallback when the +// kernel has no memory.peak. It overstates small programs because it +// includes the runner's resident set at exec. +func peakMemoryKB(state *os.ProcessState) int64 { + usage, ok := state.SysUsage().(*syscall.Rusage) + if !ok { + return 0 + } + return usage.Maxrss +} diff --git a/runner/internal/sandbox/process_other.go b/runner/internal/sandbox/process_other.go new file mode 100644 index 0000000..8002423 --- /dev/null +++ b/runner/internal/sandbox/process_other.go @@ -0,0 +1,21 @@ +//go:build !linux + +package sandbox + +import ( + "os" + "os/exec" +) + +// signalKill is the Linux SIGKILL number reported by stopped runs. +const signalKill = 9 + +func platformSupported() error { + return ErrUnsupportedPlatform +} + +func attachToCgroup(*exec.Cmd, *runCgroup) {} + +func peakMemoryKB(*os.ProcessState) int64 { + return 0 +} diff --git a/runner/internal/sandbox/sandbox.go b/runner/internal/sandbox/sandbox.go new file mode 100644 index 0000000..ac4e50d --- /dev/null +++ b/runner/internal/sandbox/sandbox.go @@ -0,0 +1,103 @@ +// Package sandbox runs one untrusted command inside nsjail. +// +// Every run gets its own cgroup v2 directory with CPU, memory, swap, and +// process limits. The supervisor creates that cgroup itself and starts nsjail +// directly inside it (CLONE_INTO_CGROUP), so the limits cover nsjail and every +// jailed process, the supervisor can read exact OOM, process-limit, and CPU +// counters, and cgroup.kill removes the whole tree. nsjail adds the namespaces +// (no network, own PID, mount, IPC, UTS, user, and cgroup namespaces), the +// read-only file system with a tmpfs work directory, the unprivileged user, +// rlimits, and the seccomp policy. +package sandbox + +import ( + "errors" + "time" +) + +// Termination names the limit that stopped a run. +type Termination string + +const ( + // TerminationNone means that the program stopped by itself. + TerminationNone Termination = "" + // TerminationCPUTime means the CPU time limit. + TerminationCPUTime Termination = "cpu_time" + // TerminationWallTime means the wall-clock limit. + TerminationWallTime Termination = "wall_time" + // TerminationMemory means the cgroup memory limit. + TerminationMemory Termination = "memory" + // TerminationOutput means the standard output limit. + TerminationOutput Termination = "output" + // TerminationProcesses means the cgroup process limit. + TerminationProcesses Termination = "processes" +) + +// Jail paths seen by the jailed program. +const ( + // BoxPath is the read-only directory with the files of a run. + BoxPath = "/box" + // ScratchPath is the writable tmpfs and the working directory. + ScratchPath = "/tmp" +) + +// ErrUnsupportedPlatform reports that the sandbox needs Linux. +var ErrUnsupportedPlatform = errors.New("sandbox requires Linux with cgroup v2") + +// Limits bound one run. +type Limits struct { + CPUTime time.Duration + WallTime time.Duration + MemoryBytes int64 + OutputBytes int64 +} + +// Spec is one command to run in the jail. +type Spec struct { + // Argv is the command inside the jail; Argv[0] is an absolute path. + Argv []string + // Stdin is written to the standard input of the command. + Stdin []byte + // BoxDir is the host directory mounted read-only at BoxPath. + BoxDir string +} + +// Result describes a finished run. It never contains host paths. +type Result struct { + Stdout []byte + // Stderr holds at most Config.StderrCaptureBytes of standard error. + Stderr []byte + // ExitCode is the exit status of the command, or -1 when a signal stopped it. + ExitCode int + // Signal is the signal that stopped the command, or 0. + Signal int + CPUTime time.Duration + WallTime time.Duration + PeakMemoryKB int64 + Termination Termination +} + +// Config holds the host-side sandbox settings shared by every run. +type Config struct { + NsjailPath string + // CgroupRoot is a cgroup v2 directory delegated to the runner. + CgroupRoot string + // WorkRoot holds one directory per run; it is emptied at startup. + WorkRoot string + SandboxUID int + SandboxGID int + // MaxProcesses bounds processes and threads of a run, nsjail excluded. + MaxProcesses int + // MemoryOverheadBytes is added to the memory limit for nsjail itself. + MemoryOverheadBytes int64 + TmpfsBytes int64 + FileSizeBytes int64 + OpenFiles int + StderrCaptureBytes int + // ReadOnlyMounts are host paths mounted read-only at the same place. + ReadOnlyMounts []string + // Env is the complete environment of the jailed command. + Env []string + // PollInterval is how often the supervisor checks the cgroup counters. + PollInterval time.Duration +} diff --git a/runner/internal/sandbox/sandbox_test.go b/runner/internal/sandbox/sandbox_test.go new file mode 100644 index 0000000..13bb197 --- /dev/null +++ b/runner/internal/sandbox/sandbox_test.go @@ -0,0 +1,212 @@ +package sandbox + +import ( + "bytes" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +func testConfig() Config { + return Config{ + NsjailPath: "/usr/bin/nsjail", + SandboxUID: 99999, + SandboxGID: 99999, + MaxProcesses: 16, + TmpfsBytes: 16 << 20, + FileSizeBytes: 8 << 20, + OpenFiles: 64, + StderrCaptureBytes: 1024, + ReadOnlyMounts: []string{"/usr", "/lib"}, + Env: []string{"LANG=C.UTF-8"}, + PollInterval: time.Millisecond, + } +} + +// flagValue returns the value after the first occurrence of flag. +func flagValue(t *testing.T, args []string, flag string) string { + t.Helper() + index := slices.Index(args, flag) + if index < 0 || index+1 >= len(args) { + t.Fatalf("flag %s is missing in %q", flag, args) + } + return args[index+1] +} + +func TestNsjailArgsKeepEveryIsolationSwitch(t *testing.T) { + t.Parallel() + + spec := Spec{Argv: []string{"/usr/local/bin/python3", "-I", "/box/main.py"}, BoxDir: "/work/run-1"} + limits := Limits{CPUTime: 1500 * time.Millisecond, WallTime: 3500 * time.Millisecond, MemoryBytes: 64 << 20, OutputBytes: 1 << 16} + args := nsjailArgs(testConfig(), spec, limits, "POLICY") + + for _, forbidden := range []string{ + "--disable_clone_newnet", "-N", "--disable_clone_newuser", "--disable_clone_newns", "--disable_clone_newpid", + "--keep_caps", "--cap", "--disable_no_new_privs", "--rw", "--keep_env", "--chroot", "--proc_rw", "--use_pasta", + } { + if slices.Contains(args, forbidden) { + t.Errorf("args contain %s: %q", forbidden, args) + } + } + checks := map[string]string{ + "--mode": "o", + "--user": "99999:99999:1", + "--group": "99999:99999:1", + "--cwd": ScratchPath, + "--rlimit_cpu": "3", + "--rlimit_fsize": "8", + "--rlimit_nofile": "64", + "--rlimit_core": "0", + "--time_limit": "6", + "--seccomp_string": "POLICY", + "--mount": "none:/tmp:tmpfs:size=16777216", + } + for flag, want := range checks { + if got := flagValue(t, args, flag); got != want { + t.Errorf("%s = %q, want %q", flag, got, want) + } + } + for _, required := range []string{"--disable_proc", "--iface_no_lo"} { + if !slices.Contains(args, required) { + t.Errorf("args miss %s", required) + } + } + if !slices.Contains(args, "/work/run-1:/box") { + t.Errorf("the box is not mounted at /box: %q", args) + } + separator := slices.Index(args, "--") + if separator < 0 || !slices.Equal(args[separator+1:], spec.Argv) { + t.Errorf("command after -- = %q, want %q", args[separator+1:], spec.Argv) + } + for _, writable := range writableMounts(args) { + if writable != "/dev/null" { + t.Errorf("unexpected writable bind mount %q", writable) + } + } +} + +func writableMounts(args []string) []string { + var mounts []string + for index, arg := range args { + if arg == "--bindmount" && index+1 < len(args) { + mounts = append(mounts, args[index+1]) + } + } + return mounts +} + +func TestSeccompPolicyKillsNamespaceAndDebugSyscalls(t *testing.T) { + t.Parallel() + + policy := seccompPolicy() + for _, fragment := range []string{"ptrace", "unshare", "setns", "mount", "bpf", "io_uring_setup", "clone(flags)", "ERRNO(38) { clone3 }", "socket(domain)", "USE runner DEFAULT ALLOW"} { + if !strings.Contains(policy, fragment) { + t.Errorf("policy misses %q", fragment) + } + } +} + +func TestParseNsjailLog(t *testing.T) { + t.Parallel() + + exited := parseNsjailLog([]byte("[I][2026] Executing '/usr/local/bin/python3'\n[I][2026] pid=12 ([STANDALONE MODE]) exited with status: 3, (PIDs left: 0)\n")) + if !exited.reported || exited.exitCode != 3 || exited.signal != 0 || exited.failure != "" { + t.Fatalf("exited report = %+v", exited) + } + signaled := parseNsjailLog([]byte("[W][2026][11] seccompViolation():291 pid=12 committed a syscall/seccomp violation\n[I][2026] pid=12 ([STANDALONE MODE]) terminated with signal: Bad system call (31), (PIDs left: 0)\n")) + if !signaled.reported || signaled.signal != 31 || signaled.exitCode != -1 || signaled.failure != "" { + t.Fatalf("signaled report = %+v", signaled) + } + failed := parseNsjailLog([]byte("[E][2026-10-10T23:37:27+0000][1] initNsInternal():361 chdir('/tmp'): No such file or directory\n[F][2026][1] runChild():506 Launching child process failed\n")) + if failed.failure != "initNsInternal():361 chdir('/tmp'): No such file or directory" { + t.Fatalf("failure = %q", failed.failure) + } +} + +func TestApplyExitStatusSeparatesSandboxFailures(t *testing.T) { + t.Parallel() + + var result Result + if err := applyExitStatus(&result, nsjailReport{failure: "execve failed", reported: true, signal: 9}, nil); err == nil { + t.Fatal("a launch failure must be an error") + } + stopped := Result{Termination: TerminationWallTime} + if err := applyExitStatus(&stopped, nsjailReport{}, nil); err != nil || stopped.Signal != signalKill { + t.Fatalf("stopped run = %+v, %v; want SIGKILL without an error", stopped, err) + } +} + +func TestReadersBoundWhatTheyKeep(t *testing.T) { + t.Parallel() + + exceeded := 0 + kept := readLimited(bytes.NewReader(bytes.Repeat([]byte("a"), 100_000)), 10, func() { exceeded++ }) + if len(kept) != 10 || exceeded != 1 { + t.Fatalf("readLimited kept %d bytes and reported %d times", len(kept), exceeded) + } + tail := readTail(strings.NewReader(strings.Repeat("x", 100_000)+"END"), 8) + if string(tail) != "xxxxxEND" { + t.Fatalf("readTail = %q", tail) + } +} + +func TestCgroupStatsAndTermination(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + files := map[string]string{ + "cpu.stat": "usage_usec 1500000\nuser_usec 1400000\n", + "memory.events": "low 0\nhigh 0\nmax 4\noom 1\noom_kill 1\noom_group_kill 0\n", + "pids.events": "max 0\n", + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil { + t.Fatalf("write %s: %v", name, err) + } + } + stats, err := (&runCgroup{path: dir}).stats() + if err != nil { + t.Fatalf("stats: %v", err) + } + if stats.cpuUsage != 1500*time.Millisecond || stats.oomKills != 1 || stats.pidsLimits != 0 { + t.Fatalf("stats = %+v", stats) + } + limits := Limits{CPUTime: time.Second} + if got := terminationFromStats(stats, limits); got != TerminationMemory { + t.Fatalf("termination = %q, want memory before CPU time", got) + } + if got := terminationFromStats(cgroupStats{pidsLimits: 1}, limits); got != TerminationProcesses { + t.Fatalf("termination = %q, want processes", got) + } + if got := terminationFromStats(cgroupStats{cpuUsage: 2 * time.Second}, limits); got != TerminationCPUTime { + t.Fatalf("termination = %q, want cpu_time", got) + } +} + +func TestBoxIsReadOnlyAndRemovable(t *testing.T) { + t.Parallel() + + root := t.TempDir() + box, err := CreateBox(root, "main.py", []byte("print(1)")) + if err != nil { + t.Fatalf("CreateBox: %v", err) + } + info, err := os.Stat(filepath.Join(box.Dir(), "main.py")) + if err != nil || info.Mode().Perm() != boxFileMode { + t.Fatalf("source file mode = %v, %v", info.Mode(), err) + } + if err := box.Remove(); err != nil { + t.Fatalf("Remove: %v", err) + } + if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 { + t.Fatalf("root after Remove = %v, %v", entries, err) + } + for _, name := range []string{"", "../main.py", ".hidden", "dir/main.py"} { + if _, err := CreateBox(root, name, nil); err == nil { + t.Errorf("CreateBox accepted file name %q", name) + } + } +} diff --git a/runner/internal/sandbox/seccomp.go b/runner/internal/sandbox/seccomp.go new file mode 100644 index 0000000..05899d3 --- /dev/null +++ b/runner/internal/sandbox/seccomp.go @@ -0,0 +1,62 @@ +package sandbox + +import ( + "runtime" + "strconv" + "strings" +) + +// Linux constants used by the seccomp policy. +const ( + afUnix = 1 + // cloneNamespaceFlags is CLONE_NEWNS | CLONE_NEWCGROUP | CLONE_NEWUTS | + // CLONE_NEWIPC | CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET. + cloneNamespaceFlags = "0x7e020000" + errnoENOSYS = "38" + errnoEAFNOSUPPORT = "97" +) + +// killedSyscalls end the whole process with SIGSYS. An ordinary program +// never needs them; they open kernel attack surface or would let the program +// observe or change the jail: debugging other processes, mounts and +// namespaces, keyrings, eBPF, perf, userfaultfd, io_uring, kernel modules, +// and host clock, name, and swap administration. +var killedSyscalls = []string{ + "acct", "add_key", "adjtimex", "bpf", "chroot", "clock_settime", + "delete_module", "finit_module", "fsconfig", "fsmount", "fsopen", "fspick", + "init_module", "io_uring_enter", "io_uring_register", "io_uring_setup", + "kexec_file_load", "kexec_load", "keyctl", "mount", "mount_setattr", + "move_mount", "name_to_handle_at", "open_by_handle_at", "open_tree", + "perf_event_open", "pivot_root", "process_vm_readv", "process_vm_writev", + "ptrace", "quotactl", "reboot", "request_key", "sethostname", + "setdomainname", "setns", "settimeofday", "swapoff", "swapon", "syslog", + "unshare", "userfaultfd", +} + +// seccompPolicy returns the kafel policy for the build architecture. +// +// It is a deny list on top of the namespaces, the dropped capabilities, and +// no_new_privs: the program keeps the syscalls an interpreter or a compiled +// program needs, while namespace creation through clone is killed, clone3 is +// reported as missing so that libc falls back to the filtered clone, and +// sockets other than AF_UNIX fail with EAFNOSUPPORT. +func seccompPolicy() string { + killed := append([]string{umountSyscall()}, killedSyscalls...) + var policy strings.Builder + policy.WriteString("POLICY runner {\n") + policy.WriteString(" KILL_PROCESS {\n ") + policy.WriteString(strings.Join(killed, ",\n ")) + policy.WriteString(",\n clone(flags) { (flags & " + cloneNamespaceFlags + ") != 0 }\n },\n") + policy.WriteString(" ERRNO(" + errnoENOSYS + ") { clone3 },\n") + policy.WriteString(" ERRNO(" + errnoEAFNOSUPPORT + ") { socket(domain) { domain != " + strconv.Itoa(afUnix) + " } }\n") + policy.WriteString("}\nUSE runner DEFAULT ALLOW\n") + return policy.String() +} + +// umountSyscall returns the kafel name of umount2 for the architecture. +func umountSyscall() string { + if runtime.GOARCH == "arm64" { + return "umount" + } + return "umount2" +} diff --git a/runner/internal/sandbox/workdir.go b/runner/internal/sandbox/workdir.go new file mode 100644 index 0000000..0c91d1c --- /dev/null +++ b/runner/internal/sandbox/workdir.go @@ -0,0 +1,84 @@ +package sandbox + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +const ( + // The jailed user only reads and traverses the box; it owns nothing. + boxDirMode = 0o555 + boxFileMode = 0o444 + // ownerOnlyMode lets the supervisor delete the box again. + ownerOnlyMode = 0o700 + // workRootMode lets nsjail traverse to a box without listing the root: + // inside its user namespace host root's DAC override does not apply. + workRootMode = 0o711 + boxPrefix = "run-" +) + +// Box is the host directory with the files of one run. It is mounted +// read-only into every jail of the run and removed with Remove. +type Box struct { + dir string +} + +// Dir returns the host path of the box. +func (b *Box) Dir() string { + return b.dir +} + +// CreateBox creates a box under root with one file. +func CreateBox(root, fileName string, content []byte) (*Box, error) { + if fileName == "" || fileName != filepath.Base(fileName) || strings.HasPrefix(fileName, ".") { + return nil, fmt.Errorf("sandbox.CreateBox - invalid file name %q", fileName) + } + dir, err := os.MkdirTemp(root, boxPrefix) + if err != nil { + return nil, fmt.Errorf("sandbox.CreateBox - create: %w", err) + } + box := &Box{dir: dir} + if err := os.WriteFile(filepath.Join(dir, fileName), content, boxFileMode); err != nil { + return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - write: %w", err), box.Remove()) + } + if err := os.Chmod(dir, boxDirMode); err != nil { + return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - chmod: %w", err), box.Remove()) + } + return box, nil +} + +// Remove deletes the box and its files. +func (b *Box) Remove() error { + if err := os.Chmod(b.dir, ownerOnlyMode); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("sandbox.Box.Remove - chmod: %w", err) + } + if err := os.RemoveAll(b.dir); err != nil { + return fmt.Errorf("sandbox.Box.Remove - remove: %w", err) + } + return nil +} + +// emptyWorkRoot removes every entry of root, for example boxes of a process +// that crashed, and creates root when it is missing. +func emptyWorkRoot(root string) error { + if err := os.MkdirAll(root, workRootMode); err != nil { + return fmt.Errorf("sandbox.emptyWorkRoot - create: %w", err) + } + if err := os.Chmod(root, workRootMode); err != nil { + return fmt.Errorf("sandbox.emptyWorkRoot - chmod: %w", err) + } + entries, err := os.ReadDir(root) + if err != nil { + return fmt.Errorf("sandbox.emptyWorkRoot - list: %w", err) + } + for _, entry := range entries { + box := &Box{dir: filepath.Join(root, entry.Name())} + if err := box.Remove(); err != nil { + return err + } + } + return nil +} diff --git a/runner/internal/server/handler.go b/runner/internal/server/handler.go new file mode 100644 index 0000000..e353447 --- /dev/null +++ b/runner/internal/server/handler.go @@ -0,0 +1,237 @@ +// Package server implements the runner HTTP API on the generated ogen server. +package server + +import ( + "context" + "errors" + "fmt" + "log/slog" + "math" + "net/http" + "strconv" + "time" + + "github.com/google/uuid" + ogenerrors "github.com/ogen-go/ogen/ogenerrors" + + "lincodex/runner/internal/api" + "lincodex/runner/internal/checker" + "lincodex/runner/internal/jobs" + "lincodex/runner/internal/judge" +) + +// maxRunCPUBudget bounds tests multiplied by the per-test CPU limit, so one +// run cannot hold a sandbox slot for longer than a few minutes. +const maxRunCPUBudget = 300 * time.Second + +// Bytes per unit of the contract limits. +const ( + bytesPerKB = 1 << 10 + bytesPerMB = 1 << 20 +) + +// Store keeps runs; jobs.Manager implements it. +type Store interface { + Submit(id uuid.UUID, request judge.Request) (jobs.Snapshot, bool, error) + Get(id uuid.UUID) (jobs.Snapshot, error) +} + +// Handler implements the generated api.Handler. +type Handler struct { + store Store + supports func(language string) bool + ready func() bool + retryAfter time.Duration + logger *slog.Logger +} + +var _ api.Handler = (*Handler)(nil) + +// NewHandler returns the API handler. +func NewHandler(store Store, supports func(string) bool, ready func() bool, retryAfter time.Duration, logger *slog.Logger) *Handler { + return &Handler{store: store, supports: supports, ready: ready, retryAfter: retryAfter, logger: logger} +} + +// GetRunnerHealthz reports that the process responds. +func (h *Handler) GetRunnerHealthz(context.Context) (*api.RunnerHealthResponse, error) { + return &api.RunnerHealthResponse{Status: api.RunnerHealthResponseStatusOk}, nil +} + +// GetRunnerReadyz reports whether the sandbox accepts runs. +func (h *Handler) GetRunnerReadyz(context.Context) (api.GetRunnerReadyzRes, error) { + if h.ready() { + return &api.GetRunnerReadyzOK{Status: api.RunnerReadinessResponseStatusReady}, nil + } + return &api.GetRunnerReadyzServiceUnavailable{Status: api.RunnerReadinessResponseStatusNotReady}, nil +} + +// SubmitRun starts a run or returns the run with the same ID and payload. +func (h *Handler) SubmitRun(_ context.Context, req *api.RunRequest, params api.SubmitRunParams) (api.SubmitRunRes, error) { + request, fieldErrors := h.toJudgeRequest(req) + if len(fieldErrors) > 0 { + return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.", fieldErrors...) + } + snapshot, created, err := h.store.Submit(params.RunID, request) + switch { + case errors.Is(err, jobs.ErrBusy): + retryAfter := int32(min(math.Ceil(h.retryAfter.Seconds()), math.MaxInt32)) + return &api.RunnerBusyHeaders{ + RetryAfter: retryAfter, + Response: newProblem(http.StatusServiceUnavailable, api.ProblemCodeRunnerBusy, "Every sandbox slot is busy. Retry later with the same run ID."), + }, nil + case errors.Is(err, jobs.ErrPayloadMismatch): + return nil, problemError(http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused, "A run with this ID exists with a different payload.") + case err != nil: + return nil, fmt.Errorf("server.Handler.SubmitRun - submit: %w", err) + } + status := toRunStatus(snapshot) + if created { + accepted := api.SubmitRunAccepted(status) + return &accepted, nil + } + existing := api.SubmitRunOK(status) + return &existing, nil +} + +// GetRun returns the state and result of a run. +func (h *Handler) GetRun(_ context.Context, params api.GetRunParams) (*api.RunStatus, error) { + snapshot, err := h.store.Get(params.RunID) + if errors.Is(err, jobs.ErrNotFound) { + return nil, problemError(http.StatusNotFound, api.ProblemCodeNotFound, "The runner holds no run with this ID.") + } + if err != nil { + return nil, fmt.Errorf("server.Handler.GetRun - get: %w", err) + } + status := toRunStatus(snapshot) + return &status, nil +} + +// NewError maps errors of handlers and of the security check to problems. +func (h *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode { + var securityErr *ogenerrors.SecurityError + if errors.As(err, &securityErr) { + return problemError(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token.") + } + h.logger.ErrorContext(ctx, "request failed", slog.String("error_type", fmt.Sprintf("%T", err))) + return problemError(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.") +} + +// toJudgeRequest converts the request and checks the rules the schema +// cannot express. Field errors never echo submitted values. +func (h *Handler) toJudgeRequest(req *api.RunRequest) (judge.Request, []api.ProblemFieldError) { + var fieldErrors []api.ProblemFieldError + if !h.supports(string(req.Language)) { + fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, "/language")) + } + timeLimit := time.Duration(req.Limits.TimeLimitMs) * time.Millisecond + request := judge.Request{ + Language: string(req.Language), + Source: req.Source, + Limits: judge.Limits{ + TimeLimit: timeLimit, + MemoryBytes: int64(req.Limits.MemoryLimitMB) * bytesPerMB, + OutputBytes: int64(req.Limits.OutputLimitKB) * bytesPerKB, + }, + Groups: make([]judge.Group, 0, len(req.Groups)), + } + groupIDs := make(map[api.TestKey]bool, len(req.Groups)) + tests := 0 + for groupIndex, group := range req.Groups { + groupPointer := "/groups/" + strconv.Itoa(groupIndex) + if groupIDs[group.ID] { + fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, groupPointer+"/id")) + } + groupIDs[group.ID] = true + converted := judge.Group{ + ID: string(group.ID), + Visibility: judge.Visibility(group.Visibility), + Checker: checker.Spec{Kind: checker.Kind(group.Checker.Kind)}, + Tests: make([]judge.Test, 0, len(group.Tests)), + } + testIDs := make(map[api.TestKey]bool, len(group.Tests)) + for testIndex, test := range group.Tests { + if testIDs[test.ID] { + fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, groupPointer+"/tests/"+strconv.Itoa(testIndex)+"/id")) + } + testIDs[test.ID] = true + converted.Tests = append(converted.Tests, judge.Test{ID: string(test.ID), Input: test.Input, ExpectedOutput: test.ExpectedOutput}) + } + tests += len(group.Tests) + request.Groups = append(request.Groups, converted) + } + if time.Duration(tests)*timeLimit > maxRunCPUBudget { + fieldErrors = append(fieldErrors, invalidField(api.ProblemFieldLocationBody, "/limits/time_limit_ms")) + } + return request, fieldErrors +} + +func toRunStatus(snapshot jobs.Snapshot) api.RunStatus { + status := api.RunStatus{RunID: snapshot.ID, State: api.RunStateRunning} + if snapshot.State != jobs.Finished || snapshot.Result == nil { + return status + } + status.State = api.RunStateFinished + status.Result = api.NewOptRunResult(toRunResult(*snapshot.Result)) + return status +} + +func toRunResult(result judge.Result) api.RunResult { + converted := api.RunResult{ + Outcome: api.RunOutcome(result.Outcome), + Groups: make([]api.GroupResult, 0, len(result.Groups)), + DurationMs: result.Duration.Milliseconds(), + } + if result.Compile != nil { + compile := api.CompileResult{Outcome: api.RunOutcome(result.Compile.Outcome)} + if result.Compile.Diagnostic != "" { + compile.Diagnostic = api.NewOptString(result.Compile.Diagnostic) + } + converted.Compile = api.NewOptCompileResult(compile) + } + for _, group := range result.Groups { + converted.Groups = append(converted.Groups, toGroupResult(group)) + } + return converted +} + +func toGroupResult(group judge.GroupResult) api.GroupResult { + converted := api.GroupResult{ + ID: api.TestKey(group.ID), + Visibility: api.TestVisibility(group.Visibility), + Outcome: api.RunOutcome(group.Outcome), + PassedTests: int32(group.Passed), //nolint:gosec // The contract allows at most 50 tests per group. + TotalTests: int32(group.Total), //nolint:gosec // The contract allows at most 50 tests per group. + Tests: make([]api.TestResult, 0, len(group.Tests)), + } + if len(group.Tests) > 0 { + converted.MaxTimeMs = api.NewOptInt64(group.MaxCPUTime.Milliseconds()) + converted.MaxMemoryKB = api.NewOptInt64(group.MaxMemoryKB) + } + for _, test := range group.Tests { + converted.Tests = append(converted.Tests, toTestResult(test)) + } + return converted +} + +func toTestResult(test judge.TestResult) api.TestResult { + converted := api.TestResult{ + ID: api.TestKey(test.ID), + Outcome: api.RunOutcome(test.Outcome), + TimeMs: test.CPUTime.Milliseconds(), + WallTimeMs: test.WallTime.Milliseconds(), + MemoryKB: test.MemoryKB, + } + if test.ExitCode != nil { + converted.ExitCode = api.NewOptInt32(int32(*test.ExitCode)) //nolint:gosec // Exit statuses are below 256. + } + if test.Signal != nil { + converted.Signal = api.NewOptInt32(int32(*test.Signal)) //nolint:gosec // Signal numbers are below 65. + } + if test.Limit != "" { + converted.Limit = api.NewOptTerminationLimit(api.TerminationLimit(test.Limit)) + } + if test.Diagnostic != "" { + converted.Diagnostic = api.NewOptString(test.Diagnostic) + } + return converted +} diff --git a/runner/internal/server/problem.go b/runner/internal/server/problem.go new file mode 100644 index 0000000..6bf1ebc --- /dev/null +++ b/runner/internal/server/problem.go @@ -0,0 +1,95 @@ +package server + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net/http" + + "github.com/go-faster/jx" + ogenerrors "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/validate" + + "lincodex/runner/internal/api" +) + +const problemTypePrefix = "urn:lincodex:problem:" + +// problemTitles are the fixed titles of the runner problem codes. +var problemTitles = map[api.ProblemCode]string{ + api.ProblemCodeValidationFailed: "Request validation failed", + api.ProblemCodeUnauthenticated: "Authentication required", + api.ProblemCodeNotFound: "Not found", + api.ProblemCodeMethodNotAllowed: "Method not allowed", + api.ProblemCodePayloadTooLarge: "Payload too large", + api.ProblemCodeUnsupportedMediaType: "Unsupported media type", + api.ProblemCodeIdempotencyKeyReused: "Run ID reused with a different payload", + api.ProblemCodeInternal: "Internal server error", + api.ProblemCodeRunnerBusy: "Runner busy", +} + +const invalidFieldMessage = "The value does not match the contract." + +func newProblem(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) api.Problem { + problem := api.Problem{ + Type: problemTypePrefix + string(code), + Title: problemTitles[code], + Status: int32(status), //nolint:gosec // HTTP status codes fit in int32. + Code: code, + Errors: fieldErrors, + } + if detail != "" { + problem.Detail = api.NewOptString(detail) + } + return problem +} + +func problemError(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) *api.ProblemStatusCode { + return &api.ProblemStatusCode{StatusCode: status, Response: newProblem(status, code, detail, fieldErrors...)} +} + +func invalidField(in api.ProblemFieldLocation, pointer string) api.ProblemFieldError { + return api.ProblemFieldError{In: in, Pointer: pointer, Code: "invalid", Message: invalidFieldMessage} +} + +// writeProblem writes a problem outside the generated handlers. +func writeProblem(w http.ResponseWriter, problem api.Problem) { + encoder := jx.GetEncoder() + defer jx.PutEncoder(encoder) + problem.Encode(encoder) + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(int(problem.Status)) + _, _ = w.Write(encoder.Bytes()) // The client may have gone away. +} + +// errorHandler answers request decoding errors of the generated server. +func errorHandler(logger *slog.Logger) ogenerrors.ErrorHandler { + return func(ctx context.Context, w http.ResponseWriter, _ *http.Request, err error) { + writeProblem(w, decodeProblem(ctx, logger, err)) + } +} + +func decodeProblem(ctx context.Context, logger *slog.Logger, err error) api.Problem { + var tooLarge *http.MaxBytesError + var contentType *validate.InvalidContentTypeError + var paramsErr *ogenerrors.DecodeParamsError + var requestErr *ogenerrors.DecodeRequestError + switch { + case errors.As(err, &tooLarge): + return newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit.") + case errors.As(err, &contentType): + return newProblem(http.StatusUnsupportedMediaType, api.ProblemCodeUnsupportedMediaType, "Send the body as application/json.") + case errors.As(err, ¶msErr): + return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.", + invalidField(api.ProblemFieldLocationPath, "/run_id")) + case errors.As(err, &requestErr): + return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.", + invalidField(api.ProblemFieldLocationBody, "")) + default: + // The error text may describe internals; only its type is logged. + logger.ErrorContext(ctx, "request handling failed", slog.String("error_type", fmt.Sprintf("%T", err))) + return newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.") + } +} diff --git a/runner/internal/server/server.go b/runner/internal/server/server.go new file mode 100644 index 0000000..1af6caa --- /dev/null +++ b/runner/internal/server/server.go @@ -0,0 +1,108 @@ +package server + +import ( + "context" + "crypto/sha256" + "crypto/subtle" + "errors" + "fmt" + "log/slog" + "net/http" + "time" + + "lincodex/runner/internal/api" +) + +var errInvalidToken = errors.New("invalid bearer token") + +// tokenAuth checks the shared service token. Comparing SHA-256 digests in +// constant time hides both the content and the length of the token. +type tokenAuth struct { + digest [sha256.Size]byte +} + +func (a tokenAuth) HandleBearerAuth(ctx context.Context, _ api.OperationName, token api.BearerAuth) (context.Context, error) { + digest := sha256.Sum256([]byte(token.Token)) + if subtle.ConstantTimeCompare(digest[:], a.digest[:]) != 1 { + return ctx, errInvalidToken + } + return ctx, nil +} + +// New returns the HTTP handler of the runner API. +func New(handler *Handler, token string, maxRequestBytes int64, logger *slog.Logger) (http.Handler, error) { + if token == "" { + return nil, errors.New("server.New - empty service token") + } + generated, err := api.NewServer(handler, tokenAuth{digest: sha256.Sum256([]byte(token))}, + api.WithErrorHandler(errorHandler(logger)), + api.WithNotFound(func(w http.ResponseWriter, _ *http.Request) { + writeProblem(w, newProblem(http.StatusNotFound, api.ProblemCodeNotFound, "The route does not exist.")) + }), + api.WithMethodNotAllowed(func(w http.ResponseWriter, _ *http.Request, allowed string) { + w.Header().Set("Allow", allowed) + writeProblem(w, newProblem(http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed, "The route does not support this method.")) + }), + ) + if err != nil { + return nil, fmt.Errorf("server.New - generated server: %w", err) + } + return accessLog(generated, logger, recoverPanics(logger, limitBody(maxRequestBytes, generated))), nil +} + +// limitBody refuses bodies above the limit before they are read. +func limitBody(limit int64, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.ContentLength > limit { + writeProblem(w, newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit.")) + return + } + r.Body = http.MaxBytesReader(w, r.Body, limit) + next.ServeHTTP(w, r) + }) +} + +func recoverPanics(logger *slog.Logger, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + defer func() { + if recovered := recover(); recovered != nil { + // The panic value may hold request data; only its type is logged. + logger.ErrorContext(ctx, "request panicked", slog.String("panic_type", fmt.Sprintf("%T", recovered))) + writeProblem(w, newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.")) + } + }() + next.ServeHTTP(w, r) + }) +} + +// accessLog writes one line per request with the operation, status, and +// duration. Bodies, headers, and query strings are never logged. +func accessLog(router *api.Server, logger *slog.Logger, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + started := time.Now() + recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK} + next.ServeHTTP(recorder, r) + operation := "unknown" + if route, ok := router.FindPath(r.Method, r.URL); ok { + operation = route.OperationID() + } + logger.InfoContext(r.Context(), "request", + slog.String("method", r.Method), + slog.String("operation", operation), + slog.Int("status", recorder.status), + slog.Int64("duration_ms", time.Since(started).Milliseconds()), + ) + }) +} + +type statusRecorder struct { + http.ResponseWriter + + status int +} + +func (r *statusRecorder) WriteHeader(status int) { + r.status = status + r.ResponseWriter.WriteHeader(status) +} diff --git a/runner/internal/server/server_test.go b/runner/internal/server/server_test.go new file mode 100644 index 0000000..d581e7d --- /dev/null +++ b/runner/internal/server/server_test.go @@ -0,0 +1,278 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/runner/internal/jobs" + "lincodex/runner/internal/judge" +) + +const ( + testToken = "test-token-0123456789abcdefghijklmnop" + // Markers that must never reach a log line. + secretSource = "print('source-marker-7f3a')" + secretInput = "input-marker-91c2" + maxBody = 64 << 10 +) + +// blockingRunner holds runs until release is closed. +type blockingRunner struct { + release chan struct{} +} + +func (r blockingRunner) Run(ctx context.Context, _ judge.Request) judge.Result { + select { + case <-r.release: + case <-ctx.Done(): + } + exit := 0 + return judge.Result{ + Outcome: judge.Accepted, + Groups: []judge.GroupResult{{ + ID: "public", Visibility: judge.Public, Outcome: judge.Accepted, Passed: 1, Total: 1, + MaxCPUTime: 25 * time.Millisecond, MaxMemoryKB: 9000, + Tests: []judge.TestResult{{ID: "t1", Outcome: judge.Accepted, CPUTime: 25 * time.Millisecond, WallTime: 40 * time.Millisecond, MemoryKB: 9000, ExitCode: &exit}}, + }}, + Duration: 50 * time.Millisecond, + } +} + +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +type testServer struct { + url string + logs *syncBuffer + // release lets every held run finish; it may be called more than once. + release func() +} + +func startServer(t *testing.T) *testServer { + t.Helper() + logs := &syncBuffer{} + logger := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})) + release := make(chan struct{}) + manager, err := jobs.NewManager(jobs.Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 8}, blockingRunner{release: release}, logger) + if err != nil { + t.Fatalf("NewManager: %v", err) + } + supports := func(language string) bool { return language == "python3" } + handler := NewHandler(manager, supports, func() bool { return !manager.Draining() }, 3*time.Second, logger) + httpHandler, err := New(handler, testToken, maxBody, logger) + if err != nil { + t.Fatalf("New: %v", err) + } + server := httptest.NewServer(httpHandler) + var releaseOnce sync.Once + releaseRuns := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(func() { + releaseRuns() + server.Close() + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _ = manager.Close(ctx) + }) + return &testServer{url: server.URL, logs: logs, release: releaseRuns} +} + +func runBody(source string) map[string]any { + return map[string]any{ + "language": "python3", + "source": source, + "limits": map[string]any{"time_limit_ms": 1000, "memory_limit_mb": 64, "output_limit_kb": 64}, + "groups": []any{map[string]any{ + "id": "public", "visibility": "public", "checker": map[string]any{"kind": "exact"}, + "tests": []any{map[string]any{"id": "t1", "input": secretInput, "expected_output": "3\n"}}, + }}, + } +} + +// reply is a response with its decoded JSON body; the body is already closed. +type reply struct { + StatusCode int + Header http.Header +} + +func (s *testServer) do(t *testing.T, method, path, token string, body any) (reply, map[string]any) { + t.Helper() + var reader io.Reader = http.NoBody + if body != nil { + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("encode body: %v", err) + } + reader = bytes.NewReader(encoded) + } + request, err := http.NewRequestWithContext(t.Context(), method, s.url+path, reader) + if err != nil { + t.Fatalf("new request: %v", err) + } + if body != nil { + request.Header.Set("Content-Type", "application/json") + } + if token != "" { + request.Header.Set("Authorization", "Bearer "+token) + } + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("do request: %v", err) + } + defer response.Body.Close() + var decoded map[string]any + raw, err := io.ReadAll(response.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + if len(raw) > 0 { + if err := json.Unmarshal(raw, &decoded); err != nil { + t.Fatalf("decode %s: %v", raw, err) + } + } + return reply{StatusCode: response.StatusCode, Header: response.Header}, decoded +} + +func runPath(id uuid.UUID) string { + return "/v1/runs/" + id.String() +} + +func TestRunOperationsRequireTheBearerToken(t *testing.T) { + t.Parallel() + + server := startServer(t) + id := uuid.New() + for _, token := range []string{"", "wrong-token-0123456789abcdefghijklmnop", testToken + "x"} { + response, body := server.do(t, http.MethodPut, runPath(id), token, runBody(secretSource)) + if response.StatusCode != http.StatusUnauthorized || body["code"] != "unauthenticated" { + t.Fatalf("PUT with token %q = %d %v, want 401 unauthenticated", token, response.StatusCode, body) + } + response, _ = server.do(t, http.MethodGet, runPath(id), token, nil) + if response.StatusCode != http.StatusUnauthorized { + t.Fatalf("GET with token %q = %d, want 401", token, response.StatusCode) + } + } + response, body := server.do(t, http.MethodGet, "/healthz", "", nil) + if response.StatusCode != http.StatusOK || body["status"] != "ok" { + t.Fatalf("healthz = %d %v", response.StatusCode, body) + } + response, body = server.do(t, http.MethodGet, "/readyz", "", nil) + if response.StatusCode != http.StatusOK || body["status"] != "ready" { + t.Fatalf("readyz = %d %v", response.StatusCode, body) + } +} + +func TestSubmitRunIsIdempotentAndAnswersBusy(t *testing.T) { + t.Parallel() + + server := startServer(t) + id := uuid.New() + response, body := server.do(t, http.MethodPut, runPath(id), testToken, runBody(secretSource)) + if response.StatusCode != http.StatusAccepted || body["state"] != "running" || body["run_id"] != id.String() { + t.Fatalf("first PUT = %d %v, want 202 running", response.StatusCode, body) + } + response, body = server.do(t, http.MethodPut, runPath(id), testToken, runBody(secretSource)) + if response.StatusCode != http.StatusOK || body["state"] != "running" { + t.Fatalf("repeated PUT = %d %v, want 200 running", response.StatusCode, body) + } + response, body = server.do(t, http.MethodPut, runPath(id), testToken, runBody("print(2)")) + if response.StatusCode != http.StatusUnprocessableEntity || body["code"] != "idempotency_key_reused" { + t.Fatalf("PUT with another payload = %d %v, want 422", response.StatusCode, body) + } + response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, runBody(secretSource)) + if response.StatusCode != http.StatusServiceUnavailable || body["code"] != "runner_busy" || response.Header.Get("Retry-After") != "3" { + t.Fatalf("PUT while busy = %d %v %q, want 503 runner_busy with Retry-After 3", response.StatusCode, body, response.Header.Get("Retry-After")) + } + + server.release() + deadline := time.Now().Add(5 * time.Second) + for { + response, body = server.do(t, http.MethodGet, runPath(id), testToken, nil) + if body["state"] == "finished" || time.Now().After(deadline) { + break + } + time.Sleep(5 * time.Millisecond) + } + result, ok := body["result"].(map[string]any) + if response.StatusCode != http.StatusOK || !ok || result["outcome"] != "accepted" { + t.Fatalf("GET finished run = %d %v", response.StatusCode, body) + } + group := result["groups"].([]any)[0].(map[string]any) + test := group["tests"].([]any)[0].(map[string]any) + if group["passed_tests"] != float64(1) || test["time_ms"] != float64(25) || test["memory_kb"] != float64(9000) { + t.Fatalf("group result = %v, want the recorded time and memory", group) + } + + logs := server.logs.String() + if strings.Contains(logs, "source-marker") || strings.Contains(logs, secretInput) || strings.Contains(logs, testToken) { + t.Fatalf("logs contain request data: %s", logs) + } +} + +func TestSubmitRunValidatesTheRequest(t *testing.T) { + t.Parallel() + + server := startServer(t) + duplicate := runBody(secretSource) + group := duplicate["groups"].([]any)[0] + duplicate["groups"] = []any{group, group} + response, body := server.do(t, http.MethodPut, runPath(uuid.New()), testToken, duplicate) + if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" { + t.Fatalf("duplicate group IDs = %d %v, want 400", response.StatusCode, body) + } + pointer := body["errors"].([]any)[0].(map[string]any)["pointer"] + if pointer != "/groups/1/id" { + t.Fatalf("pointer = %v, want /groups/1/id", pointer) + } + + unknown := runBody(secretSource) + unknown["candidate_id"] = "c-1" + response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, unknown) + if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" { + t.Fatalf("unknown field = %d %v, want 400", response.StatusCode, body) + } + + tooLarge := runBody(strings.Repeat("x", maxBody)) + response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, tooLarge) + if response.StatusCode != http.StatusRequestEntityTooLarge || body["code"] != "payload_too_large" { + t.Fatalf("large body = %d %v, want 413", response.StatusCode, body) + } + + response, body = server.do(t, http.MethodPut, "/v1/runs/not-a-uuid", testToken, runBody(secretSource)) + if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" { + t.Fatalf("invalid run ID = %d %v, want 400", response.StatusCode, body) + } + + response, body = server.do(t, http.MethodGet, runPath(uuid.New()), testToken, nil) + if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" { + t.Fatalf("unknown run = %d %v, want 404", response.StatusCode, body) + } + response, body = server.do(t, http.MethodGet, "/v1/unknown", testToken, nil) + if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" { + t.Fatalf("unknown route = %d %v, want 404", response.StatusCode, body) + } +} diff --git a/runner/testdata/hostile/manifest.json b/runner/testdata/hostile/manifest.json new file mode 100644 index 0000000..3e5ac4b --- /dev/null +++ b/runner/testdata/hostile/manifest.json @@ -0,0 +1,91 @@ +{ + "schema": "lincodex.runner-hostile-fixtures/v1", + "description": "Programs that a sandbox run must stop or contain. Each case runs as one public group with one test; expect.limit is the termination limit, or empty when the program ends by itself.", + "default_limits": { + "time_limit_ms": 1000, + "memory_limit_mb": 64, + "output_limit_kb": 64 + }, + "cases": [ + { + "name": "correct_sum", + "language": "python3", + "source": "python/sum_correct.py", + "input": "1 2 3\n", + "expected_output": "6\n", + "expect": {"outcome": "accepted", "limit": ""} + }, + { + "name": "syntax_error", + "language": "python3", + "source": "python/syntax_error.py", + "input": "", + "expected_output": "", + "expect": {"outcome": "compile_error", "limit": ""} + }, + { + "name": "infinite_loop", + "language": "python3", + "source": "python/infinite_loop.py", + "input": "", + "expected_output": "", + "expect": {"outcome": "time_limit_exceeded", "limit": "cpu_time"} + }, + { + "name": "sleep_forever", + "language": "python3", + "source": "python/sleep_forever.py", + "input": "", + "expected_output": "", + "expect": {"outcome": "time_limit_exceeded", "limit": "wall_time"} + }, + { + "name": "memory_leak", + "language": "python3", + "source": "python/memory_leak.py", + "input": "", + "expected_output": "", + "expect": {"outcome": "memory_limit_exceeded", "limit": "memory"} + }, + { + "name": "huge_output", + "language": "python3", + "source": "python/huge_output.py", + "input": "", + "expected_output": "", + "expect": {"outcome": "output_limit_exceeded", "limit": "output"} + }, + { + "name": "fork_bomb", + "language": "python3", + "source": "python/fork_bomb.py", + "input": "", + "expected_output": "", + "expect": {"outcome": "runtime_error", "limit": "processes"} + }, + { + "name": "network_probe", + "language": "python3", + "source": "python/network_probe.py", + "input": "", + "expected_output": "blocked\n", + "expect": {"outcome": "accepted", "limit": ""} + }, + { + "name": "filesystem_probe", + "language": "python3", + "source": "python/filesystem_probe.py", + "input": "", + "expected_output": "isolated\n", + "expect": {"outcome": "accepted", "limit": ""} + }, + { + "name": "privilege_probe", + "language": "python3", + "source": "python/privilege_probe.py", + "input": "", + "expected_output": "unprivileged\n", + "expect": {"outcome": "accepted", "limit": ""} + } + ] +} diff --git a/runner/testdata/hostile/python/filesystem_probe.py b/runner/testdata/hostile/python/filesystem_probe.py new file mode 100644 index 0000000..303f03b --- /dev/null +++ b/runner/testdata/hostile/python/filesystem_probe.py @@ -0,0 +1,16 @@ +# Isolation probe: the root file system and the source are read-only, the +# scratch directory is writable, and runner files are not visible. +import os + +writable = [] +for path in ("/box/injected", "/usr/injected", "/injected", "/lib/injected"): + try: + with open(path, "w") as stream: + stream.write("x") + writable.append(path) + except OSError: + pass +with open("/tmp/scratch", "w") as stream: + stream.write("ok") +visible = [path for path in ("/etc/passwd", "/run/secrets", "/opt/lincodex-runner", "/proc/1") if os.path.exists(path)] +print("isolated" if not writable and not visible else "writable=" + ",".join(writable) + " visible=" + ",".join(visible)) diff --git a/runner/testdata/hostile/python/fork_bomb.py b/runner/testdata/hostile/python/fork_bomb.py new file mode 100644 index 0000000..a58ea18 --- /dev/null +++ b/runner/testdata/hostile/python/fork_bomb.py @@ -0,0 +1,8 @@ +# Fork bomb that ignores refused forks: the cgroup process limit must stop it. +import os + +while True: + try: + os.fork() + except OSError: + pass diff --git a/runner/testdata/hostile/python/huge_output.py b/runner/testdata/hostile/python/huge_output.py new file mode 100644 index 0000000..163734a --- /dev/null +++ b/runner/testdata/hostile/python/huge_output.py @@ -0,0 +1,6 @@ +# Endless standard output: the output limit must stop it. +import sys + +block = "x" * 65536 +while True: + sys.stdout.write(block) diff --git a/runner/testdata/hostile/python/infinite_loop.py b/runner/testdata/hostile/python/infinite_loop.py new file mode 100644 index 0000000..494c305 --- /dev/null +++ b/runner/testdata/hostile/python/infinite_loop.py @@ -0,0 +1,3 @@ +# Busy loop: the CPU time limit must stop it. +while True: + pass diff --git a/runner/testdata/hostile/python/memory_leak.py b/runner/testdata/hostile/python/memory_leak.py new file mode 100644 index 0000000..b251269 --- /dev/null +++ b/runner/testdata/hostile/python/memory_leak.py @@ -0,0 +1,4 @@ +# Unbounded allocation of touched memory: the cgroup memory limit must stop it. +chunks = [] +while True: + chunks.append(b"x" * (1 << 20)) diff --git a/runner/testdata/hostile/python/network_probe.py b/runner/testdata/hostile/python/network_probe.py new file mode 100644 index 0000000..4983384 --- /dev/null +++ b/runner/testdata/hostile/python/network_probe.py @@ -0,0 +1,18 @@ +# Isolation probe: every attempt to reach a network must fail. +import socket + +attempts = [ + (socket.AF_INET, ("1.1.1.1", 53)), + (socket.AF_INET, ("127.0.0.1", 8080)), + (socket.AF_INET6, ("::1", 8080)), +] +reached = [] +for family, address in attempts: + try: + with socket.socket(family, socket.SOCK_STREAM) as connection: + connection.settimeout(1) + connection.connect(address) + reached.append(address[0]) + except OSError: + pass +print("blocked" if not reached else "reached " + " ".join(reached)) diff --git a/runner/testdata/hostile/python/privilege_probe.py b/runner/testdata/hostile/python/privilege_probe.py new file mode 100644 index 0000000..60d1c6a --- /dev/null +++ b/runner/testdata/hostile/python/privilege_probe.py @@ -0,0 +1,19 @@ +# Isolation probe: the program is an unprivileged user that cannot become +# root or take ownership for root. +import os + +checks = [os.getuid() != 0, os.geteuid() != 0, os.getgid() != 0, os.getegid() != 0] +for attempt in (lambda: os.setuid(0), lambda: os.setgid(0)): + try: + attempt() + checks.append(False) + except OSError: + checks.append(True) +with open("/tmp/owned", "w"): + pass +try: + os.chown("/tmp/owned", 0, 0) + checks.append(False) +except OSError: + checks.append(True) +print("unprivileged" if all(checks) else "privileged") diff --git a/runner/testdata/hostile/python/sleep_forever.py b/runner/testdata/hostile/python/sleep_forever.py new file mode 100644 index 0000000..3c2e105 --- /dev/null +++ b/runner/testdata/hostile/python/sleep_forever.py @@ -0,0 +1,4 @@ +# Idle wait: it uses no CPU, so only the wall-clock limit can stop it. +import time + +time.sleep(3600) diff --git a/runner/testdata/hostile/python/sum_correct.py b/runner/testdata/hostile/python/sum_correct.py new file mode 100644 index 0000000..f33214b --- /dev/null +++ b/runner/testdata/hostile/python/sum_correct.py @@ -0,0 +1,4 @@ +# Correct solution: prints the sum of the integers on standard input. +import sys + +print(sum(int(token) for token in sys.stdin.read().split())) diff --git a/runner/testdata/hostile/python/syntax_error.py b/runner/testdata/hostile/python/syntax_error.py new file mode 100644 index 0000000..189a370 --- /dev/null +++ b/runner/testdata/hostile/python/syntax_error.py @@ -0,0 +1,3 @@ +# Syntax error: the syntax check must reject it before any test runs. +def broken(: + return 1 diff --git a/scripts/check-generated.py b/scripts/check-generated.py index 69b04a8..8bf8f84 100644 --- a/scripts/check-generated.py +++ b/scripts/check-generated.py @@ -13,9 +13,11 @@ from pathlib import Path 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/postgres/sqlc/", "frontend/src/shared/api/endpoints/", "frontend/src/shared/api/schemas/", + "runner/internal/api/", ) GENERATED_BASENAMES = {"wire_gen.go"} GENERATED_FILES = { @@ -23,6 +25,8 @@ GENERATED_FILES = { "api/core/components/schemas.yml", "api/ml/openapi.bundle.yml", "api/ml/components/schemas.yml", + "api/runner/openapi.bundle.yml", + "api/runner/components/schemas.yml", "ml/src/lincodex_ml/api/models.py", } SOURCE_SUFFIXES = {".go", ".ts", ".tsx", ".js", ".sql", ".json", ".py"} diff --git a/scripts/test_runner_contract.py b/scripts/test_runner_contract.py new file mode 100644 index 0000000..ef98f5e --- /dev/null +++ b/scripts/test_runner_contract.py @@ -0,0 +1,232 @@ +"""Pin the privacy, authentication, and outcome rules of the code runner contract. + +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" +RUNNER_BUNDLE = API_DIR / "runner" / "openapi.bundle.yml" +CORE_BUNDLE = API_DIR / "core" / "openapi.bundle.yml" +SCHEMA_PREFIX = "#/components/schemas/" +HTTP_METHODS = ("get", "put", "post", "patch", "delete") +HEALTH_OPERATIONS = {"GetRunnerHealthz", "GetRunnerReadyz"} + +# Request fields that would identify a person or link a run to product +# records. The runner needs none of them. +FORBIDDEN_FIELDS = { + "account", + "account_id", + "attempt", + "attempt_id", + "candidate", + "candidate_id", + "company_id", + "contact", + "contacts", + "email", + "first_name", + "full_name", + "ip", + "ip_address", + "last_name", + "name", + "organization_id", + "phone", + "profile_id", + "session", + "session_id", + "task_id", + "telegram", + "user", + "user_agent", + "user_id", + "username", +} +FORBIDDEN_FRAGMENTS = ( + "account", + "attempt", + "candidate", + "company", + "contact", + "email", + "organization", + "person", + "phone", + "profile", + "session", + "user", +) +REQUIRED_OUTCOMES = { + "accepted", + "wrong_answer", + "compile_error", + "time_limit_exceeded", + "memory_limit_exceeded", + "output_limit_exceeded", + "runtime_error", + "infrastructure_failure", +} +PROBLEM_SHAPES = ("Problem", "ProblemFieldError", "ProblemFieldLocation") + + +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 schema_name(reference: str) -> str: + if not reference.startswith(SCHEMA_PREFIX): + raise AssertionError(f"unexpected bundled reference: {reference}") + return reference[len(SCHEMA_PREFIX) :] + + +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): + name = schema_name(reference) + 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 request_inputs(document: dict[str, Any]) -> Iterator[tuple[str, Any]]: + """Yield parameter names and request body schemas of every operation.""" + for path, method, item, operation in operations(document): + for parameter in [*item.get("parameters", []), *operation.get("parameters", [])]: + yield f"{method.upper()} {path} parameter", {"parameter": parameter["name"]} + body = operation.get("requestBody", {}) + for media in body.get("content", {}).values(): + yield f"{method.upper()} {path} body", media["schema"] + + +def forbidden_name(name: str) -> bool: + lowered = name.lower() + return lowered in FORBIDDEN_FIELDS or any(fragment in lowered for fragment in FORBIDDEN_FRAGMENTS) + + +def personal_fields(document: dict[str, Any]) -> list[str]: + schemas = document["components"]["schemas"] + found: list[str] = [] + for location, source in request_inputs(document): + if "parameter" in source: + if forbidden_name(source["parameter"]): + found.append(f"{location}: {source['parameter']}") + continue + for object_location, object_schema in walk_schema(source, schemas, set(), location): + for property_name in object_schema.get("properties", {}): + if forbidden_name(property_name): + found.append(f"{object_location}.{property_name}") + return found + + +def without_descriptions(value: Any) -> Any: + if isinstance(value, dict): + return {key: without_descriptions(item) for key, item in value.items() if key != "description"} + if isinstance(value, list): + return [without_descriptions(item) for item in value] + return value + + +class RunnerContractTest(unittest.TestCase): + def setUp(self) -> None: + self.document = load(RUNNER_BUNDLE) + self.schemas = self.document["components"]["schemas"] + + def test_requests_carry_no_personal_or_product_identifiers(self) -> None: + self.assertEqual(personal_fields(self.document), []) + + def test_detector_finds_a_planted_identifier(self) -> None: + planted = copy.deepcopy(self.document) + planted["components"]["schemas"]["TestCase"]["properties"]["candidate_id"] = {"type": "string"} + planted["components"]["schemas"]["RunLimits"]["properties"]["user_email"] = {"type": "string"} + self.assertEqual( + sorted(personal_fields(planted)), + sorted( + [ + "PUT /v1/runs/{run_id} body.groups.items.tests.items.candidate_id", + "PUT /v1/runs/{run_id} body.limits.user_email", + ] + ), + ) + + def test_request_objects_reject_unknown_fields(self) -> None: + for location, source in request_inputs(self.document): + if "parameter" in source: + continue + for object_location, object_schema in walk_schema(source, self.schemas, set(), location): + with self.subTest(location=object_location): + self.assertIs(object_schema.get("additionalProperties"), False) + + def test_run_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 HEALTH_OPERATIONS: + self.assertEqual(operation.get("security"), []) + else: + self.assertNotIn("security", operation, f"{method} {path} must use the global bearer rule") + + def test_outcomes_distinguish_every_required_result(self) -> None: + self.assertEqual(set(self.schemas["RunOutcome"]["enum"]), REQUIRED_OUTCOMES) + + def test_submit_run_is_idempotent_by_run_id(self) -> None: + item = self.document["paths"]["/v1/runs/{run_id}"] + (parameter,) = item["parameters"] + self.assertEqual((parameter["in"], parameter["schema"]["format"]), ("path", "uuid")) + responses = item["put"]["responses"] + self.assertTrue({"200", "202", "503", "default"} <= set(responses)) + busy = self.document["components"]["responses"]["RunnerBusy"] + self.assertTrue(busy["headers"]["Retry-After"]["required"]) + codes = set(self.schemas["ProblemCode"]["enum"]) + self.assertTrue({"idempotency_key_reused", "runner_busy", "unauthenticated"} <= codes) + self.assertNotIn("run_id", self.schemas["RunRequest"]["properties"]) + + def test_problem_shape_matches_core(self) -> None: + core = load(CORE_BUNDLE)["components"]["schemas"] + for name in PROBLEM_SHAPES: + with self.subTest(name=name): + self.assertEqual(without_descriptions(self.schemas[name]), without_descriptions(core[name])) + + +if __name__ == "__main__": + unittest.main()