"""HTTP adapter. The instructor's OpenAPI, not FastAPI defaults, defines errors.""" import json import logging import os import re from contextlib import asynccontextmanager from pathlib import Path from time import perf_counter from typing import Annotated from urllib.parse import quote from uuid import uuid4 from fastapi import Depends, FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse, Response, StreamingResponse from opentelemetry.context import Context from opentelemetry.trace import INVALID_SPAN, SpanKind from starlette.exceptions import HTTPException from starlette.types import ASGIApp, Message, Receive, Scope, Send from messenger import telemetry from messenger.attachments import Attachments from messenger.auth import AuthService, Identity, basic_credentials, bearer_digest, unauthorized from messenger.cache import SessionCache from messenger.domain import DomainError, User, invalid, not_found from messenger.repository import PostgresRepository from messenger.schemas import ( AttachmentView, ChatPage, ChatView, CreateChat, CreateMessage, CreateUser, MessagePage, MessageView, SessionView, UserView, canonical_uuid, ) from messenger.secrets_provider import ServiceLease from messenger.service import Messenger from messenger.settings import Settings from messenger.storage import ObjectStore logger = logging.getLogger("messenger") class RequestContext: def __init__(self, app: ASGIApp, instance_id: str): self.app = app self.instance_id = instance_id async def __call__(self, scope: Scope, receive: Receive, send: Send): if scope["type"] != "http": return await self.app(scope, receive, send) if scope.get("path") in {"/health/live", "/health/ready"}: await self.request(scope, receive, send, INVALID_SPAN) return with telemetry.span("http.request", context=Context(), kind=SpanKind.SERVER) as span: await self.request(scope, receive, send, span) async def request(self, scope, receive, send, span): request_id = str(uuid4()) scope.setdefault("state", {})["request_id"] = request_id start, status, response_started = perf_counter(), 500, False async def with_id(message: Message): nonlocal status, response_started if message["type"] == "http.response.start": response_started = True status = message["status"] message["headers"] = [ pair for pair in message.get("headers", []) if pair[0].lower() not in (b"x-request-id", b"x-instance-id") ] + [ (b"x-request-id", request_id.encode()), (b"x-instance-id", self.instance_id.encode()), ] await send(message) try: app = scope.get("app") lease = getattr(app.state, "service_lease", None) if app is not None else None if lease is not None and not lease.valid() and scope["path"] != "/health/live": await error_response( Request(scope), 503, "unavailable", "Доступ сервиса временно недоступен" )(scope, receive, with_id) return if scope["method"] in {"POST", "PUT", "PATCH"} and not scope["path"].endswith( "/attachments" ): body = bytearray() more = True while more: item = await receive() if item["type"] == "http.disconnect": return body.extend(item.get("body", b"")) if len(body) > 65536: await error_response( Request(scope), 413, "payload_too_large", "Слишком большой запрос" )(scope, receive, with_id) return more = item.get("more_body", False) original_receive = receive first = True async def limited_receive(): nonlocal first if first: first = False return {"type": "http.request", "body": bytes(body), "more_body": False} return await original_receive() receive = limited_receive await self.app(scope, receive, with_id) except Exception as exc: # Do not let Uvicorn print exception values that could contain user data. if response_started: raise logger.error(json.dumps({"event": "internal_error", "type": type(exc).__name__})) response = error_response( Request(scope), 500, "internal_error", "Внутренняя ошибка сервера" ) await response(scope, receive, with_id) finally: route = getattr(scope.get("route"), "path", "unmatched") if route not in {"/health/live", "/health/ready"}: telemetry.http( span, scope["method"], route, status, perf_counter() - start, request_id ) def error_response( request: Request, status: int, code: str, message: str, headers: dict | None = None ) -> JSONResponse: identity = getattr(request.state, "request_id", str(uuid4())) return JSONResponse( status_code=status, content={"error": {"code": code, "message": message, "request_id": identity}}, headers={"X-Request-Id": identity, **(headers or {})}, ) def create_app(settings: Settings | None = None) -> FastAPI: settings = settings or Settings.from_env() repository = PostgresRepository( settings.database_url, settings.pool_size, settings.idempotency_ttl, settings.read_autocommit, ) cache = SessionCache(settings.cache_url) store = ObjectStore(settings) authentication = AuthService(repository, cache, settings.session_ttl) @asynccontextmanager async def lifespan(app: FastAPI): repository.open() if os.getenv("BAO_ROLE") == "api": Path("/tmp/api-instance-id").write_text(app.state.instance_id) app.state.ready = True logger.info(json.dumps({"event": "started", "environment": os.getenv("APP_ENV", "lab")})) try: with ServiceLease(settings) as lease: app.state.service_lease = lease yield finally: app.state.ready = False repository.close() cache.close() store.close() logger.info(json.dumps({"event": "stopped"})) app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) app.state.instance_id = uuid4().hex app.add_middleware(RequestContext, instance_id=app.state.instance_id) app.state.messenger = Messenger(repository) app.state.attachments = Attachments(repository, app.state.messenger, store, settings) app.state.repository = repository app.state.authentication = authentication app.state.cache = cache app.state.ready = False @app.exception_handler(DomainError) async def domain_error(request: Request, exc: DomainError): return error_response(request, exc.status, exc.code, exc.message, exc.headers) @app.exception_handler(RequestValidationError) async def validation_error(request: Request, exc: RequestValidationError): return error_response(request, 400, "invalid_request", "Некорректные поля или JSON") @app.exception_handler(HTTPException) async def http_error(request: Request, exc: HTTPException): code = "not_found" if exc.status_code == 404 else "invalid_request" return error_response(request, exc.status_code, code, "Некорректный HTTP-запрос") @app.exception_handler(Exception) async def unexpected_error(request: Request, exc: Exception): logger.error(json.dumps({"event": "internal_error", "type": type(exc).__name__})) return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера") def service(request: Request) -> Messenger: return request.app.state.messenger def token_digest(request: Request) -> bytes: if len(request.headers.getlist("authorization")) != 1: raise unauthorized() return bearer_digest(request.headers.get("authorization")) def identity( digest: Annotated[bytes, Depends(token_digest)], ) -> Identity: return authentication.identify(digest) def actor(current: Annotated[Identity, Depends(identity)]) -> User: return current.user async def credentials(request: Request) -> tuple[str, str]: if len(request.headers.getlist("authorization")) != 1: raise unauthorized("Basic") result = basic_credentials(request.headers.get("authorization")) if await request.body(): raise invalid("Вход не принимает тело запроса") return result def resource_id(chat_id: str) -> str: try: return canonical_uuid(chat_id) except ValueError: raise invalid("Некорректный UUID чата") from None def pagination(request: Request) -> tuple[int, str | None]: for key in ("limit", "cursor"): if len(request.query_params.getlist(key)) > 1: raise invalid("Параметр пагинации указан несколько раз") raw = request.query_params.get("limit", "50") try: if not re.fullmatch(r"[0-9]+", raw): raise ValueError limit = int(raw) if not 1 <= limit <= 100: raise ValueError except ValueError: raise invalid("limit должен быть целым от 1 до 100") from None return limit, request.query_params.get("cursor") def json_input(request: Request): media = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() if media != "application/json": raise DomainError(415, "unsupported_media_type", "Требуется application/json") def message_key(request: Request) -> str: values = request.headers.getlist("idempotency-key") if len(values) != 1 or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", values[0]): raise invalid("Требуется корректный Idempotency-Key") return values[0] CurrentUser = Annotated[User, Depends(actor)] Service = Annotated[Messenger, Depends(service)] ChatId = Annotated[str, Depends(resource_id)] Pagination = Annotated[tuple[int, str | None], Depends(pagination)] @app.get("/health/live") def live(): return {"status": "ok"} @app.get("/health/ready") def ready(request: Request): if not request.app.state.ready: raise DomainError(503, "unavailable", "Приложение не готово") repository.ready() store.ready() return {"status": "ok"} @app.post( "/api/v1/users", status_code=201, response_model=UserView, dependencies=[Depends(json_input)], ) def register(body: CreateUser): return authentication.register(body.username, body.display_name, body.password) @app.post("/api/v1/auth/sessions", status_code=201, response_model=SessionView) def login(value: Annotated[tuple[str, str], Depends(credentials)]): return authentication.login(*value) @app.delete("/api/v1/auth/sessions/current", status_code=204) def logout(current: Annotated[Identity, Depends(identity)]): authentication.logout(current) return Response(status_code=204) @app.get("/api/v1/users/me", response_model=UserView) def me(current: CurrentUser): return current @app.post( "/api/v1/chats", status_code=201, response_model=ChatView, dependencies=[Depends(json_input)], ) def create_chat(body: CreateChat, current: CurrentUser, messenger: Service): return messenger.create_chat(current, body.title, body.member_ids) @app.get("/api/v1/chats", response_model=ChatPage) def chats(current: CurrentUser, messenger: Service, page: Pagination): return messenger.chats(current, *page) @app.get("/api/v1/chats/{chat_id}", response_model=ChatView) def chat(current: CurrentUser, chat: ChatId, messenger: Service): return messenger.chat(current, chat) @app.post( "/api/v1/chats/{chat_id}/messages", status_code=201, response_model=MessageView, dependencies=[Depends(json_input)], ) def send_message( body: CreateMessage, current: CurrentUser, chat: ChatId, messenger: Service, key: Annotated[str, Depends(message_key)], ): return messenger.send(current, chat, body.text, key, tuple(body.attachment_ids)) @app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage) def messages(current: CurrentUser, chat: ChatId, messenger: Service, page: Pagination): return messenger.messages(current, chat, *page) def attachment_id(attachment_id: str) -> str: try: return canonical_uuid(attachment_id) except ValueError: raise invalid("Некорректный UUID вложения") from None AttachmentId = Annotated[str, Depends(attachment_id)] @app.post("/api/v1/chats/{chat_id}/attachments", status_code=202, response_model=AttachmentView) async def upload(request: Request, current: CurrentUser, chat: ChatId): return await app.state.attachments.upload(request, current, chat) @app.get("/api/v1/attachments/{attachment_id}", response_model=AttachmentView) def attachment(current: CurrentUser, id: AttachmentId): return app.state.attachments.metadata(current, id) @app.get("/api/v1/attachments/{attachment_id}/content") def content(request: Request, current: CurrentUser, id: AttachmentId): row = app.state.attachments.record(current, id) if row["storage_state"] != "ready": raise DomainError(409, "conflict", "Вложение пока недоступно") values = request.query_params.getlist("variant") if ( len(values) > 1 or values and values[0] not in ("original", "thumbnail", "crop", "optimized") ): raise invalid("Некорректный вариант вложения") if values and values[0] != "original": row = next((v for v in row["variants"] if v["name"] == values[0]), None) if row is None: raise not_found() row = {**row, "filename": values[0]} body = store.download(row) def chunks(): try: while data := body.read(65536): yield data finally: body.close() return StreamingResponse( chunks(), media_type=row["content_type"], headers={ "Content-Length": str(row["size_bytes"]), "Content-Disposition": "attachment; filename*=UTF-8''" + quote(row["filename"], safe=""), "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff", }, ) return app