Platform v2 step 1.4 (APPS_PLATFORM D-3..D-6, D-21, §5). - core/modules/entitlements.py: compute() turns the evaluated license into per-module grants: the v2 token's `modules` map (own `exp` with the 5-day grace, never cut mid-service) + the free tier; no/invalid token, expired after grace, inactive, locked or clock tampering -> free tier only; core always. limit(module, name) with token value -> manifest licensed_default -> free value; None = unlimited. LICENSE_MODE=off (dev/test only) = everything - module gating says why: module.not_licensed (402, the first unlicensed module in the dependency chain) before module.disabled (403) - services/license.py accepts only v2 tokens with a modules map; the v1 "legacy unsigned 72h" path is gone - apply_license() always installs entitlements (startup before workers, every heartbeat, workday close); workers follow license changes - the global license middleware is deleted (no more whole-API 402/423); license_state moved to services/license_state.py - history_days enforced in every report/history endpoint: lower date bounds clamped (also when no "from" is given), and business days older than the limit refused by id (license.history_limited); data is never deleted - bootstrap/modules API show license mode, entitlement source and limit values - LICENSE_MODE=off in docker-compose.dev.yml and the e2e launchers; sites default to enforced - tests: entitlement rules, limits, the three done-when checks, signed-token apply_license path; license tests moved to v2 tokens Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
132 lines
6.3 KiB
Python
132 lines
6.3 KiB
Python
"""API errors as stable codes (APPS_PLATFORM D-12, §3.2).
|
|
|
|
Every error response has this shape:
|
|
{"error": {"code": "order.not_found", "params": {"order_id": 7}, "message": "Order 7 not found."},
|
|
"detail": "Order 7 not found."}
|
|
- code: stable identifier; frontends translate it (i18n key `errors.<code>`).
|
|
- params: values the translated text can use.
|
|
- message: English, for logs, curl and un-migrated screens.
|
|
- detail: kept for frontends written before v2 (they read `detail`).
|
|
|
|
New and converted code raises XeniaError:
|
|
raise XeniaError("order.not_found", order_id=order_id)
|
|
The status comes from the registry below; pass status= only to override it.
|
|
Plain HTTPException (still in most v1 routers; converted gradually, plan step 6.x)
|
|
is wrapped as code "http.<status>" with its original `detail` untouched.
|
|
Request validation errors become "validation.invalid" with the field errors in params.
|
|
Unhandled exceptions become "internal.error" (500) with the request id in params.
|
|
|
|
Agent notes:
|
|
- Add every new code to CODES with its HTTP status and English message (str.format
|
|
placeholders from params). tests/test_errors.py fails on a raised code that
|
|
isn't registered (via XeniaError's constructor).
|
|
- Codes are part of the API contract: never rename one; add a new one instead.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from http import HTTPStatus
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.encoders import jsonable_encoder
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
logger = logging.getLogger("xenia.errors")
|
|
|
|
# code -> (HTTP status, English message)
|
|
CODES: dict[str, tuple[int, str]] = {
|
|
# access / licensing / modules (filled in by steps 1.3-1.9)
|
|
"access.denied": (403, "You don't have permission to do this ({key})."),
|
|
"access.override_possible": (403, "A manager can approve this ({key})."),
|
|
"module.disabled": (403, "The {module} module is turned off."),
|
|
"module.not_licensed": (402, "This site's license doesn't include {module}."),
|
|
"module.unknown": (404, "There is no module {module}."),
|
|
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
|
|
"license.limit_reached": (402, "License limit reached for {limit} ({max})."),
|
|
"license.expired": (402, "The license has expired."),
|
|
"license.history_limited": (402, "This license shows only the last {days} days of history ({module})."),
|
|
# identity
|
|
"auth.invalid_credentials": (401, "Wrong username or password."),
|
|
"auth.session_ended": (401, "Your session has ended. Please log in again."),
|
|
"device.revoked": (401, "This device was removed. Pair it again."),
|
|
"device.not_paired": (401, "This device isn't paired with the venue."),
|
|
# validation
|
|
"validation.invalid": (422, "Some fields are invalid."),
|
|
"validation.unknown_language": (422, "Unsupported language: {language}."),
|
|
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
|
|
# server
|
|
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
|
|
# domain
|
|
"order.not_found": (404, "Order {order_id} not found."),
|
|
}
|
|
|
|
|
|
class XeniaError(Exception):
|
|
"""An API error with a registered code. raise XeniaError("order.not_found", order_id=5)."""
|
|
|
|
def __init__(self, code: str, status: int | None = None, **params):
|
|
if code not in CODES:
|
|
raise KeyError(f"unregistered error code {code!r}: add it to core/errors.py CODES")
|
|
default_status, template = CODES[code]
|
|
self.code = code
|
|
self.status = status or default_status
|
|
self.params = params
|
|
try:
|
|
self.message = template.format(**params)
|
|
except (KeyError, IndexError):
|
|
self.message = template
|
|
super().__init__(self.message)
|
|
|
|
|
|
def error_body(code: str, message: str, params: dict | None = None, detail=None) -> dict:
|
|
return {"error": {"code": code, "params": params or {}, "message": message},
|
|
"detail": message if detail is None else detail}
|
|
|
|
|
|
async def _xenia_error_handler(request: Request, exc: XeniaError):
|
|
return JSONResponse(error_body(exc.code, exc.message, exc.params), status_code=exc.status)
|
|
|
|
|
|
async def _http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
detail = exc.detail
|
|
if isinstance(detail, str):
|
|
message = detail
|
|
elif isinstance(detail, dict) and isinstance(detail.get("message"), str):
|
|
message = detail["message"]
|
|
else:
|
|
try:
|
|
message = HTTPStatus(exc.status_code).phrase
|
|
except ValueError:
|
|
message = "Error"
|
|
return JSONResponse(error_body(f"http.{exc.status_code}", message, detail=detail),
|
|
status_code=exc.status_code, headers=getattr(exc, "headers", None))
|
|
|
|
|
|
async def _validation_handler(request: Request, exc: RequestValidationError):
|
|
errors = [{"field": ".".join(str(p) for p in e.get("loc", ())[1:]) or None,
|
|
"type": e.get("type"), "message": e.get("msg")} for e in exc.errors()]
|
|
# `detail` stays FastAPI's usual list, so existing frontends keep working
|
|
return JSONResponse(error_body("validation.invalid", CODES["validation.invalid"][1],
|
|
{"errors": jsonable_encoder(errors)}, detail=jsonable_encoder(exc.errors())),
|
|
status_code=422)
|
|
|
|
|
|
async def _unhandled_handler(request: Request, exc: Exception):
|
|
"""Last resort: a bug. Logged with the traceback; the client gets the request id
|
|
(also in the X-Request-ID header) so support can find the log lines."""
|
|
from core.logging import current_request_id
|
|
rid = getattr(request.state, "request_id", None) or current_request_id() or "-"
|
|
logger.exception("http.unhandled_error request_id=%s path=%s", rid, request.url.path)
|
|
err = XeniaError("internal.error", request_id=rid)
|
|
return JSONResponse(error_body(err.code, err.message, err.params), status_code=500,
|
|
headers={"X-Request-ID": rid})
|
|
|
|
|
|
def install_error_handlers(app: FastAPI) -> None:
|
|
app.add_exception_handler(Exception, _unhandled_handler)
|
|
app.add_exception_handler(XeniaError, _xenia_error_handler)
|
|
app.add_exception_handler(StarletteHTTPException, _http_exception_handler)
|
|
app.add_exception_handler(RequestValidationError, _validation_handler)
|