Files
mtusi2026lab6/app/main.py
T

462 lines
12 KiB
Python

from __future__ import annotations
import asyncio
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from uuid import UUID
from typing import Literal
from fastapi import Depends, FastAPI, Header, Query, Request, Response, Security
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from sqlalchemy import exc as sa_exc
from starlette.exceptions import HTTPException as StarletteHTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.attachments import (
get_attachment,
janitor_loop,
open_attachment_content,
upload_attachment,
)
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,
)
from app.lifecycle import draining
from app.config import settings
from app.telemetry import HttpTelemetryMiddleware, configure, shutdown
from app.models import (
Attachment,
Chat,
ChatPage,
CreateChat,
CreateMessage,
CreateUser,
Health,
Message,
MessagePage,
Session,
User,
)
from app.storage import storage
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]:
configure("messenger-api", settings.instance_id)
await storage.start()
janitor = asyncio.create_task(janitor_loop())
try:
yield
finally:
janitor.cancel()
await asyncio.gather(janitor, return_exceptions=True)
await storage.close()
await session_cache.close()
await engine.dispose()
await asyncio.to_thread(shutdown)
app = FastAPI(
title="MTUSI Messenger — лабораторная 6",
version="1.6.0",
lifespan=lifespan,
)
@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.
# S3 is deliberately NOT checked: without it only attachments degrade
# (503), users/chats/messages keep working. If readiness depended on S3,
# an S3 outage would take every replica out of the LB.
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,
attachment_ids=payload.attachment_ids,
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,
)
UPLOAD_BODY = {
"requestBody": {
"required": True,
"description": "Raw image bytes, not multipart and not JSON/base64.",
"content": {
"image/png": {"schema": {"type": "string", "format": "binary"}},
"image/jpeg": {"schema": {"type": "string", "format": "binary"}},
},
}
}
@app.post(
"/api/v1/chats/{chat_id}/attachments",
status_code=202,
response_model=Attachment,
openapi_extra=UPLOAD_BODY,
)
async def upload_attachment_route(
chat_id: UUID,
request: Request,
filename: str = Query(min_length=1, max_length=255),
current_user: dict = Depends(require_user),
db: AsyncSession = Depends(get_db),
):
return await upload_attachment(
request,
db,
chat_id=chat_id,
filename=filename,
current_user=current_user,
)
@app.get(
"/api/v1/attachments/{attachment_id}",
response_model=Attachment,
)
async def get_attachment_route(
attachment_id: UUID,
current_user: dict = Depends(require_user),
db: AsyncSession = Depends(get_db),
):
return await get_attachment(
db,
attachment_id=attachment_id,
current_user=current_user,
)
@app.get(
"/api/v1/attachments/{attachment_id}/content",
response_class=StreamingResponse,
responses={200: {"content": {"image/png": {}, "image/jpeg": {}, "image/webp": {}}}},
)
async def download_attachment_route(
attachment_id: UUID,
# Known variant names are accepted so that a ready attachment without
# that variant answers 404 (contract); any other value is 400.
variant: Literal["original", "thumbnail", "crop", "optimized"] = Query(
default="original"
),
current_user: dict = Depends(require_user),
db: AsyncSession = Depends(get_db),
):
chunks, headers = await open_attachment_content(
db,
attachment_id=attachment_id,
variant=variant,
current_user=current_user,
)
return StreamingResponse(
chunks,
media_type=headers.pop("Content-Type"),
headers=headers,
)
# Wrap outside FastAPI ServerErrorMiddleware to observe its final 500 response.
app = HttpTelemetryMiddleware(app)