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
@@ -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):
|
||||
|
||||
@@ -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")
|
||||
@@ -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,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
|
||||
|
||||
Reference in new issue
Block a user