import hashlib import json import logging import tempfile import time from collections.abc import AsyncIterator from contextlib import asynccontextmanager from datetime import datetime from functools import partial from urllib.parse import quote from uuid import UUID, uuid4 from anyio import Semaphore, fail_after, to_thread from fastapi import FastAPI, Request from fastapi.encoders import jsonable_encoder from pydantic import ValidationError from starlette.exceptions import HTTPException from starlette.requests import ClientDisconnect from starlette.responses import JSONResponse, Response, StreamingResponse from src import images from src.attachments import Attachments 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.object_store import ObjectStore 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) store = ObjectStore() try: await run_io(database.open) passwords = await run_io(Passwords) app.state.database = database app.state.store = store app.state.upload_slots = Semaphore(2) app.state.attachments = Attachments( database=database, store=store, instance=INSTANCE_ID ) 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(store.close) 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) await run_io(app.state.store.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) chat = 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=chat, 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) @app.post("/api/v1/chats/{chat_id}/attachments") async def upload(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) names = request.query_params.getlist("filename") if len(names) != 1: raise invalid() name = images.filename(names[0]) declared = ( request.headers.get("content-type", "") .partition(";")[0] .strip() .lower() ) if declared not in {"image/png", "image/jpeg"}: raise DomainError( 415, "unsupported_media_type", "PNG or JPEG required" ) length = request.headers.get("content-length") if length and (not length.isdecimal() or len(length) > 12): raise invalid() if length and int(length) > images.MAX_BYTES: raise DomainError(413, "payload_too_large", "Byte limit exceeded") try: with fail_after(20): async with app.state.upload_slots: with tempfile.SpooledTemporaryFile( max_size=1024 * 1024, mode="w+b" ) as stream: size = 0 digest = hashlib.sha256() async for chunk in request.stream(): size += len(chunk) if size > images.MAX_BYTES: raise DomainError( 413, "payload_too_large", "Byte limit exceeded" ) digest.update(chunk) stream.write(chunk) await run_io( images.verify, stream=stream, declared=declared ) result = await run_io( app.state.attachments.upload, chat_id=cid, owner_id=user.id, filename=name, content_type=declared, size=size, sha256=digest.hexdigest(), stream=stream, ) return response(result, status=201) except ClientDisconnect: raise invalid() from None except TimeoutError: raise DomainError( 503, "unavailable", "Upload deadline exceeded" ) from None @app.get("/api/v1/attachments/{attachment_id}") async def attachment_metadata(request: Request, attachment_id: str): user = await actor(request) return response( await run_io( app.state.attachments.metadata, identity=parse_uuid(attachment_id), actor_id=user.id, ) ) @app.get("/api/v1/attachments/{attachment_id}/content") async def attachment_content(request: Request, attachment_id: str): user = await actor(request) variants = request.query_params.getlist("variant") if len(variants) > 1: raise invalid() row, upstream = await run_io( app.state.attachments.content, identity=parse_uuid(attachment_id), actor_id=user.id, variant=variants[0] if variants else "original", ) def chunks(): try: while data := upstream.read(65536): yield data finally: upstream.close() upstream.release_conn() return StreamingResponse( chunks(), media_type=row["content_type"], headers={ "Content-Length": str(row["size_bytes"]), "Content-Disposition": "inline; filename*=UTF-8''" + quote(row["filename"], safe=""), }, )