forked from mtusi2026/mtusi2026lab3
chore: перенос решения lab2 (src, миграции, student-tests, Dockerfile, compose, lock) без изменений
Исходная точка lab3: код из solution/bvt2302-bodanyuk лабы 2, коммит ef44e48 (PR mtusi2026/mtusi2026lab2#42 принят). README, COURSE, contracts/ и tests/ преподавателя не тронуты; к Makefile дописан студенческий раздел lab2, .env.example — версия lab2. Исследование трека 2 lab2 (bench/track2) не переносилось. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
0ab3a341aa
commit
4f6cfda37a
@@ -0,0 +1,332 @@
|
||||
"""HTTP layer: Starlette routes, request-id/logging middleware and error mapping."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from starlette.applications import Starlette
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, Response
|
||||
from starlette.routing import Route
|
||||
from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Send
|
||||
|
||||
from . import authhdr, cursor, docs, passwords, repo, validation
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
from .errors import BASIC_CHALLENGE, ApiError, InvalidRequest, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .sessions import SessionStore, build_store
|
||||
from .timefmt import rfc3339
|
||||
|
||||
log = logging.getLogger("messenger")
|
||||
access_log = logging.getLogger("messenger.access")
|
||||
|
||||
REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Responses
|
||||
# --------------------------------------------------------------------------
|
||||
def error_response(request_id: str, status: int, code: str, message: str, headers: dict[str, str] | None = None) -> JSONResponse:
|
||||
body = {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
return JSONResponse(body, status_code=status, headers={"X-Request-Id": request_id, **(headers or {})})
|
||||
|
||||
|
||||
async def api_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
assert isinstance(exc, ApiError)
|
||||
return error_response(request.state.request_id, exc.status, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
async def http_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
"""Unknown routes and wrong methods also answer in the contract error format."""
|
||||
assert isinstance(exc, HTTPException)
|
||||
if exc.status_code == 404:
|
||||
return error_response(request.state.request_id, 404, "not_found", "Объект не найден")
|
||||
if exc.status_code == 405:
|
||||
return error_response(request.state.request_id, 405, "invalid_request", "Метод не поддерживается", exc.headers)
|
||||
return error_response(request.state.request_id, exc.status_code, "invalid_request", "Неверный запрос")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Middleware (pure ASGI, so it also covers 404/405 and unexpected exceptions)
|
||||
# --------------------------------------------------------------------------
|
||||
class RequestContextMiddleware:
|
||||
"""Assigns X-Request-Id to every response, writes one access-log line, turns crashes into 500."""
|
||||
|
||||
def __init__(self, app: ASGIApp):
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
incoming = dict(scope["headers"]).get(b"x-request-id", b"").decode("latin-1")
|
||||
request_id = incoming if REQUEST_ID_RE.fullmatch(incoming) else uuid.uuid4().hex
|
||||
scope.setdefault("state", {})["request_id"] = request_id
|
||||
status = 500
|
||||
started = False
|
||||
begin = time.perf_counter()
|
||||
|
||||
async def send_with_id(message: AsgiMessage) -> None:
|
||||
nonlocal status, started
|
||||
if message["type"] == "http.response.start":
|
||||
started = True
|
||||
status = message["status"]
|
||||
headers = [(k, v) for k, v in message.get("headers", []) if k.lower() != b"x-request-id"]
|
||||
headers.append((b"x-request-id", request_id.encode("latin-1")))
|
||||
message = {**message, "headers": headers}
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, send_with_id)
|
||||
except asyncio.CancelledError:
|
||||
# uvicorn cancels requests still running when SHUTDOWN_TIMEOUT_SECONDS expires:
|
||||
# answer 503 (retryable) instead of a generic 500, then let the cancellation proceed.
|
||||
if not started:
|
||||
status = 503
|
||||
response = error_response(request_id, 503, "unavailable", "Сервер завершает работу")
|
||||
await response(scope, receive, send)
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("unhandled_error", extra={"fields": {"request_id": request_id}})
|
||||
if not started:
|
||||
status = 500
|
||||
response = error_response(request_id, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
await response(scope, receive, send)
|
||||
finally:
|
||||
access_log.info("request", extra={"fields": {
|
||||
"request_id": request_id,
|
||||
"method": scope["method"],
|
||||
"path": scope["path"], # ids only; query (cursor) and bodies are never logged
|
||||
"status": status,
|
||||
"duration_ms": round((time.perf_counter() - begin) * 1000, 3),
|
||||
}})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Request helpers
|
||||
# --------------------------------------------------------------------------
|
||||
def db_of(request: Request) -> Database:
|
||||
return request.app.state.db
|
||||
|
||||
|
||||
def sessions_of(request: Request) -> SessionStore:
|
||||
return request.app.state.sessions
|
||||
|
||||
|
||||
async def authenticate(request: Request) -> str:
|
||||
"""User id of a valid Bearer session, otherwise 401. X-User-Id is ignored since lab 2.
|
||||
|
||||
Store failures are 503 (Unavailable), never 401 and never anonymous access.
|
||||
"""
|
||||
token = authhdr.parse_bearer(request.headers.get("authorization"))
|
||||
user_id = await sessions_of(request).user_id_for(token)
|
||||
if user_id is None:
|
||||
raise Unauthorized("Сессия недействительна, истекла или отозвана")
|
||||
return user_id
|
||||
|
||||
|
||||
def path_uuid(request: Request, name: str) -> str:
|
||||
return validation.parse_uuid(request.path_params[name], name)
|
||||
|
||||
|
||||
async def read_json(request: Request) -> dict[str, Any]:
|
||||
content_type = request.headers.get("content-type", "")
|
||||
media_type, _, params = content_type.partition(";")
|
||||
if media_type.strip().lower() != "application/json":
|
||||
raise InvalidRequest("Content-Type должен быть application/json")
|
||||
charset = params.strip().lower()
|
||||
if charset and charset.replace(" ", "") not in {"charset=utf-8", "charset=\"utf-8\""}:
|
||||
raise InvalidRequest("Поддерживается только кодировка UTF-8")
|
||||
limit: int = request.app.state.settings.max_body_bytes
|
||||
declared = request.headers.get("content-length")
|
||||
if declared is not None and declared.isdigit() and int(declared) > limit:
|
||||
raise PayloadTooLarge()
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise PayloadTooLarge()
|
||||
chunks.append(chunk)
|
||||
return validation.parse_json_object(b"".join(chunks))
|
||||
|
||||
|
||||
def page_params(request: Request) -> tuple[int, str | None]:
|
||||
query = request.query_params.multi_items()
|
||||
limit = validation.parse_limit(validation.single_query_param(query, "limit"))
|
||||
raw_cursor = validation.single_query_param(query, "cursor")
|
||||
if raw_cursor is not None and raw_cursor == "":
|
||||
raise InvalidRequest("cursor не может быть пустым")
|
||||
return limit, raw_cursor
|
||||
|
||||
|
||||
def ok(body: Any, status: int = 200) -> JSONResponse:
|
||||
return JSONResponse(body, status_code=status)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Handlers
|
||||
# --------------------------------------------------------------------------
|
||||
async def live(request: Request) -> JSONResponse:
|
||||
return ok({"status": "ok"})
|
||||
|
||||
|
||||
async def ready(request: Request) -> JSONResponse:
|
||||
"""200 only if the mandatory synchronous path can be served: PostgreSQL and,
|
||||
with SESSION_STORE=valkey, Valkey answer. 503 while draining after SIGTERM."""
|
||||
if request.app.state.draining:
|
||||
raise Unavailable("Сервер завершает работу")
|
||||
db_ok, store_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping())
|
||||
if not db_ok:
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
if not store_ok:
|
||||
raise Unavailable("Хранилище сессий недоступно")
|
||||
return ok({"status": "ok"})
|
||||
|
||||
|
||||
async def register_user(request: Request) -> JSONResponse:
|
||||
data = await read_json(request)
|
||||
validation.check_fields(data, {"username", "display_name", "password"})
|
||||
username = validation.username_field(data)
|
||||
display_name = validation.text_field(data, "display_name", 100)
|
||||
password = validation.password_field(data)
|
||||
password_hash = await passwords.hash_password(password)
|
||||
user = await repo.create_user(db_of(request), username, display_name, password_hash)
|
||||
log.info("user_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}})
|
||||
return ok(user.to_json(), 201)
|
||||
|
||||
|
||||
async def create_session(request: Request) -> JSONResponse:
|
||||
"""Login: only `Authorization: Basic`; wrong user and wrong password give the same 401."""
|
||||
username, password = authhdr.parse_basic(request.headers.get("authorization"))
|
||||
found = await repo.get_credentials(db_of(request), username)
|
||||
user, stored_hash = found if found else (None, None)
|
||||
if not await passwords.verify_password(stored_hash, password) or user is None:
|
||||
log.info("login_failed", extra={"fields": {"request_id": request.state.request_id}})
|
||||
raise Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE)
|
||||
ttl = request.app.state.settings.session_ttl_seconds
|
||||
token, expires_at = await sessions_of(request).create(user.id, ttl)
|
||||
log.info("session_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}})
|
||||
return ok({"token": token, "token_type": "Bearer", "expires_at": rfc3339(expires_at), "user": user.to_json()}, 201)
|
||||
|
||||
|
||||
async def revoke_session(request: Request) -> Response:
|
||||
token = authhdr.parse_bearer(request.headers.get("authorization"))
|
||||
if not await sessions_of(request).revoke(token):
|
||||
raise Unauthorized("Сессия недействительна, истекла или отозвана")
|
||||
log.info("session_revoked", extra={"fields": {"request_id": request.state.request_id}})
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
async def me(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
user = await repo.get_user(db_of(request), user_id)
|
||||
if user is None:
|
||||
raise Unauthorized("Сессия недействительна, истекла или отозвана")
|
||||
return ok(user.to_json())
|
||||
|
||||
|
||||
async def create_chat(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
data = await read_json(request)
|
||||
validation.check_fields(data, {"title", "member_ids"})
|
||||
title = validation.text_field(data, "title", 100)
|
||||
member_ids = validation.member_ids_field(data)
|
||||
chat = await repo.create_chat(db_of(request), user_id, title, member_ids)
|
||||
log.info("chat_created", extra={"fields": {"request_id": request.state.request_id, "chat_id": chat.id, "members": len(member_ids)}})
|
||||
return ok(chat.to_json(), 201)
|
||||
|
||||
|
||||
async def list_chats(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
limit, raw_cursor = page_params(request)
|
||||
after = cursor.decode(raw_cursor, cursor.CHATS, user_id) if raw_cursor else None
|
||||
items, has_more = await repo.list_chats(db_of(request), user_id, after, limit)
|
||||
next_cursor = cursor.encode(cursor.CHATS, user_id, items[-1].key) if has_more else None
|
||||
return ok({"items": [c.to_json() for c in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
async def get_chat(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
return ok((await repo.get_chat(db_of(request), user_id, chat_id)).to_json())
|
||||
|
||||
|
||||
async def create_message(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
db = db_of(request)
|
||||
await repo.ensure_member(db, user_id, chat_id) # outsiders get 404 before the body is read
|
||||
data = await read_json(request)
|
||||
validation.check_fields(data, {"text"})
|
||||
text = validation.text_field(data, "text", 4000)
|
||||
# sender_id is derived from the session, never taken from the body.
|
||||
message = await repo.add_message(db, user_id, chat_id, text)
|
||||
return ok(message.to_json(), 201)
|
||||
|
||||
|
||||
async def list_messages(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
db = db_of(request)
|
||||
await repo.ensure_member(db, user_id, chat_id) # 404 for outsiders before cursor details leak
|
||||
limit, raw_cursor = page_params(request)
|
||||
after = cursor.decode(raw_cursor, cursor.MESSAGES, chat_id) if raw_cursor else None
|
||||
items, has_more = await repo.list_messages(db, chat_id, after, limit)
|
||||
next_cursor = cursor.encode(cursor.MESSAGES, chat_id, items[-1].key) if has_more else None
|
||||
return ok({"items": [m.to_json() for m in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None) -> Starlette:
|
||||
settings = settings or Settings.from_env()
|
||||
db = Database(settings)
|
||||
sessions = build_store(settings, db)
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(app: Starlette):
|
||||
passwords.configure(settings.hash_concurrency)
|
||||
await db.open()
|
||||
log.info("dependencies_configured", extra={"fields": {
|
||||
"session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds,
|
||||
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds}})
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await sessions.close()
|
||||
await db.close()
|
||||
|
||||
routes = [
|
||||
Route("/health/live", live, methods=["GET"]),
|
||||
Route("/health/ready", ready, methods=["GET"]),
|
||||
Route("/api/v1/users", register_user, methods=["POST"]),
|
||||
Route("/api/v1/users/me", me, methods=["GET"]),
|
||||
Route("/api/v1/auth/sessions", create_session, methods=["POST"]),
|
||||
Route("/api/v1/auth/sessions/current", revoke_session, methods=["DELETE"]),
|
||||
Route("/api/v1/chats", create_chat, methods=["POST"]),
|
||||
Route("/api/v1/chats", list_chats, methods=["GET"]),
|
||||
Route("/api/v1/chats/{chat_id}", get_chat, methods=["GET"]),
|
||||
Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]),
|
||||
Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]),
|
||||
]
|
||||
if settings.docs_enabled: # Swagger UI for manual experiments, not part of the contract
|
||||
routes += [
|
||||
Route("/docs", docs.swagger_page, methods=["GET"]),
|
||||
Route("/openapi.json", docs.openapi_json, methods=["GET"]),
|
||||
]
|
||||
app = Starlette(
|
||||
routes=routes,
|
||||
exception_handlers={ApiError: api_error_handler, HTTPException: http_exception_handler},
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
app.state.settings = settings
|
||||
app.state.db = db
|
||||
app.state.sessions = sessions
|
||||
app.state.draining = False
|
||||
return app
|
||||
Reference in New Issue
Block a user