import json import logging import re import uuid from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException from .cache import SessionCache, open_cache from .config import load_settings from .db import open_pool from .errors import ApiError from .migrate import apply_migrations from .routes import router from .store import Store logger = logging.getLogger('messenger') _SAFE_REQUEST_ID = re.compile(r'^[A-Za-z0-9._:-]{1,128}$') _CODES = { 400: 'invalid_request', 401: 'unauthorized', 404: 'not_found', 409: 'conflict', 413: 'payload_too_large', 415: 'unsupported_media_type', 429: 'rate_limited', 503: 'unavailable', } _MESSAGES = { 'invalid_request': 'Некорректный запрос', 'unauthorized': 'Требуется идентификация', 'not_found': 'Объект не найден', 'internal_error': 'Внутренняя ошибка', } _BEARER_CHALLENGE = 'Bearer realm="messenger"' def _error(status: int, code: str, message: str, request_id: str, challenge: str | None = None) -> JSONResponse: body = {'error': {'code': code, 'message': message, 'request_id': request_id}} headers = {'X-Request-Id': request_id} if challenge: headers['WWW-Authenticate'] = challenge return JSONResponse(body, status_code=status, headers=headers) def _request_id(request: Request) -> str: return getattr(request.state, 'request_id', None) or str(uuid.uuid4()) _OPENAPI_PATH = Path(__file__).resolve().parents[1] / 'contracts' / 'openapi.json' @asynccontextmanager async def lifespan(app: FastAPI): settings = load_settings() pool = await open_pool(settings.database_url) cache = SessionCache(open_cache(settings.redis_url)) try: await apply_migrations(pool) app.state.store = Store(pool, cache, settings.session_ttl_seconds) yield finally: try: await cache.close() finally: await pool.close() def create_app() -> FastAPI: app = FastAPI( title='MTUSI Messenger lab2', version='1.2.0', lifespan=lifespan, ) def openapi(): if app.openapi_schema is None: app.openapi_schema = json.loads(_OPENAPI_PATH.read_text(encoding='utf-8')) return app.openapi_schema app.openapi = openapi @app.middleware('http') async def request_context(request: Request, call_next): """Gives every response, including unexpected failures, an X-Request-Id.""" incoming = request.headers.get('X-Request-Id') request_id = incoming if incoming and _SAFE_REQUEST_ID.match(incoming) else str(uuid.uuid4()) request.state.request_id = request_id try: response = await call_next(request) except Exception: logger.exception('request %s failed: %s %s', request_id, request.method, request.url.path) response = _error(500, 'internal_error', _MESSAGES['internal_error'], request_id) response.headers['X-Request-Id'] = request_id return response @app.exception_handler(ApiError) async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse: return _error(exc.status, exc.code, exc.message, _request_id(request), exc.challenge) @app.exception_handler(RequestValidationError) async def handle_validation_error(request: Request, exc: RequestValidationError) -> JSONResponse: return _error(400, 'invalid_request', _MESSAGES['invalid_request'], _request_id(request)) @app.exception_handler(StarletteHTTPException) async def handle_http_error(request: Request, exc: StarletteHTTPException) -> JSONResponse: code = _CODES.get(exc.status_code, 'internal_error' if exc.status_code >= 500 else 'invalid_request') challenge = _BEARER_CHALLENGE if exc.status_code == 401 else None return _error(exc.status_code, code, _MESSAGES.get(code, _MESSAGES['invalid_request']), _request_id(request), challenge) app.include_router(router) return app app = create_app()