This commit is contained in:
2026-09-30 12:13:29 +03:00
parent 6bc82eaa2a
commit f4198de3c8
45 changed files with 4027 additions and 875 deletions
+285 -160
View File
@@ -1,40 +1,20 @@
"""
Lab1: In-memory API мессенджера.
Реализует 7 обязательных эндпоинтов по contracts/openapi.json:
GET /health/live
GET /health/ready
POST /api/v1/users
GET /api/v1/users/me
POST /api/v1/chats
GET /api/v1/chats
GET /api/v1/chats/{chat_id}
POST /api/v1/chats/{chat_id}/messages
GET /api/v1/chats/{chat_id}/messages
from __future__ import annotations
Конфигурация (host/port/log-level) приходит из окружения — см. app/config.py.
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from uuid import UUID, uuid4
Запуск через Docker (см. Dockerfile):
uvicorn app.main:app --host ${APP_HOST} --port ${APP_PORT}
Запуск напрямую (для локальной отладки без контейнера):
python -m app.main
"""
import uuid
from typing import Optional
from fastapi import Depends, FastAPI, Request
from fastapi import Depends, FastAPI, Request, Response, Security
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.responses import JSONResponse
from sqlalchemy import exc as sa_exc
from sqlalchemy.ext.asyncio import AsyncSession
from app import config
from app.deps import pagination_params, require_user
from app.errors import (
ApiError,
api_error_handler,
http_error_handler,
unhandled_error_handler,
validation_error_handler,
)
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, Unavailable, api_error_handler
from app.models import (
Chat,
ChatPage,
@@ -44,161 +24,306 @@ from app.models import (
Health,
Message,
MessagePage,
Session,
User,
)
from app.storage import storage
from pathlib import Path
from app.services import (
create_chat,
create_message,
create_user_session,
get_chat,
list_chats,
list_messages,
logout_current_session,
register_user,
)
app = FastAPI(title="MTUSI Messenger Lab1", version="1.0.0")
app.add_exception_handler(ApiError, api_error_handler)
app.add_exception_handler(RequestValidationError, validation_error_handler)
app.add_exception_handler(StarletteHTTPException, http_error_handler)
app.add_exception_handler(Exception, unhandled_error_handler)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
yield
await session_cache.close()
await engine.dispose()
app = FastAPI(
title="MTUSI Messenger — лабораторная 2",
version="1.2.0",
lifespan=lifespan,
)
@app.middleware("http")
async def add_request_id(request: Request, call_next):
request.state.request_id = str(uuid.uuid4())
request.state.request_id = (
request.headers.get("X-Request-Id")
or str(uuid4())
)
response = await call_next(request)
response.headers["X-Request-Id"] = request.state.request_id
return response
# ---------- Health ----------
@app.exception_handler(ApiError)
async def handle_api_error(
request: Request,
exc: Exception,
) -> JSONResponse:
if not isinstance(exc, ApiError):
raise exc
@app.get("/health/live", response_model=Health)
async def liveness():
return Health(status="ok")
return await api_error_handler(request, exc)
@app.get("/health/ready", response_model=Health)
async def readiness():
# В Lab1 нет внешних зависимостей (БД появится в Lab2), поэтому
# процесс всегда готов, если он успешно поднялся.
return Health(status="ok")
@app.exception_handler(RequestValidationError)
async def validation_error_handler(
request: Request,
_exc: RequestValidationError,
) -> JSONResponse:
request_id = getattr(request.state, "request_id", str(uuid4()))
@app.get("/internal/metrics")
async def internal_metrics():
return {
"rss_bytes": process_rss_bytes(),
**storage.counts(),
}
def process_rss_bytes() -> int:
try:
for line in Path("/proc/self/status").read_text(encoding="utf-8").splitlines():
if line.startswith("VmRSS:"):
return int(line.split()[1]) * 1024
except OSError:
pass
return 0
# ---------- Пользователи ----------
@app.post("/api/v1/users", response_model=User, status_code=201)
async def register_user(payload: CreateUser):
user = storage.create_user(payload.username, payload.display_name)
if user is None:
raise ApiError(409, "Username is already taken.")
return user
return JSONResponse(
status_code=400,
content={
"error": {
"code": "invalid_request",
"message": "Invalid request.",
"request_id": request_id,
}
},
headers={
"X-Request-Id": request_id,
},
)
@app.get("/api/v1/users/me", response_model=User)
async def current_user(user: dict = Depends(require_user)):
return user
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
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
async def create_chat(payload: CreateChat, user: dict = Depends(require_user)):
member_ids = [str(m) for m in payload.member_ids]
if user["id"] not in member_ids:
raise ApiError(400, "Caller must be included in member_ids.")
for member_id in member_ids:
if storage.get_user(member_id) is None:
raise ApiError(400, f"Unknown member_id: {member_id}")
chat = storage.create_chat(payload.title, member_ids)
return chat
return isinstance(exc, sa_exc.DBAPIError) and exc.connection_invalidated
@app.get("/api/v1/chats", response_model=ChatPage)
async def list_chats(
user: dict = Depends(require_user),
pagination: tuple[int, Optional[str]] = Depends(pagination_params),
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:
request_id = getattr(request.state, "request_id", str(uuid4()))
# 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": request_id,
}
},
headers={
"X-Request-Id": request_id,
},
)
@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]:
if 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),
):
limit, cursor = pagination
try:
items, next_cursor = storage.list_chats_for_user(user["id"], limit, cursor)
except ValueError:
raise ApiError(400, "Invalid cursor.")
return ChatPage(items=items, next_cursor=next_cursor)
return await register_user(
db,
username=payload.username,
display_name=payload.display_name,
password=payload.password,
)
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
async def get_chat(chat_id: str, user: dict = Depends(require_user)):
try:
uuid.UUID(chat_id)
except ValueError:
raise ApiError(400, "chat_id must be a valid UUID.")
chat = storage.get_chat(chat_id)
if chat is None or user["id"] not in chat["member_ids"]:
raise ApiError(404, "Chat 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, payload: CreateMessage, user: dict = Depends(require_user)):
try:
uuid.UUID(chat_id)
except ValueError:
raise ApiError(400, "chat_id must be a valid UUID.")
chat = storage.get_chat(chat_id)
if chat is None or user["id"] not in chat["member_ids"]:
raise ApiError(404, "Chat not found.")
message = storage.create_message(chat_id, user["id"], payload.text)
return message
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
async def list_messages(
chat_id: str,
user: dict = Depends(require_user),
pagination: tuple[int, Optional[str]] = Depends(pagination_params),
@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),
):
try:
uuid.UUID(chat_id)
except ValueError:
raise ApiError(400, "chat_id must be a valid UUID.")
return await create_user_session(
db,
request.headers.get("Authorization"),
)
chat = storage.get_chat(chat_id)
if chat is None or user["id"] not in chat["member_ids"]:
raise ApiError(404, "Chat not found.")
limit, cursor = pagination
try:
items, next_cursor = storage.list_messages(chat_id, limit, cursor)
except ValueError:
raise ApiError(400, "Invalid cursor.")
return MessagePage(items=items, next_cursor=next_cursor)
@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(" ")
def process_rss_bytes() -> int:
try:
for line in Path("/proc/self/status").read_text(encoding="utf-8").splitlines():
if line.startswith("VmRSS:"):
return int(line.split()[1]) * 1024
except OSError:
pass
return 0
await logout_current_session(
db,
token.strip(),
)
if __name__ == "__main__":
import uvicorn
return Response(status_code=204)
uvicorn.run(app, host=config.HOST, port=config.PORT, log_level=config.LOG_LEVEL)
@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,
current_user: dict = Depends(require_user),
db: AsyncSession = Depends(get_db),
):
return await create_message(
db,
chat_id=chat_id,
text_value=payload.text,
current_user=current_user,
)
@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,
)