"""HTTP API. Every response carries X-Request-Id and X-Instance-Id.""" import asyncio import base64 import contextvars import json import logging import uuid from contextlib import asynccontextmanager import asyncpg from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, Response from starlette.datastructures import MutableHeaders from starlette.exceptions import HTTPException as StarletteHTTPException from app.config import load_settings from app.db import close, connect, migrate from app.errors import ApiError, unauthorized from app import logic logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") logger = logging.getLogger("messenger") settings = load_settings() request_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="") _ERROR_CODES = { 400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type", 429: "rate_limited", 503: "unavailable", } def _error_body(status: int, code: str, message: str) -> dict: return {"error": {"code": code, "message": message, "request_id": request_id_var.get() or "error"}} def _error_response(status: int, code: str, message: str, headers: dict | None = None) -> JSONResponse: response = JSONResponse(status_code=status, content=_error_body(status, code, message)) for key, value in (headers or {}).items(): response.headers[key] = value return response class ContextMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): if scope["type"] != "http": await self.app(scope, receive, send) return request_id = str(uuid.uuid4()) token = request_id_var.set(request_id) started = False async def send_wrapper(message): nonlocal started if message["type"] == "http.response.start": started = True headers = MutableHeaders(raw=message["headers"]) headers["X-Request-Id"] = request_id headers["X-Instance-Id"] = settings.instance_id await send(message) try: await self.app(scope, receive, send_wrapper) except Exception: logger.exception("unhandled ASGI error") if not started: body = json.dumps(_error_body(500, "internal_error", "Внутренняя ошибка")).encode("utf-8") await send( { "type": "http.response.start", "status": 500, "headers": [ (b"content-type", b"application/json"), (b"x-request-id", request_id.encode("ascii")), (b"x-instance-id", settings.instance_id.encode("utf-8")), ], } ) await send({"type": "http.response.body", "body": body}) finally: request_id_var.reset(token) @asynccontextmanager async def lifespan(_app: FastAPI): delay = 1 for attempt in range(30): try: await connect(settings) await migrate(settings) logger.info("instance %s ready to serve", settings.instance_id) break except Exception: logger.exception("startup attempt %s failed", attempt + 1) await asyncio.sleep(delay) delay = min(delay * 2, 5) else: raise RuntimeError("database startup failed") try: yield finally: await close() app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None, redirect_slashes=False) app.add_middleware(ContextMiddleware) @app.exception_handler(ApiError) async def handle_api_error(_request: Request, exc: ApiError): return _error_response(exc.status, exc.code, exc.message, exc.headers) @app.exception_handler(StarletteHTTPException) async def handle_http(_request: Request, exc: StarletteHTTPException): status = exc.status_code if exc.status_code in _ERROR_CODES else 500 return _error_response(status, _ERROR_CODES.get(status, "internal_error"), "Запрос отклонён") @app.exception_handler(asyncpg.PostgresConnectionError) async def handle_db_down(_request: Request, exc: asyncpg.PostgresConnectionError): logger.exception("database connection failed") return _error_response(503, "unavailable", "База данных недоступна") @app.exception_handler(Exception) async def handle_unexpected(_request: Request, exc: Exception): logger.exception("unhandled error") return _error_response(500, "internal_error", "Внутренняя ошибка") def _bearer(request: Request) -> str: header = request.headers.get("authorization", "") if not header.lower().startswith("bearer "): raise unauthorized("bearer") token = header.split(" ", 1)[1].strip() if not token: raise unauthorized("bearer") return token def _basic(request: Request) -> tuple[str, str]: header = request.headers.get("authorization", "") if not header.lower().startswith("basic "): raise unauthorized("basic") encoded = header.split(" ", 1)[1].strip() try: decoded = base64.b64decode(encoded).decode("utf-8") except (ValueError, UnicodeError) as exc: raise unauthorized("basic") from exc if ":" not in decoded: raise unauthorized("basic") username, password = decoded.split(":", 1) return username, password async def _current_user(request: Request) -> dict: return await logic.authenticate(_bearer(request)) async def _json_object(request: Request) -> dict: media = (request.headers.get("content-type") or "").split(";", 1)[0].strip().lower() if media != "application/json": raise ApiError(400, "invalid_request", "Ожидается application/json") raw = bytearray() async for chunk in request.stream(): if len(raw) + len(chunk) > 65536: raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") raw.extend(chunk) try: data = json.loads(bytes(raw) if raw else b"") except (json.JSONDecodeError, UnicodeError) as exc: raise ApiError(400, "invalid_request", "Некорректный JSON") from exc if not isinstance(data, dict): raise ApiError(400, "invalid_request", "Ожидается JSON-объект") return data @app.get("/health/live") async def live(): return {"status": "ok"} @app.get("/health/ready") async def ready(): await logic.ready(settings) return {"status": "ok"} @app.post("/api/v1/users", status_code=201) async def register(request: Request): return await logic.register_user(await _json_object(request)) @app.post("/api/v1/auth/sessions", status_code=201) async def login(request: Request): username, password = _basic(request) return await logic.create_session(username, password, settings) @app.delete("/api/v1/auth/sessions/current", status_code=204) async def logout(request: Request): token = _bearer(request) await logic.authenticate(token) await logic.revoke_session(token) return Response(status_code=204) @app.get("/api/v1/users/me") async def me(request: Request): return await _current_user(request) @app.post("/api/v1/chats", status_code=201) async def create_chat(request: Request): user = await _current_user(request) return await logic.create_chat(user["id"], await _json_object(request)) @app.get("/api/v1/chats") async def list_chats(request: Request): user = await _current_user(request) limit = logic.parse_limit(request.query_params.get("limit")) return await logic.list_chats(user["id"], limit, request.query_params.get("cursor")) @app.get("/api/v1/chats/{chat_id}") async def get_chat(chat_id: str, request: Request): user = await _current_user(request) return await logic.get_chat(user["id"], chat_id) @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) async def create_message(chat_id: str, request: Request): user = await _current_user(request) body = await _json_object(request) return await logic.create_message( user["id"], chat_id, body, request.headers.get("idempotency-key"), settings, ) @app.get("/api/v1/chats/{chat_id}/messages") async def list_messages(chat_id: str, request: Request): user = await _current_user(request) limit = logic.parse_limit(request.query_params.get("limit")) return await logic.list_messages(user["id"], chat_id, limit, request.query_params.get("cursor")) @app.post("/api/v1/chats/{chat_id}/attachments", status_code=201) async def upload(chat_id: str, request: Request): user = await _current_user(request) payload = await logic.upload_attachment( user["id"], chat_id, request.query_params.get("filename"), request.headers.get("content-type"), request.headers.get("content-length"), request.stream(), settings, ) return JSONResponse(status_code=201, content=payload) @app.get("/api/v1/attachments/{attachment_id}") async def attachment_meta(attachment_id: str, request: Request): user = await _current_user(request) return await logic.get_attachment(user["id"], attachment_id) @app.get("/api/v1/attachments/{attachment_id}/content") async def attachment_content(attachment_id: str, request: Request): user = await _current_user(request) data, media = await logic.download_attachment( user["id"], attachment_id, request.query_params.get("variant"), settings, ) return Response(content=data, media_type=media, headers={"Content-Length": str(len(data))})