"""Точка входа FastAPI: сборка приложения, middleware, инициализация ядра. Запуск: uvicorn app.main:app (см. docs/07-развертывание.md). """ from __future__ import annotations import logging import time import uuid from contextlib import asynccontextmanager from pathlib import Path import yaml 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 # Спецификация — рукописный файл по контракту docs/05: автогенерация FastAPI # не видит multipart-части, разбираемые вручную. Отдаётся на /openapi.json и # рендерится в /docs. _OPENAPI_SPEC_PATH = Path(__file__).resolve().parent.parent / "openapi.yaml" 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 # Документация под префиксом /api: при проксировании наружу только /api/* # Swagger, ReDoc и спека остаются достижимы (эндпоинты API — /api/v1/*). app = FastAPI( title="open_cv", version="1.0.0", lifespan=lifespan, docs_url="/api/docs", redoc_url="/api/redoc", openapi_url="/api/openapi.json", ) app.state.config = config app.state.cv = CvService(config) app.state.ready = False _install_openapi(app) 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 _install_openapi(app: FastAPI) -> None: """Отдаёт /openapi.json и /docs из openapi.yaml. Multipart-контракт разбирается вручную (starlette request.form), поэтому автогенерация FastAPI пуста — спецификация поддерживается как файл. """ if not _OPENAPI_SPEC_PATH.exists(): logger.warning("openapi.yaml не найден: /docs отдаст пустую автогенерацию") return with _OPENAPI_SPEC_PATH.open(encoding="utf-8") as fh: spec = yaml.safe_load(fh) def custom_openapi(): return spec app.openapi = custom_openapi # type: ignore[method-assign] 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 if path == "/api/v1/calibrate": return config.calibration_max_body_bytes return None