feat(api): define public problem errors, pagination, and retry contract
This commit is contained in:
1 parent
b2f6e87bfe
commit
565ca94bbb
86 files changed
+8200
-154
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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-сервиса это окружение не требуется.
|
||||
|
||||
Reference in new issue
Block a user