"""Мессенджер, лабораторная 3: балансировка, X-Instance-Id, идемпотентность.""" import logging import re import uuid from contextlib import asynccontextmanager from typing import NamedTuple import anyio.to_thread import psycopg from fastapi import Depends, FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse, Response from starlette.exceptions import HTTPException as StarletteHTTPException from app import config, cursor, db, idempotency, repo, security, sessions, validation from app.errors import BASIC_CHALLENGE, BEARER_CHALLENGE, ApiError, bad_request, not_found, unauthorized logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") log = logging.getLogger("api") _REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}") # Уникальный ID инстанса для X-Instance-Id INSTANCE_ID = config.INSTANCE_ID @asynccontextmanager async def lifespan(_app): anyio.to_thread.current_default_thread_limiter().total_tokens = config.THREAD_LIMIT yield db.close() app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) def make_error(code, message, request_id): return {"error": {"code": code, "message": message, "request_id": request_id}} def _rid(request): return getattr(request.state, "request_id", None) or uuid.uuid4().hex def error_response(request, status, code, message, headers=None): rid = _rid(request) out = {"X-Request-Id": rid, "Cache-Control": "no-store"} out.update(headers or {}) return JSONResponse(status_code=status, content=make_error(code, message, rid), headers=out) @app.middleware("http") async def add_request_id(request: Request, call_next): incoming = request.headers.get("X-Request-Id", "") rid = incoming if _REQUEST_ID_RE.fullmatch(incoming) else uuid.uuid4().hex request.state.request_id = rid response = await call_next(request) response.headers["X-Request-Id"] = rid response.headers["X-Instance-Id"] = INSTANCE_ID # <--- НОВОЕ В LAB3 response.headers["Cache-Control"] = "no-store" return response @app.exception_handler(ApiError) async def api_error_handler(request: Request, exc: ApiError): return error_response(request, exc.status, exc.code, exc.message, exc.headers) @app.exception_handler(RequestValidationError) async def validation_handler(request: Request, exc): return error_response(request, 400, "invalid_request", "Некорректный запрос") @app.exception_handler(StarletteHTTPException) async def http_exc_handler(request: Request, exc: StarletteHTTPException): mapping = {404: ("not_found", "Объект не найден"), 405: ("invalid_request", "Метод не поддерживается")} code, message = mapping.get(exc.status_code, ("invalid_request", "Ошибка запроса")) return error_response(request, exc.status_code, code, message) @app.exception_handler(Exception) async def generic_handler(request: Request, exc: Exception): if isinstance(exc, db.TRANSIENT): log.warning("dependency unavailable [%s]: %s", _rid(request), type(exc).__name__) return error_response(request, 503, "unavailable", "Сервис временно недоступен") log.error("unhandled error [%s]", _rid(request), exc_info=exc) return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера") class Auth(NamedTuple): user: dict user_id: uuid.UUID digest: bytes def authenticated(request: Request) -> Auth: token = security.parse_bearer(request.headers.get("Authorization")) if token is None: raise unauthorized(BEARER_CHALLENGE) found = sessions.lookup(token) if found is None: raise unauthorized(BEARER_CHALLENGE) return Auth(found["user"], uuid.UUID(found["user"]["id"]), found["digest"]) class RawBody(NamedTuple): content_type: str data: bytes async def raw_body(request: Request) -> RawBody: declared = request.headers.get("content-length") if declared is not None and declared.isdigit() and int(declared) > config.MAX_BODY_BYTES: raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") chunks, size = [], 0 async for chunk in request.stream(): size += len(chunk) if size > config.MAX_BODY_BYTES: raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") chunks.append(chunk) return RawBody(request.headers.get("content-type", ""), b"".join(chunks)) @app.get("/health/live") def live(): return {"status": "ok"} @app.get("/health/ready") def ready(): db.ping() return {"status": "ok"} @app.post("/api/v1/users", status_code=201) def create_user(body: RawBody = Depends(raw_body)): data = validation.json_body(body.content_type, body.data, {"username", "display_name", "password"}, {"username", "display_name", "password"}) username = validation.username_field(data["username"]) display_name = validation.text_field(data["display_name"], "display_name", 1, 100) password = validation.text_field(data["password"], "password", 12, 128) with db.connection() as conn: if repo.username_exists(conn, username): raise ApiError(409, "conflict", "Имя пользователя занято") password_hash = security.hash_password(password) try: with db.connection() as conn: row = repo.insert_user(conn, username, display_name, password_hash) except psycopg.errors.UniqueViolation: raise ApiError(409, "conflict", "Имя пользователя занято") return sessions.user_json(row) @app.get("/api/v1/users/me") def get_me(auth: Auth = Depends(authenticated)): return auth.user @app.post("/api/v1/auth/sessions", status_code=201) def login(request: Request): creds = security.parse_basic(request.headers.get("Authorization")) if creds is None: raise unauthorized(BASIC_CHALLENGE) username, password = creds with db.connection() as conn: user = repo.user_for_login(conn, username) if validation._USERNAME_RE.fullmatch(username) else None if user is None: security.burn_verify(password) raise unauthorized(BASIC_CHALLENGE) ok, new_hash = security.verify_password(user["password_hash"], password) if not ok: raise unauthorized(BASIC_CHALLENGE) with db.connection() as conn: if new_hash: repo.update_password_hash(conn, user["id"], new_hash) token, expires_at = sessions.create(conn, user) user_json = sessions.user_json(user) sessions.warm(token, user_json, expires_at) return {"token": token, "token_type": "Bearer", "expires_at": sessions.fmt_ts(expires_at), "user": user_json} @app.delete("/api/v1/auth/sessions/current") def logout(auth: Auth = Depends(authenticated)): sessions.revoke(auth.digest) return Response(status_code=204) @app.post("/api/v1/chats", status_code=201) def create_chat(auth: Auth = Depends(authenticated), body: RawBody = Depends(raw_body)): data = validation.json_body(body.content_type, body.data, {"title", "member_ids"}, {"title", "member_ids"}) title = validation.text_field(data["title"], "title", 1, 100) raw = data["member_ids"] if not isinstance(raw, list) or not 1 <= len(raw) <= 100: raise bad_request("member_ids: от 1 до 100 элементов") members = [validation.require_uuid(x, "member_id") for x in raw] if len(set(members)) != len(members) or auth.user_id not in members: raise bad_request("member_ids должны быть уникальны и включать вызывающего") with db.connection() as conn: chat = repo.create_chat(conn, auth.user_id, title, members) return repo.chat_json(chat) @app.get("/api/v1/chats") def list_chats(request: Request, auth: Auth = Depends(authenticated)): limit = validation.limit_param(request.query_params) raw = request.query_params.get("cursor") after = cursor.decode(raw, "chats", auth.user_id) if raw is not None else None with db.connection() as conn: items, nxt = repo.list_chats(conn, auth.user_id, after, limit) return {"items": items, "next_cursor": nxt} @app.get("/api/v1/chats/{chat_id}") def get_chat(chat_id: str, auth: Auth = Depends(authenticated)): cid = validation.require_uuid(chat_id, "chat_id") with db.connection() as conn: chat = repo.get_chat(conn, cid, auth.user_id) if chat is None: raise not_found() return repo.chat_json(chat) @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) def create_message(chat_id: str, request: Request, auth: Auth = Depends(authenticated), body: RawBody = Depends(raw_body)): cid = validation.require_uuid(chat_id, "chat_id") # 1. Проверка доступа (до блокировок, чтобы не держать лок зря) with db.connection() as conn: if not repo.is_member(conn, cid, auth.user_id): raise not_found() # 2. Валидация тела data = validation.json_body(body.content_type, body.data, {"text"}, {"text"}) text = validation.text_field(data["text"], "text", 1, 4000) # 3. Идемпотентность idem_key = request.headers.get("Idempotency-Key") path = f"/api/v1/chats/{chat_id}/messages" req_hash = idempotency.get_request_hash(data) with db.connection() as conn: # Очистка старых ключей idempotency.cleanup(conn, config.IDEMPOTENCY_TTL_SECONDS) # Проверка и захват блокировки (pg_advisory_xact_lock) need_exec, cached_resp = idempotency.check_and_lock( conn, str(auth.user_id), "POST", path, idem_key, req_hash ) if not need_exec: return JSONResponse(status_code=201, content=cached_resp) # Создание сообщения msg = repo.insert_message(conn, cid, auth.user_id, text) msg_json = repo.message_json(msg) # Сохранение ответа для будущих повторов idempotency.save_result( conn, str(auth.user_id), "POST", path, idem_key, req_hash, 201, msg_json ) return msg_json @app.get("/api/v1/chats/{chat_id}/messages") def list_messages(chat_id: str, request: Request, auth: Auth = Depends(authenticated)): cid = validation.require_uuid(chat_id, "chat_id") limit = validation.limit_param(request.query_params) raw = request.query_params.get("cursor") after = cursor.decode(raw, "messages", cid) if raw is not None else None with db.connection() as conn: if not repo.is_member(conn, cid, auth.user_id): raise not_found() items, nxt = repo.list_messages(conn, cid, after, limit) return {"items": items, "next_cursor": nxt}