Files
mtusi2026lab2/app/api.py
T
User name 376f1a9a10
application / application (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
ЛР 2 — БПИ-2304 — Саламатин — на 4
2026-10-31 02:44:10 +03:00

169 lines
7.0 KiB
Python

import asyncio
from contextlib import asynccontextmanager
import json
import logging
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
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
try:
await store.open()
yield
finally:
await store.close()
app = FastAPI(title="Lab 2 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(5):
response = await call_next(request)
except (psycopg.Error, PoolTimeout, TooManyRequests, RedisError, TimeoutError):
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
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()
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)
return await app.state.store.create_message(user["id"], chat_id, await body(request, CreateMessage))
@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.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()