from __future__ import annotations import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager from uuid import UUID from fastapi import Depends, FastAPI, Header, Request, Response, Security from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from sqlalchemy import exc as sa_exc from starlette.exceptions import HTTPException as StarletteHTTPException from sqlalchemy.ext.asyncio import AsyncSession from app.cache import session_cache from app.db import check_database_ready, engine, get_db from app.deps import basic_scheme, pagination_params, require_user from app.errors import ( ApiError, InvalidRequest, Unavailable, api_error_handler, common_headers, incoming_request_id, ) from app.lifecycle import draining from app.models import ( Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Health, Message, MessagePage, Session, User, ) from app.services import ( create_chat, create_message, create_user_session, get_chat, list_chats, list_messages, logout_current_session, register_user, ) @asynccontextmanager async def lifespan(_app: FastAPI) -> AsyncIterator[None]: yield await session_cache.close() await engine.dispose() app = FastAPI( title="MTUSI Messenger — лабораторная 3", version="1.3.0", lifespan=lifespan, ) @app.middleware("http") async def add_request_id(request: Request, call_next): request.state.request_id = incoming_request_id(request) response = await call_next(request) response.headers.update(common_headers(request)) return response @app.exception_handler(ApiError) async def handle_api_error( request: Request, exc: Exception, ) -> JSONResponse: if not isinstance(exc, ApiError): raise exc return await api_error_handler(request, exc) @app.exception_handler(StarletteHTTPException) async def http_error_handler( request: Request, exc: StarletteHTTPException, ) -> JSONResponse: # Unknown routes/methods: the contract error format instead of # FastAPI's default {"detail": ...}. if exc.status_code == 404: error = ApiError(404, "not_found", "Route not found.") else: error = ApiError(exc.status_code, "invalid_request", "Invalid request.") return await api_error_handler(request, error) @app.exception_handler(RequestValidationError) async def validation_error_handler( request: Request, _exc: RequestValidationError, ) -> JSONResponse: return JSONResponse( status_code=400, content={ "error": { "code": "invalid_request", "message": "Invalid request.", "request_id": common_headers(request)["X-Request-Id"], } }, headers=common_headers(request), ) logger = logging.getLogger("messenger.api") def is_dependency_failure(exc: Exception) -> bool: """PostgreSQL is unreachable, restarting, overloaded or timed out.""" if isinstance( exc, ( sa_exc.OperationalError, sa_exc.InterfaceError, sa_exc.TimeoutError, # connection pool exhausted OSError, TimeoutError, ), ): return True return isinstance(exc, sa_exc.DBAPIError) and exc.connection_invalidated async def dependency_error_handler( request: Request, exc: Exception, ) -> JSONResponse: if not is_dependency_failure(exc): return await unexpected_error_handler(request, exc) logger.warning("database unavailable: %s", type(exc).__name__) return await api_error_handler(request, Unavailable()) for _exc_class in (sa_exc.DBAPIError, sa_exc.TimeoutError, OSError, TimeoutError): app.add_exception_handler(_exc_class, dependency_error_handler) @app.exception_handler(Exception) async def unexpected_error_handler( request: Request, exc: Exception, ) -> JSONResponse: headers = common_headers(request) # Only the type: SQL parameters and headers may contain secrets. logger.error("unexpected error: %s", type(exc).__name__) return JSONResponse( status_code=500, content={ "error": { "code": "internal_error", "message": "Internal server error.", "request_id": headers["X-Request-Id"], } }, headers=headers, ) @app.get( "/health/live", response_model=Health, ) async def liveness() -> dict[str, str]: return {"status": "ok"} @app.get( "/health/ready", response_model=Health, ) async def readiness() -> dict[str, str]: # A draining replica reports "not ready" so HAProxy stops sending new # requests to it before the listener is closed. if draining.is_set() or not await check_database_ready(): raise Unavailable() return {"status": "ok"} @app.post( "/api/v1/users", status_code=201, response_model=User, ) async def register_user_route( payload: CreateUser, db: AsyncSession = Depends(get_db), ): return await register_user( db, username=payload.username, display_name=payload.display_name, password=payload.password, ) @app.post( "/api/v1/auth/sessions", status_code=201, response_model=Session, ) async def login( request: Request, db: AsyncSession = Depends(get_db), _basic: None = Security(basic_scheme), ): # Contract: login takes only "Authorization: Basic", no request body. # Any body (malformed JSON, "{}", ...) is rejected before the password check. if await request.body(): raise InvalidRequest("POST /auth/sessions does not accept a request body.") return await create_user_session( db, request.headers.get("Authorization"), ) @app.delete( "/api/v1/auth/sessions/current", status_code=204, ) async def logout( request: Request, db: AsyncSession = Depends(get_db), _current_user: dict = Depends(require_user), ) -> Response: _, _, token = request.headers["Authorization"].partition(" ") await logout_current_session( db, token.strip(), ) return Response(status_code=204) @app.get( "/api/v1/users/me", response_model=User, ) async def current_user_route( current_user: dict = Depends(require_user), ): return current_user @app.post( "/api/v1/chats", status_code=201, response_model=Chat, ) async def create_chat_route( payload: CreateChat, current_user: dict = Depends(require_user), db: AsyncSession = Depends(get_db), ): return await create_chat( db, title=payload.title, member_ids=payload.member_ids, current_user=current_user, ) @app.get( "/api/v1/chats", response_model=ChatPage, ) async def list_chats_route( page: tuple[int, str | None] = Depends(pagination_params), current_user: dict = Depends(require_user), db: AsyncSession = Depends(get_db), ): limit, cursor = page return await list_chats( db, limit=limit, cursor=cursor, current_user=current_user, ) @app.get( "/api/v1/chats/{chat_id}", response_model=Chat, ) async def get_chat_route( chat_id: UUID, current_user: dict = Depends(require_user), db: AsyncSession = Depends(get_db), ): return await get_chat( db, chat_id=chat_id, current_user=current_user, ) @app.post( "/api/v1/chats/{chat_id}/messages", status_code=201, response_model=Message, ) async def create_message_route( chat_id: UUID, payload: CreateMessage, response: Response, idempotency_key: str | None = Header( default=None, alias="Idempotency-Key", ), current_user: dict = Depends(require_user), db: AsyncSession = Depends(get_db), ): message, replayed = await create_message( db, chat_id=chat_id, text_value=payload.text, idempotency_key=idempotency_key, current_user=current_user, ) if replayed: response.headers["Idempotent-Replayed"] = "true" return message @app.get( "/api/v1/chats/{chat_id}/messages", response_model=MessagePage, ) async def list_messages_route( chat_id: UUID, page: tuple[int, str | None] = Depends(pagination_params), current_user: dict = Depends(require_user), db: AsyncSession = Depends(get_db), ): limit, cursor = page return await list_messages( db, chat_id=chat_id, limit=limit, cursor=cursor, current_user=current_user, )