Files
open_cv/app/main.py
T
2026-09-29 00:17:58 +03:00

106 lines
4.0 KiB
Python

"""Точка входа FastAPI: сборка приложения, middleware, инициализация ядра.
Запуск: uvicorn app.main:app (см. docs/07-развертывание.md).
"""
from __future__ import annotations
import logging
import time
import uuid
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from app.api.errors import error_body, install_error_handlers
from app.api.routes import health_router, router
from app.config import Config
from app.cv.service import CvService
from app.logging_setup import log_event, setup_logging
logger = logging.getLogger("opencv")
# Запас на multipart-обёртки и settings при ранней проверке Content-Length
# для /features: сама image-часть проверяется точно после разбора.
_FEATURES_BODY_SLACK_BYTES = 1024 * 1024
def create_app(config: Config | None = None) -> FastAPI:
config = config or Config.from_env()
config.validate_cross()
setup_logging(config.log_level)
@asynccontextmanager
async def lifespan(app: FastAPI):
# FR-005: пробное извлечение признаков служебного изображения
ok, _ = app.state.cv.init_core()
app.state.ready = ok
if ok:
log_event(logger, logging.INFO, "CV core initialized")
else:
log_event(logger, logging.ERROR, "CV core not ready", reasons=app.state.cv.ready_reasons)
yield
app = FastAPI(title="open_cv", version="1.0.0", lifespan=lifespan)
app.state.config = config
app.state.cv = CvService(config)
app.state.ready = False
app.include_router(router)
app.include_router(health_router)
install_error_handlers(app)
@app.middleware("http")
async def observability(request: Request, call_next):
request.state.trace_id = uuid.uuid4().hex[:12]
# Ранние проверки размера — до чтения тела в память (docs/03 §3.6)
if request.method == "POST":
limit = _body_limit(request.url.path, config)
content_length = request.headers.get("content-length")
if limit is not None and content_length is not None:
try:
declared = int(content_length)
except ValueError:
declared = None
if declared is not None and declared > limit:
return JSONResponse(
status_code=413,
content=error_body(
"PAYLOAD_TOO_LARGE",
f"Тело запроса превышает лимит {limit // (1024 * 1024)} МБ",
request.state.trace_id,
{"limit": limit, "content_length": declared},
),
)
started = time.perf_counter()
try:
response = await call_next(request)
except Exception:
log_event(
logger, logging.ERROR, "request failed",
method=request.method, path=request.url.path,
trace_id=request.state.trace_id,
duration_ms=int((time.perf_counter() - started) * 1000),
)
raise
if request.url.path.startswith("/api/"):
log_event(
logger, logging.INFO, "request",
method=request.method, path=request.url.path,
status=response.status_code,
duration_ms=int((time.perf_counter() - started) * 1000),
trace_id=request.state.trace_id,
)
response.headers["X-Trace-Id"] = request.state.trace_id
return response
return app
def _body_limit(path: str, config: Config) -> int | None:
if path == "/api/v1/verify":
return config.verify_max_body_bytes
if path == "/api/v1/features":
return config.max_image_bytes + _FEATURES_BODY_SLACK_BYTES
return None