Files
mtusi2026lab2/app/main.py

204 lines
7.3 KiB
Python

from __future__ import annotations
import logging
import uuid
from contextlib import asynccontextmanager
from typing import Optional
import asyncpg
from fastapi import Depends, FastAPI, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from app import auth, config
from app.cache import SessionCache
from app.errors import ApiError
from app.models import Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Health, Message, MessagePage, Session, User
from app.storage import Store
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("messenger")
store = Store()
cache = SessionCache(config.CACHE_URL)
@asynccontextmanager
async def lifespan(_app: FastAPI):
if not config.DATABASE_URL:
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
await store.open()
logger.info("session cache: %s", "valkey" if cache.enabled else "disabled")
yield
await cache.close()
await store.close()
app = FastAPI(title="MTUSI Messenger — lab2", lifespan=lifespan)
DB_UNAVAILABLE = (
OSError,
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.TooManyConnectionsError,
asyncpg.exceptions.OperatorInterventionError,
asyncpg.exceptions.QueryCanceledError,
)
def error_body(code: str, message: str, request_id: str) -> dict:
return {"error": {"code": code, "message": message, "request_id": request_id}}
def error_response(request: Request, status: int, code: str, message: str, headers: Optional[dict] = None) -> JSONResponse:
request_id = getattr(request.state, "request_id", "")
return JSONResponse(status_code=status, content=error_body(code, message, request_id), headers=headers)
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request_id = uuid.uuid4().hex
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
logger.exception("unhandled error for request_id=%s", request_id)
response = JSONResponse(status_code=500, content=error_body("internal_error", "internal error", request_id))
response.headers["X-Request-Id"] = request_id
return response
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return error_response(request, exc.status_code, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(request, 400, "invalid_request", "request failed validation")
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
code = {404: "not_found", 405: "invalid_request", 415: "unsupported_media_type"}.get(exc.status_code, "invalid_request")
message = exc.detail if isinstance(exc.detail, str) else "request failed"
return error_response(request, exc.status_code, code, message)
async def db_unavailable_handler(request: Request, exc: Exception):
logger.warning("database unavailable for request_id=%s: %s", request.state.request_id, type(exc).__name__)
return error_response(request, 503, "unavailable", "service temporarily unavailable")
for _exc in DB_UNAVAILABLE:
app.add_exception_handler(_exc, db_unavailable_handler)
async def current_user(request: Request) -> dict:
return await auth.authenticate(store, cache, request.headers.get("Authorization"))
def parse_uuid(value: str, field: str) -> uuid.UUID:
try:
return uuid.UUID(value)
except ValueError:
raise ApiError(400, "invalid_request", f"{field} is not a valid UUID") from None
def not_found() -> ApiError:
return ApiError(404, "not_found", "chat not found")
@app.get("/health/live", response_model=Health)
async def liveness():
return Health()
@app.get("/health/ready", response_model=Health)
async def readiness():
try:
await store.ping()
except DB_UNAVAILABLE:
raise ApiError(503, "unavailable", "database is not available") from None
return Health()
@app.post("/api/v1/users", response_model=User, status_code=201)
async def register_user(body: CreateUser):
if not body.display_name.strip() or not body.password.strip():
raise ApiError(400, "invalid_request", "display_name and password must not be blank")
password_hash = await auth.hash_password(body.password)
return await store.create_user(body.username, body.display_name, password_hash)
@app.get("/api/v1/users/me", response_model=User)
async def current_user_endpoint(user: dict = Depends(current_user)):
return user
@app.post("/api/v1/auth/sessions", response_model=Session, status_code=201)
async def create_session(request: Request):
return await auth.login(store, request.headers.get("Authorization"))
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def delete_session(request: Request):
await auth.logout(store, cache, request.headers.get("Authorization"))
return Response(status_code=204)
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
if not body.title.strip():
raise ApiError(400, "invalid_request", "title must not be blank")
if len(set(body.member_ids)) != len(body.member_ids):
raise ApiError(400, "invalid_request", "member_ids must not contain duplicates")
if uuid.UUID(user["id"]) not in body.member_ids:
raise ApiError(400, "invalid_request", "caller must be a member of the chat")
return await store.create_chat(body.title, list(body.member_ids))
@app.get("/api/v1/chats", response_model=ChatPage)
async def list_chats(
user: dict = Depends(current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None, min_length=1),
):
return await store.list_chats(uuid.UUID(user["id"]), limit, cursor)
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
async def get_chat(chat_id: str, user: dict = Depends(current_user)):
chat = await store.get_chat_for_member(parse_uuid(chat_id, "chat_id"), uuid.UUID(user["id"]))
if chat is None:
raise not_found()
return chat
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
async def create_message(chat_id: str, body: CreateMessage, user: dict = Depends(current_user)):
chat_uuid = parse_uuid(chat_id, "chat_id")
if not body.text.strip():
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
raise not_found()
raise ApiError(400, "invalid_request", "text must not be blank")
message = await store.create_message(chat_uuid, uuid.UUID(user["id"]), body.text)
if message is None:
raise not_found()
return message
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
async def list_messages(
chat_id: str,
user: dict = Depends(current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None, min_length=1),
):
chat_uuid = parse_uuid(chat_id, "chat_id")
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
raise not_found()
return await store.list_messages(chat_uuid, limit, cursor)