import json import logging import time from collections.abc import AsyncIterator from contextlib import asynccontextmanager from datetime import datetime from functools import partial from uuid import UUID, uuid4 from anyio import to_thread from fastapi import FastAPI, Request from fastapi.encoders import jsonable_encoder from pydantic import ValidationError from starlette.exceptions import HTTPException from starlette.responses import JSONResponse, Response from src.cache import UserCache from src.cursor import parse_uuid from src.database import Database from src.domain import timestamp from src.errors import DomainError, invalid from src.password import Passwords from src.repository import PostgresRepository from src.schemas import CreateChat, CreateMessage, CreateUser, Input from src.service import MessengerService from src.settings import Settings logger = logging.getLogger("messenger") INSTANCE_ID = uuid4().hex def response(data: object, *, status: int = 200) -> JSONResponse: return JSONResponse( jsonable_encoder( data, custom_encoder={datetime: timestamp, UUID: str} ), status_code=status, ) async def body(request: Request, model: type[Input]) -> Input: try: data = await request.body() return model.model_validate( json.loads( data.decode("utf-8"), parse_constant=lambda _: (_ for _ in ()).throw(ValueError()), ) ) except ValueError, ValidationError, UnicodeError, RecursionError: raise invalid() from None def pagination(request: Request) -> tuple[int, str | None]: limits = request.query_params.getlist("limit") cursors = request.query_params.getlist("cursor") if len(limits) > 1 or len(cursors) > 1: raise invalid() raw = limits[0] if limits else "50" if not raw.isascii() or not raw.isdecimal(): raise invalid() raw = raw.lstrip("0") or "0" if len(raw) > 3: raise invalid() limit = int(raw) if not 1 <= limit <= 100: raise invalid() return limit, cursors[0] if cursors else None def service(request: Request) -> MessengerService: return request.app.state.service async def run_io(function, **kwargs): return await to_thread.run_sync(partial(function, **kwargs)) async def actor(request: Request): return await run_io( service(request).identify, value=request.headers.get("authorization") ) @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: settings = Settings.load() database = Database(url=settings.database_url, size=settings.pool_size) cache = UserCache(url=settings.cache_url) try: await run_io(database.open) passwords = await run_io(Passwords) app.state.database = database app.state.service = MessengerService( repository=PostgresRepository(database=database, cache=cache), passwords=passwords, session_ttl=settings.session_ttl, ) app.state.ready = True yield finally: app.state.ready = False await run_io(cache.close) await run_io(database.close) app = FastAPI( lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None ) @app.middleware("http") async def request_context(request: Request, call_next): request_id = str(uuid4()) request.state.request_id = request_id started = time.perf_counter() try: result = await call_next(request) except Exception: logger.error( json.dumps({"event": "internal_error", "request_id": request_id}) ) result = response( { "error": { "code": "internal_error", "message": "Internal error", "request_id": request_id, } }, status=500, ) result.headers["X-Request-Id"] = request_id result.headers["X-Instance-Id"] = INSTANCE_ID route = request.scope.get("route") logger.info( json.dumps( { "event": "request", "request_id": request_id, "method": request.method, "route": getattr(route, "path", "unmatched"), "status": result.status_code, "elapsed_ms": round((time.perf_counter() - started) * 1000, 3), } ) ) return result @app.exception_handler(DomainError) async def domain_error(request: Request, error: DomainError): result = response( { "error": { "code": error.code, "message": error.message, "request_id": request.state.request_id, } }, status=error.status, ) result.headers.update(error.headers) return result @app.exception_handler(HTTPException) async def http_error(request: Request, error: HTTPException): code = "not_found" if error.status_code == 404 else "invalid_request" return response( { "error": { "code": code, "message": "Resource not found" if error.status_code == 404 else "Invalid request", "request_id": request.state.request_id, } }, status=error.status_code, ) @app.get("/health/live") async def live(): return response({"status": "ok"}) @app.get("/health/ready") async def ready(): if not getattr(app.state, "ready", False): raise DomainError(503, "unavailable", "Not ready") await run_io(app.state.database.ping) return response({"status": "ok"}) @app.post("/api/v1/users") async def register(request: Request): data = await body(request, CreateUser) return response( await run_io(service(request).register, **data.model_dump()), status=201, ) @app.get("/api/v1/users/me") async def current(request: Request): return response(await actor(request)) @app.post("/api/v1/chats") async def create_chat(request: Request): user = await actor(request) data = await body(request, CreateChat) return response( await run_io( service(request).create_chat, actor_id=user.id, **data.model_dump() ), status=201, ) @app.get("/api/v1/chats") async def list_chats(request: Request): user = await actor(request) limit, cursor = pagination(request) return response( await run_io( service(request).chats, actor_id=user.id, limit=limit, cursor=cursor, ) ) @app.get("/api/v1/chats/{chat_id}") async def get_chat(request: Request, chat_id: str): user = await actor(request) return response( await run_io( service(request).get_chat, actor_id=user.id, chat_id=parse_uuid(chat_id), ) ) @app.post("/api/v1/chats/{chat_id}/messages") async def send(request: Request, chat_id: str): user = await actor(request) cid = parse_uuid(chat_id) await run_io(service(request).get_chat, actor_id=user.id, chat_id=cid) data = await body(request, CreateMessage) return response( await run_io( service(request).send, actor_id=user.id, chat_id=cid, idempotency_key=request.headers.get("idempotency-key"), **data.model_dump(), ), status=201, ) @app.get("/api/v1/chats/{chat_id}/messages") async def history(request: Request, chat_id: str): user = await actor(request) cid = parse_uuid(chat_id) await run_io(service(request).get_chat, actor_id=user.id, chat_id=cid) limit, cursor = pagination(request) return response( await run_io( service(request).history, actor_id=user.id, chat_id=cid, limit=limit, cursor=cursor, ) ) @app.post("/api/v1/auth/sessions") async def login(request: Request): return response( await run_io( service(request).login, authorization=request.headers.get("authorization"), ), status=201, ) @app.delete("/api/v1/auth/sessions/current") async def logout(request: Request): await run_io( service(request).logout, authorization=request.headers.get("authorization"), ) return Response(status_code=204)