This commit is contained in:
2026-09-29 00:17:58 +03:00
parent 2f8d4098c5
commit da32158789
38 changed files with 3106 additions and 10 deletions
+5
View File
@@ -0,0 +1,5 @@
"""API-слой: маршруты, multipart, лимиты, X-API-Key, единый формат ошибок.
Бизнес-логики нет — только валидация транспорта и делегация в CV-ядро
(docs/03 §3.2.1).
"""
+39
View File
@@ -0,0 +1,39 @@
"""Аутентификация X-API-Key (FR-004, docs/05 §5.2): 401 — нет, 403 — неверен."""
from __future__ import annotations
import secrets
from fastapi import Request
from app.api.errors import ApiError
ALLOWED_IMAGE_CONTENT_TYPES = {"image/jpeg", "image/png", "image/webp"}
def require_api_key(request: Request) -> None:
provided = request.headers.get("x-api-key")
if not provided:
raise ApiError(401, "UNAUTHORIZED", "Требуется заголовок X-API-Key")
expected = request.app.state.config.api_key
if not secrets.compare_digest(provided.encode(), expected.encode()):
raise ApiError(403, "FORBIDDEN", "Неверный API-ключ")
def check_image_content_type(content_type: str | None, part: str) -> None:
"""415, если часть заявлена как изображение недопустимого типа.
application/octet-stream пропускаем: фактический формат определяет
декодер, а не заголовок части (docs/05 §5.5-1).
"""
if content_type is None:
return
base = content_type.split(";", 1)[0].strip().lower()
if base == "application/octet-stream":
return
if base.startswith("image/") and base not in ALLOWED_IMAGE_CONTENT_TYPES:
raise ApiError(
415,
"UNSUPPORTED_MEDIA_TYPE",
f"Часть {part}: формат {base} не поддерживается; разрешены JPEG, PNG, WebP",
{"part": part, "content_type": base},
)
+114
View File
@@ -0,0 +1,114 @@
"""Единый формат ошибок и маппинг исключений на HTTP (docs/05 §5.3).
Тело любой ошибки: {"error": {"code", "message", "details", "trace_id"}}.
"""
from __future__ import annotations
from fastapi import Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.cv.exceptions import (
BlobInvalid,
CvError,
FormatUnsupported,
ImageDecodeFailed,
ImageFormatUnsupported,
ImageTooSmall,
InvalidSettings,
UnknownProfile,
)
# Маппинг исключений CV-ядра на коды ответов — единственная точка,
# где ядро «узнаёт» о HTTP (docs/03 §3.5-1).
_CV_ERROR_MAP: list[tuple[type[CvError], int, str]] = [
(ImageDecodeFailed, 400, "IMAGE_DECODE_FAILED"),
(ImageTooSmall, 400, "IMAGE_TOO_SMALL"),
(BlobInvalid, 400, "FEATURE_BLOB_INVALID"),
(FormatUnsupported, 400, "FEATURE_FORMAT_UNSUPPORTED"),
(UnknownProfile, 400, "UNKNOWN_PROFILE"),
(ImageFormatUnsupported, 415, "UNSUPPORTED_MEDIA_TYPE"),
(InvalidSettings, 422, "INVALID_SETTINGS"),
]
class ApiError(Exception):
"""Транспортная ошибка API-слоя с готовым кодом ответа."""
def __init__(self, status_code: int, code: str, message: str, details: dict | None = None):
super().__init__(message)
self.status_code = status_code
self.code = code
self.message = message
self.details = details or {}
def error_body(code: str, message: str, trace_id: str, details: dict | None = None) -> dict:
return {"error": {"code": code, "message": message, "details": details or {}, "trace_id": trace_id}}
def _trace_id(request: Request) -> str:
return getattr(request.state, "trace_id", "")
def install_error_handlers(app) -> None:
@app.exception_handler(ApiError)
async def _api_error(request: Request, exc: ApiError):
return JSONResponse(
status_code=exc.status_code,
content=error_body(exc.code, exc.message, _trace_id(request), exc.details),
)
@app.exception_handler(CvError)
async def _cv_error(request: Request, exc: CvError):
for exc_type, status, code in _CV_ERROR_MAP:
if isinstance(exc, exc_type):
return JSONResponse(
status_code=status,
content=error_body(code, str(exc), _trace_id(request), exc.details),
)
return JSONResponse(
status_code=500,
content=error_body("INTERNAL", "Внутренняя ошибка сервиса", _trace_id(request)),
)
@app.exception_handler(RequestValidationError)
async def _validation(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content=error_body(
"VALIDATION_ERROR", "Некорректный запрос", _trace_id(request),
{"errors": [
{"loc": [str(p) for p in e.get("loc", [])], "msg": e.get("msg", "")}
for e in exc.errors()
]},
),
)
@app.exception_handler(StarletteHTTPException)
async def _http_error(request: Request, exc: StarletteHTTPException):
code = {401: "UNAUTHORIZED", 403: "FORBIDDEN", 404: "NOT_FOUND", 405: "METHOD_NOT_ALLOWED"}.get(
exc.status_code, "HTTP_ERROR"
)
return JSONResponse(
status_code=exc.status_code,
content=error_body(code, str(exc.detail), _trace_id(request)),
headers=getattr(exc, "headers", None),
)
@app.exception_handler(Exception)
async def _unhandled(request: Request, exc: Exception):
import logging
logging.getLogger("opencv").exception(
"Необработанное исключение", extra={"fields": {"trace_id": _trace_id(request)}}
)
return JSONResponse(
status_code=500,
content=error_body(
"INTERNAL",
"Внутренняя ошибка сервиса; детали в логах по trace_id",
_trace_id(request),
),
)
+245
View File
@@ -0,0 +1,245 @@
"""Маршруты API (docs/05-rest-api.md): /features, /verify, /profiles, /health, /ready."""
from __future__ import annotations
import json
import logging
import time
from fastapi import APIRouter, Depends, Request
from fastapi.responses import Response
from starlette.concurrency import run_in_threadpool
from starlette.datastructures import UploadFile
from app.api.deps import check_image_content_type, require_api_key
from app.api.errors import ApiError
from app.api.schemas import (
ProfileModel,
ProfilesResponse,
StatusResponse,
UnreadyResponse,
VerifyResponse,
)
from app.cv.exceptions import InvalidSettings
from app.cv.params import PROFILES, base_comparison, base_extraction
from app.cv.service import CvService
from app.logging_setup import log_event
logger = logging.getLogger("opencv.api")
router = APIRouter()
_SETTINGS_MAX_BYTES = 4096 # settings ≤ 4 КБ (FR-008, docs/05 §5.5-6)
# ------------------------------------------------------------------ helpers
def _config(request: Request):
return request.app.state.config
def _service(request: Request) -> CvService:
return request.app.state.cv
async def _read_file_part(form, name: str) -> tuple[bytes, str | None]:
"""Достаёт файловую часть: (байты, content-type). Строковая часть — 422."""
part = form.get(name)
if part is None or isinstance(part, str):
raise ApiError(
422, "VALIDATION_ERROR",
f"Отсутствует обязательная multipart-часть {name!r}",
{"part": name},
)
return await part.read(), part.content_type
async def _read_settings(form) -> dict | None:
"""form-часть settings (JSON ≤ 4 КБ); отсутствует → None."""
raw = form.get("settings")
if raw is None:
return None
if isinstance(raw, UploadFile):
raw = (await raw.read()).decode("utf-8", errors="replace")
encoded = raw.encode("utf-8")
if len(encoded) > _SETTINGS_MAX_BYTES:
raise InvalidSettings(
f"settings превышает лимит {_SETTINGS_MAX_BYTES} байт", {"size": len(encoded)}
)
try:
parsed = json.loads(raw)
except json.JSONDecodeError as exc:
raise InvalidSettings(f"settings не является корректным JSON: {exc}") from exc
return parsed
def _check_image_size(data: bytes, part: str, limit: int) -> None:
if len(data) > limit:
raise ApiError(
413, "PAYLOAD_TOO_LARGE",
f"Часть {part} превышает лимит {limit // (1024 * 1024)} МБ",
{"part": part, "size": len(data), "limit": limit},
)
# ---------------------------------------------------------------- /features
@router.post("/api/v1/features", dependencies=[Depends(require_api_key)])
async def extract_features(request: Request):
form = await request.form()
image_bytes, content_type = await _read_file_part(form, "image")
check_image_content_type(content_type, "image")
_check_image_size(image_bytes, "image", _config(request).max_image_bytes)
settings = await _read_settings(form)
started = time.perf_counter()
outcome = await run_in_threadpool(_service(request).extract_to_blob, image_bytes, settings)
duration_ms = int((time.perf_counter() - started) * 1000)
log_event(
logger, logging.INFO, "features extracted",
trace_id=getattr(request.state, "trace_id", ""),
keypoints=outcome.keypoints_count,
algo_id=outcome.algo_id,
duration_ms=duration_ms,
)
return Response(
content=outcome.blob,
media_type="application/octet-stream",
headers={
"Content-Disposition": 'attachment; filename="features.npz"',
"X-Feature-Format-Version": str(outcome.format_version),
"X-Algo-Id": outcome.algo_id,
"X-Keypoints-Count": str(outcome.keypoints_count),
"X-Image-Width": str(outcome.image_width),
"X-Image-Height": str(outcome.image_height),
},
)
# ------------------------------------------------------------------ /verify
@router.post("/api/v1/verify", dependencies=[Depends(require_api_key)])
async def verify(request: Request):
config = _config(request)
form = await request.form()
probe_bytes, probe_ct = await _read_file_part(form, "probe")
check_image_content_type(probe_ct, "probe")
_check_image_size(probe_bytes, "probe", config.max_image_bytes)
ref_parts = form.getlist("reference")
if not ref_parts:
raise ApiError(
422, "VALIDATION_ERROR",
"Отсутствуют части reference: нужен хотя бы один эталон",
{"part": "reference"},
)
if len(ref_parts) > config.max_references:
raise ApiError(
400, "TOO_MANY_REFERENCES",
f"Число эталонов {len(ref_parts)} превышает лимит {config.max_references}",
{"references": len(ref_parts), "limit": config.max_references},
)
reference_payloads: list[bytes] = []
for i, part in enumerate(ref_parts):
if isinstance(part, str):
raise ApiError(
422, "VALIDATION_ERROR",
f"Часть reference[{i}] должна быть файлом",
{"part": "reference", "index": i},
)
data = await part.read()
_check_image_size(data, f"reference[{i}]", config.verify_max_body_bytes)
reference_payloads.append(data)
settings = await _read_settings(form)
started = time.perf_counter()
outcome = await run_in_threadpool(
_service(request).verify, probe_bytes, reference_payloads, settings
)
processing_ms = int((time.perf_counter() - started) * 1000)
log_event(
logger, logging.INFO, "verify completed",
trace_id=getattr(request.state, "trace_id", ""),
verdict=outcome.verdict,
confidence=round(outcome.confidence, 4),
best_reference_index=outcome.best_reference_index,
references=outcome.references_compared,
processing_ms=processing_ms,
)
return VerifyResponse(
verdict=outcome.verdict,
is_match=outcome.is_match,
confidence=round(outcome.confidence, 4),
details={
"references_compared": outcome.references_compared,
"best_reference_index": outcome.best_reference_index,
"metrics": {
"good_matches": outcome.metrics.good_matches,
"inliers": outcome.metrics.inliers,
"inlier_ratio": round(outcome.metrics.inlier_ratio, 4),
"coverage": round(outcome.metrics.coverage, 4),
},
"thresholds": outcome.thresholds,
},
probe_sha256=outcome.probe_sha256,
processing_ms=processing_ms,
)
# ---------------------------------------------------------------- /profiles
@router.get(
"/api/v1/profiles",
dependencies=[Depends(require_api_key)],
response_model=ProfilesResponse,
)
async def list_profiles(request: Request):
"""Каталог профилей (FR-009): только отличия от базовых значений (docs/05 §5.4.4)."""
config = _config(request)
return ProfilesResponse(
profiles=[
ProfileModel(
name=name,
description=spec["description"],
extraction=spec["extraction"],
comparison=spec["comparison"],
)
for name, spec in PROFILES.items()
],
defaults={
"extraction": base_extraction(config).fingerprint_payload(),
"comparison": base_comparison(config).thresholds_payload(),
},
)
# ------------------------------------------------------- /health and /ready
health_router = APIRouter()
@health_router.get("/health", response_model=StatusResponse)
async def health():
return StatusResponse(status="ok")
@health_router.get("/ready")
async def ready(request: Request):
"""FR-005: конфигурация валидна и CV-ядро инициализировано."""
cv: CvService = request.app.state.cv
reasons = cv.ready_reasons
if request.app.state.ready and not reasons:
return StatusResponse(status="ready")
return Response(
content=UnreadyResponse(status="unavailable", reasons=reasons).model_dump_json(),
status_code=503,
media_type="application/json",
)
+62
View File
@@ -0,0 +1,62 @@
"""Pydantic-модели JSON-ответов (docs/05 §5.4.2, §5.4.4)."""
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
class PairMetricsModel(BaseModel):
good_matches: int = Field(description="Число пар после теста Лоу")
inliers: int = Field(description="Число инлаеров RANSAC")
inlier_ratio: float = Field(description="inliers / good_matches")
coverage: float = Field(description="Доля площади пробы под оболочкой инлаеров")
class ThresholdsModel(BaseModel):
"""Эффективные пороги сравнения лучшей пары (+ аддитивные поля диагностики)."""
inliers_match: int
inlier_ratio_match: float
coverage_min: float
inliers_uncertain_min: int
geometry_model: str
lowe_ratio: float
ransac_reproj_threshold: float
class VerifyDetailsModel(BaseModel):
references_compared: int
best_reference_index: int = Field(description="Индекс части reference (0-based)")
metrics: PairMetricsModel
thresholds: ThresholdsModel
class VerifyResponse(BaseModel):
verdict: Literal["match", "uncertain", "no_match"]
is_match: bool = Field(description="true только при verdict = match")
confidence: float = Field(ge=0.0, le=1.0)
details: VerifyDetailsModel
probe_sha256: str
processing_ms: int
class ProfileModel(BaseModel):
name: str
description: str
extraction: dict
comparison: dict
class ProfilesResponse(BaseModel):
profiles: list[ProfileModel]
defaults: dict = Field(description="Базовые значения (env-умолчания) для наследования")
class StatusResponse(BaseModel):
status: str
class UnreadyResponse(BaseModel):
status: str
reasons: list[str]