import os import uuid from contextvars import ContextVar from typing import Optional from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.middleware.base import BaseHTTPMiddleware from .models import CreateChat, CreateMessage, CreateUser from .storage import storage request_id_var: ContextVar[str] = ContextVar("request_id", default="") def err(status_code: int, code: str, message: str) -> JSONResponse: return JSONResponse( status_code=status_code, content={ "error": { "code": code, "message": message, "request_id": request_id_var.get(), } }, ) class RequestIdMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex request_id_var.set(rid) response = await call_next(request) response.headers["X-Request-Id"] = rid return response app = FastAPI(title="MTUSI Messenger — lab1") app.add_middleware(RequestIdMiddleware) # ---------- exception handlers ---------- _HTTP_CODES = { 400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type", 429: "rate_limited", 503: "unavailable", 500: "internal_error", } @app.exception_handler(RequestValidationError) async def _validation_handler(request: Request, exc: RequestValidationError): # пустое сообщение, limit=0, чужой json и т.п. return err(400, "invalid_request", "Validation error") @app.exception_handler(HTTPException) async def _http_handler(request: Request, exc: HTTPException): code = _HTTP_CODES.get(exc.status_code, "internal_error") message = exc.detail if isinstance(exc.detail, str) and exc.detail else "Error" return err(exc.status_code, code, message) @app.exception_handler(Exception) async def _generic_handler(request: Request, exc: Exception): # ноль деталей -> ошибка return err(500, "internal_error", "Internal server error") # dependency def get_actor(x_user_id: Optional[str] = Header(None, alias="X-User-Id")) -> dict: if not x_user_id: raise HTTPException(401, "Unauthorized") user = storage.get_user(x_user_id) if user is None: raise HTTPException(401, "Unauthorized") return user # health @app.get("/health/live") def health_live(): return {"status": "ok"} @app.get("/health/ready") def health_ready(): return {"status": "ok"} # users @app.post("/api/v1/users", status_code=201) def create_user(body: CreateUser): user = storage.create_user(body.username, body.display_name) if user is None: raise HTTPException(409, "Username already exists") return user @app.get("/api/v1/users/me") def current_user(actor: dict = Depends(get_actor)): return actor # chats @app.post("/api/v1/chats", status_code=201) def create_chat(body: CreateChat, actor: dict = Depends(get_actor)): if actor["id"] not in body.member_ids: raise HTTPException(400, "Caller must be in member_ids") chat, error = storage.create_chat(body.title, body.member_ids, actor["id"]) if error == "member_not_found": raise HTTPException(404, "Member not found") if error: raise HTTPException(400, error) return chat @app.get("/api/v1/chats") def list_chats( actor: dict = Depends(get_actor), limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = Query(None, min_length=1), ): items, next_cursor = storage.list_chats(actor["id"], limit, cursor) return {"items": items, "next_cursor": next_cursor} @app.get("/api/v1/chats/{chat_id}") def get_chat(chat_id: str, actor: dict = Depends(get_actor)): chat = storage.get_chat(chat_id, actor["id"]) if chat is None: raise HTTPException(404, "Chat not found") return chat # messages @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) def post_message( chat_id: str, body: CreateMessage, actor: dict = Depends(get_actor), ): msg, error = storage.post_message(chat_id, actor["id"], body.text) if error == "chat_not_found": raise HTTPException(404, "Chat not found") if error: raise HTTPException(400, error) return msg @app.get("/api/v1/chats/{chat_id}/messages") def list_messages( chat_id: str, actor: dict = Depends(get_actor), limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = Query(None, min_length=1), ): items, next_cursor, error = storage.list_messages( chat_id, actor["id"], limit, cursor ) if error == "chat_not_found": raise HTTPException(404, "Chat not found") return {"items": items, "next_cursor": next_cursor} if __name__ == "__main__": import uvicorn port = int(os.getenv("PORT", "8080")) uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")