import asyncio from contextlib import asynccontextmanager import json import logging import os from pathlib import Path import re from time import perf_counter from uuid import uuid4 from fastapi import Depends, FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from fastapi.responses import Response import psycopg from psycopg_pool import PoolTimeout, TooManyRequests from redis.exceptions import RedisError from pydantic import ValidationError from starlette.exceptions import HTTPException from .config import Settings from .errors import APIError, invalid, unavailable from .models import CreateChat, CreateMessage, CreateUser from .security import basic_credentials, identifier from .store import Store from .attachments import Attachments, metadata from botocore.exceptions import BotoCoreError, ClientError from starlette.requests import ClientDisconnect logger = logging.getLogger("messenger") def error_response(request, status, code, message, headers=None): return JSONResponse(status_code=status, headers=headers, content={"error": { "code": code, "message": message, "request_id": request.state.request_id}}) async def body(request, model): content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() if content_type != "application/json": raise APIError(415, "unsupported_media_type", "Use application/json") try: raw = (await request.body()).decode("utf-8") def reject_constant(value): raise ValueError("Nonstandard JSON constant") data = json.loads(raw, parse_constant=reject_constant) return model.model_validate(data) except (ValueError, UnicodeError, ValidationError): raise invalid("Body must be valid UTF-8 JSON with the required fields and types") from None def pagination(request): raw = request.query_params.get("limit", "50") if re.fullmatch(r"[0-9]+", raw) is None or len(raw) > 3 or not 1 <= int(raw) <= 100: raise invalid("Limit must be an integer from 1 to 100") return int(raw), request.query_params.get("cursor") def create_app(settings=None): @asynccontextmanager async def lifespan(app): store = Store(settings or Settings.load()) app.state.store = store app.state.attachments = Attachments(store) try: await store.open() yield finally: await store.close() instance_id = os.getenv("HOSTNAME", "api") + "-" + uuid4().hex[:12] app = FastAPI(title="Lab 4 messenger", docs_url=None, redoc_url=None, openapi_url=None, redirect_slashes=False, lifespan=lifespan) @app.middleware("http") async def request_context(request, call_next): request.state.request_id = str(uuid4()) start = perf_counter() try: async with asyncio.timeout(35): response = await call_next(request) except (psycopg.Error, PoolTimeout, TooManyRequests, RedisError, BotoCoreError, ClientError, TimeoutError, ClientDisconnect): error = unavailable() logger.warning("Storage unavailable request_id=%s", request.state.request_id) response = error_response(request, error.status, error.code, error.message) except Exception: logger.error("Unhandled error request_id=%s", request.state.request_id) response = error_response(request, 500, "internal_error", "Internal server error") response.headers["X-Request-Id"] = request.state.request_id response.headers["X-Instance-Id"] = instance_id response.headers["X-App-Version"] = os.getenv("APP_VERSION", "lab3-v1") logger.info("request_id=%s method=%s path=%s status=%s duration_ms=%.2f", request.state.request_id, request.method, request.url.path, response.status_code, (perf_counter() - start) * 1000) return response @app.exception_handler(APIError) async def api_error(request, error): return error_response(request, error.status, error.code, error.message, error.headers) @app.exception_handler(RequestValidationError) async def validation_error(request, error): return error_response(request, 400, "invalid_request", "Invalid request parameters") @app.exception_handler(HTTPException) async def routing_error(request, error): code = "not_found" if error.status_code == 404 else "invalid_request" return error_response(request, error.status_code, code, "Unknown path or unsupported method") async def current_user(request: Request): user, token = await app.state.store.authenticate(request.headers.get("authorization")) request.state.session_token = token return user @app.get("/health/live") async def health(): return {"status": "ok"} @app.get("/health/ready") async def readiness(): await app.state.store.ready() await asyncio.to_thread(app.state.attachments.s3.head_bucket, Bucket="attachments") return {"status": "ok"} @app.post("/api/v1/auth/sessions", status_code=201) async def login(request: Request): credentials = basic_credentials(request.headers.get("authorization")) if await request.body(): raise invalid("Session creation does not accept a body") return await app.state.store.login(*credentials) @app.delete("/api/v1/auth/sessions/current", status_code=204) async def logout(request: Request, user=Depends(current_user)): await app.state.store.logout(request.state.session_token) return Response(status_code=204) @app.post("/api/v1/users", status_code=201) async def create_user(request: Request): return await app.state.store.create_user(await body(request, CreateUser)) @app.get("/api/v1/users/me") async def me(user=Depends(current_user)): return user @app.post("/api/v1/chats", status_code=201) async def create_chat(request: Request, user=Depends(current_user)): return await app.state.store.create_chat(user["id"], await body(request, CreateChat)) @app.get("/api/v1/chats") async def list_chats(request: Request, user=Depends(current_user)): return await app.state.store.list_chats(user["id"], *pagination(request)) @app.get("/api/v1/chats/{chat_id}") async def get_chat(chat_id: str, user=Depends(current_user)): return await app.state.store.get_chat(user["id"], identifier(chat_id)) @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) async def create_message(chat_id: str, request: Request, user=Depends(current_user)): chat_id = identifier(chat_id) await app.state.store.get_chat(user["id"], chat_id) key = request.headers.get("idempotency-key", "") if re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key, flags=re.ASCII) is None: raise invalid("A valid Idempotency-Key is required") return await app.state.store.create_message(user["id"], chat_id, await body(request, CreateMessage), key) @app.get("/api/v1/chats/{chat_id}/messages") async def list_messages(chat_id: str, request: Request, user=Depends(current_user)): chat_id = identifier(chat_id) await app.state.store.get_chat(user["id"], chat_id) return await app.state.store.list_messages(user["id"], chat_id, *pagination(request)) @app.post("/api/v1/chats/{chat_id}/attachments", status_code=201) async def upload(chat_id: str, request: Request, user=Depends(current_user)): return await app.state.attachments.upload(user["id"], identifier(chat_id), request) @app.get("/api/v1/attachments/{attachment_id}") async def attachment(attachment_id: str, user=Depends(current_user)): return metadata(await app.state.attachments.get(user["id"], identifier(attachment_id))) @app.get("/api/v1/attachments/{attachment_id}/content") async def content(attachment_id: str, request: Request, user=Depends(current_user)): row = await app.state.attachments.get(user["id"], identifier(attachment_id)) if request.query_params.get("variant", "original") != "original": raise APIError(404, "not_found", "Variant not found") return await app.state.attachments.download(row) @app.get("/openapi.json", include_in_schema=False) async def contract(): path = Path(__file__).resolve().parents[1] / "contracts" / "openapi.json" return json.loads(path.read_text(encoding="utf-8")) return app app = create_app()