feat(api): define public problem errors, pagination, and retry contract

This commit is contained in:
shira committed 2026-10-05 22:09:36 +03:00
1 parent b2f6e87bfe
commit 565ca94bbb
86 files changed
+8200 -154

No files matched your search

+23 -1
View File
@@ -21,7 +21,7 @@ jobs:
api:
name: API contracts
runs-on: ubuntu-24.04
timeout-minutes: 20
timeout-minutes: 30
steps:
- name: Check out source
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
@@ -46,8 +46,30 @@ jobs:
python-version-file: ml/.python-version
cache: pip
cache-dependency-path: scripts/requirements-codegen.txt
# make -C api verify runs check-toolchain, which generates the OpenAPI 3.2
# fixture with ogen, Orval, and datamodel-code-generator, so the job also
# needs the frontend and ML toolchains.
- name: Install declared pnpm
run: npm install --global "$(node -p "require('./frontend/package.json').packageManager")"
- name: Cache pnpm store
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ~/.local/share/pnpm/store
key: ${{ runner.os }}-pnpm-${{ hashFiles('frontend/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-
- name: Set up uv
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
with:
version: 0.12.22
enable-cache: true
cache-dependency-glob: ml/uv.lock
- name: Install API tooling
run: make -C api install
- name: Install frontend dependencies
run: make -C frontend install
- name: Install ML dependencies
run: make -C ml install
- name: Check API formatting and compatibility
run: make -C api fmt-check verify
- name: Check compatibility with the pull request base
+4 -1
View File
@@ -30,15 +30,18 @@ lint: bundle ## Lint both bundled contracts
.PHONY: check
check: lint ## Build and lint both contract bundles
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'
.PHONY: check-compat
check-compat: bundle ## Compare the public contract with API_BASE_REF
API_BASE_REF="$(API_BASE_REF)" REDOCLY="$(REDOCLY)" CODEGEN_PYTHON="$(CODEGEN_PYTHON)" bash "$(ROOT_DIR)/scripts/check-api-compat.sh"
.PHONY: check-toolchain
check-toolchain: ## Check OpenAPI 3.2.0 support and generated validation behavior
check-toolchain: ## Check OpenAPI 3.2.0 support with ogen, Orval, and Pydantic on the compatibility fixture
"$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/testdata/openapi-3.2.0.yml"
$(MAKE) -C "$(ROOT_DIR)/backend" check-ogen-compat
$(MAKE) -C "$(ROOT_DIR)/frontend" check-orval-compat
$(MAKE) -C "$(ROOT_DIR)/ml" check-pydantic-compat
.PHONY: fmt
fmt: ## Format handwritten OpenAPI YAML files
+89
View File
@@ -12,4 +12,93 @@ Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml`
From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code.
## Contract conventions
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for future business operations; no public operation uses them yet.
### Errors
Every error is an RFC 9457 problem with the `application/problem+json` media type and the `Problem` schema. Required fields are `type` (`urn:lincodex:problem:<code>`), `title`, `status`, and `code`; optional ones are `detail`, `instance`, `trace_id` (equal to the `X-Request-ID` response header), and `errors`. Clients branch on `code`. Titles and details are fixed per code and never contain internal error text, stack traces, credentials, contact data, or submitted values.
| Code | Status | Meaning |
| --- | --- | --- |
| `validation_failed` | 400 | Parameters or body do not match the contract, or the body violates a domain rule; `errors` lists the fields |
| `unauthenticated` | 401 | No valid session |
| `forbidden` | 403 | The caller may not perform the operation |
| `not_found` | 404 | Unknown route, or an object that does not exist or is not visible |
| `method_not_allowed` | 405 | Unsupported method; see `Allow` |
| `idempotency_in_progress` | 409 | A request with the same Idempotency-Key is still running |
| `state_conflict` | 409 | The operation is not allowed in the current state of the resource |
| `version_conflict` | 412 | If-Match does not match the current version |
| `payload_too_large` | 413 | The body exceeds the operation limit |
| `unsupported_media_type` | 415 | The request Content-Type is not accepted |
| `idempotency_key_reused` | 422 | The Idempotency-Key was used with a different request |
| `precondition_required` | 428 | The operation requires If-Match |
| `rate_limited` | 429 | Too many requests; see `Retry-After` |
| `internal` | 500 | Unexpected server error |
| `not_implemented` | 501 | The operation is in the contract but not implemented |
Request validation uses 400 rather than 422. The generated ogen server reports malformed and schema-invalid parameters and bodies through the same decoding errors, and for parameters it does not separate syntax from schema violations; one status keeps client handling uniform. 422 then stays free for Idempotency-Key reuse, as the IETF Idempotency-Key header draft recommends. Domain rules on the body, such as `salary_from <= salary_to`, also answer 400 `validation_failed` with body pointers to the fields involved. Each `errors` item has `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` in the body, an empty string for the whole body, `/limit` for a parameter), `code` (`required` or `invalid`; clients tolerate new values), and a fixed `message`. When the decoder does not record the path of a nested body field, the pointer is the whole body. A body cut by an `http.MaxBytesReader` limit answers 413 `payload_too_large`.
`state_conflict` covers business state conflicts, such as accepting an invitation that was already withdrawn. `idempotency_in_progress` is reserved for concurrent retries; the reusable responses are `StateConflict` and `IdempotencyInProgress`.
Every operation declares `default: $ref: ../components/responses.yml#/Problem`; ogen then generates a single error type. An operation adds a specific response (for example `PreconditionFailed`) when clients need it in the generated types. In the Go API, unknown paths under `/api`, including paths outside `/api/v1`, answer 404 `not_found`, and a panic in an operation answers 500 `internal`; only the panic type and stack are logged.
### Retries and Idempotency-Key
A mutating command declares the `IdempotencyKey` parameter. The client generates a key (a UUID v4 is recommended) and sends it in the `Idempotency-Key` header without quotes: 1-255 characters `A-Z a-z 0-9 . _ : -`. The server scopes the key by caller and operation and fingerprints the request by method, path, and body.
Stored for 24 hours and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 `not_found` or 409 `state_conflict`. A replay does not repeat the side effect.
Not stored, so a retry with the same key is evaluated again: 400 `validation_failed`, 413, and 415 for the request itself; 401 and 403; 409 `idempotency_in_progress`; 412 `version_conflict` and 428 `precondition_required` (nothing changed; read the resource again and retry); 422 `idempotency_key_reused`; 429; and every 5xx.
The server checks in this order:
1. Authentication (401), request validation (400, 413, 415), and authorization (403). Nothing is recorded for the key.
2. A stored or running request with the same key and a different fingerprint: 422 `idempotency_key_reused`. This check comes before the in-progress check.
3. A running request with the same key and fingerprint: 409 `idempotency_in_progress`; retry later.
4. A stored outcome with the same key and fingerprint: the outcome is replayed.
5. If-Match (428, 412), then the command itself; a storable outcome is recorded.
Because the replay check comes before If-Match, a retry of a completed change replays its outcome instead of failing on the version that the change itself advanced. A missing or malformed key returns 400 `validation_failed` with the pointer `/Idempotency-Key`. After 24 hours the key may be accepted as new.
### Versions: ETag and If-Match
A response with a versioned resource returns a strong `ETag`, for example `"v7"`. An operation that changes such a resource says in its description that it requires `If-Match` with that value. A missing value returns 428 `precondition_required`; a value that does not equal the current ETag returns 412 `version_conflict` and changes nothing. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. Weak tags, lists, and `*` fail validation with 400.
### Pagination
Lists use cursor pagination: `limit` from 1 to 100 (20 by default) and an opaque `cursor` of up to 512 characters `A-Z a-z 0-9 _ -`. The response holds the items in a bounded array and `page` (`PageInfo`) with `has_more` and `next_cursor`, which is null on the last page. A malformed cursor returns 400 `validation_failed`.
### Time and money
Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with the `Z` suffix (RFC 3339). Servers always emit UTC. ogen generates `Timestamp` as a named Go type over `time.Time`; call `.UTC()` where a value is converted to it. Money is planned as an integer number of whole rubles with explicit fields for the base, such as the pay period and gross or net; the schema is added with the first business field that carries money.
### ML service errors
The ML service answers its errors with the same `Problem` schema. 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.
### Generator checks
`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core.
`make -C api check-toolchain` lints the fixture and runs the three generators on it; it needs the backend Go toolchain, pnpm, and uv, so pass the same `UV` override as for `make generate`.
| Target | Generator | Exercised conventions |
| --- | --- | --- |
| `make -C backend check-ogen-compat` | ogen | All of them: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Its tests check validation errors, the retry scenario, the preconditions, and the 413 body limit against the backend problem mapping |
| `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. The output is type-checked with the frontend compiler settings |
| `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. The models pass `mypy --strict` and a validation script |
Each target writes its output to a temporary directory and removes it.
Known generator limitations:
- Orval 8.40 writes no Zod schema for `components/responses` but imports a `<Name>Response` type for each reference. `frontend/codegen/orval.config.ts` therefore inlines response references before generation.
- Orval passes header parameters as a typed argument only with `headers: true`. With `exactOptionalPropertyTypes`, an optional header such as `If-Match` fits `RequestInit` only when Zod emits exact optional properties, so the configuration also sets `override.zod.exactOptional`.
- Orval generates no type for response headers, and `apiRequest` returns only the body, so a generated client cannot read `ETag` yet. The first operation with a versioned resource must expose it, for example through the response body or the mutator.
- datamodel-code-generator 0.83.0 generates models only for schemas and query and path parameters; header parameters and response headers (Idempotency-Key, If-Match, ETag) produce no Python model.
- Orval does not generate `additionalOperations` methods.
- ogen writes the header name in its canonical Go form (`Etag`); HTTP header names are case-insensitive.
See the [development guide](../docs/en/DEVELOPMENT.md).
+89
View File
@@ -12,4 +12,93 @@
Из корня: `make -C api check` проверяет контракты, `make generate` обновляет весь сгенерированный код.
## Соглашения контракта
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение будущих бизнес-операций; ни одна публичная операция их пока не использует.
### Ошибки
Любая ошибка - problem по RFC 9457 с media type `application/problem+json` и схемой `Problem`. Обязательные поля: `type` (`urn:lincodex:problem:<code>`), `title`, `status` и `code`; необязательные: `detail`, `instance`, `trace_id` (равен заголовку ответа `X-Request-ID`) и `errors`. Клиенты принимают решения по `code`. Заголовок и описание фиксированы для каждого кода и никогда не содержат текст внутренних ошибок, stack trace, учетные данные, контакты или отправленные значения.
| Код | Статус | Значение |
| --- | --- | --- |
| `validation_failed` | 400 | Параметры или тело не соответствуют контракту или тело нарушает доменное правило; `errors` перечисляет поля |
| `unauthenticated` | 401 | Нет действующей сессии |
| `forbidden` | 403 | Вызывающему запрещена операция |
| `not_found` | 404 | Неизвестный маршрут или объект, который не существует или недоступен |
| `method_not_allowed` | 405 | Метод не поддерживается; см. `Allow` |
| `idempotency_in_progress` | 409 | Запрос с тем же Idempotency-Key еще выполняется |
| `state_conflict` | 409 | Операция недопустима в текущем состоянии ресурса |
| `version_conflict` | 412 | If-Match не совпадает с текущей версией |
| `payload_too_large` | 413 | Тело превышает лимит операции |
| `unsupported_media_type` | 415 | Content-Type запроса не принимается |
| `idempotency_key_reused` | 422 | Idempotency-Key уже использован с другим запросом |
| `precondition_required` | 428 | Операция требует If-Match |
| `rate_limited` | 429 | Слишком много запросов; см. `Retry-After` |
| `internal` | 500 | Непредвиденная ошибка сервера |
| `not_implemented` | 501 | Операция есть в контракте, но не реализована |
Для валидации запроса выбран 400, а не 422. Сгенерированный ogen-сервер сообщает о синтаксически неверных и не прошедших проверку схемы параметрах и теле через одни и те же ошибки декодирования, а для параметров не отделяет синтаксис от нарушения схемы; единый статус упрощает обработку на клиенте. Поэтому 422 остается для повторного использования Idempotency-Key, как рекомендует черновик IETF о заголовке Idempotency-Key. Доменные правила тела, например `salary_from <= salary_to`, тоже отвечают 400 `validation_failed` с body pointer на участвующие поля. Каждый элемент `errors` содержит `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` в теле, пустая строка для всего тела, `/limit` для параметра), `code` (`required` или `invalid`; клиенты допускают новые значения) и фиксированный `message`. Если декодер не сохранил путь вложенного поля тела, pointer указывает на все тело. Тело, обрезанное лимитом `http.MaxBytesReader`, дает 413 `payload_too_large`.
`state_conflict` обозначает конфликты бизнес-состояния, например принятие уже отозванного приглашения. `idempotency_in_progress` зарезервирован для параллельных повторов; переиспользуемые ответы - `StateConflict` и `IdempotencyInProgress`.
Каждая операция объявляет `default: $ref: ../components/responses.yml#/Problem`; тогда ogen генерирует единый тип ошибки. Конкретный ответ (например, `PreconditionFailed`) операция добавляет, когда он нужен клиентам в сгенерированных типах. В Go API неизвестные пути под `/api`, включая пути вне `/api/v1`, отвечают 404 `not_found`, а panic в операции - 500 `internal`; в лог попадают только тип panic и stack.
### Повторы и Idempotency-Key
Изменяющая команда объявляет параметр `IdempotencyKey`. Клиент создает ключ (рекомендуется UUID v4) и передает его в заголовке `Idempotency-Key` без кавычек: 1-255 символов `A-Z a-z 0-9 . _ : -`. Сервер ограничивает ключ вызывающим и операцией и снимает отпечаток запроса по методу, пути и телу.
Хранятся 24 часа и воспроизводятся с теми же статусом, заголовками и телом: итоговый 2xx-результат и итоговые детерминированные бизнес-результаты 4xx, например 404 `not_found` или 409 `state_conflict`. Воспроизведение не повторяет побочный эффект.
Не хранятся, поэтому повтор с тем же ключом обрабатывается заново: 400 `validation_failed`, 413 и 415 для самого запроса; 401 и 403; 409 `idempotency_in_progress`; 412 `version_conflict` и 428 `precondition_required` (ничего не изменилось; прочитайте ресурс снова и повторите); 422 `idempotency_key_reused`; 429; любой 5xx.
Порядок проверок на сервере:
1. Аутентификация (401), валидация запроса (400, 413, 415) и авторизация (403). Для ключа ничего не записывается.
2. Сохраненный или выполняющийся запрос с тем же ключом и другим отпечатком: 422 `idempotency_key_reused`. Эта проверка идет раньше проверки выполнения.
3. Выполняющийся запрос с тем же ключом и отпечатком: 409 `idempotency_in_progress`; повторите позже.
4. Сохраненный результат с тем же ключом и отпечатком: результат воспроизводится.
5. If-Match (428, 412), затем сама команда; результат, который можно хранить, записывается.
Поскольку проверка воспроизведения идет раньше If-Match, повтор завершенного изменения воспроизводит его результат, а не падает на версии, которую само изменение и увеличило. Отсутствующий или некорректный ключ дает 400 `validation_failed` с pointer `/Idempotency-Key`. Через 24 часа ключ может быть принят как новый.
### Версии: ETag и If-Match
Ответ с версионируемым ресурсом возвращает сильный `ETag`, например `"v7"`. Операция, изменяющая такой ресурс, указывает в описании, что требует `If-Match` с этим значением. Отсутствующее значение дает 428 `precondition_required`; значение, не равное текущему ETag, дает 412 `version_conflict` без изменений. В схеме параметр необязательный, чтобы отсутствие заголовка доходило до приложения, которое отвечает 428. Слабые теги, списки и `*` не проходят валидацию и дают 400.
### Пагинация
Списки используют cursor pagination: `limit` от 1 до 100 (по умолчанию 20) и непрозрачный `cursor` длиной до 512 символов `A-Z a-z 0-9 _ -`. Ответ содержит элементы в ограниченном массиве и `page` (`PageInfo`) с `has_more` и `next_cursor`, который равен null на последней странице. Некорректный cursor дает 400 `validation_failed`.
### Время и деньги
Метки времени используют схему `Timestamp`: `string`, `format: date-time`, UTC с суффиксом `Z` (RFC 3339). Серверы всегда отдают UTC. ogen генерирует `Timestamp` как именованный Go-тип поверх `time.Time`; при преобразовании к нему вызывайте `.UTC()`. Деньги запланированы как целое число полных рублей с явными полями базы, например периодом оплаты и gross или net; схема появится вместе с первым бизнес-полем с деньгами.
### Ошибки ML-сервиса
ML-сервис отвечает на ошибки той же схемой `Problem`. Валидация запроса 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.
### Проверки генераторов
`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core.
`make -C api check-toolchain` проверяет фикстуру линтером и запускает на ней три генератора; нужны Go toolchain backend, pnpm и uv, поэтому передавайте тот же `UV` override, что и для `make generate`.
| Target | Генератор | Проверяемые соглашения |
| --- | --- | --- |
| `make -C backend check-ogen-compat` | ogen | Все: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Тесты проверяют ошибки валидации, сценарий повтора, предусловия и лимит тела 413 вместе с backend-маппингом problem |
| `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. Результат проходит проверку типов с настройками компилятора frontend |
| `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. Модели проходят `mypy --strict` и скрипт валидации |
Каждый target пишет результат во временный каталог и удаляет его.
Известные ограничения генераторов:
- Orval 8.40 не создает Zod-схемы для `components/responses`, но импортирует тип `<Name>Response` для каждой ссылки. Поэтому `frontend/codegen/orval.config.ts` встраивает ссылки на ответы перед генерацией.
- Orval передает header-параметры типизированным аргументом только с `headers: true`. С `exactOptionalPropertyTypes` необязательный заголовок, например `If-Match`, совместим с `RequestInit` только при точных необязательных свойствах Zod, поэтому конфигурация также задает `override.zod.exactOptional`.
- Orval не генерирует типы заголовков ответа, а `apiRequest` возвращает только тело, поэтому сгенерированный клиент пока не может прочитать `ETag`. Первая операция с версионируемым ресурсом должна открыть его, например через тело ответа или mutator.
- datamodel-code-generator 0.83.0 создает модели только для схем и query- и path-параметров; header-параметры и заголовки ответа (Idempotency-Key, If-Match, ETag) не дают Python-моделей.
- Orval не генерирует методы для `additionalOperations`.
- ogen записывает имя заголовка в канонической Go-форме (`Etag`); имена HTTP-заголовков не зависят от регистра.
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md).
+140
View File
@@ -0,0 +1,140 @@
ValidationFailed:
summary: Request parameters 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.
trace_id: 0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10
errors:
- in: query
pointer: /limit
code: invalid
message: The value does not match the contract.
- in: header
pointer: /Idempotency-Key
code: required
message: The value is required.
Unauthenticated:
summary: No valid session
value:
type: urn:lincodex:problem:unauthenticated
title: Authentication required
status: 401
code: unauthenticated
detail: Sign in and repeat the request.
trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b
Forbidden:
summary: The caller may not access the object
value:
type: urn:lincodex:problem:forbidden
title: Access denied
status: 403
code: forbidden
detail: You do not have permission to perform this operation.
trace_id: 7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d
NotFound:
summary: Unknown route or invisible object
value:
type: urn:lincodex:problem:not_found
title: Resource not found
status: 404
code: not_found
detail: The requested resource does not exist.
trace_id: 1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f
IdempotencyInProgress:
summary: The first request with this key is still running
value:
type: urn:lincodex:problem:idempotency_in_progress
title: Request with this idempotency key is in progress
status: 409
code: idempotency_in_progress
detail: Retry after the original request completes.
trace_id: 2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a
StateConflict:
summary: The resource state does not allow the operation
value:
type: urn:lincodex:problem:state_conflict
title: Resource state conflict
status: 409
code: state_conflict
detail: The resource is in a state that does not allow this operation.
trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b
DomainValidationFailed:
summary: The body violates a domain rule
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6c
errors:
- in: body
pointer: /salary_from
code: invalid
message: The value does not match the contract.
VersionConflict:
summary: If-Match does not match the current version
value:
type: urn:lincodex:problem:version_conflict
title: Resource version conflict
status: 412
code: version_conflict
detail: The resource changed after it was read. Read it again before retrying.
trace_id: 3e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b
PayloadTooLarge:
summary: The request body exceeds the limit
value:
type: urn:lincodex:problem:payload_too_large
title: Request body too large
status: 413
code: payload_too_large
detail: Reduce the request body size and retry.
trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e
IdempotencyKeyReused:
summary: The same Idempotency-Key was sent with a different body
value:
type: urn:lincodex:problem:idempotency_key_reused
title: Idempotency key reused with a different request
status: 422
code: idempotency_key_reused
detail: Use a new Idempotency-Key for a different request.
trace_id: 4f5a6b7c-8d9e-4f0a-9b1c-3d4e5f6a7b8c
PreconditionRequired:
summary: The operation requires If-Match
value:
type: urn:lincodex:problem:precondition_required
title: Precondition required
status: 428
code: precondition_required
detail: Send If-Match with the ETag of the version you read.
trace_id: 5a6b7c8d-9e0f-4a1b-8c2d-4e5f6a7b8c9d
RateLimited:
summary: Too many requests
value:
type: urn:lincodex:problem:rate_limited
title: Too many requests
status: 429
code: rate_limited
detail: Wait for the Retry-After interval and retry.
trace_id: 6b7c8d9e-0f1a-4b2c-9d3e-5f6a7b8c9d0e
Internal:
summary: Unexpected server error
value:
type: urn:lincodex:problem:internal
title: Internal server error
status: 500
code: internal
detail: The server could not complete the request.
trace_id: 9c0d1e2f-3a4b-4c5d-8e6f-7a8b9c0d1e2f
NotImplemented:
summary: Operation declared in the contract without an implementation
value:
type: urn:lincodex:problem:not_implemented
title: Operation not implemented
status: 501
code: not_implemented
detail: This operation is not available yet.
trace_id: 0d1e2f3a-4b5c-4d6e-9f7a-8b9c0d1e2f3a
+19
View File
@@ -0,0 +1,19 @@
ETag:
description: >-
Strong entity tag of the returned resource version. Send it back in
If-Match to change this version.
required: true
schema:
type: string
minLength: 3
maxLength: 130
pattern: '^"[A-Za-z0-9._~-]{1,128}"$'
example: '"v7"'
RetryAfter:
description: Number of seconds to wait before retrying the request.
schema:
type: integer
format: int32
minimum: 0
maximum: 86400
example: 30
+58
View File
@@ -0,0 +1,58 @@
IdempotencyKey:
name: Idempotency-Key
in: header
required: true
description: |-
Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value is sent without quotes. The server scopes the key by caller and operation and fingerprints the request by method, path, and body.
Stored for 24 hours after the first request and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect.
Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry), 422 idempotency_key_reused, 429, and every 5xx.
Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused before any other key check; a running request with the same fingerprint returns 409 idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that does the server check If-Match, so a retry of a completed change replays its outcome instead of failing on the version it has just changed. After 24 hours the key may be accepted as new.
schema:
type: string
minLength: 1
maxLength: 255
pattern: "^[A-Za-z0-9._:-]+$"
example: 5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11
IfMatch:
name: If-Match
in: header
required: false
description: |-
Strong entity tag of the resource version the client last read, copied from the ETag response header. An operation that changes a versioned resource says in its own description that it requires If-Match.
On such an operation, a missing If-Match returns 428 precondition_required. An If-Match that does not equal the current ETag returns 412 version_conflict and changes nothing; read the resource again before retrying. Only one strong entity tag is accepted; weak tags, lists, and `*` fail validation with 400. The parameter is optional in the schema so that a missing header reaches the application, which answers 428.
schema:
type: string
minLength: 3
maxLength: 130
pattern: '^"[A-Za-z0-9._~-]{1,128}"$'
example: '"v7"'
PageLimit:
name: limit
in: query
required: false
description: >-
Maximum number of items in the page. The server may return fewer items
even when more remain; use `page.has_more` to detect the end.
schema:
type: integer
format: int32
minimum: 1
maximum: 100
default: 20
PageCursor:
name: cursor
in: query
required: false
description: >-
Opaque `page.next_cursor` value from the previous page of the same listing.
Omit it to read the first page. A malformed or foreign cursor returns 400
with code validation_failed.
schema:
type: string
minLength: 1
maxLength: 512
pattern: "^[A-Za-z0-9_-]+$"
+159
View File
@@ -0,0 +1,159 @@
ValidationFailed:
description: >-
Parameters, headers, or the body do not match the contract, or the body
violates a domain rule such as salary_from <= salary_to. The body has code
validation_failed and lists the failing fields in `errors` with body or
parameter pointers.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
validation_failed:
$ref: ./examples.yml#/ValidationFailed
domain_rule:
$ref: ./examples.yml#/DomainValidationFailed
Unauthenticated:
description: No valid session or credentials; code unauthenticated.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
unauthenticated:
$ref: ./examples.yml#/Unauthenticated
Forbidden:
description: >-
The caller is authenticated but may not perform the operation; code
forbidden.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
forbidden:
$ref: ./examples.yml#/Forbidden
NotFound:
description: >-
The object does not exist or is not visible to the caller; code
not_found. Missing and inaccessible objects are not distinguished.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
not_found:
$ref: ./examples.yml#/NotFound
IdempotencyInProgress:
description: >-
A request with the same Idempotency-Key and the same fingerprint is still
being processed; code idempotency_in_progress. Retry after the original
request completes.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
StateConflict:
description: >-
The operation conflicts with the current state of the resource, for
example a transition that is not allowed from its current status; code
state_conflict.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
state_conflict:
$ref: ./examples.yml#/StateConflict
PreconditionFailed:
description: >-
If-Match does not match the current resource version; code
version_conflict. Nothing was changed.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
version_conflict:
$ref: ./examples.yml#/VersionConflict
PayloadTooLarge:
description: The request body exceeds the operation limit; code payload_too_large.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
payload_too_large:
$ref: ./examples.yml#/PayloadTooLarge
UnprocessableContent:
description: >-
The Idempotency-Key was already used with a different request within 24
hours; code idempotency_key_reused. Nothing was changed.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
idempotency_key_reused:
$ref: ./examples.yml#/IdempotencyKeyReused
PreconditionRequired:
description: The operation requires If-Match; code precondition_required.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
precondition_required:
$ref: ./examples.yml#/PreconditionRequired
TooManyRequests:
description: Too many requests; code rate_limited.
headers:
Retry-After:
$ref: ./headers.yml#/RetryAfter
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
rate_limited:
$ref: ./examples.yml#/RateLimited
Internal:
description: Unexpected server error; code internal.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
internal:
$ref: ./examples.yml#/Internal
NotImplemented:
description: >-
The operation is declared in the contract but not implemented yet; code
not_implemented.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
not_implemented:
$ref: ./examples.yml#/NotImplemented
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:
$ref: ./examples.yml#/ValidationFailed
not_found:
$ref: ./examples.yml#/NotFound
internal:
$ref: ./examples.yml#/Internal
not_implemented:
$ref: ./examples.yml#/NotImplemented
+161
View File
@@ -1,3 +1,28 @@
Timestamp:
type: string
format: date-time
description: UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.
examples:
- '2026-10-05T09:30:00Z'
PageInfo:
type: object
description: Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.
additionalProperties: false
required:
- has_more
- next_cursor
properties:
has_more:
type: boolean
description: Whether another page follows this one.
next_cursor:
type:
- string
- 'null'
minLength: 1
maxLength: 512
pattern: ^[A-Za-z0-9_-]+$
description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.
HealthResponse:
type: object
additionalProperties: false
@@ -8,3 +33,139 @@ HealthResponse:
type: string
enum:
- ok
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: '#/ProblemCode'
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; 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 public error code. 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 body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.
- unauthenticated (401): no valid session or credentials.
- forbidden (403): the caller is authenticated but not allowed.
- not_found (404): the route or object does not exist or is not visible.
- method_not_allowed (405): the route does not support the method.
- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.
- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.
- version_conflict (412): If-Match does not match the current version.
- 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 Idempotency-Key was already used with a different request.
- precondition_required (428): the operation requires If-Match.
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.'
enum:
- validation_failed
- unauthenticated
- forbidden
- not_found
- method_not_allowed
- idempotency_in_progress
- state_conflict
- version_conflict
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- precondition_required
- rate_limited
- internal
- not_implemented
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 `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.
code:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z][a-z0-9_]*$
description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.
message:
type: string
minLength: 1
maxLength: 500
description: Fixed English message that never echoes the submitted value.
ProblemFieldLocation:
type: string
description: Part of the request that contains the invalid field.
enum:
- body
- query
- path
- header
- cookie
@@ -0,0 +1,34 @@
schemas:
Timestamp:
type: string
format: date-time
description: >-
UTC instant in RFC 3339 format with the Z suffix, for example
2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in
this contract uses this schema.
examples:
- "2026-10-05T09:30:00Z"
PageInfo:
type: object
description: >-
Cursor pagination state of a list response. Lists are ordered by a
stable server-defined key. To read the next page, repeat the request
with the same filters and `cursor` set to `next_cursor`.
additionalProperties: false
required:
- has_more
- next_cursor
properties:
has_more:
type: boolean
description: Whether another page follows this one.
next_cursor:
type:
- string
- "null"
minLength: 1
maxLength: 512
pattern: "^[A-Za-z0-9_-]+$"
description: >-
Opaque cursor of the next page, or null on the last page. Clients
must not parse, build, or store it beyond the current listing.
@@ -0,0 +1,146 @@
schemas:
Problem:
type: object
description: >-
Problem details (RFC 9457) returned with the application/problem+json
media type for every error response. `code` is the stable,
machine-readable reason; clients branch on it rather than on `title`,
`detail`, or the HTTP status alone. The body never contains internal
error text, stack traces, SQL, file paths, credentials, contact data, or
echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: >-
URI that identifies the problem type. It has the form
`urn:lincodex:problem:<code>` and is an identifier, not a link to
dereference.
title:
type: string
minLength: 1
maxLength: 200
description: >-
Short, fixed English summary of the problem type. It does not change
between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: "#/schemas/ProblemCode"
detail:
type: string
maxLength: 1000
description: >-
Safe English explanation of this occurrence. It never contains
internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: "^[A-Za-z0-9._-]+$"
description: >-
Request identifier, equal to the X-Request-ID response header. Quote
it when reporting the problem; 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 public error code. 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 body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.
- unauthenticated (401): no valid session or credentials.
- forbidden (403): the caller is authenticated but not allowed.
- not_found (404): the route or object does not exist or is not visible.
- method_not_allowed (405): the route does not support the method.
- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.
- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.
- version_conflict (412): If-Match does not match the current version.
- 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 Idempotency-Key was already used with a different request.
- precondition_required (428): the operation requires If-Match.
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.
enum:
- validation_failed
- unauthenticated
- forbidden
- not_found
- method_not_allowed
- idempotency_in_progress
- state_conflict
- version_conflict
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- precondition_required
- rate_limited
- internal
- not_implemented
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 `/salary_from`; an empty string means the whole
body. For a parameter it is `/` followed by the parameter name, for
example `/limit` or `/Idempotency-Key`.
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
+505
View File
@@ -19,8 +19,162 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HealthResponse'
examples:
ok:
summary: The process is responding
value:
status: ok
default:
$ref: '#/components/responses/Problem'
components:
schemas:
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: '#/components/schemas/ProblemCode'
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; 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'
ProblemCode:
type: string
description: |-
Stable public error code. 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 body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.
- unauthenticated (401): no valid session or credentials.
- forbidden (403): the caller is authenticated but not allowed.
- not_found (404): the route or object does not exist or is not visible.
- method_not_allowed (405): the route does not support the method.
- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.
- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.
- version_conflict (412): If-Match does not match the current version.
- 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 Idempotency-Key was already used with a different request.
- precondition_required (428): the operation requires If-Match.
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.
enum:
- validation_failed
- unauthenticated
- forbidden
- not_found
- method_not_allowed
- idempotency_in_progress
- state_conflict
- version_conflict
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- precondition_required
- rate_limited
- internal
- not_implemented
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 `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.
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
Timestamp:
type: string
format: date-time
description: UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.
examples:
- '2026-10-05T09:30:00Z'
PageInfo:
type: object
description: Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.
additionalProperties: false
required:
- has_more
- next_cursor
properties:
has_more:
type: boolean
description: Whether another page follows this one.
next_cursor:
type:
- string
- 'null'
minLength: 1
maxLength: 512
pattern: ^[A-Za-z0-9_-]+$
description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.
HealthResponse:
type: object
additionalProperties: false
@@ -31,3 +185,354 @@ components:
type: string
enum:
- ok
parameters:
IdempotencyKey:
name: Idempotency-Key
in: header
required: true
description: |-
Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value is sent without quotes. The server scopes the key by caller and operation and fingerprints the request by method, path, and body.
Stored for 24 hours after the first request and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect.
Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry), 422 idempotency_key_reused, 429, and every 5xx.
Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused before any other key check; a running request with the same fingerprint returns 409 idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that does the server check If-Match, so a retry of a completed change replays its outcome instead of failing on the version it has just changed. After 24 hours the key may be accepted as new.
schema:
type: string
minLength: 1
maxLength: 255
pattern: ^[A-Za-z0-9._:-]+$
example: 5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11
IfMatch:
name: If-Match
in: header
required: false
description: |-
Strong entity tag of the resource version the client last read, copied from the ETag response header. An operation that changes a versioned resource says in its own description that it requires If-Match.
On such an operation, a missing If-Match returns 428 precondition_required. An If-Match that does not equal the current ETag returns 412 version_conflict and changes nothing; read the resource again before retrying. Only one strong entity tag is accepted; weak tags, lists, and `*` fail validation with 400. The parameter is optional in the schema so that a missing header reaches the application, which answers 428.
schema:
type: string
minLength: 3
maxLength: 130
pattern: ^"[A-Za-z0-9._~-]{1,128}"$
example: '"v7"'
PageLimit:
name: limit
in: query
required: false
description: Maximum number of items in the page. The server may return fewer items even when more remain; use `page.has_more` to detect the end.
schema:
type: integer
format: int32
minimum: 1
maximum: 100
default: 20
PageCursor:
name: cursor
in: query
required: false
description: Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the first page. A malformed or foreign cursor returns 400 with code validation_failed.
schema:
type: string
minLength: 1
maxLength: 512
pattern: ^[A-Za-z0-9_-]+$
headers:
ETag:
description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version.
required: true
schema:
type: string
minLength: 3
maxLength: 130
pattern: ^"[A-Za-z0-9._~-]{1,128}"$
example: '"v7"'
RetryAfter:
description: Number of seconds to wait before retrying the request.
schema:
type: integer
format: int32
minimum: 0
maximum: 86400
example: 30
responses:
ValidationFailed:
description: Parameters, headers, or the body do not match the contract, or the body violates a domain rule such as salary_from <= salary_to. The body has code validation_failed and lists the failing fields in `errors` with body or parameter pointers.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
validation_failed:
$ref: '#/components/examples/ValidationFailed'
domain_rule:
$ref: '#/components/examples/DomainValidationFailed'
Unauthenticated:
description: No valid session or credentials; code unauthenticated.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
unauthenticated:
$ref: '#/components/examples/Unauthenticated'
Forbidden:
description: The caller is authenticated but may not perform the operation; code forbidden.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
forbidden:
$ref: '#/components/examples/Forbidden'
NotFound:
description: The object does not exist or is not visible to the caller; code not_found. Missing and inaccessible objects are not distinguished.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
not_found:
$ref: '#/components/examples/NotFound'
IdempotencyInProgress:
description: A request with the same Idempotency-Key and the same fingerprint is still being processed; code idempotency_in_progress. Retry after the original request completes.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
idempotency_in_progress:
$ref: '#/components/examples/IdempotencyInProgress'
StateConflict:
description: The operation conflicts with the current state of the resource, for example a transition that is not allowed from its current status; code state_conflict.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
state_conflict:
$ref: '#/components/examples/StateConflict'
PreconditionFailed:
description: If-Match does not match the current resource version; code version_conflict. Nothing was changed.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
version_conflict:
$ref: '#/components/examples/VersionConflict'
PayloadTooLarge:
description: The request body exceeds the operation limit; code payload_too_large.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
payload_too_large:
$ref: '#/components/examples/PayloadTooLarge'
UnprocessableContent:
description: The Idempotency-Key was already used with a different request within 24 hours; code idempotency_key_reused. Nothing was changed.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
idempotency_key_reused:
$ref: '#/components/examples/IdempotencyKeyReused'
PreconditionRequired:
description: The operation requires If-Match; code precondition_required.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
precondition_required:
$ref: '#/components/examples/PreconditionRequired'
TooManyRequests:
description: Too many requests; code rate_limited.
headers:
Retry-After:
$ref: '#/components/headers/RetryAfter'
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
rate_limited:
$ref: '#/components/examples/RateLimited'
Internal:
description: Unexpected server error; code internal.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
internal:
$ref: '#/components/examples/Internal'
NotImplemented:
description: The operation is declared in the contract but not implemented yet; code not_implemented.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
not_implemented:
$ref: '#/components/examples/NotImplemented'
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:
$ref: '#/components/examples/ValidationFailed'
not_found:
$ref: '#/components/examples/NotFound'
internal:
$ref: '#/components/examples/Internal'
not_implemented:
$ref: '#/components/examples/NotImplemented'
examples:
ValidationFailed:
summary: Request parameters 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.
trace_id: 0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10
errors:
- in: query
pointer: /limit
code: invalid
message: The value does not match the contract.
- in: header
pointer: /Idempotency-Key
code: required
message: The value is required.
NotFound:
summary: Unknown route or invisible object
value:
type: urn:lincodex:problem:not_found
title: Resource not found
status: 404
code: not_found
detail: The requested resource does not exist.
trace_id: 1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f
Internal:
summary: Unexpected server error
value:
type: urn:lincodex:problem:internal
title: Internal server error
status: 500
code: internal
detail: The server could not complete the request.
trace_id: 9c0d1e2f-3a4b-4c5d-8e6f-7a8b9c0d1e2f
NotImplemented:
summary: Operation declared in the contract without an implementation
value:
type: urn:lincodex:problem:not_implemented
title: Operation not implemented
status: 501
code: not_implemented
detail: This operation is not available yet.
trace_id: 0d1e2f3a-4b5c-4d6e-9f7a-8b9c0d1e2f3a
DomainValidationFailed:
summary: The body violates a domain rule
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6c
errors:
- in: body
pointer: /salary_from
code: invalid
message: The value does not match the contract.
Unauthenticated:
summary: No valid session
value:
type: urn:lincodex:problem:unauthenticated
title: Authentication required
status: 401
code: unauthenticated
detail: Sign in and repeat the request.
trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b
Forbidden:
summary: The caller may not access the object
value:
type: urn:lincodex:problem:forbidden
title: Access denied
status: 403
code: forbidden
detail: You do not have permission to perform this operation.
trace_id: 7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d
IdempotencyInProgress:
summary: The first request with this key is still running
value:
type: urn:lincodex:problem:idempotency_in_progress
title: Request with this idempotency key is in progress
status: 409
code: idempotency_in_progress
detail: Retry after the original request completes.
trace_id: 2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a
StateConflict:
summary: The resource state does not allow the operation
value:
type: urn:lincodex:problem:state_conflict
title: Resource state conflict
status: 409
code: state_conflict
detail: The resource is in a state that does not allow this operation.
trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b
VersionConflict:
summary: If-Match does not match the current version
value:
type: urn:lincodex:problem:version_conflict
title: Resource version conflict
status: 412
code: version_conflict
detail: The resource changed after it was read. Read it again before retrying.
trace_id: 3e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b
PayloadTooLarge:
summary: The request body exceeds the limit
value:
type: urn:lincodex:problem:payload_too_large
title: Request body too large
status: 413
code: payload_too_large
detail: Reduce the request body size and retry.
trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e
IdempotencyKeyReused:
summary: The same Idempotency-Key was sent with a different body
value:
type: urn:lincodex:problem:idempotency_key_reused
title: Idempotency key reused with a different request
status: 422
code: idempotency_key_reused
detail: Use a new Idempotency-Key for a different request.
trace_id: 4f5a6b7c-8d9e-4f0a-9b1c-3d4e5f6a7b8c
PreconditionRequired:
summary: The operation requires If-Match
value:
type: urn:lincodex:problem:precondition_required
title: Precondition required
status: 428
code: precondition_required
detail: Send If-Match with the ETag of the version you read.
trace_id: 5a6b7c8d-9e0f-4a1b-8c2d-4e5f6a7b8c9d
RateLimited:
summary: Too many requests
value:
type: urn:lincodex:problem:rate_limited
title: Too many requests
status: 429
code: rate_limited
detail: Wait for the Retry-After interval and retry.
trace_id: 6b7c8d9e-0f1a-4b2c-9d3e-5f6a7b8c9d0e
+57
View File
@@ -7,3 +7,60 @@ servers:
paths:
/api/v1/healthz:
$ref: ./routes/healthz.yml
components:
schemas:
Problem:
$ref: ./components/schemas.yml#/Problem
ProblemCode:
$ref: ./components/schemas.yml#/ProblemCode
ProblemFieldError:
$ref: ./components/schemas.yml#/ProblemFieldError
ProblemFieldLocation:
$ref: ./components/schemas.yml#/ProblemFieldLocation
Timestamp:
$ref: ./components/schemas.yml#/Timestamp
PageInfo:
$ref: ./components/schemas.yml#/PageInfo
parameters:
IdempotencyKey:
$ref: ./components/parameters.yml#/IdempotencyKey
IfMatch:
$ref: ./components/parameters.yml#/IfMatch
PageLimit:
$ref: ./components/parameters.yml#/PageLimit
PageCursor:
$ref: ./components/parameters.yml#/PageCursor
headers:
ETag:
$ref: ./components/headers.yml#/ETag
RetryAfter:
$ref: ./components/headers.yml#/RetryAfter
responses:
ValidationFailed:
$ref: ./components/responses.yml#/ValidationFailed
Unauthenticated:
$ref: ./components/responses.yml#/Unauthenticated
Forbidden:
$ref: ./components/responses.yml#/Forbidden
NotFound:
$ref: ./components/responses.yml#/NotFound
IdempotencyInProgress:
$ref: ./components/responses.yml#/IdempotencyInProgress
StateConflict:
$ref: ./components/responses.yml#/StateConflict
PreconditionFailed:
$ref: ./components/responses.yml#/PreconditionFailed
PayloadTooLarge:
$ref: ./components/responses.yml#/PayloadTooLarge
UnprocessableContent:
$ref: ./components/responses.yml#/UnprocessableContent
PreconditionRequired:
$ref: ./components/responses.yml#/PreconditionRequired
TooManyRequests:
$ref: ./components/responses.yml#/TooManyRequests
Internal:
$ref: ./components/responses.yml#/Internal
NotImplemented:
$ref: ./components/responses.yml#/NotImplemented
Problem:
$ref: ./components/responses.yml#/Problem
+7
View File
@@ -11,3 +11,10 @@ get:
application/json:
schema:
$ref: ../components/schemas.yml#/HealthResponse
examples:
ok:
summary: The process is responding
value:
status: ok
default:
$ref: ../components/responses.yml#/Problem
+30
View File
@@ -0,0 +1,30 @@
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 parameters 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: query
pointer: /limit
code: invalid
message: The value does not match the contract.
internal:
summary: Unexpected server error
value:
type: urn:lincodex:problem:internal
title: Internal server error
status: 500
code: internal
detail: The server could not complete the request.
+136
View File
@@ -8,6 +8,142 @@ MLHealthResponse:
type: string
enum:
- ok
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the ML service copy of the public api/core Problem schema; keep both copies identical except for descriptions. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: '#/ProblemCode'
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier of the call when the caller propagated one; it is not a secret.
errors:
type: array
maxItems: 100
description: Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: '#/ProblemFieldError'
ProblemCode:
type: string
description: 'Stable public error code. 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 body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.
- unauthenticated (401): no valid session or credentials.
- forbidden (403): the caller is authenticated but not allowed.
- not_found (404): the route or object does not exist or is not visible.
- method_not_allowed (405): the route does not support the method.
- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.
- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.
- version_conflict (412): If-Match does not match the current version.
- 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 Idempotency-Key was already used with a different request.
- precondition_required (428): the operation requires If-Match.
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.'
enum:
- validation_failed
- unauthenticated
- forbidden
- not_found
- method_not_allowed
- idempotency_in_progress
- state_conflict
- version_conflict
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- precondition_required
- rate_limited
- internal
- not_implemented
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 `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.
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
MLReadinessResponse:
type: object
additionalProperties: false
@@ -0,0 +1,148 @@
schemas:
Problem:
type: object
description: >-
Problem details (RFC 9457) returned with the application/problem+json
media type for every error response. This is the ML service copy of the
public api/core Problem schema; keep both copies identical except for
descriptions. `code` is the stable,
machine-readable reason; clients branch on it rather than on `title`,
`detail`, or the HTTP status alone. The body never contains internal
error text, stack traces, SQL, file paths, credentials, contact data, or
echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: >-
URI that identifies the problem type. It has the form
`urn:lincodex:problem:<code>` and is an identifier, not a link to
dereference.
title:
type: string
minLength: 1
maxLength: 200
description: >-
Short, fixed English summary of the problem type. It does not change
between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: "#/schemas/ProblemCode"
detail:
type: string
maxLength: 1000
description: >-
Safe English explanation of this occurrence. It never contains
internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: "^[A-Za-z0-9._-]+$"
description: >-
Request identifier of the call when the caller propagated one; it is
not a secret.
errors:
type: array
maxItems: 100
description: >-
Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: "#/schemas/ProblemFieldError"
ProblemCode:
type: string
description: |-
Stable public error code. 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 body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.
- unauthenticated (401): no valid session or credentials.
- forbidden (403): the caller is authenticated but not allowed.
- not_found (404): the route or object does not exist or is not visible.
- method_not_allowed (405): the route does not support the method.
- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.
- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.
- version_conflict (412): If-Match does not match the current version.
- 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 Idempotency-Key was already used with a different request.
- precondition_required (428): the operation requires If-Match.
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.
enum:
- validation_failed
- unauthenticated
- forbidden
- not_found
- method_not_allowed
- idempotency_in_progress
- state_conflict
- version_conflict
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- precondition_required
- rate_limited
- internal
- not_implemented
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 `/salary_from`; an empty string means the whole
body. For a parameter it is `/` followed by the parameter name, for
example `/limit` or `/Idempotency-Key`.
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
+155
View File
@@ -19,6 +19,8 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/MLHealthResponse'
default:
$ref: '#/components/responses/Problem'
/readyz:
get:
operationId: GetMLReadyz
@@ -39,8 +41,161 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/MLReadinessResponse'
default:
$ref: '#/components/responses/Problem'
components:
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 parameters 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: query
pointer: /limit
code: invalid
message: The value does not match the contract.
internal:
summary: Unexpected server error
value:
type: urn:lincodex:problem:internal
title: Internal server error
status: 500
code: internal
detail: The server could not complete the request.
schemas:
ProblemCode:
type: string
description: |-
Stable public error code. 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 body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.
- unauthenticated (401): no valid session or credentials.
- forbidden (403): the caller is authenticated but not allowed.
- not_found (404): the route or object does not exist or is not visible.
- method_not_allowed (405): the route does not support the method.
- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.
- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.
- version_conflict (412): If-Match does not match the current version.
- 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 Idempotency-Key was already used with a different request.
- precondition_required (428): the operation requires If-Match.
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.
enum:
- validation_failed
- unauthenticated
- forbidden
- not_found
- method_not_allowed
- idempotency_in_progress
- state_conflict
- version_conflict
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- precondition_required
- rate_limited
- internal
- not_implemented
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 `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.
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 ML service copy of the public api/core Problem schema; keep both copies identical except for descriptions. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: '#/components/schemas/ProblemCode'
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier of the call when the caller propagated one; it is not a secret.
errors:
type: array
maxItems: 100
description: Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: '#/components/schemas/ProblemFieldError'
MLHealthResponse:
type: object
additionalProperties: false
+4
View File
@@ -9,3 +9,7 @@ paths:
$ref: ./routes/healthz.yml
/readyz:
$ref: ./routes/readyz.yml
components:
responses:
Problem:
$ref: ./components/responses.yml#/Problem
+2
View File
@@ -11,3 +11,5 @@ get:
application/json:
schema:
$ref: ../components/schemas.yml#/MLHealthResponse
default:
$ref: ../components/responses.yml#/Problem
+2
View File
@@ -17,3 +17,5 @@ get:
application/json:
schema:
$ref: ../components/schemas.yml#/MLReadinessResponse
default:
$ref: ../components/responses.yml#/Problem
+394
View File
@@ -2,6 +2,12 @@ openapi: 3.2.0
info:
title: OpenAPI 3.2 compatibility fixture
version: 0.1.0
description: >-
Exercises the OpenAPI 3.2 subset and the api/core conventions (problem
details, cursor pagination, Idempotency-Key, If-Match, and ETag) through
the pinned generators. The operations are test fixtures, not product
endpoints. Component definitions shared with api/core are copies that must
stay identical to the api/core bundle.
servers:
- url: /
paths:
@@ -25,6 +31,8 @@ paths:
application/json:
schema:
$ref: "#/components/schemas/NullablePayload"
default:
$ref: "#/components/responses/Problem"
additionalOperations:
PURGE:
operationId: PurgeProbe
@@ -33,6 +41,90 @@ paths:
responses:
"204":
description: The compatibility fixture operation completed.
default:
$ref: "#/components/responses/Problem"
/probe/items:
get:
operationId: ListProbeItems
summary: Exercise bounded cursor pagination.
security: []
parameters:
- $ref: "#/components/parameters/PageLimit"
- $ref: "#/components/parameters/PageCursor"
responses:
"200":
description: One page of fixture items.
content:
application/json:
schema:
$ref: "#/components/schemas/ProbeItemPage"
default:
$ref: "#/components/responses/Problem"
post:
operationId: CreateProbeItem
summary: Exercise an idempotent mutating command.
security: []
parameters:
- $ref: "#/components/parameters/IdempotencyKey"
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/ProbeItemInput"
responses:
"201":
description: The fixture item was created or the stored response was replayed.
headers:
ETag:
$ref: "#/components/headers/ETag"
content:
application/json:
schema:
$ref: "#/components/schemas/ProbeItem"
"409":
$ref: "#/components/responses/IdempotencyInProgress"
"422":
$ref: "#/components/responses/UnprocessableContent"
default:
$ref: "#/components/responses/Problem"
/probe/items/{item_id}:
patch:
operationId: UpdateProbeItem
summary: Exercise optimistic concurrency with If-Match and ETag.
description: This operation requires If-Match; without it the fixture handler answers 428 precondition_required.
security: []
parameters:
- name: item_id
in: path
required: true
schema:
type: string
format: uuid
- $ref: "#/components/parameters/IdempotencyKey"
- $ref: "#/components/parameters/IfMatch"
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/ProbeItemInput"
responses:
"200":
description: The fixture item was updated.
headers:
ETag:
$ref: "#/components/headers/ETag"
content:
application/json:
schema:
$ref: "#/components/schemas/ProbeItem"
"412":
$ref: "#/components/responses/PreconditionFailed"
"428":
$ref: "#/components/responses/PreconditionRequired"
default:
$ref: "#/components/responses/Problem"
components:
schemas:
NullablePayload:
@@ -45,3 +137,305 @@ components:
type:
- string
- "null"
ProbeItemInput:
type: object
additionalProperties: false
required:
- name
properties:
name:
type: string
minLength: 1
maxLength: 100
ProbeItem:
type: object
additionalProperties: false
required:
- id
- name
- updated_at
properties:
id:
type: string
format: uuid
name:
type: string
minLength: 1
maxLength: 100
updated_at:
$ref: "#/components/schemas/Timestamp"
ProbeItemPage:
type: object
additionalProperties: false
required:
- items
- page
properties:
items:
type: array
maxItems: 100
items:
$ref: "#/components/schemas/ProbeItem"
page:
$ref: "#/components/schemas/PageInfo"
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: "#/components/schemas/ProblemCode"
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; 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"
ProblemCode:
type: string
description:
"Stable public error code. 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 body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.
- unauthenticated (401): no valid session or credentials.
- forbidden (403): the caller is authenticated but not allowed.
- not_found (404): the route or object does not exist or is not visible.
- method_not_allowed (405): the route does not support the method.
- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.
- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.
- version_conflict (412): If-Match does not match the current version.
- 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 Idempotency-Key was already used with a different request.
- precondition_required (428): the operation requires If-Match.
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet."
enum:
- validation_failed
- unauthenticated
- forbidden
- not_found
- method_not_allowed
- idempotency_in_progress
- state_conflict
- version_conflict
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- precondition_required
- rate_limited
- internal
- not_implemented
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 `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.
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
Timestamp:
type: string
format: date-time
description: UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.
examples:
- "2026-10-05T09:30:00Z"
PageInfo:
type: object
description: Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.
additionalProperties: false
required:
- has_more
- next_cursor
properties:
has_more:
type: boolean
description: Whether another page follows this one.
next_cursor:
type:
- string
- "null"
minLength: 1
maxLength: 512
pattern: ^[A-Za-z0-9_-]+$
description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.
parameters:
IdempotencyKey:
name: Idempotency-Key
in: header
required: true
description:
"Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value is sent without quotes. The server scopes the key by caller and operation and fingerprints the request by method, path, and body.
Stored for 24 hours after the first request and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect.
Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry), 422 idempotency_key_reused, 429, and every 5xx.
Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused before any other key check; a running request with the same fingerprint returns 409 idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that does the server check If-Match, so a retry of a completed change replays its outcome instead of failing on the version it has just changed. After 24 hours the key may be accepted as new."
schema:
type: string
minLength: 1
maxLength: 255
pattern: ^[A-Za-z0-9._:-]+$
example: 5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11
IfMatch:
name: If-Match
in: header
required: false
description:
"Strong entity tag of the resource version the client last read, copied from the ETag response header. An operation that changes a versioned resource says in its own description that it requires If-Match.
On such an operation, a missing If-Match returns 428 precondition_required. An If-Match that does not equal the current ETag returns 412 version_conflict and changes nothing; read the resource again before retrying. Only one strong entity tag is accepted; weak tags, lists, and `*` fail validation with 400. The parameter is optional in the schema so that a missing header reaches the application, which answers 428."
schema:
type: string
minLength: 3
maxLength: 130
pattern: ^"[A-Za-z0-9._~-]{1,128}"$
example: '"v7"'
PageLimit:
name: limit
in: query
required: false
description: Maximum number of items in the page. The server may return fewer items even when more remain; use `page.has_more` to detect the end.
schema:
type: integer
format: int32
minimum: 1
maximum: 100
default: 20
PageCursor:
name: cursor
in: query
required: false
description: Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the first page. A malformed or foreign cursor returns 400 with code validation_failed.
schema:
type: string
minLength: 1
maxLength: 512
pattern: ^[A-Za-z0-9_-]+$
headers:
ETag:
description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version.
required: true
schema:
type: string
minLength: 3
maxLength: 130
pattern: ^"[A-Za-z0-9._~-]{1,128}"$
example: '"v7"'
responses:
IdempotencyInProgress:
description: A request with the same Idempotency-Key and the same fingerprint is still being processed; code idempotency_in_progress. Retry after the original request completes.
content:
application/problem+json:
schema:
$ref: "#/components/schemas/Problem"
UnprocessableContent:
description: The Idempotency-Key was already used with a different request within 24 hours; code idempotency_key_reused. Nothing was changed.
content:
application/problem+json:
schema:
$ref: "#/components/schemas/Problem"
PreconditionFailed:
description: If-Match does not match the current resource version; code version_conflict. Nothing was changed.
content:
application/problem+json:
schema:
$ref: "#/components/schemas/Problem"
PreconditionRequired:
description: The operation requires If-Match; code precondition_required.
content:
application/problem+json:
schema:
$ref: "#/components/schemas/Problem"
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"
+1 -1
View File
@@ -79,7 +79,7 @@ mocks: ## Generate configured mocks when interfaces are selected
fi
.PHONY: check-ogen-compat
check-ogen-compat: ## Verify OpenAPI 3.2 nullable values, validation, and additionalOperations
check-ogen-compat: ## Verify OpenAPI 3.2 features and API error, pagination, and retry conventions with ogen
@set -euo pipefail; mkdir -p bin; temporary_dir=$$(mktemp -d "$(CURDIR)/bin/ogen-compat.XXXXXX"); trap 'rm -rf "$$temporary_dir"' EXIT; \
$(GO_TOOL) ogen -config codegen/ogen-compat.yml --target "$$temporary_dir" --package compat --clean ../api/testdata/openapi-3.2.0.yml; \
cp testdata/ogen_compat_test.go "$$temporary_dir/ogen_compat_test.go"; \
@@ -8,6 +8,7 @@ import (
"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"
@@ -15,6 +16,11 @@ import (
"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-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
}
var (
// Allocate option closure once.
serverSpanKind = trace.WithSpanKind(trace.SpanKindServer)
@@ -142,8 +142,19 @@ func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w htt
response, err = s.h.GetHealthz(ctx)
}
if err != nil {
defer recordError("Internal", err)
s.cfg.ErrorHandler(ctx, w, r, err)
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
}
@@ -142,3 +142,519 @@ func (s *HealthResponseStatus) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes string as json.
func (o OptString) Encode(e *jx.Encoder) {
if !o.Set {
return
}
e.Str(string(o.Value))
}
// Decode decodes string from json.
func (o *OptString) Decode(d *jx.Decoder) error {
if o == nil {
return errors.New("invalid: unable to decode OptString to nil")
}
o.Set = true
v, err := d.Str()
if err != nil {
return err
}
o.Value = string(v)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s OptString) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *OptString) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *Problem) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *Problem) encodeFields(e *jx.Encoder) {
{
e.FieldStart("type")
e.Str(s.Type)
}
{
e.FieldStart("title")
e.Str(s.Title)
}
{
e.FieldStart("status")
e.Int32(s.Status)
}
{
e.FieldStart("code")
s.Code.Encode(e)
}
{
if s.Detail.Set {
e.FieldStart("detail")
s.Detail.Encode(e)
}
}
{
if s.Instance.Set {
e.FieldStart("instance")
s.Instance.Encode(e)
}
}
{
if s.TraceID.Set {
e.FieldStart("trace_id")
s.TraceID.Encode(e)
}
}
{
if s.Errors != nil {
e.FieldStart("errors")
e.ArrStart()
for _, elem := range s.Errors {
elem.Encode(e)
}
e.ArrEnd()
}
}
}
var jsonFieldsNameOfProblem = [8]string{
0: "type",
1: "title",
2: "status",
3: "code",
4: "detail",
5: "instance",
6: "trace_id",
7: "errors",
}
// Decode decodes Problem from json.
func (s *Problem) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode Problem to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "type":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Str()
s.Type = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"type\"")
}
case "title":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Str()
s.Title = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"title\"")
}
case "status":
requiredBitSet[0] |= 1 << 2
if err := func() error {
v, err := d.Int32()
s.Status = int32(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"status\"")
}
case "code":
requiredBitSet[0] |= 1 << 3
if err := func() error {
if err := s.Code.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"code\"")
}
case "detail":
if err := func() error {
s.Detail.Reset()
if err := s.Detail.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"detail\"")
}
case "instance":
if err := func() error {
s.Instance.Reset()
if err := s.Instance.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"instance\"")
}
case "trace_id":
if err := func() error {
s.TraceID.Reset()
if err := s.TraceID.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"trace_id\"")
}
case "errors":
if err := func() error {
s.Errors = make([]ProblemFieldError, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem ProblemFieldError
if err := elem.Decode(d); err != nil {
return err
}
s.Errors = append(s.Errors, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"errors\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode Problem")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00001111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfProblem) {
name = jsonFieldsNameOfProblem[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *Problem) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *Problem) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ProblemCode as json.
func (s ProblemCode) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ProblemCode from json.
func (s *ProblemCode) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProblemCode to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ProblemCode(v) {
case ProblemCodeValidationFailed:
*s = ProblemCodeValidationFailed
case ProblemCodeUnauthenticated:
*s = ProblemCodeUnauthenticated
case ProblemCodeForbidden:
*s = ProblemCodeForbidden
case ProblemCodeNotFound:
*s = ProblemCodeNotFound
case ProblemCodeMethodNotAllowed:
*s = ProblemCodeMethodNotAllowed
case ProblemCodeIdempotencyInProgress:
*s = ProblemCodeIdempotencyInProgress
case ProblemCodeStateConflict:
*s = ProblemCodeStateConflict
case ProblemCodeVersionConflict:
*s = ProblemCodeVersionConflict
case ProblemCodePayloadTooLarge:
*s = ProblemCodePayloadTooLarge
case ProblemCodeUnsupportedMediaType:
*s = ProblemCodeUnsupportedMediaType
case ProblemCodeIdempotencyKeyReused:
*s = ProblemCodeIdempotencyKeyReused
case ProblemCodePreconditionRequired:
*s = ProblemCodePreconditionRequired
case ProblemCodeRateLimited:
*s = ProblemCodeRateLimited
case ProblemCodeInternal:
*s = ProblemCodeInternal
case ProblemCodeNotImplemented:
*s = ProblemCodeNotImplemented
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)
}
@@ -7,6 +7,8 @@ import (
"github.com/go-faster/errors"
"github.com/go-faster/jx"
ht "github.com/ogen-go/ogen/http"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
@@ -22,3 +24,28 @@ func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, s
return nil
}
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
}
@@ -3,9 +3,15 @@
package api
import (
"fmt"
"github.com/go-faster/errors"
)
func (s *ProblemStatusCode) Error() string {
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
}
// Ref: #/components/schemas/HealthResponse
type HealthResponse struct {
Status HealthResponseStatus `json:"status"`
@@ -54,3 +60,454 @@ func (s *HealthResponseStatus) UnmarshalText(data []byte) error {
return errors.Errorf("invalid value: %q", data)
}
}
// NewOptString returns new OptString with value set to v.
func NewOptString(v string) OptString {
return OptString{
Value: v,
Set: true,
}
}
// OptString is optional string.
type OptString struct {
Value string
Set bool
}
// IsSet returns true if OptString was set.
func (o OptString) IsSet() bool { return o.Set }
// Reset unsets value.
func (o *OptString) Reset() {
var v string
o.Value = v
o.Set = false
}
// SetTo sets value to v.
func (o *OptString) SetTo(v string) {
o.Set = true
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o OptString) Get() (v string, ok bool) {
if !o.Set {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o OptString) Or(d string) string {
if v, ok := o.Get(); ok {
return v
}
return d
}
// Problem details (RFC 9457) returned with the application/problem+json media type for every error
// response. `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:<code>` 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, equal to the X-Request-ID response header. Quote it when reporting the problem;
// 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 public error code. 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 body violates a
// domain rule such as salary_from <= salary_to; `errors` points at the fields.
// - unauthenticated (401): no valid session or credentials.
// - forbidden (403): the caller is authenticated but not allowed.
// - not_found (404): the route or object does not exist or is not visible.
// - method_not_allowed (405): the route does not support the method.
// - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.
// - state_conflict (409): the operation conflicts with the current state of the resource, for example
// an invitation that was already accepted.
// - version_conflict (412): If-Match does not match the current version.
// - 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 Idempotency-Key was already used with a different request.
// - precondition_required (428): the operation requires If-Match.
// - rate_limited (429): too many requests; see Retry-After.
// - internal (500): unexpected server error.
// - not_implemented (501): the operation is in the contract but not implemented yet.
//
// Ref: #/components/schemas/ProblemCode
type ProblemCode string
const (
ProblemCodeValidationFailed ProblemCode = "validation_failed"
ProblemCodeUnauthenticated ProblemCode = "unauthenticated"
ProblemCodeForbidden ProblemCode = "forbidden"
ProblemCodeNotFound ProblemCode = "not_found"
ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed"
ProblemCodeIdempotencyInProgress ProblemCode = "idempotency_in_progress"
ProblemCodeStateConflict ProblemCode = "state_conflict"
ProblemCodeVersionConflict ProblemCode = "version_conflict"
ProblemCodePayloadTooLarge ProblemCode = "payload_too_large"
ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type"
ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused"
ProblemCodePreconditionRequired ProblemCode = "precondition_required"
ProblemCodeRateLimited ProblemCode = "rate_limited"
ProblemCodeInternal ProblemCode = "internal"
ProblemCodeNotImplemented ProblemCode = "not_implemented"
)
// AllValues returns all ProblemCode values.
func (ProblemCode) AllValues() []ProblemCode {
return []ProblemCode{
ProblemCodeValidationFailed,
ProblemCodeUnauthenticated,
ProblemCodeForbidden,
ProblemCodeNotFound,
ProblemCodeMethodNotAllowed,
ProblemCodeIdempotencyInProgress,
ProblemCodeStateConflict,
ProblemCodeVersionConflict,
ProblemCodePayloadTooLarge,
ProblemCodeUnsupportedMediaType,
ProblemCodeIdempotencyKeyReused,
ProblemCodePreconditionRequired,
ProblemCodeRateLimited,
ProblemCodeInternal,
ProblemCodeNotImplemented,
}
}
// 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 ProblemCodeForbidden:
return []byte(s), nil
case ProblemCodeNotFound:
return []byte(s), nil
case ProblemCodeMethodNotAllowed:
return []byte(s), nil
case ProblemCodeIdempotencyInProgress:
return []byte(s), nil
case ProblemCodeStateConflict:
return []byte(s), nil
case ProblemCodeVersionConflict:
return []byte(s), nil
case ProblemCodePayloadTooLarge:
return []byte(s), nil
case ProblemCodeUnsupportedMediaType:
return []byte(s), nil
case ProblemCodeIdempotencyKeyReused:
return []byte(s), nil
case ProblemCodePreconditionRequired:
return []byte(s), nil
case ProblemCodeRateLimited:
return []byte(s), nil
case ProblemCodeInternal:
return []byte(s), nil
case ProblemCodeNotImplemented:
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 ProblemCodeForbidden:
*s = ProblemCodeForbidden
return nil
case ProblemCodeNotFound:
*s = ProblemCodeNotFound
return nil
case ProblemCodeMethodNotAllowed:
*s = ProblemCodeMethodNotAllowed
return nil
case ProblemCodeIdempotencyInProgress:
*s = ProblemCodeIdempotencyInProgress
return nil
case ProblemCodeStateConflict:
*s = ProblemCodeStateConflict
return nil
case ProblemCodeVersionConflict:
*s = ProblemCodeVersionConflict
return nil
case ProblemCodePayloadTooLarge:
*s = ProblemCodePayloadTooLarge
return nil
case ProblemCodeUnsupportedMediaType:
*s = ProblemCodeUnsupportedMediaType
return nil
case ProblemCodeIdempotencyKeyReused:
*s = ProblemCodeIdempotencyKeyReused
return nil
case ProblemCodePreconditionRequired:
*s = ProblemCodePreconditionRequired
return nil
case ProblemCodeRateLimited:
*s = ProblemCodeRateLimited
return nil
case ProblemCodeInternal:
*s = ProblemCodeInternal
return nil
case ProblemCodeNotImplemented:
*s = ProblemCodeNotImplemented
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
// `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the
// parameter name, for example `/limit` or `/Idempotency-Key`.
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
}
@@ -14,6 +14,10 @@ type Handler interface {
//
// GET /api/v1/healthz
GetHealthz(ctx context.Context) (*HealthResponse, 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
@@ -21,3 +21,11 @@ var _ Handler = UnimplementedHandler{}
func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse, _ 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
}
@@ -3,6 +3,8 @@
package api
import (
"fmt"
"github.com/go-faster/errors"
"github.com/ogen-go/ogen/validate"
)
@@ -38,3 +40,388 @@ func (s HealthResponseStatus) Validate() error {
return errors.Errorf("invalid value: %v", s)
}
}
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 "forbidden":
return nil
case "not_found":
return nil
case "method_not_allowed":
return nil
case "idempotency_in_progress":
return nil
case "state_conflict":
return nil
case "version_conflict":
return nil
case "payload_too_large":
return nil
case "unsupported_media_type":
return nil
case "idempotency_key_reused":
return nil
case "precondition_required":
return nil
case "rate_limited":
return nil
case "internal":
return nil
case "not_implemented":
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
}
@@ -0,0 +1,142 @@
// Package problem writes RFC 9457 problem details for the public HTTP API.
//
// Every public error body is an api.Problem with a stable api.ProblemCode.
// The status, title, and detail of each code are fixed here, so a response
// never carries internal error text or echoed request values.
package problem
import (
"context"
"net/http"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
"lincodex/backend/internal/adapter/primary/http/api"
)
// MediaType is the RFC 9457 media type of every public error response.
const MediaType = "application/problem+json"
// typePrefix forms the problem type URI; the contract documents this form.
const typePrefix = "urn:lincodex:problem:"
type definition struct {
status int32
title string
detail string
}
var definitions = map[api.ProblemCode]definition{
api.ProblemCodeValidationFailed: {
status: http.StatusBadRequest,
title: "Request validation failed",
detail: "One or more request fields are invalid.",
},
api.ProblemCodeUnauthenticated: {
status: http.StatusUnauthorized,
title: "Authentication required",
detail: "Sign in and repeat the request.",
},
api.ProblemCodeForbidden: {
status: http.StatusForbidden,
title: "Access denied",
detail: "You do not have permission to perform this operation.",
},
api.ProblemCodeNotFound: {
status: http.StatusNotFound,
title: "Resource not found",
detail: "The requested resource does not exist.",
},
api.ProblemCodeMethodNotAllowed: {
status: http.StatusMethodNotAllowed,
title: "Method not allowed",
detail: "The resource does not support this method; see the Allow header.",
},
api.ProblemCodeIdempotencyInProgress: {
status: http.StatusConflict,
title: "Request with this idempotency key is in progress",
detail: "Retry after the original request completes.",
},
api.ProblemCodeStateConflict: {
status: http.StatusConflict,
title: "Resource state conflict",
detail: "The resource is in a state that does not allow this operation.",
},
api.ProblemCodeVersionConflict: {
status: http.StatusPreconditionFailed,
title: "Resource version conflict",
detail: "The resource changed after it was read. Read it again before retrying.",
},
api.ProblemCodePayloadTooLarge: {
status: http.StatusRequestEntityTooLarge,
title: "Request body too large",
detail: "Reduce the request body size and retry.",
},
api.ProblemCodeUnsupportedMediaType: {
status: http.StatusUnsupportedMediaType,
title: "Unsupported media type",
detail: "Send the request body with a media type that the operation accepts.",
},
api.ProblemCodeIdempotencyKeyReused: {
status: http.StatusUnprocessableEntity,
title: "Idempotency key reused with a different request",
detail: "Use a new Idempotency-Key for a different request.",
},
api.ProblemCodePreconditionRequired: {
status: http.StatusPreconditionRequired,
title: "Precondition required",
detail: "Send If-Match with the ETag of the version you read.",
},
api.ProblemCodeRateLimited: {
status: http.StatusTooManyRequests,
title: "Too many requests",
detail: "Wait for the Retry-After interval and retry.",
},
api.ProblemCodeInternal: {
status: http.StatusInternalServerError,
title: "Internal server error",
detail: "The server could not complete the request.",
},
api.ProblemCodeNotImplemented: {
status: http.StatusNotImplemented,
title: "Operation not implemented",
detail: "This operation is not available yet.",
},
}
// New returns the problem response for code with its fixed status, title,
// and detail, and the request ID of ctx as trace_id. An unknown code yields
// the internal problem, so a caller cannot produce an undocumented status.
func New(ctx context.Context, code api.ProblemCode) *api.ProblemStatusCode {
known, ok := definitions[code]
if !ok {
code = api.ProblemCodeInternal
known = definitions[code]
}
response := api.Problem{
Type: typePrefix + string(code),
Title: known.title,
Status: known.status,
Code: code,
Detail: api.NewOptString(known.detail),
}
if requestID := kitmiddleware.GetRequestID(ctx); requestID != "" {
response.TraceID = api.NewOptString(requestID)
}
return &api.ProblemStatusCode{StatusCode: int(known.status), Response: response}
}
// Write sends problem as an application/problem+json response.
func Write(w http.ResponseWriter, problem *api.ProblemStatusCode) {
body, err := problem.Response.MarshalJSON()
if err != nil {
// The generated encoder does not fail for a Problem value; keep the
// status so the client still sees an error.
w.WriteHeader(problem.StatusCode)
return
}
w.Header().Set("Content-Type", MediaType)
w.WriteHeader(problem.StatusCode)
// The status is already committed; a failed write cannot be reported.
_, _ = w.Write(body)
}
@@ -0,0 +1,98 @@
package problem
import (
"bufio"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"runtime/debug"
"github.com/felixge/httpsnoop"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
"lincodex/backend/internal/adapter/primary/http/api"
)
// Recover answers a panic in next with the internal problem response and logs
// the panic type and stack once. It must run inside the request ID middleware so the problem
// and the log entry carry the request ID. When next has already started the
// response, the status is committed and no second body is written. A panic
// with http.ErrAbortHandler is re-raised so net/http aborts the response as
// that sentinel requires.
func (responder *Responder) Recover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tracked, started := trackResponseStart(w)
defer responder.recoverPanic(w, r, started)
next.ServeHTTP(tracked, r)
})
}
// recoverPanic must be deferred directly so that recover stops the panic.
func (responder *Responder) recoverPanic(w http.ResponseWriter, r *http.Request, started *bool) {
recovered := recover()
if recovered == nil {
return
}
if err, ok := recovered.(error); ok && errors.Is(err, http.ErrAbortHandler) {
panic(recovered)
}
ctx := r.Context()
responder.logger.ErrorContext(ctx, "public API request panicked",
slog.String("request_id", kitmiddleware.GetRequestID(ctx)),
// The panic value may hold request data, so only its type is logged.
slog.String("panic_type", fmt.Sprintf("%T", recovered)),
slog.String("stack", string(debug.Stack())),
slog.Bool("response_started", *started),
)
if !*started {
Write(w, New(ctx, api.ProblemCodeInternal))
}
}
// trackResponseStart wraps w, keeping its optional interfaces, and reports
// whether the handler has started the response.
func trackResponseStart(w http.ResponseWriter) (http.ResponseWriter, *bool) {
started := new(bool)
tracked := httpsnoop.Wrap(w, httpsnoop.Hooks{
WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
return func(code int) {
*started = true
next(code)
}
},
Write: func(next httpsnoop.WriteFunc) httpsnoop.WriteFunc {
return func(body []byte) (int, error) {
*started = true
return next(body)
}
},
WriteString: func(next httpsnoop.WriteStringFunc) httpsnoop.WriteStringFunc {
return func(body string) (int, error) {
*started = true
return next(body)
}
},
ReadFrom: func(next httpsnoop.ReadFromFunc) httpsnoop.ReadFromFunc {
return func(source io.Reader) (int64, error) {
*started = true
return next(source)
}
},
Flush: func(next httpsnoop.FlushFunc) httpsnoop.FlushFunc {
return func() {
*started = true
next()
}
},
Hijack: func(next httpsnoop.HijackFunc) httpsnoop.HijackFunc {
return func() (net.Conn, *bufio.ReadWriter, error) {
*started = true
return next()
}
},
})
return tracked, started
}
@@ -0,0 +1,66 @@
package problem
import (
"bytes"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"lincodex/backend/internal/adapter/primary/http/api"
)
func TestRecoverKeepsAStartedResponse(t *testing.T) {
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
handler := responder.Recover(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"partial":`))
panic("encoder failed")
}))
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/items", nil))
if response.Code != http.StatusAccepted || response.Body.String() != `{"partial":` {
t.Fatalf("response = %d %q, want the started response without a second body", response.Code, response.Body.String())
}
if !strings.Contains(logs.String(), `"response_started":true`) {
t.Fatalf("panic was not logged with the started response: %s", logs.String())
}
}
func TestRecoverWritesInternalProblemBeforeTheResponseStarts(t *testing.T) {
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
handler := responder.Recover(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
panic("profile of jane@example.com")
}))
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/items", nil))
decodeProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
if strings.Contains(response.Body.String(), "jane") || strings.Contains(logs.String(), "jane") {
t.Fatalf("panic value leaked; body %s, logs %s", response.Body.String(), logs.String())
}
if !strings.Contains(logs.String(), `"panic_type":"string"`) {
t.Fatalf("panic type was not logged: %s", logs.String())
}
}
func TestRecoverReraisesAbortHandler(t *testing.T) {
responder := NewResponder(slog.New(slog.DiscardHandler))
handler := responder.Recover(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
panic(http.ErrAbortHandler)
}))
defer func() {
if recovered := recover(); recovered != http.ErrAbortHandler { //nolint:errorlint // net/http compares the sentinel by identity
t.Fatalf("recovered %v, want http.ErrAbortHandler", recovered)
}
}()
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/v1/items", nil))
t.Fatal("ServeHTTP returned instead of re-raising http.ErrAbortHandler")
}
@@ -0,0 +1,240 @@
package problem
import (
"context"
"errors"
"log/slog"
"net/http"
"regexp"
"strings"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/openapi"
"github.com/ogen-go/ogen/validate"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
"lincodex/backend/internal/adapter/primary/http/api"
)
// Field reasons published in ProblemFieldError.code.
const (
fieldCodeRequired = "required"
fieldCodeInvalid = "invalid"
)
const (
fieldMessageRequired = "The value is required."
fieldMessageInvalid = "The value does not match the contract."
// maxFieldErrors matches the maxItems bound of Problem.errors.
maxFieldErrors = 100
// wholeBodyPointer is the JSON Pointer of the request body root.
wholeBodyPointer = ""
)
// arrayIndexName matches the "[index]" names that generated validators use
// for array items.
var arrayIndexName = regexp.MustCompile(`^\[(\d+)\]$`)
var pointerTokenEscaper = strings.NewReplacer("~", "~0", "/", "~1")
var parameterLocations = map[openapi.ParameterLocation]api.ProblemFieldLocation{
openapi.LocationQuery: api.ProblemFieldLocationQuery,
openapi.LocationHeader: api.ProblemFieldLocationHeader,
openapi.LocationPath: api.ProblemFieldLocationPath,
openapi.LocationCookie: api.ProblemFieldLocationCookie,
}
// Responder maps errors at the public HTTP boundary to problem responses and
// logs the errors that are not the client's fault. It logs the error text of
// internal failures, so handwritten errors must follow the backend error
// standard and never carry personal data, request bodies, credentials, or
// other secrets. A request canceled by its client is logged at info level
// because it is not a server failure.
type Responder struct {
logger *slog.Logger
}
func NewResponder(logger *slog.Logger) *Responder {
return &Responder{logger: logger}
}
// HandlerError builds the response for an error returned by an api.Handler
// operation; it implements the contract of api.Handler.NewError. The
// generated server passes security failures here as well, so a
// *ogenerrors.SecurityError becomes 401. Authorization decisions that need 403
// return a typed *api.ProblemStatusCode from the operation instead, which the
// generated server encodes without calling NewError.
func (responder *Responder) HandlerError(ctx context.Context, err error) *api.ProblemStatusCode {
if _, ok := errors.AsType[*ogenerrors.SecurityError](err); ok {
return New(ctx, api.ProblemCodeUnauthenticated)
}
responder.logInternal(ctx, err)
return New(ctx, api.ProblemCodeInternal)
}
// HandleServerError is the ErrorHandler of the generated server. It receives
// ht.ErrNotImplemented, request decoding and validation errors, and response
// encoding failures.
func (responder *Responder) HandleServerError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
Write(w, responder.serverErrorProblem(ctx, r, err))
}
// NotFound answers a path that matches no operation of the generated server.
func (*Responder) NotFound(w http.ResponseWriter, r *http.Request) {
Write(w, New(r.Context(), api.ProblemCodeNotFound))
}
// MethodNotAllowed answers a known path requested with an unsupported method.
// The generated server has already set Access-Control-Allow-Methods for a
// CORS preflight, which keeps its empty 204 response.
func (*Responder) MethodNotAllowed(w http.ResponseWriter, r *http.Request, allowed string) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
w.Header().Set("Allow", allowed)
Write(w, New(r.Context(), api.ProblemCodeMethodNotAllowed))
}
func (responder *Responder) serverErrorProblem(ctx context.Context, r *http.Request, err error) *api.ProblemStatusCode {
if errors.Is(err, ht.ErrNotImplemented) {
return New(ctx, api.ProblemCodeNotImplemented)
}
// A body limit set with http.MaxBytesReader surfaces inside the decoding
// error, so it is checked before the generic request decoding branch.
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
return New(ctx, api.ProblemCodePayloadTooLarge)
}
if _, ok := errors.AsType[*validate.InvalidContentTypeError](err); ok {
return New(ctx, api.ProblemCodeUnsupportedMediaType)
}
if _, ok := errors.AsType[*ogenerrors.SecurityError](err); ok {
return New(ctx, api.ProblemCodeUnauthenticated)
}
if paramsErr, ok := errors.AsType[*ogenerrors.DecodeParamsError](err); ok {
return validationProblem(ctx, parameterFieldErrors(r, paramsErr))
}
if requestErr, ok := errors.AsType[*ogenerrors.DecodeRequestError](err); ok {
return validationProblem(ctx, bodyFieldErrors(requestErr))
}
responder.logInternal(ctx, err)
return New(ctx, api.ProblemCodeInternal)
}
func (responder *Responder) logInternal(ctx context.Context, err error) {
if errors.Is(err, context.Canceled) {
responder.logger.InfoContext(ctx, "public API request canceled by client",
slog.String("request_id", kitmiddleware.GetRequestID(ctx)),
)
return
}
responder.logger.ErrorContext(ctx, "public API request failed",
slog.String("request_id", kitmiddleware.GetRequestID(ctx)),
slog.String("error", err.Error()),
)
}
func validationProblem(ctx context.Context, fields []api.ProblemFieldError) *api.ProblemStatusCode {
problem := New(ctx, api.ProblemCodeValidationFailed)
problem.Response.Errors = fields
return problem
}
func parameterFieldErrors(r *http.Request, err error) []api.ProblemFieldError {
paramErr, ok := errors.AsType[*ogenerrors.DecodeParamError](err)
if !ok {
return nil
}
location, ok := parameterLocations[paramErr.In]
if !ok {
return nil
}
code := fieldCodeInvalid
if errors.Is(paramErr.Err, validate.ErrFieldRequired) || !parameterPresent(r, paramErr.In, paramErr.Name) {
code = fieldCodeRequired
}
return []api.ProblemFieldError{fieldError(location, "/"+escapePointerToken(paramErr.Name), code)}
}
// parameterPresent reports whether the request carries the parameter. The
// generated decoder reports a missing query parameter with a plain error, so
// presence is checked on the request instead of in the error text.
func parameterPresent(r *http.Request, in openapi.ParameterLocation, name string) bool {
switch in {
case openapi.LocationQuery:
return r.URL.Query().Has(name)
case openapi.LocationHeader:
return len(r.Header.Values(name)) > 0
case openapi.LocationCookie:
_, err := r.Cookie(name)
return err == nil
case openapi.LocationPath:
// A request without the path segment matches no route.
return true
default:
return true
}
}
func bodyFieldErrors(err error) []api.ProblemFieldError {
if errors.Is(err, validate.ErrBodyRequired) {
return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, wholeBodyPointer, fieldCodeRequired)}
}
var fields []api.ProblemFieldError
if decodeErr, ok := errors.AsType[*ogenerrors.DecodeBodyError](err); ok {
// Only a validation error that is the direct decoding cause names
// top-level fields. A wrapped one comes from a nested object whose
// path the decoder does not record, so it maps to the whole body.
if topLevel, ok := decodeErr.Err.(*validate.Error); ok { //nolint:errorlint // the unwrapped cause alone identifies top-level fields
fields = appendSchemaFieldErrors(fields, topLevel, wholeBodyPointer)
}
} else if validationErr, ok := errors.AsType[*validate.Error](err); ok {
// Schema validation after decoding nests field errors by path.
fields = appendSchemaFieldErrors(fields, validationErr, wholeBodyPointer)
}
if len(fields) == 0 {
return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, wholeBodyPointer, fieldCodeInvalid)}
}
return fields
}
func appendSchemaFieldErrors(fields []api.ProblemFieldError, err *validate.Error, prefix string) []api.ProblemFieldError {
for _, field := range err.Fields {
if len(fields) >= maxFieldErrors {
return fields
}
pointer := prefix + "/" + pointerToken(field.Name)
if nested, ok := field.Error.(*validate.Error); ok { //nolint:errorlint // only a direct nested validation error carries child paths
fields = appendSchemaFieldErrors(fields, nested, pointer)
continue
}
code := fieldCodeInvalid
if errors.Is(field.Error, validate.ErrFieldRequired) {
code = fieldCodeRequired
}
fields = append(fields, fieldError(api.ProblemFieldLocationBody, pointer, code))
}
return fields
}
func pointerToken(name string) string {
if match := arrayIndexName.FindStringSubmatch(name); match != nil {
return match[1]
}
return escapePointerToken(name)
}
// escapePointerToken escapes a reference token as RFC 6901 requires.
func escapePointerToken(token string) string {
return pointerTokenEscaper.Replace(token)
}
func fieldError(location api.ProblemFieldLocation, pointer, code string) api.ProblemFieldError {
message := fieldMessageInvalid
if code == fieldCodeRequired {
message = fieldMessageRequired
}
return api.ProblemFieldError{In: location, Pointer: pointer, Code: code, Message: message}
}
@@ -0,0 +1,261 @@
package problem
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/openapi"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"lincodex/backend/internal/adapter/primary/http/api"
)
// The errors below are built the way the generated server builds them, so the
// tests cover the mapping for decoder paths that the current public contract
// has no input for. The compatibility fixture exercises the same mapping
// through a real generated server in make -C backend check-ogen-compat.
func TestHandleServerErrorMapsGeneratedErrors(t *testing.T) {
operation := ogenerrors.OperationContext{Name: "CreateItem", ID: "CreateItem"}
for _, test := range []struct {
name string
request *http.Request
err error
statusCode int
code api.ProblemCode
fields []api.ProblemFieldError
}{
{
name: "not implemented",
request: httptest.NewRequest(http.MethodGet, "/api/v1/items", nil),
err: ht.ErrNotImplemented,
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "missing query parameter",
request: httptest.NewRequest(http.MethodGet, "/api/v1/items", nil),
err: &ogenerrors.DecodeParamsError{OperationContext: operation, Err: &ogenerrors.DecodeParamError{
Name: "state", In: openapi.LocationQuery, Err: missingQueryParameter("state"),
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationQuery, Pointer: "/state", Code: "required", Message: fieldMessageRequired}},
},
{
name: "invalid query parameter",
request: httptest.NewRequest(http.MethodGet, "/api/v1/items?limit=1000", nil),
err: &ogenerrors.DecodeParamsError{OperationContext: operation, Err: &ogenerrors.DecodeParamError{
Name: "limit", In: openapi.LocationQuery,
Err: fmt.Errorf("int: %w", validate.Int{MinSet: true, Min: 1, MaxSet: true, Max: 100}.Validate(1000)),
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationQuery, Pointer: "/limit", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "missing header",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", nil),
err: &ogenerrors.DecodeParamsError{OperationContext: operation, Err: &ogenerrors.DecodeParamError{
Name: "Idempotency-Key", In: openapi.LocationHeader,
Err: &validate.Error{Fields: []validate.FieldError{{Name: "Idempotency-Key", Error: validate.ErrFieldRequired}}},
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationHeader, Pointer: "/Idempotency-Key", Code: "required", Message: fieldMessageRequired}},
},
{
name: "missing body",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", nil),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: validate.ErrBodyRequired},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "required", Message: fieldMessageRequired}},
},
{
name: "missing top-level body field",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: &ogenerrors.DecodeBodyError{
ContentType: "application/json", Body: []byte(`{}`),
Err: &validate.Error{Fields: []validate.FieldError{{Name: "name", Error: validate.ErrFieldRequired}}},
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/name", Code: "required", Message: fieldMessageRequired}},
},
{
name: "nested decoding failure has no reliable path",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{"page":{}}`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: &ogenerrors.DecodeBodyError{
ContentType: "application/json", Body: []byte(`{"page":{}}`),
Err: fmt.Errorf("decode field \"page\": %w", &validate.Error{Fields: []validate.FieldError{{Name: "has_more", Error: validate.ErrFieldRequired}}}),
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "schema validation keeps nested paths",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: fmt.Errorf("validate: %w", &validate.Error{Fields: []validate.FieldError{
{Name: "items", Error: &validate.Error{Fields: []validate.FieldError{
{Name: "[2]", Error: &validate.Error{Fields: []validate.FieldError{{Name: "a/b", Error: &validate.MaxLengthError{Len: 101, MaxLength: 100}}}}},
}}},
}})},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/items/2/a~1b", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "body over the size limit",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{"name":"probe"}`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: readOverLimit(t)},
statusCode: http.StatusRequestEntityTooLarge,
code: api.ProblemCodePayloadTooLarge,
},
{
name: "unsupported media type",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`name`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: validate.InvalidContentType("text/plain")},
statusCode: http.StatusUnsupportedMediaType,
code: api.ProblemCodeUnsupportedMediaType,
},
{
name: "security failure",
request: httptest.NewRequest(http.MethodGet, "/api/v1/items", nil),
err: &ogenerrors.SecurityError{OperationContext: operation, Security: "cookieAuth", Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
} {
t.Run(test.name, func(t *testing.T) {
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
response := httptest.NewRecorder()
responder.HandleServerError(test.request.Context(), response, test.request, test.err)
body := decodeProblem(t, response, test.statusCode, test.code)
if !reflect.DeepEqual(body.Errors, test.fields) {
t.Fatalf("errors = %+v, want %+v", body.Errors, test.fields)
}
if logs.Len() != 0 {
t.Fatalf("a client error was logged as a server failure: %s", logs.String())
}
})
}
}
func TestHandleServerErrorHidesAndLogsUnexpectedErrors(t *testing.T) {
const internalText = "encode response: write failed"
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
request := httptest.NewRequest(http.MethodGet, "/api/v1/items", nil)
response := httptest.NewRecorder()
responder.HandleServerError(request.Context(), response, request, errors.New(internalText))
decodeProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
if strings.Contains(response.Body.String(), "write failed") {
t.Fatalf("response exposes internal error text: %s", response.Body.String())
}
if !strings.Contains(logs.String(), internalText) || !strings.Contains(logs.String(), `"level":"ERROR"`) {
t.Fatalf("unexpected error was not logged as an error: %s", logs.String())
}
}
func TestClientCancellationIsNotLoggedAsServerFailure(t *testing.T) {
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
got := responder.HandlerError(context.Background(), fmt.Errorf("HealthHandler.GetHealthz - query: %w", context.Canceled))
if got.StatusCode != http.StatusInternalServerError || got.Response.Code != api.ProblemCodeInternal {
t.Fatalf("canceled request = %d %q, want 500 internal", got.StatusCode, got.Response.Code)
}
if strings.Contains(logs.String(), `"level":"ERROR"`) || !strings.Contains(logs.String(), "canceled by client") {
t.Fatalf("client cancellation was not logged at info level: %s", logs.String())
}
}
func TestHandlerErrorSeparatesSecurityFailures(t *testing.T) {
responder := NewResponder(slog.New(slog.DiscardHandler))
securityErr := &ogenerrors.SecurityError{Security: "cookieAuth", Err: errors.New("session expired")}
if got := responder.HandlerError(context.Background(), securityErr); got.StatusCode != http.StatusUnauthorized || got.Response.Code != api.ProblemCodeUnauthenticated {
t.Fatalf("security failure = %d %q, want 401 unauthenticated", got.StatusCode, got.Response.Code)
}
if got := responder.HandlerError(context.Background(), errors.New("query failed")); got.StatusCode != http.StatusInternalServerError || got.Response.Code != api.ProblemCodeInternal {
t.Fatalf("internal failure = %d %q, want 500 internal", got.StatusCode, got.Response.Code)
}
}
func TestNewFallsBackToInternalForUnknownCode(t *testing.T) {
got := New(context.Background(), api.ProblemCode("undocumented"))
if got.StatusCode != http.StatusInternalServerError || got.Response.Code != api.ProblemCodeInternal {
t.Fatalf("unknown code = %d %q, want 500 internal", got.StatusCode, got.Response.Code)
}
}
func TestEveryContractCodeHasAnErrorStatus(t *testing.T) {
for _, code := range api.ProblemCodeInternal.AllValues() {
got := New(context.Background(), code)
if got.Response.Code != code {
t.Errorf("code %q has no definition and falls back to %q", code, got.Response.Code)
}
if err := got.Response.Validate(); err != nil {
t.Errorf("code %q builds an invalid problem: %v", code, err)
}
}
}
func decodeProblem(t *testing.T, response *httptest.ResponseRecorder, statusCode int, code api.ProblemCode) api.Problem {
t.Helper()
if response.Code != statusCode {
t.Fatalf("status code = %d, want %d: %s", response.Code, statusCode, response.Body.String())
}
if contentType := response.Header().Get("Content-Type"); contentType != MediaType {
t.Fatalf("Content-Type = %q, want %q", contentType, MediaType)
}
var body api.Problem
if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil {
t.Fatalf("decode problem %s: %v", response.Body.String(), err)
}
if err := body.Validate(); err != nil {
t.Fatalf("problem %s violates the contract: %v", response.Body.String(), err)
}
if body.Code != code {
t.Fatalf("code = %q, want %q", body.Code, code)
}
return body
}
func missingQueryParameter(name string) error {
return uri.NewQueryDecoder(url.Values{}).HasParam(uri.QueryParameterDecodingConfig{
Name: name, Style: uri.QueryStyleForm, Explode: true,
})
}
// readOverLimit returns the error that http.MaxBytesReader produces, as the
// generated request decoder would receive it.
func readOverLimit(t *testing.T) error {
t.Helper()
body := http.MaxBytesReader(httptest.NewRecorder(), io.NopCloser(strings.NewReader(`{"name":"probe"}`)), 4)
_, err := io.ReadAll(body)
if err == nil {
t.Fatal("MaxBytesReader accepted a body over its limit")
}
return err
}
@@ -10,36 +10,62 @@ import (
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
)
const (
healthPath = "/healthz"
readinessPath = "/readyz"
apiRoot = "/api"
publicPrefix = apiRoot + "/v1"
)
// NewRouter mounts the internal operational routes and the generated public API.
// The generated server keeps ogen's default error handler, which answers
// ht.ErrNotImplemented with HTTP 501; operations without a business
// implementation in apiHandler rely on that mapping.
// Every error under /api/v1 is an RFC 9457 problem response: problems maps
// ht.ErrNotImplemented to 501, request decoding and validation errors to 400,
// unknown routes under /api to 404, unsupported methods to 405, and any other
// server error or panic to 500 without exposing its text. Operation errors go
// through apiHandler.NewError.
func NewRouter(
health *v1.HealthHandler,
apiHandler apiadapter.Handler,
problems *problem.Responder,
collector httpmiddleware.RequestMetrics,
logger *slog.Logger,
) (http.Handler, error) {
apiServer, err := apiadapter.NewServer(apiHandler)
apiServer, err := apiadapter.NewServer(
apiHandler,
apiadapter.WithErrorHandler(problems.HandleServerError),
apiadapter.WithNotFound(problems.NotFound),
apiadapter.WithMethodNotAllowed(problems.MethodNotAllowed),
)
if err != nil {
return nil, fmt.Errorf("httpadapter.NewRouter - create API server: %w", err)
}
router := chi.NewRouter()
// Request ID, request logging, and metrics wrap every route, so both
// recovery middlewares below run inside them: a recovered panic carries the
// request ID and its 500 is logged and counted.
router.Use(kitmiddleware.RequestID())
router.Use(kitmiddleware.Recoverer(logger))
router.Use(kitmiddleware.Logger(logger, nil, kitmiddleware.WithSkipPaths(healthPath, readinessPath)))
router.Use(httpmiddleware.CollectMetrics(collector))
router.Get(healthPath, health.Healthz)
router.Get(readinessPath, health.Readyz)
router.Handle("/api/v1/*", apiServer)
router.Group(func(operational chi.Router) {
operational.Use(kitmiddleware.Recoverer(logger))
operational.Get(healthPath, health.Healthz)
operational.Get(readinessPath, health.Readyz)
})
// The public API uses only problems.Recover, which answers panics with the
// contract's internal problem and re-raises http.ErrAbortHandler so the
// server aborts the response; the kit Recoverer would swallow that panic.
router.Group(func(public chi.Router) {
public.Use(problems.Recover)
public.Handle(publicPrefix+"/*", apiServer)
// Unknown /api paths outside the versioned prefix are also problems,
// so every error under /api has the contract's format.
public.Handle(apiRoot, http.HandlerFunc(problems.NotFound))
public.Handle(apiRoot+"/*", http.HandlerFunc(problems.NotFound))
})
return router, nil
}
@@ -1,26 +1,47 @@
package httpadapter
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/usecase/health"
)
// internalFailureText stands for internal error text that must stay in logs.
const internalFailureText = "dial tcp 10.0.0.5:5432: connection refused"
type readinessFunc func(context.Context) error
func (check readinessFunc) Check(ctx context.Context) error {
return check(ctx)
}
// healthzOverride replaces GetHealthz of the production composite handler,
// keeping its NewError, so a test can drive operation error handling without
// adding operations to the public contract.
type healthzOverride struct {
*v1.Handler
getHealthz func(context.Context) (*api.HealthResponse, error)
}
func (handler healthzOverride) GetHealthz(ctx context.Context) (*api.HealthResponse, error) {
return handler.getHealthz(ctx)
}
func TestOperationalHealthRoutes(t *testing.T) {
for _, test := range []struct {
name string
@@ -60,14 +81,12 @@ func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) {
if response.Code != http.StatusOK {
t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String())
}
var body struct {
Status string `json:"status"`
var body api.HealthResponse
if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil {
t.Fatalf("decode response %s: %v", response.Body.String(), err)
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
if body.Status != "ok" {
t.Fatalf("status = %q, want %q", body.Status, "ok")
if body.Status != api.HealthResponseStatusOk {
t.Fatalf("status = %q, want %q", body.Status, api.HealthResponseStatusOk)
}
}
@@ -75,29 +94,256 @@ func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) {
// router instead of a successful stub or a generic 500. GetHealthz served by
// api.UnimplementedHandler stands in for any such operation, so the check needs
// no extra contract operation.
func TestPublicUnimplementedOperationReturnsNotImplemented(t *testing.T) {
func TestPublicUnimplementedOperationReturnsNotImplementedProblem(t *testing.T) {
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router := newTestRouterWithAPI(t, healthHandler, api.UnimplementedHandler{})
router := newTestRouterWithAPI(t, healthHandler, api.UnimplementedHandler{}, slog.New(slog.DiscardHandler))
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
if response.Code != http.StatusNotImplemented {
t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusNotImplemented, response.Body.String())
body := requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
if body.Errors != nil {
t.Fatalf("errors = %v, want none", body.Errors)
}
}
func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) {
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
router := newOverrideRouter(t, logger, func(context.Context) (*api.HealthResponse, error) {
return nil, fmt.Errorf("HealthHandler.GetHealthz - check database: %w", errors.New(internalFailureText))
})
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
body := requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
if body.Title != "Internal server error" {
t.Fatalf("title = %q, want the fixed internal title", body.Title)
}
if strings.Contains(response.Body.String(), "connection refused") || strings.Contains(response.Body.String(), "HealthHandler") {
t.Fatalf("response exposes internal error text: %s", response.Body.String())
}
if !strings.Contains(logs.String(), internalFailureText) {
t.Fatalf("internal error was not logged at the HTTP boundary: %s", logs.String())
}
if requestID := response.Header().Get("X-Request-ID"); !strings.Contains(logs.String(), requestID) {
t.Fatalf("log entry has no request ID %q: %s", requestID, logs.String())
}
}
// recordedRequest is one observation passed to the metrics middleware.
type recordedRequest struct {
route string
status int
}
type requestRecorder struct {
requests []recordedRequest
}
func (recorder *requestRecorder) ObserveRequest(_, route string, status int, _ time.Duration) {
recorder.requests = append(recorder.requests, recordedRequest{route: route, status: status})
}
func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) {
const panicText = "nil map write for candidate jane@example.com"
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
handler := healthzOverride{
Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)),
getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) },
}
recorder := &requestRecorder{}
router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), recorder, logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
body := requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
if body.Title != "Internal server error" {
t.Fatalf("title = %q, want the fixed internal title", body.Title)
}
if strings.Contains(response.Body.String(), "jane") || strings.Contains(response.Body.String(), "nil map") {
t.Fatalf("response exposes the panic: %s", response.Body.String())
}
if count := strings.Count(logs.String(), "public API request panicked"); count != 1 {
t.Fatalf("panic logged %d times, want once: %s", count, logs.String())
}
if !strings.Contains(logs.String(), response.Header().Get("X-Request-ID")) {
t.Fatalf("panic log has no request ID: %s", logs.String())
}
if strings.Contains(logs.String(), "jane@example.com") {
t.Fatalf("panic value with personal data reached the logs: %s", logs.String())
}
want := []recordedRequest{{route: "/api/v1/*", status: http.StatusInternalServerError}}
if fmt.Sprint(recorder.requests) != fmt.Sprint(want) {
t.Fatalf("metrics observed %v, want %v", recorder.requests, want)
}
}
// http.ErrAbortHandler must reach net/http, which then aborts the response
// instead of sending a problem or a success.
func TestPublicOperationAbortPropagatesToTheServer(t *testing.T) {
recorder := &requestRecorder{}
router := newOverrideRouterWithMetrics(t, recorder, func(context.Context) (*api.HealthResponse, error) {
panic(http.ErrAbortHandler)
})
func() {
defer func() {
if recovered := recover(); recovered != http.ErrAbortHandler { //nolint:errorlint // net/http compares the sentinel by identity
t.Fatalf("recovered %v, want http.ErrAbortHandler", recovered)
}
}()
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
t.Fatal("ServeHTTP returned instead of re-raising http.ErrAbortHandler")
}()
server := httptest.NewServer(router)
defer server.Close()
request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL+"/api/v1/healthz", nil)
if err != nil {
t.Fatalf("build request: %v", err)
}
response, err := server.Client().Do(request)
if err == nil {
_ = response.Body.Close()
t.Fatalf("server answered %d, want an aborted connection", response.StatusCode)
}
}
func TestUnknownAPIPathsOutsideTheVersionReturnNotFoundProblem(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
for _, path := range []string{"/api", "/api/", "/api/v2/healthz", "/api/v1"} {
t.Run(path, func(t *testing.T) {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil))
requireProblem(t, response, http.StatusNotFound, api.ProblemCodeNotFound)
})
}
}
// Operations report expected failures as typed problems, which the generated
// server encodes directly with their own status.
func TestPublicOperationTypedProblemKeepsItsStatus(t *testing.T) {
for _, test := range []struct {
name string
code api.ProblemCode
statusCode int
}{
{name: "forbidden", code: api.ProblemCodeForbidden, statusCode: http.StatusForbidden},
{name: "version conflict", code: api.ProblemCodeVersionConflict, statusCode: http.StatusPreconditionFailed},
} {
t.Run(test.name, func(t *testing.T) {
router := newOverrideRouter(t, slog.New(slog.DiscardHandler), func(ctx context.Context) (*api.HealthResponse, error) {
return nil, problem.New(ctx, test.code)
})
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
requireProblem(t, response, test.statusCode, test.code)
})
}
}
func TestPublicUnknownRouteReturnsNotFoundProblem(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/missing", nil))
requireProblem(t, response, http.StatusNotFound, api.ProblemCodeNotFound)
}
func TestPublicUnsupportedMethodReturnsMethodNotAllowedProblem(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/v1/healthz", nil))
requireProblem(t, response, http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed)
if allowed := response.Header().Get("Allow"); allowed != http.MethodGet {
t.Fatalf("Allow = %q, want %q", allowed, http.MethodGet)
}
}
func TestPublicPreflightKeepsEmptyResponse(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodOptions, "/api/v1/healthz", nil))
if response.Code != http.StatusNoContent || response.Body.Len() != 0 {
t.Fatalf("preflight = %d %q, want empty 204", response.Code, response.Body.String())
}
if methods := response.Header().Get("Access-Control-Allow-Methods"); methods != http.MethodGet {
t.Fatalf("Access-Control-Allow-Methods = %q, want %q", methods, http.MethodGet)
}
}
// requireProblem checks the problem+json envelope and returns the body decoded
// and validated by the generated contract types.
func requireProblem(t *testing.T, response *httptest.ResponseRecorder, statusCode int, code api.ProblemCode) api.Problem {
t.Helper()
if response.Code != statusCode {
t.Fatalf("status code = %d, want %d: %s", response.Code, statusCode, response.Body.String())
}
if contentType := response.Header().Get("Content-Type"); contentType != problem.MediaType {
t.Fatalf("Content-Type = %q, want %q", contentType, problem.MediaType)
}
var body api.Problem
if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil {
t.Fatalf("decode problem %s: %v", response.Body.String(), err)
}
if err := body.Validate(); err != nil {
t.Fatalf("problem %s violates the contract: %v", response.Body.String(), err)
}
if body.Code != code || int(body.Status) != statusCode {
t.Fatalf("problem code/status = %q/%d, want %q/%d", body.Code, body.Status, code, statusCode)
}
if body.Type != "urn:lincodex:problem:"+string(code) {
t.Fatalf("problem type = %q", body.Type)
}
traceID, ok := body.TraceID.Get()
if !ok || traceID != response.Header().Get("X-Request-ID") {
t.Fatalf("trace_id = %q, want the X-Request-ID header %q", traceID, response.Header().Get("X-Request-ID"))
}
return body
}
func newTestRouter(t *testing.T, checker readinessFunc) http.Handler {
t.Helper()
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(checker)
return newTestRouterWithAPI(t, healthHandler, v1.NewHandler(healthHandler))
return newTestRouterWithAPI(t, healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), logger)
}
func newOverrideRouter(t *testing.T, logger *slog.Logger, getHealthz func(context.Context) (*api.HealthResponse, error)) http.Handler {
t.Helper()
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz}
return newTestRouterWithAPI(t, healthHandler, handler, logger)
}
func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler {
return v1.NewHealthHandler(health.NewReadiness(checker), time.Second)
}
func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler) http.Handler {
func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler {
t.Helper()
router, err := NewRouter(healthHandler, apiHandler, metrics.New(), slog.New(slog.DiscardHandler))
router, err := NewRouter(healthHandler, apiHandler, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return router
}
func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getHealthz func(context.Context) (*api.HealthResponse, error)) http.Handler {
t.Helper()
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz}
router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), collector, logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -4,6 +4,7 @@ import (
"context"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
)
// Handler is the composite implementation of the generated api.Handler.
@@ -11,17 +12,17 @@ import (
// The embedded api.UnimplementedHandler keeps the backend compiling after the
// contract gains an operation that has no business implementation yet. Such an
// operation returns ht.ErrNotImplemented without side effects. The generated
// server passes that error to its configured ErrorHandler, and the default
// ogenerrors.DefaultErrorHandler maps it to HTTP 501. When the contract defines
// a default error response, the generated server still sends
// ht.ErrNotImplemented to ErrorHandler before calling NewError. The embedded
// NewError, however, returns a zero status code that the generated encoder
// sends as HTTP 200, so the composite must then define NewError explicitly.
// That NewError must answer *ogenerrors.SecurityError with 401 or 403, which
// the generated server passes to it directly, and answer every other error
// with 500 and a sanitized message, never err.Error() of an internal error.
// Errors of the generated status-code error type (*<Schema>StatusCode) are
// encoded before NewError is called, so it does not need to handle them.
// server passes that error to the ErrorHandler configured in the router, which
// answers 501 with code not_implemented, before it would call NewError.
//
// The contract's common default response makes ogen add NewError to
// api.Handler. The embedded api.UnimplementedHandler.NewError returns a zero
// status code that the generated encoder sends as HTTP 200, so Handler defines
// NewError explicitly: *ogenerrors.SecurityError, which the generated server
// passes to it directly, becomes 401, and every other error becomes 500 with a
// fixed body and is logged here, never exposing err.Error(). Errors of the
// generated *api.ProblemStatusCode type are encoded before NewError is called,
// so operations return them for expected failures such as 403 or 404.
//
// Each implemented operation gets an explicit method here that delegates to
// the handler owning it. Each implemented operation also gets a router test
@@ -30,15 +31,21 @@ import (
type Handler struct {
api.UnimplementedHandler
health *HealthHandler
health *HealthHandler
problems *problem.Responder
}
var _ api.Handler = (*Handler)(nil)
func NewHandler(health *HealthHandler) *Handler {
return &Handler{health: health}
func NewHandler(health *HealthHandler, problems *problem.Responder) *Handler {
return &Handler{health: health, problems: problems}
}
func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) {
return handler.health.GetHealthz(ctx)
}
// NewError implements api.Handler for errors returned by operations.
func (handler *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
return handler.problems.HandlerError(ctx, err)
}
@@ -3,9 +3,12 @@ package v1
import (
"context"
"errors"
"log/slog"
"net/http"
"reflect"
"testing"
"lincodex/backend/internal/adapter/primary/http/problem"
)
// Once the contract defines a default error response, ogen adds NewError to
@@ -13,7 +16,7 @@ import (
// status code, which the generated encoder sends as HTTP 200. A handler error
// would then look like a success, so the composite must define its own NewError.
func TestHandlerNewErrorDoesNotReportSuccess(t *testing.T) {
newError := reflect.ValueOf(NewHandler(nil)).MethodByName("NewError")
newError := reflect.ValueOf(NewHandler(nil, problem.NewResponder(slog.New(slog.DiscardHandler)))).MethodByName("NewError")
if !newError.IsValid() {
t.Skip("the contract has no default error response, so the generated server has no NewError")
}
@@ -6,6 +6,7 @@ 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"
@@ -13,6 +14,11 @@ import (
"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-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
}
var (
// Allocate option closure once.
clientSpanKind = trace.WithSpanKind(trace.SpanKindClient)
@@ -352,3 +352,519 @@ func (s *MLReadinessResponseStatus) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes string as json.
func (o OptString) Encode(e *jx.Encoder) {
if !o.Set {
return
}
e.Str(string(o.Value))
}
// Decode decodes string from json.
func (o *OptString) Decode(d *jx.Decoder) error {
if o == nil {
return errors.New("invalid: unable to decode OptString to nil")
}
o.Set = true
v, err := d.Str()
if err != nil {
return err
}
o.Value = string(v)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s OptString) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *OptString) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *Problem) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *Problem) encodeFields(e *jx.Encoder) {
{
e.FieldStart("type")
e.Str(s.Type)
}
{
e.FieldStart("title")
e.Str(s.Title)
}
{
e.FieldStart("status")
e.Int32(s.Status)
}
{
e.FieldStart("code")
s.Code.Encode(e)
}
{
if s.Detail.Set {
e.FieldStart("detail")
s.Detail.Encode(e)
}
}
{
if s.Instance.Set {
e.FieldStart("instance")
s.Instance.Encode(e)
}
}
{
if s.TraceID.Set {
e.FieldStart("trace_id")
s.TraceID.Encode(e)
}
}
{
if s.Errors != nil {
e.FieldStart("errors")
e.ArrStart()
for _, elem := range s.Errors {
elem.Encode(e)
}
e.ArrEnd()
}
}
}
var jsonFieldsNameOfProblem = [8]string{
0: "type",
1: "title",
2: "status",
3: "code",
4: "detail",
5: "instance",
6: "trace_id",
7: "errors",
}
// Decode decodes Problem from json.
func (s *Problem) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode Problem to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "type":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Str()
s.Type = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"type\"")
}
case "title":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Str()
s.Title = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"title\"")
}
case "status":
requiredBitSet[0] |= 1 << 2
if err := func() error {
v, err := d.Int32()
s.Status = int32(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"status\"")
}
case "code":
requiredBitSet[0] |= 1 << 3
if err := func() error {
if err := s.Code.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"code\"")
}
case "detail":
if err := func() error {
s.Detail.Reset()
if err := s.Detail.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"detail\"")
}
case "instance":
if err := func() error {
s.Instance.Reset()
if err := s.Instance.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"instance\"")
}
case "trace_id":
if err := func() error {
s.TraceID.Reset()
if err := s.TraceID.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"trace_id\"")
}
case "errors":
if err := func() error {
s.Errors = make([]ProblemFieldError, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem ProblemFieldError
if err := elem.Decode(d); err != nil {
return err
}
s.Errors = append(s.Errors, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"errors\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode Problem")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00001111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfProblem) {
name = jsonFieldsNameOfProblem[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *Problem) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *Problem) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ProblemCode as json.
func (s ProblemCode) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ProblemCode from json.
func (s *ProblemCode) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProblemCode to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ProblemCode(v) {
case ProblemCodeValidationFailed:
*s = ProblemCodeValidationFailed
case ProblemCodeUnauthenticated:
*s = ProblemCodeUnauthenticated
case ProblemCodeForbidden:
*s = ProblemCodeForbidden
case ProblemCodeNotFound:
*s = ProblemCodeNotFound
case ProblemCodeMethodNotAllowed:
*s = ProblemCodeMethodNotAllowed
case ProblemCodeIdempotencyInProgress:
*s = ProblemCodeIdempotencyInProgress
case ProblemCodeStateConflict:
*s = ProblemCodeStateConflict
case ProblemCodeVersionConflict:
*s = ProblemCodeVersionConflict
case ProblemCodePayloadTooLarge:
*s = ProblemCodePayloadTooLarge
case ProblemCodeUnsupportedMediaType:
*s = ProblemCodeUnsupportedMediaType
case ProblemCodeIdempotencyKeyReused:
*s = ProblemCodeIdempotencyKeyReused
case ProblemCodePreconditionRequired:
*s = ProblemCodePreconditionRequired
case ProblemCodeRateLimited:
*s = ProblemCodeRateLimited
case ProblemCodeInternal:
*s = ProblemCodeInternal
case ProblemCodeNotImplemented:
*s = ProblemCodeNotImplemented
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)
}
@@ -60,7 +60,58 @@ func decodeGetMLHealthzResponse(resp *http.Response) (res *MLHealthResponse, _ e
return res, validate.InvalidContentType(ct)
}
}
return res, validate.UnexpectedStatusCodeWithResponse(resp)
// 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 decodeGetMLReadyzResponse(resp *http.Response) (res GetMLReadyzRes, _ error) {
@@ -154,5 +205,56 @@ func decodeGetMLReadyzResponse(resp *http.Response) (res GetMLReadyzRes, _ error
return res, validate.InvalidContentType(ct)
}
}
return res, validate.UnexpectedStatusCodeWithResponse(resp)
// 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")
}
@@ -3,9 +3,15 @@
package api
import (
"fmt"
"github.com/go-faster/errors"
)
func (s *ProblemStatusCode) Error() string {
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
}
type GetMLReadyzOK MLReadinessResponse
func (*GetMLReadyzOK) getMLReadyzRes() {}
@@ -118,3 +124,454 @@ func (s *MLReadinessResponseStatus) UnmarshalText(data []byte) error {
return errors.Errorf("invalid value: %q", data)
}
}
// NewOptString returns new OptString with value set to v.
func NewOptString(v string) OptString {
return OptString{
Value: v,
Set: true,
}
}
// OptString is optional string.
type OptString struct {
Value string
Set bool
}
// IsSet returns true if OptString was set.
func (o OptString) IsSet() bool { return o.Set }
// Reset unsets value.
func (o *OptString) Reset() {
var v string
o.Value = v
o.Set = false
}
// SetTo sets value to v.
func (o *OptString) SetTo(v string) {
o.Set = true
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o OptString) Get() (v string, ok bool) {
if !o.Set {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o OptString) Or(d string) string {
if v, ok := o.Get(); ok {
return v
}
return d
}
// Problem details (RFC 9457) returned with the application/problem+json media type for every error
// response. This is the ML service copy of the public api/core Problem schema; keep both copies
// identical except for descriptions. `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:<code>` 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 public error code. 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 body violates a
// domain rule such as salary_from <= salary_to; `errors` points at the fields.
// - unauthenticated (401): no valid session or credentials.
// - forbidden (403): the caller is authenticated but not allowed.
// - not_found (404): the route or object does not exist or is not visible.
// - method_not_allowed (405): the route does not support the method.
// - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.
// - state_conflict (409): the operation conflicts with the current state of the resource, for example
// an invitation that was already accepted.
// - version_conflict (412): If-Match does not match the current version.
// - 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 Idempotency-Key was already used with a different request.
// - precondition_required (428): the operation requires If-Match.
// - rate_limited (429): too many requests; see Retry-After.
// - internal (500): unexpected server error.
// - not_implemented (501): the operation is in the contract but not implemented yet.
//
// Ref: #/components/schemas/ProblemCode
type ProblemCode string
const (
ProblemCodeValidationFailed ProblemCode = "validation_failed"
ProblemCodeUnauthenticated ProblemCode = "unauthenticated"
ProblemCodeForbidden ProblemCode = "forbidden"
ProblemCodeNotFound ProblemCode = "not_found"
ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed"
ProblemCodeIdempotencyInProgress ProblemCode = "idempotency_in_progress"
ProblemCodeStateConflict ProblemCode = "state_conflict"
ProblemCodeVersionConflict ProblemCode = "version_conflict"
ProblemCodePayloadTooLarge ProblemCode = "payload_too_large"
ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type"
ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused"
ProblemCodePreconditionRequired ProblemCode = "precondition_required"
ProblemCodeRateLimited ProblemCode = "rate_limited"
ProblemCodeInternal ProblemCode = "internal"
ProblemCodeNotImplemented ProblemCode = "not_implemented"
)
// AllValues returns all ProblemCode values.
func (ProblemCode) AllValues() []ProblemCode {
return []ProblemCode{
ProblemCodeValidationFailed,
ProblemCodeUnauthenticated,
ProblemCodeForbidden,
ProblemCodeNotFound,
ProblemCodeMethodNotAllowed,
ProblemCodeIdempotencyInProgress,
ProblemCodeStateConflict,
ProblemCodeVersionConflict,
ProblemCodePayloadTooLarge,
ProblemCodeUnsupportedMediaType,
ProblemCodeIdempotencyKeyReused,
ProblemCodePreconditionRequired,
ProblemCodeRateLimited,
ProblemCodeInternal,
ProblemCodeNotImplemented,
}
}
// 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 ProblemCodeForbidden:
return []byte(s), nil
case ProblemCodeNotFound:
return []byte(s), nil
case ProblemCodeMethodNotAllowed:
return []byte(s), nil
case ProblemCodeIdempotencyInProgress:
return []byte(s), nil
case ProblemCodeStateConflict:
return []byte(s), nil
case ProblemCodeVersionConflict:
return []byte(s), nil
case ProblemCodePayloadTooLarge:
return []byte(s), nil
case ProblemCodeUnsupportedMediaType:
return []byte(s), nil
case ProblemCodeIdempotencyKeyReused:
return []byte(s), nil
case ProblemCodePreconditionRequired:
return []byte(s), nil
case ProblemCodeRateLimited:
return []byte(s), nil
case ProblemCodeInternal:
return []byte(s), nil
case ProblemCodeNotImplemented:
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 ProblemCodeForbidden:
*s = ProblemCodeForbidden
return nil
case ProblemCodeNotFound:
*s = ProblemCodeNotFound
return nil
case ProblemCodeMethodNotAllowed:
*s = ProblemCodeMethodNotAllowed
return nil
case ProblemCodeIdempotencyInProgress:
*s = ProblemCodeIdempotencyInProgress
return nil
case ProblemCodeStateConflict:
*s = ProblemCodeStateConflict
return nil
case ProblemCodeVersionConflict:
*s = ProblemCodeVersionConflict
return nil
case ProblemCodePayloadTooLarge:
*s = ProblemCodePayloadTooLarge
return nil
case ProblemCodeUnsupportedMediaType:
*s = ProblemCodeUnsupportedMediaType
return nil
case ProblemCodeIdempotencyKeyReused:
*s = ProblemCodeIdempotencyKeyReused
return nil
case ProblemCodePreconditionRequired:
*s = ProblemCodePreconditionRequired
return nil
case ProblemCodeRateLimited:
*s = ProblemCodeRateLimited
return nil
case ProblemCodeInternal:
*s = ProblemCodeInternal
return nil
case ProblemCodeNotImplemented:
*s = ProblemCodeNotImplemented
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
// `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the
// parameter name, for example `/limit` or `/Idempotency-Key`.
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
}
@@ -3,6 +3,8 @@
package api
import (
"fmt"
"github.com/go-faster/errors"
"github.com/ogen-go/ogen/validate"
)
@@ -88,3 +90,388 @@ func (s MLReadinessResponseStatus) Validate() error {
return errors.Errorf("invalid value: %v", s)
}
}
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 "forbidden":
return nil
case "not_found":
return nil
case "method_not_allowed":
return nil
case "idempotency_in_progress":
return nil
case "state_conflict":
return nil
case "version_conflict":
return nil
case "payload_too_large":
return nil
case "unsupported_media_type":
return nil
case "idempotency_key_reused":
return nil
case "precondition_required":
return nil
case "rate_limited":
return nil
case "internal":
return nil
case "not_implemented":
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
}
+2
View File
@@ -12,6 +12,7 @@ import (
httpadapter "lincodex/backend/internal/adapter/primary/http"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
@@ -33,6 +34,7 @@ func initialize(ctx context.Context, config config.Config, logger *slog.Logger)
newReadiness,
metrics.New,
newHealthHandler,
problem.NewResponder,
v1.NewHandler,
httpadapter.NewRouter,
NewApplication,
+4 -2
View File
@@ -10,6 +10,7 @@ import (
"context"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/primary/http"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
@@ -40,9 +41,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger)
}
readiness := newReadiness(healthChecker, cache, storage)
healthHandler := newHealthHandler(readiness, config2)
handler := v1.NewHandler(healthHandler)
responder := problem.NewResponder(logger)
handler := v1.NewHandler(healthHandler, responder)
metrics := prometheus.New()
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, metrics, logger)
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, responder, metrics, logger)
if err != nil {
cleanup3()
cleanup2()
+265 -14
View File
@@ -3,30 +3,160 @@ package compat
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/problem"
)
type compatibilityHandler struct{}
const (
defaultPageLimit = 20
fixtureETag = `"v2"`
staleETag = `"v1"`
)
func (compatibilityHandler) GetProbe(context.Context, GetProbeParams) (*NullablePayload, error) {
var fixtureUpdatedAt = time.Date(2026, time.October, 5, 9, 30, 0, 0, time.UTC)
// compatibilityHandler implements the fixture operations. CreateProbeItem keeps
// a minimal in-memory idempotency record so the test can show that the
// generated types express the contract's retry scenario; it is not product
// behavior.
type compatibilityHandler struct {
mu sync.Mutex
requests map[string]string
responses map[string]*ProbeItemHeaders
lastLimit int32
}
func newCompatibilityHandler() *compatibilityHandler {
return &compatibilityHandler{requests: map[string]string{}, responses: map[string]*ProbeItemHeaders{}}
}
func (*compatibilityHandler) GetProbe(context.Context, GetProbeParams) (*NullablePayload, error) {
return &NullablePayload{}, nil
}
func (compatibilityHandler) PurgeProbe(context.Context) error {
func (*compatibilityHandler) PurgeProbe(context.Context) error {
return nil
}
func TestGeneratedServerRejectsInvalidInput(t *testing.T) {
server, err := NewServer(compatibilityHandler{})
func (handler *compatibilityHandler) ListProbeItems(_ context.Context, params ListProbeItemsParams) (*ProbeItemPage, error) {
handler.mu.Lock()
handler.lastLimit = params.Limit.Or(0)
handler.mu.Unlock()
return &ProbeItemPage{Items: []ProbeItem{}, Page: PageInfo{HasMore: false, NextCursor: NilString{Null: true}}}, nil
}
func (handler *compatibilityHandler) CreateProbeItem(_ context.Context, request *ProbeItemInput, params CreateProbeItemParams) (CreateProbeItemRes, error) {
handler.mu.Lock()
defer handler.mu.Unlock()
if fingerprint, seen := handler.requests[params.IdempotencyKey]; seen {
if fingerprint != request.Name {
reused := CreateProbeItemUnprocessableEntity(fixtureProblem(http.StatusUnprocessableEntity, ProblemCodeIdempotencyKeyReused))
return &reused, nil
}
return handler.responses[params.IdempotencyKey], nil
}
response := &ProbeItemHeaders{
ETag: fixtureETag,
Response: ProbeItem{ID: uuid.New(), Name: request.Name, UpdatedAt: Timestamp(fixtureUpdatedAt)},
}
handler.requests[params.IdempotencyKey] = request.Name
handler.responses[params.IdempotencyKey] = response
return response, nil
}
func (*compatibilityHandler) UpdateProbeItem(_ context.Context, request *ProbeItemInput, params UpdateProbeItemParams) (UpdateProbeItemRes, error) {
ifMatch, ok := params.IfMatch.Get()
if !ok {
required := UpdateProbeItemPreconditionRequired(fixtureProblem(http.StatusPreconditionRequired, ProblemCodePreconditionRequired))
return &required, nil
}
if ifMatch != fixtureETag {
conflict := UpdateProbeItemPreconditionFailed(fixtureProblem(http.StatusPreconditionFailed, ProblemCodeVersionConflict))
return &conflict, nil
}
return &ProbeItemHeaders{
ETag: `"v3"`,
Response: ProbeItem{ID: params.ItemID, Name: request.Name, UpdatedAt: Timestamp(fixtureUpdatedAt)},
}, nil
}
func (*compatibilityHandler) NewError(context.Context, error) *ProblemStatusCode {
return &ProblemStatusCode{StatusCode: http.StatusInternalServerError, Response: fixtureProblem(http.StatusInternalServerError, ProblemCodeInternal)}
}
func fixtureProblem(status int32, code ProblemCode) Problem {
return Problem{Type: "urn:lincodex:problem:" + string(code), Title: "Fixture problem", Status: status, Code: code}
}
// newServer mounts the fixture with the backend's problem mapping, so decoding
// and validation errors produced by real generated code are checked against
// the public error contract.
func newServer(t *testing.T, handler Handler) *Server {
t.Helper()
problems := problem.NewResponder(slog.New(slog.DiscardHandler))
server, err := NewServer(handler,
WithErrorHandler(problems.HandleServerError),
WithNotFound(problems.NotFound),
WithMethodNotAllowed(problems.MethodNotAllowed),
)
if err != nil {
t.Fatalf("NewServer() error = %v", err)
}
return server
}
func serve(t *testing.T, server http.Handler, method, target, body string, headers map[string]string) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(method, target, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
for name, value := range headers {
request.Header.Set(name, value)
}
response := httptest.NewRecorder()
server.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/probe?state=invalid", nil))
if response.Code != http.StatusBadRequest {
t.Fatalf("status code = %d, want %d", response.Code, http.StatusBadRequest)
server.ServeHTTP(response, request)
return response
}
func decodeProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code ProblemCode) Problem {
t.Helper()
if response.Code != status {
t.Fatalf("status code = %d, want %d: %s", response.Code, status, response.Body.String())
}
if contentType := response.Header().Get("Content-Type"); contentType != problem.MediaType {
t.Fatalf("Content-Type = %q, want %q", contentType, problem.MediaType)
}
var body Problem
if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil {
t.Fatalf("decode problem %s: %v", response.Body.String(), err)
}
if err := body.Validate(); err != nil {
t.Fatalf("problem %s violates the contract: %v", response.Body.String(), err)
}
if body.Code != code || int(body.Status) != status {
t.Fatalf("problem code/status = %q/%d, want %q/%d", body.Code, body.Status, code, status)
}
return body
}
func TestGeneratedServerRejectsInvalidInput(t *testing.T) {
server := newServer(t, newCompatibilityHandler())
response := serve(t, server, http.MethodGet, "/probe?state=invalid", "", nil)
body := decodeProblem(t, response, http.StatusBadRequest, ProblemCodeValidationFailed)
want := []ProblemFieldError{{In: ProblemFieldLocationQuery, Pointer: "/state", Code: "invalid", Message: "The value does not match the contract."}}
if !reflect.DeepEqual(body.Errors, want) {
t.Fatalf("errors = %+v, want %+v", body.Errors, want)
}
}
@@ -41,13 +171,134 @@ func TestNullableTypeArrayPreservesNull(t *testing.T) {
}
func TestAdditionalOperationIsRouted(t *testing.T) {
server, err := NewServer(compatibilityHandler{})
if err != nil {
t.Fatalf("NewServer() error = %v", err)
}
response := httptest.NewRecorder()
server.ServeHTTP(response, httptest.NewRequest("PURGE", "/probe", nil))
server := newServer(t, newCompatibilityHandler())
response := serve(t, server, "PURGE", "/probe", "", nil)
if response.Code != http.StatusNoContent {
t.Fatalf("status code = %d, want %d", response.Code, http.StatusNoContent)
}
}
func TestGeneratedValidationErrorsMapToProblemFields(t *testing.T) {
validKey := map[string]string{"Idempotency-Key": "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11"}
for _, test := range []struct {
name string
method string
target string
body string
headers map[string]string
field ProblemFieldError
}{
{name: "limit below range", method: http.MethodGet, target: "/probe/items?limit=0", field: invalidField(ProblemFieldLocationQuery, "/limit")},
{name: "limit above range", method: http.MethodGet, target: "/probe/items?limit=101", field: invalidField(ProblemFieldLocationQuery, "/limit")},
{name: "cursor too long", method: http.MethodGet, target: "/probe/items?cursor=" + strings.Repeat("a", 513), field: invalidField(ProblemFieldLocationQuery, "/cursor")},
{name: "cursor charset", method: http.MethodGet, target: "/probe/items?cursor=a+b", field: invalidField(ProblemFieldLocationQuery, "/cursor")},
{name: "missing idempotency key", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe"}`, field: requiredField(ProblemFieldLocationHeader, "/Idempotency-Key")},
{name: "idempotency key too long", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": strings.Repeat("k", 256)}, field: invalidField(ProblemFieldLocationHeader, "/Idempotency-Key")},
{name: "idempotency key charset", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": "key with spaces"}, field: invalidField(ProblemFieldLocationHeader, "/Idempotency-Key")},
{name: "weak if-match", method: http.MethodPatch, target: "/probe/items/" + uuid.NewString(), body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": "k1", "If-Match": `W/"v2"`}, field: invalidField(ProblemFieldLocationHeader, "/If-Match")},
{name: "invalid path id", method: http.MethodPatch, target: "/probe/items/not-a-uuid", body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": "k1"}, field: invalidField(ProblemFieldLocationPath, "/item_id")},
{name: "missing body", method: http.MethodPost, target: "/probe/items", headers: map[string]string{"Idempotency-Key": "k1", "Content-Type": "application/json"}, field: requiredField(ProblemFieldLocationBody, "")},
{name: "missing body field", method: http.MethodPost, target: "/probe/items", body: `{}`, headers: validKey, field: requiredField(ProblemFieldLocationBody, "/name")},
{name: "body field too long", method: http.MethodPost, target: "/probe/items", body: `{"name":"` + strings.Repeat("n", 101) + `"}`, headers: validKey, field: invalidField(ProblemFieldLocationBody, "/name")},
{name: "unknown body field", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe","extra":true}`, headers: validKey, field: invalidField(ProblemFieldLocationBody, "")},
{name: "malformed body", method: http.MethodPost, target: "/probe/items", body: `{"name":`, headers: validKey, field: invalidField(ProblemFieldLocationBody, "")},
} {
t.Run(test.name, func(t *testing.T) {
server := newServer(t, newCompatibilityHandler())
response := serve(t, server, test.method, test.target, test.body, test.headers)
body := decodeProblem(t, response, http.StatusBadRequest, ProblemCodeValidationFailed)
if want := []ProblemFieldError{test.field}; !reflect.DeepEqual(body.Errors, want) {
t.Fatalf("errors = %+v, want %+v", body.Errors, want)
}
if strings.Contains(response.Body.String(), "nnnnn") || strings.Contains(response.Body.String(), "spaces") {
t.Fatalf("problem echoes the submitted value: %s", response.Body.String())
}
})
}
}
func TestUnsupportedRequestMediaTypeIsRejected(t *testing.T) {
server := newServer(t, newCompatibilityHandler())
response := serve(t, server, http.MethodPost, "/probe/items", "name", map[string]string{"Idempotency-Key": "k1", "Content-Type": "text/plain"})
decodeProblem(t, response, http.StatusUnsupportedMediaType, ProblemCodeUnsupportedMediaType)
}
// A body limit applied with http.MaxBytesReader reaches the problem mapping
// through the generated request decoder.
func TestBodyOverLimitIsRejected(t *testing.T) {
const bodyLimit = 16
server := newServer(t, newCompatibilityHandler())
limited := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, bodyLimit)
server.ServeHTTP(w, r)
})
request := httptest.NewRequest(http.MethodPost, "/probe/items", strings.NewReader(`{"name":"`+strings.Repeat("n", 64)+`"}`))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "k1")
response := httptest.NewRecorder()
limited.ServeHTTP(response, request)
decodeProblem(t, response, http.StatusRequestEntityTooLarge, ProblemCodePayloadTooLarge)
}
func TestPaginationAppliesDefaultLimitAndEncodesLastPage(t *testing.T) {
handler := newCompatibilityHandler()
response := serve(t, newServer(t, handler), http.MethodGet, "/probe/items", "", nil)
if response.Code != http.StatusOK {
t.Fatalf("status code = %d: %s", response.Code, response.Body.String())
}
if handler.lastLimit != defaultPageLimit {
t.Fatalf("limit = %d, want the contract default %d", handler.lastLimit, defaultPageLimit)
}
if !strings.Contains(response.Body.String(), `"page":{"has_more":false,"next_cursor":null}`) {
t.Fatalf("last page = %s, want an explicit null cursor", response.Body.String())
}
}
// The same Idempotency-Key with the same body replays the stored response; the
// same key with a different body is rejected with idempotency_key_reused.
func TestIdempotencyRetryScenario(t *testing.T) {
server := newServer(t, newCompatibilityHandler())
key := map[string]string{"Idempotency-Key": "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11"}
first := serve(t, server, http.MethodPost, "/probe/items", `{"name":"probe"}`, key)
if first.Code != http.StatusCreated || first.Header().Get("ETag") != fixtureETag {
t.Fatalf("first response = %d ETag %q: %s", first.Code, first.Header().Get("ETag"), first.Body.String())
}
if !strings.Contains(first.Body.String(), `"updated_at":"2026-10-05T09:30:00Z"`) {
t.Fatalf("timestamp is not UTC RFC 3339: %s", first.Body.String())
}
replay := serve(t, server, http.MethodPost, "/probe/items", `{"name":"probe"}`, key)
if replay.Code != http.StatusCreated || replay.Body.String() != first.Body.String() {
t.Fatalf("replay = %d %s, want the stored response %s", replay.Code, replay.Body.String(), first.Body.String())
}
reused := serve(t, server, http.MethodPost, "/probe/items", `{"name":"other"}`, key)
decodeProblem(t, reused, http.StatusUnprocessableEntity, ProblemCodeIdempotencyKeyReused)
}
func TestIfMatchPreconditions(t *testing.T) {
server := newServer(t, newCompatibilityHandler())
target := "/probe/items/" + uuid.NewString()
missing := serve(t, server, http.MethodPatch, target, `{"name":"probe"}`, map[string]string{"Idempotency-Key": "k1"})
decodeProblem(t, missing, http.StatusPreconditionRequired, ProblemCodePreconditionRequired)
stale := serve(t, server, http.MethodPatch, target, `{"name":"probe"}`, map[string]string{"Idempotency-Key": "k2", "If-Match": staleETag})
decodeProblem(t, stale, http.StatusPreconditionFailed, ProblemCodeVersionConflict)
current := serve(t, server, http.MethodPatch, target, `{"name":"probe"}`, map[string]string{"Idempotency-Key": "k3", "If-Match": fixtureETag})
if current.Code != http.StatusOK || current.Header().Get("ETag") != `"v3"` {
t.Fatalf("update = %d ETag %q: %s", current.Code, current.Header().Get("ETag"), current.Body.String())
}
}
func invalidField(in ProblemFieldLocation, pointer string) ProblemFieldError {
return ProblemFieldError{In: in, Pointer: pointer, Code: "invalid", Message: "The value does not match the contract."}
}
func requiredField(in ProblemFieldLocation, pointer string) ProblemFieldError {
return ProblemFieldError{In: in, Pointer: pointer, Code: "required", Message: "The value is required."}
}
+2 -1
View File
@@ -88,6 +88,7 @@ backend/
adapter/primary/http/
api/ generated ogen handler
middleware/ request metrics
problem/ RFC 9457 error responses
v1/ handwritten health endpoint
router.go chi composition
adapter/secondary/
@@ -230,7 +231,7 @@ Vacancies and voluntary applications, recurring assessments, employer complaints
Examples of stable operations are `POST /api/v1/searches`, `POST /api/v1/searches/{id}/refinements`, `POST /api/v1/candidates/{id}/invitations`, and `POST /api/v1/invitations/{id}/accept`. These are target examples, not implemented endpoints. Every business operation, response, and error belongs in OpenAPI with a stable `operationId`.
Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amounts for the MVP, and bounded cursor pagination. Distinguish null from absent fields. Errors have a stable `code`, safe message, optional field errors, and request ID. Use idempotency keys for invitation creation, analysis start, and assessment submission; scope keys by actor and operation, and reject reuse with a different body. Check access for every object ID, job, search run, and PDF. Never include contacts in common errors or public examples.
Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amounts for the MVP, and bounded cursor pagination. Distinguish null from absent fields. Errors have a stable `code`, safe message, optional field errors, and request ID. Use idempotency keys for invitation creation, analysis start, and assessment submission; scope keys by actor and operation, and reject reuse with a different body. Check access for every object ID, job, search run, and PDF. Never include contacts in common errors or public examples. The contract fixes the error model, Idempotency-Key, If-Match, pagination, and time format in [api/README.en.md](../../api/README.en.md#contract-conventions); of these, only the problem-based error mapping is implemented.
## Metrics, telemetry, and alerts
+2
View File
@@ -112,6 +112,8 @@ The target is OpenAPI 3.2.0, with ogen for Go, Orval for TypeScript, and datamod
datamodel-code-generator 0.83.0 reads api/ml/openapi.bundle.yml and writes ml/src/lincodex_ml/api/models.py. Settings live in ml/codegen/pyproject.toml; this file configures the tool, while dependencies remain in ml/pyproject.toml and uv.lock. Health/readiness handlers import the generated models instead of maintaining handwritten schema copies. make -C ml generate bundles the API first; when called by root make generate, API_PREPARED=1 reuses the prepared bundle. make -C ml check-generated compares output with --check without rewriting the file. CI uses the shared make generate target, which includes the Python models.
Errors, retries, versions, pagination, and time follow the [contract conventions](../../api/README.en.md#contract-conventions). Implemented: every error of the public Go API and of the ML service is an RFC 9457 problem (`application/problem+json`) with a stable `code`. The Go mapping of ogen errors lives in backend/internal/adapter/primary/http/problem/: request validation gives 400, unknown routes under /api 404, unimplemented operations 501, and other errors and panics 500 without internal text; errors are logged at that boundary, panics only by type and stack. The frontend API client throws `ApiRequestError` for problems, network failures (`network_error`), and invalid 2xx bodies (`invalid_response`); a caller's abort propagates unchanged. The ML service maps FastAPI errors in ml/src/lincodex_ml/api/problems.py and routes uvicorn logs through its JSON format without exception text. Idempotency-Key storage, If-Match checks, and pagination are planned: the contract defines their components, and the first business operation that needs them implements them.
## Code boundaries
SQL linter dependencies are listed in `backend/requirements-quality.txt` beside `.sqlfluff`. The `make -C backend lint-sql` command installs them in the local `.venv-quality` environment and checks migrations and queries. Running the Go service does not require this environment.
+2 -1
View File
@@ -88,6 +88,7 @@ backend/
adapter/primary/http/
api/ generated ogen handler
middleware/ метрики запросов
problem/ ответы об ошибках по RFC 9457
v1/ написанный вручную health endpoint
router.go сборка chi router
adapter/secondary/
@@ -230,7 +231,7 @@ k3s не входит в критический путь. Его можно ра
Примеры стабильных операций: `POST /api/v1/searches`, `POST /api/v1/searches/{id}/refinements`, `POST /api/v1/candidates/{id}/invitations`, `POST /api/v1/invitations/{id}/accept`. Это целевые примеры, они пока не реализованы. Все бизнес-операции, ответы и ошибки должны входить в OpenAPI и иметь стабильные `operationId`.
Правила контракта: UUID для идентификаторов, UTC date-time, явные enums, целые рубли для MVP, ограниченная cursor pagination. Различать null и отсутствующее поле. Ошибка содержит стабильный `code`, безопасное сообщение, опциональные field errors и request ID. Idempotency keys нужны для создания invitation, запуска анализа и отправки assessment; ключ ограничен actor и операцией, повтор с другим телом отклоняется. Проверять доступ для каждого object ID, job, search run и PDF. Контакты не включаются в общие ошибки и публичные примеры.
Правила контракта: UUID для идентификаторов, UTC date-time, явные enums, целые рубли для MVP, ограниченная cursor pagination. Различать null и отсутствующее поле. Ошибка содержит стабильный `code`, безопасное сообщение, опциональные field errors и request ID. Idempotency keys нужны для создания invitation, запуска анализа и отправки assessment; ключ ограничен actor и операцией, повтор с другим телом отклоняется. Проверять доступ для каждого object ID, job, search run и PDF. Контакты не включаются в общие ошибки и публичные примеры. Модель ошибок, Idempotency-Key, If-Match, пагинация и формат времени закреплены в контракте, см. [api/README.md](../../api/README.md#соглашения-контракта); из них реализован только маппинг ошибок в problem.
## Метрики, телеметрия и alerts
+2
View File
@@ -112,6 +112,8 @@ make check не является бизнес-E2E проверкой. make verif
Python-генератор datamodel-code-generator 0.83.0 читает api/ml/openapi.bundle.yml и создает ml/src/lincodex_ml/api/models.py. Настройки хранятся в ml/codegen/pyproject.toml; это конфигурация инструмента, а зависимости остаются в ml/pyproject.toml и uv.lock. Health/readiness handlers импортируют сгенерированные модели вместо ручных копий схем. make -C ml generate сначала собирает API; при вызове из корневого make generate параметр API_PREPARED=1 использует уже собранный bundle. make -C ml check-generated сравнивает результат через --check без перезаписи файла. CI использует общий make generate, который включает Python-модели.
Ошибки, повторы, версии, пагинация и время следуют [соглашениям контракта](../../api/README.md#соглашения-контракта). Реализовано: любая ошибка публичного Go API и ML-сервиса - problem по RFC 9457 (`application/problem+json`) со стабильным `code`. Go-маппинг ошибок ogen находится в backend/internal/adapter/primary/http/problem/: валидация запроса дает 400, неизвестный маршрут под /api - 404, нереализованная операция - 501, остальные ошибки и panic - 500 без внутреннего текста; ошибки логируются на этой границе, panic - только типом и stack. Frontend API client бросает `ApiRequestError` для problem, сетевых сбоев (`network_error`) и некорректных 2xx-тел (`invalid_response`); отмена вызывающим пробрасывается без изменений. ML-сервис преобразует ошибки FastAPI в ml/src/lincodex_ml/api/problems.py и направляет логи uvicorn через свой JSON-формат без текста исключений. Хранение Idempotency-Key, проверки If-Match и пагинация запланированы: контракт определяет их компоненты, а реализует их первая бизнес-операция, которой они нужны.
## Код и слои
Зависимости SQL-линтера перечислены в `backend/requirements-quality.txt` рядом с `.sqlfluff`. Команда `make -C backend lint-sql` устанавливает их в локальное окружение `.venv-quality` и проверяет миграции и запросы. Для запуска Go-сервиса это окружение не требуется.
+1
View File
@@ -13,3 +13,4 @@ test-results/
.env.*
!.env.example
*.log
.orval-compat-*/
+1
View File
@@ -5,3 +5,4 @@ src/shared/api/endpoints/
src/shared/api/schemas/
scripts/fixtures/
pnpm-lock.yaml
.orval-compat-*/
+4 -1
View File
@@ -1,5 +1,5 @@
.DEFAULT_GOAL := help
.PHONY: help install dev build generate fmt fmt-check lint lint-fix typecheck test check verify
.PHONY: help install dev build generate check-orval-compat fmt fmt-check lint lint-fix typecheck test check verify
help: ## Show available frontend commands.
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-12s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -17,6 +17,9 @@ generate: ## Generate API client, query hooks, schemas, and MSW handlers.
@if [ "$${API_PREPARED:-0}" != "1" ]; then $(MAKE) -C ../api bundle; fi
pnpm run generate
check-orval-compat: ## Generate and type-check the OpenAPI 3.2 compatibility fixture in a temporary directory.
pnpm run check:orval-compat
fmt: ## Format frontend source and configuration.
pnpm run fmt
+1 -1
View File
@@ -7,7 +7,7 @@ A React and TypeScript SPA built with Vite and organized using FSD. The current
- `src/app/` starts the application; `pages/`, `widgets/`, `features/`, and `entities/` are the interface layers.
- `src/shared/` contains shared components and the API client, including generated endpoints, Zod schemas, and MSW mocks.
- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract.
- `scripts/` checks FSD boundaries.
- `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture.
From the repository root, `make -C frontend dev` starts development and `make -C frontend check` runs checks and builds the app. In Docker, Nginx serves the built files using configuration from `deploy/nginx/`.
+1 -1
View File
@@ -7,7 +7,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
- `src/app/` - запуск приложения; `pages/`, `widgets/`, `features/`, `entities/` - слои интерфейса.
- `src/shared/` - общие компоненты и API-клиент, включая сгенерированные endpoints, схемы Zod и MSW-моки.
- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта.
- `scripts/` - проверки границ FSD.
- `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2.
Из корня: `make -C frontend dev` запускает разработку, `make -C frontend check` - проверки и сборку. В Docker собранные файлы раздает Nginx с конфигурацией из `deploy/nginx/`.
+86 -8
View File
@@ -1,16 +1,70 @@
import { defineConfig } from "orval";
import { defineConfig, defineTransformer, type Options } from "orval";
export default defineConfig({
lincodex: {
const responseReferencePrefix = "#/components/responses/";
// Replaces each reference to components/responses with the referenced response
// object. Schema, header, and example references inside it stay references.
function inlineResponseReferences(
value: unknown,
responses: Readonly<Record<string, unknown>>,
): unknown {
if (Array.isArray(value)) {
return value.map((item) => inlineResponseReferences(item, responses));
}
if (value === null || typeof value !== "object") {
return value;
}
const reference = (value as { $ref?: unknown }).$ref;
if (typeof reference === "string" && reference.startsWith(responseReferencePrefix)) {
const name = reference.slice(responseReferencePrefix.length);
if (!Object.hasOwn(responses, name)) {
throw new Error(`Unknown response reference ${reference}.`);
}
return inlineResponseReferences(responses[name], responses);
}
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [key, inlineResponseReferences(item, responses)]),
);
}
// Orval 8.40 writes no Zod schema for components/responses entries, yet an
// operation that references one imports a `<Name>Response` type that is never
// generated. Inlining the references keeps the contract's reusable responses
// while generated operations import only the component schemas Orval writes.
const inlineReusableResponses = defineTransformer((spec) => {
if (spec.paths === undefined) {
return spec;
}
const responses = spec.components?.responses ?? {};
return {
...spec,
paths: inlineResponseReferences(spec.paths, responses) as typeof spec.paths,
};
});
// The API compatibility check sets this variable to a temporary directory to
// generate the OpenAPI 3.2 fixture with the production settings.
const compatOutput = process.env["ORVAL_COMPAT_OUTPUT"];
function project(inputTarget: string, endpoints: string, schemas: string): Options {
return {
input: {
target: "../../api/core/openapi.bundle.yml",
target: inputTarget,
override: {
transformer: inlineReusableResponses,
},
},
output: {
mode: "tags-split",
target: "../src/shared/api/endpoints",
target: endpoints,
indexFiles: true,
// Generated operations take header parameters such as Idempotency-Key
// and If-Match as a typed argument instead of dropping them.
headers: true,
schemas: {
path: "../src/shared/api/schemas",
path: schemas,
type: "zod",
splitByTags: true,
},
@@ -31,7 +85,31 @@ export default defineConfig({
query: {
signal: true,
},
// Optional properties are typed `{ x?: T }`, which the strict
// exactOptionalPropertyTypes setting needs for optional header
// parameters to fit RequestInit headers.
zod: {
exactOptional: true,
},
},
},
},
});
};
}
export default defineConfig(
compatOutput === undefined
? {
lincodex: project(
"../../api/core/openapi.bundle.yml",
"../src/shared/api/endpoints",
"../src/shared/api/schemas",
),
}
: {
compat: project(
"../../api/testdata/openapi-3.2.0.yml",
`${compatOutput}/endpoints`,
`${compatOutput}/schemas`,
),
},
);
+2 -1
View File
@@ -18,7 +18,8 @@
"test": "vitest run",
"test:fsd": "node ./scripts/test-fsd-boundaries.mjs",
"check": "pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run test:fsd && pnpm run build",
"verify": "pnpm run generate && pnpm run check"
"verify": "pnpm run generate && pnpm run check",
"check:orval-compat": "node ./scripts/check-orval-compat.mjs"
},
"dependencies": {
"@tanstack/react-query": "5.104.1",
+72
View File
@@ -0,0 +1,72 @@
// Generates the OpenAPI 3.2 compatibility fixture with the production Orval
// settings into a temporary directory, type-checks the output with the
// frontend compiler settings, and checks that the API conventions reached the
// generated code. The directory is removed afterwards.
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join, relative, resolve } from "node:path";
import { env, stdout } from "node:process";
import { fileURLToPath } from "node:url";
const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bin = (name) => resolve(frontendRoot, "node_modules/.bin", name);
// Text that each fixture convention leaves in the generated TypeScript.
const expectedFragments = {
IdempotencyKey: '"Idempotency-Key": zod.string().min(1).max(',
IfMatch: '"If-Match": zod.string().min(',
PageLimit: '"limit": zod.int().min(1).max(',
PageCursor: '"cursor": zod.string().min(1).max(',
PageInfo: '"next_cursor": zod.string().min(1).max(',
Timestamp: "export const Timestamp = zod.iso.datetime(",
Problem: "export const Problem = zod.object(",
ProblemErrorType: "TError = ErrorType<Problem>",
HeaderArgument: "headers: CreateProbeItemHeaders",
OptionalHeaderArgument: "headers: UpdateProbeItemHeaders",
};
function run(command, args, extraEnv = {}) {
const result = spawnSync(command, args, {
cwd: frontendRoot,
encoding: "utf8",
env: { ...env, ...extraEnv },
});
assert.equal(
result.status,
0,
`${relative(frontendRoot, command)} failed:\n${result.stdout}\n${result.stderr}`,
);
}
function typeScriptFiles(directory) {
return readdirSync(directory, { recursive: true, encoding: "utf8" })
.filter((name) => name.endsWith(".ts"))
.map((name) => join(directory, name));
}
const outputDirectory = mkdtempSync(join(frontendRoot, ".orval-compat-"));
try {
run(bin("orval"), ["--config", "./codegen/orval.config.ts"], {
ORVAL_COMPAT_OUTPUT: outputDirectory,
});
const files = typeScriptFiles(outputDirectory);
assert.ok(files.length > 0, "Orval generated no files for the compatibility fixture.");
writeFileSync(
join(outputDirectory, "tsconfig.json"),
JSON.stringify({
extends: "../tsconfig.json",
files: files.map((file) => relative(outputDirectory, file)),
}),
);
run(bin("tsc"), ["--noEmit", "-p", outputDirectory]);
const generated = files.map((file) => readFileSync(file, "utf8")).join("\n");
for (const [component, fragment] of Object.entries(expectedFragments)) {
assert.ok(generated.includes(fragment), `Generated code lacks ${component}: ${fragment}`);
}
stdout.write(`Orval compatibility fixture: ${files.length} files type-checked.\n`);
} finally {
rmSync(outputDirectory, { recursive: true, force: true });
}
+175 -14
View File
@@ -1,7 +1,13 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest";
import { z } from "zod";
import { apiRequest } from "./client";
import { getHealthz } from "./endpoints/health/health";
import {
ApiRequestError,
apiRequest,
invalidResponseCode,
networkErrorCode,
unknownErrorCode,
} from "./client";
import { getHealthz, type GetHealthzQueryError } from "./endpoints/health/health";
const healthSchema = z.object({ status: z.literal("ok") });
@@ -53,31 +59,186 @@ describe("apiRequest", () => {
});
});
it("maps structured HTTP errors to a stable error type", async () => {
it("maps an RFC 9457 problem response to ApiRequestError", async () => {
const request = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
code: "service_unavailable",
message: "Service unavailable",
request_id: "req-test",
type: "urn:lincodex:problem:validation_failed",
title: "Request validation failed",
status: 400,
code: "validation_failed",
detail: "One or more request fields are invalid.",
trace_id: "0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10",
errors: [
{
in: "query",
pointer: "/limit",
code: "invalid",
message: "The value does not match the contract.",
},
],
}),
{
status: 503,
headers: { "content-type": "application/json" },
status: 400,
headers: { "content-type": "application/problem+json" },
},
),
);
vi.stubGlobal("fetch", request);
const error: unknown = await apiRequest("/healthz").catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(ApiRequestError);
expect(error).toMatchObject({
name: "ApiRequestError",
message: "One or more request fields are invalid.",
status: 400,
code: "validation_failed",
title: "Request validation failed",
detail: "One or more request fields are invalid.",
traceId: "0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10",
fieldErrors: [
{
in: "query",
pointer: "/limit",
code: "invalid",
message: "The value does not match the contract.",
},
],
});
});
it("uses the title and the request ID header when the problem omits them", async () => {
const request = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
type: "urn:lincodex:problem:forbidden",
title: "Access denied",
status: 403,
code: "forbidden",
}),
{
status: 403,
headers: {
"content-type": "application/problem+json; charset=utf-8",
"x-request-id": "req-403",
},
},
),
);
vi.stubGlobal("fetch", request);
await expect(apiRequest("/healthz")).rejects.toMatchObject({
name: "ApiRequestError",
message: "Service unavailable",
status: 503,
code: "service_unavailable",
requestId: "req-test",
message: "Access denied",
status: 403,
code: "forbidden",
detail: undefined,
traceId: "req-403",
fieldErrors: [],
});
});
it.each([
{
name: "a JSON body that is not a problem",
body: JSON.stringify({ code: "service_unavailable", message: "Service unavailable" }),
contentType: "application/json",
},
{
name: "a problem with an unknown code",
body: JSON.stringify({
type: "urn:lincodex:problem:new",
title: "New",
status: 503,
code: "new",
}),
contentType: "application/problem+json",
},
{ name: "a proxy error page", body: "<html>Bad gateway</html>", contentType: "text/html" },
])("falls back to http_error for $name", async ({ body, contentType }) => {
const request = vi.fn().mockResolvedValue(
new Response(body, {
status: 503,
headers: { "content-type": contentType, "x-request-id": "req-503" },
}),
);
vi.stubGlobal("fetch", request);
await expect(apiRequest("/healthz")).rejects.toMatchObject({
name: "ApiRequestError",
message: "Request failed with status 503.",
status: 503,
code: unknownErrorCode,
traceId: "req-503",
fieldErrors: [],
});
});
it("maps a network failure to ApiRequestError with status 0", async () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch")));
const error: unknown = await apiRequest("/healthz").catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(ApiRequestError);
expect(error).toMatchObject({ status: 0, code: networkErrorCode, fieldErrors: [] });
});
it("lets a cancellation by the caller propagate unchanged", async () => {
const controller = new AbortController();
const abortError = new DOMException("The operation was aborted.", "AbortError");
vi.stubGlobal(
"fetch",
vi.fn().mockImplementation(() => {
controller.abort(abortError);
return Promise.reject(abortError);
}),
);
await expect(apiRequest("/healthz", { signal: controller.signal })).rejects.toBe(abortError);
});
it.each([
{
name: "a body that is not JSON",
body: "<html>ok</html>",
schema: healthSchema,
},
{
name: "a body that does not match the response schema",
body: JSON.stringify({ status: "degraded" }),
schema: healthSchema,
},
])("maps a 2xx response with $name to invalid_response", async ({ body, schema }) => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
new Response(body, {
status: 200,
headers: { "content-type": "application/json", "x-request-id": "req-200" },
}),
),
);
const error: unknown = await apiRequest("/healthz", {}, schema).catch(
(caught: unknown) => caught,
);
expect(error).toBeInstanceOf(ApiRequestError);
expect(error).toMatchObject({ status: 200, code: invalidResponseCode, traceId: "req-200" });
});
it("reports a cross-origin path as a programming error before any request", async () => {
const request = vi.fn();
vi.stubGlobal("fetch", request);
await expect(apiRequest("https://example.com/api/v1/healthz")).rejects.toThrow(TypeError);
expect(request).not.toHaveBeenCalled();
});
it("types generated query errors as ApiRequestError", () => {
expectTypeOf<GetHealthzQueryError>().toEqualTypeOf<ApiRequestError>();
});
it("rejects an already-prefixed path before making a request", async () => {
const request = vi.fn();
vi.stubGlobal("fetch", request);
+132 -37
View File
@@ -1,28 +1,73 @@
import { z } from "zod";
import type { z } from "zod";
import { Problem, type ProblemCode, type ProblemFieldError } from "./schemas";
const apiPrefix = "/api/v1";
const localOrigin = "http://lincodex.local";
const problemMediaType = "application/problem+json";
const requestIdHeader = "X-Request-ID";
const errorEnvelopeSchema = z
.object({
code: z.string().optional(),
message: z.string().optional(),
request_id: z.string().optional(),
})
.passthrough();
/** Code used when an error response is not a contract problem document. */
export const unknownErrorCode = "http_error";
/** Code used when the request did not produce an HTTP response. */
export const networkErrorCode = "network_error";
/** Code used when a 2xx response body is not valid JSON or does not match its schema. */
export const invalidResponseCode = "invalid_response";
/**
* Contract problem codes plus client-side codes that never appear in a
* server response.
*/
export type ApiErrorCode =
ProblemCode | typeof unknownErrorCode | typeof networkErrorCode | typeof invalidResponseCode;
type ApiRequestErrorInit = {
status: number;
code: ApiErrorCode;
title: string;
detail?: string | undefined;
traceId?: string | undefined;
fieldErrors?: readonly ProblemFieldError[] | undefined;
};
/**
* Error for every failed API request. For RFC 9457 problem responses it
* carries the contract fields. `status` is 0 when no HTTP response arrived.
*/
export class ApiRequestError extends Error {
constructor(
message: string,
readonly status: number,
readonly code: string,
readonly requestId: string | undefined,
) {
super(message);
readonly status: number;
readonly code: ApiErrorCode;
readonly title: string;
readonly detail: string | undefined;
readonly traceId: string | undefined;
readonly fieldErrors: readonly ProblemFieldError[];
constructor(init: ApiRequestErrorInit) {
super(init.detail ?? init.title);
this.name = "ApiRequestError";
this.status = init.status;
this.code = init.code;
this.title = init.title;
this.detail = init.detail;
this.traceId = init.traceId;
this.fieldErrors = init.fieldErrors ?? [];
}
}
/**
* Error type of generated query hooks. Orval passes the contract error schema
* as the argument; the conditional only consumes it.
*
* apiRequest rejects with ApiRequestError for every request failure: an error
* response, a network failure, and a 2xx body that is not valid JSON or does
* not match its schema. It rejects with another error in two cases that are
* not request failures: when the caller's AbortSignal cancels the request,
* the original abort error propagates unchanged (TanStack Query treats it as
* cancellation, not as a query error); and when a generated path is not a
* same-origin /api/v1 path, a TypeError reports the programming error before
* any request is sent.
*/
export type ErrorType<ContractError> = ContractError extends unknown ? ApiRequestError : never;
function buildApiUrl(path: string): string {
const parsed = new URL(path, localOrigin);
if (parsed.origin !== localOrigin) {
@@ -40,25 +85,49 @@ function buildApiUrl(path: string): string {
return `${pathname}${parsed.search}`;
}
async function toApiError(response: Response): Promise<ApiRequestError> {
const body: unknown = await response.json().catch(() => undefined);
const parsed = errorEnvelopeSchema.safeParse(body);
function isAbort(error: unknown, signal: AbortSignal | null | undefined): boolean {
return signal?.aborted === true || (error instanceof DOMException && error.name === "AbortError");
}
if (parsed.success) {
return new ApiRequestError(
parsed.data.message ?? `Request failed with status ${response.status}.`,
response.status,
parsed.data.code ?? "http_error",
parsed.data.request_id,
);
function isProblemResponse(response: Response): boolean {
const mediaType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
return mediaType === problemMediaType;
}
async function toApiError(response: Response): Promise<ApiRequestError> {
const headerTraceId = response.headers.get(requestIdHeader) ?? undefined;
if (isProblemResponse(response)) {
const body: unknown = await response.json().catch(() => undefined);
const parsed = Problem.safeParse(body);
if (parsed.success) {
const problem = parsed.data;
return new ApiRequestError({
status: response.status,
code: problem.code,
title: problem.title,
detail: problem.detail,
traceId: problem.trace_id ?? headerTraceId,
fieldErrors: problem.errors,
});
}
}
return new ApiRequestError(
`Request failed with status ${response.status}.`,
response.status,
"http_error",
undefined,
);
return new ApiRequestError({
status: response.status,
code: unknownErrorCode,
title: `Request failed with status ${response.status}.`,
traceId: headerTraceId,
});
}
function invalidResponseError(response: Response): ApiRequestError {
return new ApiRequestError({
status: response.status,
code: invalidResponseCode,
title: "The response does not match the API contract.",
traceId: response.headers.get(requestIdHeader) ?? undefined,
});
}
export async function apiRequest<T>(
@@ -66,15 +135,41 @@ export async function apiRequest<T>(
init: RequestInit = {},
responseSchema?: z.ZodType<T>,
): Promise<T> {
const response = await fetch(buildApiUrl(path), {
...init,
credentials: "include",
});
const url = buildApiUrl(path);
let response: Response;
try {
response = await fetch(url, { ...init, credentials: "include" });
} catch (error: unknown) {
if (isAbort(error, init.signal)) {
throw error;
}
throw new ApiRequestError({
status: 0,
code: networkErrorCode,
title: "The request did not reach the server.",
});
}
if (!response.ok) {
throw await toApiError(response);
}
const body: unknown = response.status === 204 ? undefined : await response.json();
return responseSchema ? responseSchema.parse(body) : (body as T);
let body: unknown;
try {
body = response.status === 204 ? undefined : await response.json();
} catch (error: unknown) {
if (isAbort(error, init.signal)) {
throw error;
}
throw invalidResponseError(response);
}
if (!responseSchema) {
return body as T;
}
const parsed = responseSchema.safeParse(body);
if (!parsed.success) {
throw invalidResponseError(response);
}
return parsed.data;
}
@@ -20,10 +20,12 @@ import type {
} from '@tanstack/react-query';
import type {
HealthResponse
HealthResponse,
Problem
} from '../../schemas';
import { apiRequest } from '../../client';
import type { ErrorType } from '../../client';
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
@@ -78,7 +80,7 @@ export const getGetHealthzQueryKey = () => {
}
export const getGetHealthzQueryOptions = <TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
export const getGetHealthzQueryOptions = <TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
@@ -97,10 +99,10 @@ const {query: queryOptions, request: requestOptions} = options ?? {};
}
export type GetHealthzQueryResult = NonNullable<Awaited<ReturnType<typeof getHealthz>>>
export type GetHealthzQueryError = unknown
export type GetHealthzQueryError = ErrorType<Problem>
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getHealthz>>,
@@ -110,7 +112,7 @@ export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TE
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getHealthz>>,
@@ -120,7 +122,7 @@ export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TE
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
@@ -128,7 +130,7 @@ export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TE
* @summary Check whether the API process is responding.
*/
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
+8 -1
View File
@@ -1 +1,8 @@
export { ApiRequestError, apiRequest } from "./client";
export {
ApiRequestError,
apiRequest,
invalidResponseCode,
networkErrorCode,
unknownErrorCode,
type ApiErrorCode,
} from "./client";
@@ -6,3 +6,7 @@
*/
export * from './healthResponse.zod';
export * from './problem.zod';
export * from './problemCode.zod';
export * from './problemFieldError.zod';
export * from './problemFieldLocation.zod';
@@ -0,0 +1,54 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const problemTypeMax = 256;
export const problemTitleMax = 200;
export const problemStatusMin = 400;
export const problemStatusMax = 599;
export const problemDetailMax = 1000;
export const problemInstanceMax = 2048;
export const problemTraceIdMax = 128;
export const problemTraceIdRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const problemErrorsItemPointerMax = 1024;
export const problemErrorsItemPointerRegExp = new RegExp('^(/([^~/]|~[01])*)*$');
export const problemErrorsItemCodeMax = 64;
export const problemErrorsItemCodeRegExp = new RegExp('^[a-z][a-z0-9_]*$');
export const problemErrorsItemMessageMax = 500;
export const problemErrorsMax = 100;
export const Problem = zod.object({
"type": zod.string().max(problemTypeMax).describe('URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.'),
"title": zod.string().min(1).max(problemTitleMax).describe('Short, fixed English summary of the problem type. It does not change between occurrences.'),
"status": zod.int().min(problemStatusMin).max(problemStatusMax).describe('HTTP status code generated by the origin server.'),
"code": zod.enum(['validation_failed', 'unauthenticated', 'forbidden', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. 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.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.'),
"detail": zod.string().max(problemDetailMax).exactOptional().describe('Safe English explanation of this occurrence. It never contains internal error text or request values.'),
"instance": zod.string().max(problemInstanceMax).exactOptional().describe('URI reference that identifies this occurrence, when one exists.'),
"trace_id": zod.string().min(1).max(problemTraceIdMax).regex(problemTraceIdRegExp).exactOptional().describe('Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret.'),
"errors": zod.array(zod.object({
"in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'),
"pointer": zod.string().max(problemErrorsItemPointerMax).regex(problemErrorsItemPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'),
"code": zod.string().min(1).max(problemErrorsItemCodeMax).regex(problemErrorsItemCodeRegExp).describe('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": zod.string().min(1).max(problemErrorsItemMessageMax).describe('Fixed English message that never echoes the submitted value.')
}).describe('One reason why a request field or parameter is invalid.')).max(problemErrorsMax).exactOptional().describe('Field-level reasons for validation_failed. Other codes omit it.')
}).describe('Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.')
export type Problem = zod.input<typeof Problem>;
export type ProblemOutput = zod.output<typeof Problem>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ProblemCode = zod.enum(['validation_failed', 'unauthenticated', 'forbidden', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. 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.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.')
export type ProblemCode = zod.input<typeof ProblemCode>;
export type ProblemCodeOutput = zod.output<typeof ProblemCode>;
@@ -0,0 +1,28 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const problemFieldErrorPointerMax = 1024;
export const problemFieldErrorPointerRegExp = new RegExp('^(/([^~/]|~[01])*)*$');
export const problemFieldErrorCodeMax = 64;
export const problemFieldErrorCodeRegExp = new RegExp('^[a-z][a-z0-9_]*$');
export const problemFieldErrorMessageMax = 500;
export const ProblemFieldError = zod.object({
"in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'),
"pointer": zod.string().max(problemFieldErrorPointerMax).regex(problemFieldErrorPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'),
"code": zod.string().min(1).max(problemFieldErrorCodeMax).regex(problemFieldErrorCodeRegExp).describe('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": zod.string().min(1).max(problemFieldErrorMessageMax).describe('Fixed English message that never echoes the submitted value.')
}).describe('One reason why a request field or parameter is invalid.')
export type ProblemFieldError = zod.input<typeof ProblemFieldError>;
export type ProblemFieldErrorOutput = zod.output<typeof ProblemFieldError>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ProblemFieldLocation = zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.')
export type ProblemFieldLocation = zod.input<typeof ProblemFieldLocation>;
export type ProblemFieldLocationOutput = zod.output<typeof ProblemFieldLocation>;
+2
View File
@@ -5,4 +5,6 @@
* OpenAPI spec version: 0.1.0
*/
export * from './pageInfo.zod';
export * from './timestamp.zod';
export * from './health';
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const pageInfoNextCursorMax = 512;
export const pageInfoNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const PageInfo = zod.object({
"has_more": zod.boolean().describe('Whether another page follows this one.'),
"next_cursor": zod.string().min(1).max(pageInfoNextCursorMax).regex(pageInfoNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.')
}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.')
export type PageInfo = zod.input<typeof PageInfo>;
export type PageInfoOutput = zod.output<typeof PageInfo>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const Timestamp = zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
export type Timestamp = zod.input<typeof Timestamp>;
export type TimestampOutput = zod.output<typeof Timestamp>;
+11 -5
View File
@@ -1,7 +1,7 @@
.DEFAULT_GOAL := help
UV ?= uv
API_PREPARED ?= 0
.PHONY: help install generate check-generated build run fmt fmt-check lint lint-fix typecheck test test-contract check verify
.PHONY: help install generate check-generated check-pydantic-compat build run fmt fmt-check lint lint-fix typecheck test test-contract check verify
help: ## Show available ML service commands.
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-14s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -16,6 +16,12 @@ generate: ## Generate Pydantic models from the shared ML contract.
check-generated: ## Check Pydantic models against the bundled contract without rewriting them.
cd codegen && $(UV) run --project .. datamodel-codegen --check
check-pydantic-compat: ## Generate Pydantic models from the OpenAPI 3.2 compatibility fixture into a temporary directory and check them.
@temporary_dir=$$(mktemp -d) && trap 'rm -rf "$$temporary_dir"' EXIT && \
(cd codegen && $(UV) run --project .. datamodel-codegen --input ../../api/testdata/openapi-3.2.0.yml --output "$$temporary_dir/fixture_models.py" --openapi-scopes schemas parameters paths) && \
$(UV) run mypy --strict "$$temporary_dir/fixture_models.py" && \
$(UV) run python scripts/check_fixture_models.py "$$temporary_dir/fixture_models.py"
build: ## Build the service wheel.
$(UV) build
@@ -23,16 +29,16 @@ run: ## Run the operational API on port 8000.
$(UV) run uvicorn lincodex_ml.main:app --host 0.0.0.0 --port 8000
fmt: ## Format Python source.
$(UV) run ruff format src tests
$(UV) run ruff format src tests scripts
fmt-check: ## Check Python formatting.
$(UV) run ruff format --check src tests
$(UV) run ruff format --check src tests scripts
lint: ## Run Ruff checks.
$(UV) run ruff check src tests
$(UV) run ruff check src tests scripts
lint-fix: ## Apply safe Ruff fixes.
$(UV) run ruff check --fix src tests
$(UV) run ruff check --fix src tests scripts
typecheck: ## Run strict mypy checks.
$(UV) run mypy src
+1
View File
@@ -7,6 +7,7 @@ A separate Python service using FastAPI for future resume analysis and candidate
- `src/lincodex_ml/` contains the application, HTTP routes, and infrastructure code.
- `codegen/` configures Pydantic model generation from `api/ml/`.
- `tests/` checks service health and contract conformance.
- `scripts/` checks Pydantic models generated from the OpenAPI 3.2 fixture.
- `pyproject.toml` and `uv.lock` define dependencies and Python tool settings.
From the repository root, `make -C ml check` runs checks and `make -C ml run` starts the service locally. To use its separate Compose project, run `make -C deploy ml-up` after preparing `.env`.
+1
View File
@@ -7,6 +7,7 @@
- `src/lincodex_ml/` - приложение, HTTP-маршруты и инфраструктурный код.
- `codegen/` - настройки генерации моделей Pydantic из `api/ml/`.
- `tests/` - проверки состояния сервиса и соответствия контракту.
- `scripts/` - проверка Pydantic-моделей, сгенерированных из фикстуры OpenAPI 3.2.
- `pyproject.toml` и `uv.lock` - зависимости и настройки Python-инструментов.
Из корня: `make -C ml check` запускает проверки, `make -C ml run` - сервис локально. Для запуска через отдельный Compose используйте `make -C deploy ml-up` после подготовки `.env`.
+2
View File
@@ -8,3 +8,5 @@ openapi-scopes = ["schemas"]
enum-field-as-literal = "all"
disable-timestamp = true
formatters = ["ruff-check", "ruff-format"]
field-constraints = true
use-annotated = true
+86
View File
@@ -0,0 +1,86 @@
"""Validate Pydantic models generated from the OpenAPI 3.2 compatibility fixture.
make check-pydantic-compat generates the models into a temporary file and
passes its path. The checks cover the api/core conventions that
datamodel-code-generator turns into models: Problem, PageInfo, Timestamp, and
the PageLimit and PageCursor query parameters. It does not generate header
parameters or response headers, so Idempotency-Key, If-Match, and ETag have no
model to check.
"""
import importlib.util
import sys
from pathlib import Path
from types import ModuleType
from pydantic import BaseModel, ValidationError
def load(path: Path) -> ModuleType:
spec = importlib.util.spec_from_file_location("fixture_models", path)
if spec is None or spec.loader is None:
raise SystemExit(f"cannot load generated models from {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def rejects(model: type[BaseModel], payload: object) -> bool:
try:
model.model_validate(payload)
except ValidationError:
return True
return False
def main(path: Path) -> None:
models = load(path)
problem = models.Problem.model_validate(
{
"type": "urn:lincodex:problem:state_conflict",
"title": "Resource state conflict",
"status": 409,
"code": "state_conflict",
"errors": [{"in": "body", "pointer": "/name", "code": "invalid", "message": "m"}],
}
)
assert problem.code.root == "state_conflict"
assert rejects(models.Problem, {"type": "t", "title": "t", "status": 409, "code": "unknown"})
assert rejects(models.Problem, {"type": "t", "title": "t", "status": 200, "code": "internal"})
page = models.PageInfo.model_validate({"has_more": False, "next_cursor": None})
assert page.next_cursor is None
assert rejects(models.PageInfo, {"has_more": False})
assert rejects(models.PageInfo, {"has_more": True, "next_cursor": "a" * 513})
stamp = models.Timestamp.model_validate("2026-10-05T09:30:00Z")
assert models.Timestamp(stamp.root).model_dump_json() == '"2026-10-05T09:30:00Z"'
assert rejects(models.Timestamp, "2026-10-05T09:30:00")
query = models.ProbeItemsGetParametersQuery.model_validate({})
assert query.limit == 20
assert rejects(models.ProbeItemsGetParametersQuery, {"limit": 0})
assert rejects(models.ProbeItemsGetParametersQuery, {"limit": 101})
assert rejects(models.ProbeItemsGetParametersQuery, {"cursor": "a b"})
item_page = models.ProbeItemPage.model_validate(
{
"items": [
{
"id": "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11",
"name": "probe",
"updated_at": "2026-10-05T09:30:00Z",
}
],
"page": {"has_more": False, "next_cursor": None},
}
)
assert len(item_page.items) == 1
print("Pydantic compatibility fixture: generated models validated.")
if __name__ == "__main__":
if len(sys.argv) != 2:
raise SystemExit("usage: check_fixture_models.py <generated models file>")
main(Path(sys.argv[1]))
+141 -2
View File
@@ -1,9 +1,148 @@
# generated by datamodel-codegen:
# filename: openapi.bundle.yml
from typing import Literal
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict
from pydantic import BaseModel, ConfigDict, Field, RootModel
class ProblemCode(
RootModel[
Literal[
"validation_failed",
"unauthenticated",
"forbidden",
"not_found",
"method_not_allowed",
"idempotency_in_progress",
"state_conflict",
"version_conflict",
"payload_too_large",
"unsupported_media_type",
"idempotency_key_reused",
"precondition_required",
"rate_limited",
"internal",
"not_implemented",
]
]
):
root: Annotated[
Literal[
"validation_failed",
"unauthenticated",
"forbidden",
"not_found",
"method_not_allowed",
"idempotency_in_progress",
"state_conflict",
"version_conflict",
"payload_too_large",
"unsupported_media_type",
"idempotency_key_reused",
"precondition_required",
"rate_limited",
"internal",
"not_implemented",
],
Field(
description="Stable public error code. 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.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet."
),
]
class ProblemFieldLocation(RootModel[Literal["body", "query", "path", "header", "cookie"]]):
root: Annotated[
Literal["body", "query", "path", "header", "cookie"],
Field(description="Part of the request that contains the invalid field."),
]
class ProblemFieldError(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
in_: Annotated[ProblemFieldLocation, Field(alias="in")]
pointer: Annotated[
str,
Field(
description="JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.",
max_length=1024,
pattern="^(/([^~/]|~[01])*)*$",
),
]
code: Annotated[
str,
Field(
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.",
max_length=64,
min_length=1,
pattern="^[a-z][a-z0-9_]*$",
),
]
message: Annotated[
str,
Field(
description="Fixed English message that never echoes the submitted value.",
max_length=500,
min_length=1,
),
]
class Problem(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
type: Annotated[
str,
Field(
description="URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.",
max_length=256,
),
]
title: Annotated[
str,
Field(
description="Short, fixed English summary of the problem type. It does not change between occurrences.",
max_length=200,
min_length=1,
),
]
status: Annotated[
int, Field(description="HTTP status code generated by the origin server.", ge=400, le=599)
]
code: ProblemCode
detail: Annotated[
str | None,
Field(
description="Safe English explanation of this occurrence. It never contains internal error text or request values.",
max_length=1000,
),
] = None
instance: Annotated[
str | None,
Field(
description="URI reference that identifies this occurrence, when one exists.",
max_length=2048,
),
] = None
trace_id: Annotated[
str | None,
Field(
description="Request identifier of the call when the caller propagated one; it is not a secret.",
max_length=128,
min_length=1,
pattern="^[A-Za-z0-9._-]+$",
),
] = None
errors: Annotated[
list[ProblemFieldError] | None,
Field(
description="Field-level reasons for validation_failed. Other codes omit it.",
max_length=100,
),
] = None
class MLHealthResponse(BaseModel):
+281
View File
@@ -0,0 +1,281 @@
"""RFC 9457 problem responses that match the shared ML contract."""
import logging
import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any, Final
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from lincodex_ml.api.models import Problem, ProblemCode, ProblemFieldError, ProblemFieldLocation
PROBLEM_MEDIA_TYPE: Final = "application/problem+json"
_TYPE_PREFIX: Final = "urn:lincodex:problem:"
_REQUEST_ID_HEADER: Final = "X-Request-ID"
_REQUEST_ID_PATTERN: Final = re.compile(r"[A-Za-z0-9._-]{1,128}")
# Matches the maxItems bound of Problem.errors.
_MAX_FIELD_ERRORS: Final = 100
_FIELD_CODE_REQUIRED: Final = "required"
_FIELD_CODE_INVALID: Final = "invalid"
_FIELD_MESSAGES: Final = {
_FIELD_CODE_REQUIRED: "The value is required.",
_FIELD_CODE_INVALID: "The value does not match the contract.",
}
_FIELD_LOCATIONS: Final = frozenset({"body", "query", "path", "header", "cookie"})
logger = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class _Definition:
code: ProblemCode
status: int
title: str
detail: str
_VALIDATION_FAILED: Final = _Definition(
ProblemCode("validation_failed"),
status.HTTP_400_BAD_REQUEST,
"Request validation failed",
"One or more request fields are invalid.",
)
_INTERNAL: Final = _Definition(
ProblemCode("internal"),
status.HTTP_500_INTERNAL_SERVER_ERROR,
"Internal server error",
"The server could not complete the request.",
)
# Problem for each HTTP status that has a contract code. FastAPI reports body
# validation as 422, which the contract answers as 400 validation_failed; 422
# idempotency_key_reused belongs to the public API and has no ML use.
_STATUS_DEFINITIONS: Final[Mapping[int, _Definition]] = {
status.HTTP_400_BAD_REQUEST: _VALIDATION_FAILED,
status.HTTP_401_UNAUTHORIZED: _Definition(
ProblemCode("unauthenticated"),
status.HTTP_401_UNAUTHORIZED,
"Authentication required",
"Sign in and repeat the request.",
),
status.HTTP_403_FORBIDDEN: _Definition(
ProblemCode("forbidden"),
status.HTTP_403_FORBIDDEN,
"Access denied",
"You do not have permission to perform this operation.",
),
status.HTTP_404_NOT_FOUND: _Definition(
ProblemCode("not_found"),
status.HTTP_404_NOT_FOUND,
"Resource not found",
"The requested resource does not exist.",
),
status.HTTP_405_METHOD_NOT_ALLOWED: _Definition(
ProblemCode("method_not_allowed"),
status.HTTP_405_METHOD_NOT_ALLOWED,
"Method not allowed",
"The resource does not support this method; see the Allow header.",
),
status.HTTP_409_CONFLICT: _Definition(
ProblemCode("state_conflict"),
status.HTTP_409_CONFLICT,
"Resource state conflict",
"The resource is in a state that does not allow this operation.",
),
status.HTTP_412_PRECONDITION_FAILED: _Definition(
ProblemCode("version_conflict"),
status.HTTP_412_PRECONDITION_FAILED,
"Resource version conflict",
"The resource changed after it was read. Read it again before retrying.",
),
status.HTTP_413_CONTENT_TOO_LARGE: _Definition(
ProblemCode("payload_too_large"),
status.HTTP_413_CONTENT_TOO_LARGE,
"Request body too large",
"Reduce the request body size and retry.",
),
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE: _Definition(
ProblemCode("unsupported_media_type"),
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
"Unsupported media type",
"Send the request body with a media type that the operation accepts.",
),
status.HTTP_422_UNPROCESSABLE_CONTENT: _VALIDATION_FAILED,
status.HTTP_428_PRECONDITION_REQUIRED: _Definition(
ProblemCode("precondition_required"),
status.HTTP_428_PRECONDITION_REQUIRED,
"Precondition required",
"Send If-Match with the ETag of the version you read.",
),
status.HTTP_429_TOO_MANY_REQUESTS: _Definition(
ProblemCode("rate_limited"),
status.HTTP_429_TOO_MANY_REQUESTS,
"Too many requests",
"Wait for the Retry-After interval and retry.",
),
status.HTTP_501_NOT_IMPLEMENTED: _Definition(
ProblemCode("not_implemented"),
status.HTTP_501_NOT_IMPLEMENTED,
"Operation not implemented",
"This operation is not available yet.",
),
}
# Response headers of an HTTP exception that a problem response keeps.
_FORWARDED_HEADERS: Final = ("Allow", "Retry-After")
def install_problem_handlers(application: FastAPI) -> None:
"""Answer every framework and unhandled error with a problem response."""
application.add_exception_handler(RequestValidationError, _handle_validation_error)
application.add_exception_handler(StarletteHTTPException, _handle_http_exception)
application.add_middleware(UnhandledErrorMiddleware)
def _definition_for_status(status_code: int) -> _Definition:
"""Return the problem for an HTTP status raised inside the service.
A status without a contract code is still a client error when it is 4xx and
becomes 400 validation_failed; every other unmapped status is internal.
"""
definition = _STATUS_DEFINITIONS.get(status_code)
if definition is not None:
return definition
if status.HTTP_400_BAD_REQUEST <= status_code < status.HTTP_500_INTERNAL_SERVER_ERROR:
return _VALIDATION_FAILED
return _INTERNAL
class UnhandledErrorMiddleware:
"""Answer an unhandled exception with the internal problem.
Starlette's ServerErrorMiddleware re-raises after its handler, and uvicorn
then logs the exception with its text. Catching the exception here, inside
that middleware, ends it at this boundary: only its type is logged, and the
exception text reaches neither the client nor any log record. When the
response has already started it cannot be replaced, so the exception is
logged and the incomplete response is left for the server to close.
"""
def __init__(self, app: ASGIApp) -> None:
self._app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self._app(scope, receive, send)
return
response_started = False
async def tracked_send(message: Message) -> None:
nonlocal response_started
if message["type"] == "http.response.start":
response_started = True
await send(message)
try:
await self._app(scope, receive, tracked_send)
except Exception as exc:
request = Request(scope)
# Exception text may contain document content or model output, so
# only the type is logged.
logger.error(
"Unhandled %s in %s %s",
type(exc).__name__,
request.method,
request.url.path,
)
if response_started:
return
response = _problem_response(request, _INTERNAL)
await response(scope, receive, send)
async def _handle_validation_error(request: Request, exc: Exception) -> JSONResponse:
errors = exc.errors() if isinstance(exc, RequestValidationError) else []
return _problem_response(request, _VALIDATION_FAILED, _field_errors(errors))
async def _handle_http_exception(request: Request, exc: Exception) -> JSONResponse:
status_code = (
exc.status_code
if isinstance(exc, StarletteHTTPException)
else status.HTTP_500_INTERNAL_SERVER_ERROR
)
definition = _definition_for_status(status_code)
if definition is _INTERNAL:
logger.error("HTTP status %d in %s %s", status_code, request.method, request.url.path)
raised_headers = exc.headers if isinstance(exc, StarletteHTTPException) else None
headers = {
name: raised_headers[name]
for name in _FORWARDED_HEADERS
if raised_headers and name in raised_headers
}
return _problem_response(request, definition, headers=headers or None)
def _problem_response(
request: Request,
definition: _Definition,
errors: list[ProblemFieldError] | None = None,
headers: Mapping[str, str] | None = None,
) -> JSONResponse:
problem = Problem(
type=f"{_TYPE_PREFIX}{definition.code.root}",
title=definition.title,
status=definition.status,
code=definition.code,
detail=definition.detail,
trace_id=_request_id(request),
errors=errors,
)
return JSONResponse(
content=problem.model_dump(mode="json", by_alias=True, exclude_none=True),
status_code=definition.status,
headers=headers,
media_type=PROBLEM_MEDIA_TYPE,
)
def _request_id(request: Request) -> str | None:
value = request.headers.get(_REQUEST_ID_HEADER)
if value is not None and _REQUEST_ID_PATTERN.fullmatch(value):
return value
return None
def _field_errors(errors: Sequence[Any]) -> list[ProblemFieldError]:
fields: list[ProblemFieldError] = []
for error in errors[:_MAX_FIELD_ERRORS]:
if not isinstance(error, Mapping):
continue
location = tuple(error.get("loc", ()))
names_part = bool(location) and location[0] in _FIELD_LOCATIONS
part = str(location[0]) if names_part else "body"
path = location[1:] if names_part else location
if error.get("type") == "json_invalid":
# The location of a JSON syntax error is a character offset, not a
# field, so the error points at the whole body.
path = ()
code = _FIELD_CODE_REQUIRED if error.get("type") == "missing" else _FIELD_CODE_INVALID
fields.append(
ProblemFieldError.model_validate(
{
"in": ProblemFieldLocation.model_validate(part),
"pointer": "".join(f"/{_escape_pointer_token(str(token))}" for token in path),
"code": code,
"message": _FIELD_MESSAGES[code],
}
)
)
return fields
def _escape_pointer_token(token: str) -> str:
"""Escape a JSON Pointer reference token as RFC 6901 requires."""
return token.replace("~", "~0").replace("/", "~1")
+25 -11
View File
@@ -1,22 +1,32 @@
import json
import logging
from datetime import UTC, datetime
from typing import override
from typing import Final, override
# uvicorn configures these loggers with its own text handlers before it imports
# the application. They are routed through the service handler instead, so
# that no uvicorn record prints exception text or a traceback.
UVICORN_LOGGERS: Final = ("uvicorn", "uvicorn.error", "uvicorn.access")
class JsonFormatter(logging.Formatter):
"""Format records as JSON lines without exception text or tracebacks.
Exception messages may contain resume text, contact data, or model output,
so a record with exception information keeps only the exception type.
"""
@override
def format(self, record: logging.LogRecord) -> str:
return json.dumps(
{
"timestamp": datetime.now(UTC).isoformat(),
"level": record.levelname.lower(),
"logger": record.name,
"message": record.getMessage(),
},
ensure_ascii=False,
separators=(",", ":"),
)
entry: dict[str, str] = {
"timestamp": datetime.now(UTC).isoformat(),
"level": record.levelname.lower(),
"logger": record.name,
"message": record.getMessage(),
}
if record.exc_info and record.exc_info[0] is not None:
entry["exception_type"] = record.exc_info[0].__name__
return json.dumps(entry, ensure_ascii=False, separators=(",", ":"))
def configure_logging() -> None:
@@ -26,3 +36,7 @@ def configure_logging() -> None:
root_logger.handlers.clear()
root_logger.addHandler(handler)
root_logger.setLevel(logging.INFO)
for name in UVICORN_LOGGERS:
uvicorn_logger = logging.getLogger(name)
uvicorn_logger.handlers.clear()
uvicorn_logger.propagate = True
+2
View File
@@ -2,6 +2,7 @@ from fastapi import FastAPI
from prometheus_client import REGISTRY, make_asgi_app
from lincodex_ml.api.health import router as health_router
from lincodex_ml.api.problems import install_problem_handlers
from lincodex_ml.infra.logging import configure_logging
@@ -9,6 +10,7 @@ def create_app() -> FastAPI:
configure_logging()
application = FastAPI(title="Lincodex ML Operational API", version="0.1.0")
application.openapi_version = "3.1.2"
install_problem_handlers(application)
application.include_router(health_router)
application.mount("/metrics", make_asgi_app(registry=REGISTRY))
return application
+34 -1
View File
@@ -6,7 +6,7 @@ import pytest
import yaml
from pydantic import BaseModel, ValidationError
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse, Problem
from lincodex_ml.main import app
CONTRACT_PATH = Path(__file__).resolve().parents[2] / "api" / "ml" / "openapi.bundle.yml"
@@ -20,6 +20,14 @@ def _resolve_schema(document: dict[str, Any], schema: dict[str, Any]) -> dict[st
return document["components"]["schemas"][component_name]
def _resolve_response(document: dict[str, Any], response: dict[str, Any]) -> dict[str, Any]:
reference = response.get("$ref")
if reference is None:
return response
component_name = reference.rsplit("/", maxsplit=1)[-1]
return document["components"]["responses"][component_name]
def _status_values(document: dict[str, Any], response: dict[str, Any]) -> list[str]:
content = response["content"]["application/json"]["schema"]
response_schema = _resolve_schema(document, content)
@@ -47,6 +55,10 @@ def test_health_and_readiness_match_shared_openapi_contract() -> None:
assert actual_operation["operationId"] == expected_operation["operationId"]
for response_code, expected_response in expected_operation["responses"].items():
# The default problem response is checked at runtime below; FastAPI
# cannot describe it with the problem media type.
if response_code == "default":
continue
actual_response = actual_operation["responses"][response_code]
assert _status_values(contract, expected_response) == _status_values(
implementation, actual_response
@@ -68,6 +80,27 @@ async def test_unready_probe_returns_the_contractual_503_response() -> None:
assert response.json()["status"] in _status_values(contract, readiness["503"])
@pytest.mark.anyio
@pytest.mark.parametrize(("method", "path"), [("POST", "/healthz"), ("GET", "/missing")])
async def test_error_responses_match_the_contractual_default_response(
method: str, path: str
) -> None:
contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8"))
default = _resolve_response(
contract, contract["paths"]["/healthz"]["get"]["responses"]["default"]
)
(media_type,) = default["content"]
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://test"
) as client:
response = await client.request(method, path)
assert response.headers["content-type"] == media_type
problem = Problem.model_validate(response.json())
assert problem.status == response.status_code
@pytest.mark.parametrize(
("model", "valid_status"),
[(MLHealthResponse, "ok"), (MLReadinessResponse, "ready"), (MLReadinessResponse, "not_ready")],
+215
View File
@@ -0,0 +1,215 @@
import logging
import logging.config
from typing import Annotated
import httpx
import pytest
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
from uvicorn.config import LOGGING_CONFIG
from lincodex_ml.api.models import Problem
from lincodex_ml.api.problems import PROBLEM_MEDIA_TYPE
from lincodex_ml.infra.logging import UVICORN_LOGGERS, JsonFormatter, configure_logging
from lincodex_ml.main import create_app
SENSITIVE_TEXT = "resume of Jane Doe, phone +7 900 000-00-00"
class ProbeInput(BaseModel):
name: str
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
@pytest.fixture
def probe_app() -> FastAPI:
"""The service app plus test-only routes that the ML contract does not have."""
application = create_app()
@application.get("/probe")
async def probe(limit: Annotated[int, Query(ge=1, le=100)]) -> dict[str, int]:
return {"limit": limit}
@application.post("/probe")
async def create_probe(payload: ProbeInput) -> dict[str, str]:
return {"name": payload.name}
@application.get("/failure")
async def failure() -> None:
raise RuntimeError(SENSITIVE_TEXT)
@application.get("/status/{code}")
async def raise_status(code: int) -> None:
headers = {"Retry-After": "30"} if code == 429 else None
raise HTTPException(status_code=code, detail=SENSITIVE_TEXT, headers=headers)
return application
async def _request(
application: FastAPI,
method: str,
path: str,
json: object = None,
content: str | None = None,
headers: dict[str, str] | None = None,
) -> httpx.Response:
# Unhandled errors must reach the problem handler instead of the test client.
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application, raise_app_exceptions=False),
base_url="http://test",
) as client:
return await client.request(method, path, json=json, content=content, headers=headers)
def _problem(response: httpx.Response, status: int, code: str) -> Problem:
assert response.status_code == status
assert response.headers["content-type"] == PROBLEM_MEDIA_TYPE
problem = Problem.model_validate(response.json())
assert problem.status == status
assert problem.code.root == code
assert problem.type == f"urn:lincodex:problem:{code}"
return problem
@pytest.mark.anyio
async def test_unhandled_exception_ends_at_the_problem_boundary(probe_app: FastAPI) -> None:
# The default transport re-raises anything that escapes the application,
# so a problem response here proves that nothing reaches Starlette's
# ServerErrorMiddleware, which would re-raise to uvicorn.
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=probe_app), base_url="http://test"
) as client:
response = await client.get("/failure", headers={"X-Request-ID": "req-1"})
problem = _problem(response, 500, "internal")
assert problem.trace_id == "req-1"
assert "Jane" not in response.text
@pytest.mark.anyio
async def test_unhandled_exception_text_reaches_no_log_record(
probe_app: FastAPI, caplog: pytest.LogCaptureFixture
) -> None:
# create_app replaced the root handlers, so capture at the root again.
logging.getLogger().addHandler(caplog.handler)
caplog.set_level(logging.DEBUG)
try:
response = await _request(probe_app, "GET", "/failure")
finally:
logging.getLogger().removeHandler(caplog.handler)
_problem(response, 500, "internal")
assert any("RuntimeError" in record.getMessage() for record in caplog.records)
formatter = JsonFormatter()
for record in caplog.records:
assert "Jane" not in record.getMessage()
assert "Jane" not in formatter.format(record)
assert record.exc_info is None or "Jane" not in str(record.exc_info[1])
def test_uvicorn_loggers_are_redacted_after_uvicorn_configures_them(
capsys: pytest.CaptureFixture[str],
) -> None:
# uvicorn applies its logging configuration before it imports the
# application; configure_logging then takes its loggers over.
logging.config.dictConfig(LOGGING_CONFIG)
configure_logging()
capsys.readouterr()
try:
raise RuntimeError(SENSITIVE_TEXT)
except RuntimeError:
logging.getLogger("uvicorn.error").exception("Exception in ASGI application")
output = capsys.readouterr().err
assert '"exception_type":"RuntimeError"' in output
assert "Exception in ASGI application" in output
assert "Jane" not in output
assert "Traceback" not in output
for name in UVICORN_LOGGERS:
assert logging.getLogger(name).handlers == []
@pytest.mark.anyio
@pytest.mark.parametrize(
("raised", "status", "code"),
[
(400, 400, "validation_failed"),
(401, 401, "unauthenticated"),
(403, 403, "forbidden"),
(409, 409, "state_conflict"),
(413, 413, "payload_too_large"),
(415, 415, "unsupported_media_type"),
(422, 400, "validation_failed"),
(428, 428, "precondition_required"),
(429, 429, "rate_limited"),
(501, 501, "not_implemented"),
(418, 400, "validation_failed"),
(503, 500, "internal"),
],
)
async def test_http_exceptions_map_to_contract_problems(
probe_app: FastAPI, raised: int, status: int, code: str
) -> None:
response = await _request(probe_app, "GET", f"/status/{raised}")
_problem(response, status, code)
assert "Jane" not in response.text
if raised == 429:
assert response.headers["retry-after"] == "30"
@pytest.mark.anyio
@pytest.mark.parametrize(
("method", "path", "body", "expected"),
[
("GET", "/probe?limit=0", None, [{"in": "query", "pointer": "/limit", "code": "invalid"}]),
("GET", "/probe", None, [{"in": "query", "pointer": "/limit", "code": "required"}]),
("POST", "/probe", {}, [{"in": "body", "pointer": "/name", "code": "required"}]),
("POST", "/probe", {"name": 1}, [{"in": "body", "pointer": "/name", "code": "invalid"}]),
("POST", "/probe", '{"name":', [{"in": "body", "pointer": "", "code": "invalid"}]),
],
)
async def test_request_validation_returns_validation_problem(
probe_app: FastAPI,
method: str,
path: str,
body: object,
expected: list[dict[str, str]],
) -> None:
if isinstance(body, str):
response = await _request(
probe_app, method, path, content=body, headers={"Content-Type": "application/json"}
)
else:
response = await _request(probe_app, method, path, json=body)
problem = _problem(response, 400, "validation_failed")
fields = [
{"in": field.in_.root, "pointer": field.pointer, "code": field.code}
for field in problem.errors or []
]
assert fields == expected
assert all(field.message for field in problem.errors or [])
@pytest.mark.anyio
async def test_unknown_route_and_method_return_problems(probe_app: FastAPI) -> None:
missing = await _request(probe_app, "GET", "/missing")
_problem(missing, 404, "not_found")
not_allowed = await _request(probe_app, "DELETE", "/healthz")
_problem(not_allowed, 405, "method_not_allowed")
assert not_allowed.headers["allow"] == "GET"
@pytest.mark.anyio
async def test_invalid_request_id_is_not_echoed(probe_app: FastAPI) -> None:
response = await _request(probe_app, "GET", "/missing", headers={"X-Request-ID": "bad id"})
assert _problem(response, 404, "not_found").trace_id is None
+1 -1
View File
@@ -8,7 +8,7 @@ Helper tools that work across multiple parts of the repository.
- `check-api-compat.sh` checks public API compatibility against a selected Git ref.
- `check-generated.py` detects generated files that differ from Git.
- `docs-check.py` checks documentation, README language pairs, and local links.
- `test_docs_check.py` and `test_merge_schemas.py` test documentation validation and schema merging.
- `test_docs_check.py` and `test_merge_schemas.py` test documentation validation and schema merging; `test_contract_copies.py` checks that the OpenAPI 3.2 fixture and the ML contract keep identical copies of the api/core conventions.
Run them through Make from the repository root: `make -C api check`, `make -C api check-compat API_BASE_REF=<ref>`, `make check-generated`, and `make docs-check`. Service-specific scripts live in their service directories.
+1 -1
View File
@@ -8,7 +8,7 @@
- `check-api-compat.sh` проверяет совместимость публичного API с выбранной Git-ссылкой.
- `check-generated.py` обнаруживает расхождения сгенерированных файлов с Git.
- `docs-check.py` проверяет документацию, языковые пары README и локальные ссылки.
- `test_docs_check.py` и `test_merge_schemas.py` проверяют валидацию документации и объединение схем.
- `test_docs_check.py` и `test_merge_schemas.py` проверяют валидацию документации и объединение схем; `test_contract_copies.py` проверяет, что фикстура OpenAPI 3.2 и ML-контракт хранят идентичные копии соглашений api/core.
Запускайте их через Make из корня: `make -C api check`, `make -C api check-compat API_BASE_REF=<ref>`, `make check-generated` и `make docs-check`. Скрипты конкретного сервиса находятся в его каталоге.
+107
View File
@@ -0,0 +1,107 @@
"""Check that contract convention copies stay identical to api/core.
The OpenAPI 3.2 compatibility fixture and the ML contract cannot reference
api/core files: ogen rejects external references and the ML contract is a
separate specification. They therefore carry copies of the api/core
conventions. These tests read the bundled api/core contract, so run them after
`make -C api bundle`.
"""
from __future__ import annotations
import unittest
from pathlib import Path
from typing import Any
import yaml
API_DIR = Path(__file__).resolve().parents[1] / "api"
CORE_BUNDLE = API_DIR / "core" / "openapi.bundle.yml"
ML_BUNDLE = API_DIR / "ml" / "openapi.bundle.yml"
FIXTURE = API_DIR / "testdata" / "openapi-3.2.0.yml"
SHARED_SECTIONS = ("schemas", "parameters", "headers")
# Every api/core convention component that the fixture must exercise.
EXPECTED_FIXTURE_COPIES = {
("schemas", "Problem"),
("schemas", "ProblemCode"),
("schemas", "ProblemFieldError"),
("schemas", "ProblemFieldLocation"),
("schemas", "Timestamp"),
("schemas", "PageInfo"),
("parameters", "IdempotencyKey"),
("parameters", "IfMatch"),
("parameters", "PageLimit"),
("parameters", "PageCursor"),
("headers", "ETag"),
}
PROBLEM_SCHEMAS = ("Problem", "ProblemCode", "ProblemFieldError", "ProblemFieldLocation")
def load_components(path: Path) -> dict[str, Any]:
with path.open(encoding="utf-8") as stream:
document = yaml.safe_load(stream)
components = document.get("components")
if not isinstance(components, dict):
raise AssertionError(f"{path} has no components mapping")
return components
def without_descriptions(value: Any) -> Any:
"""Return a copy of a schema without description text."""
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
def without_examples(response: dict[str, Any]) -> dict[str, Any]:
"""Return a copy of a response without media type examples."""
content = {
media_type: {key: item for key, item in media.items() if key != "examples"}
for media_type, media in response.get("content", {}).items()
}
return {**response, "content": content}
class ContractCopiesTest(unittest.TestCase):
def setUp(self) -> None:
self.core = load_components(CORE_BUNDLE)
def test_fixture_copies_match_core_definitions(self) -> None:
fixture = load_components(FIXTURE)
compared = set()
for section in SHARED_SECTIONS:
for name, definition in fixture.get(section, {}).items():
if name not in self.core.get(section, {}):
continue
compared.add((section, name))
with self.subTest(section=section, name=name):
self.assertEqual(definition, self.core[section][name])
self.assertEqual(compared, EXPECTED_FIXTURE_COPIES)
def test_fixture_responses_match_core_without_examples(self) -> None:
fixture_responses = load_components(FIXTURE)["responses"]
for name, definition in fixture_responses.items():
with self.subTest(name=name):
self.assertIn(name, self.core["responses"])
expected = without_examples(self.core["responses"][name])
self.assertEqual(definition, expected)
def test_ml_problem_schemas_match_core_except_descriptions(self) -> None:
ml_schemas = load_components(ML_BUNDLE)["schemas"]
for name in PROBLEM_SCHEMAS:
with self.subTest(name=name):
self.assertIn(name, ml_schemas)
self.assertEqual(
without_descriptions(ml_schemas[name]),
without_descriptions(self.core["schemas"][name]),
)
if __name__ == "__main__":
unittest.main()