import base64 import json import logging import re import sys import time import uuid from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import datetime, timedelta, timezone from uuid import UUID import psycopg import redis import uvicorn from fastapi import Depends, FastAPI, Query, Request, Response from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException import config import security from errors import ApiError, bad_credentials, error_response, invalid, not_found, unauthorized from schemas import CreateChat, CreateMessage, CreateUser from sessions import Sessions from store import TIME_FORMAT, Store, UnknownMember, UsernameTaken, timestamp logging.basicConfig( level=config.LOG_LEVEL.upper(), format="%(asctime)s %(levelname)s %(name)s: %(message)s", stream=sys.stdout, ) log = logging.getLogger("messenger") if config.SESSION_STORE != "redis": sys.exit("поддерживается только SESSION_STORE=redis") USERNAME = re.compile(r"[a-z0-9_]{3,32}") store = Store(config.database_url()) sessions = Sessions(config.cache_url()) @asynccontextmanager async def lifespan(app: FastAPI): store.open() log.info( "started env=%s listen=%s:%d session_ttl=%ds db_pool_max=%d", config.ENV, config.HOST, config.PORT, config.SESSION_TTL_SECONDS, config.DB_POOL_MAX_SIZE, ) yield store.close() sessions.close() log.info("stopped") app = FastAPI(title="MTUSI Messenger lab2", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) @app.middleware("http") async def request_context(request: Request, call_next): request_id = uuid.uuid4().hex request.state.request_id = request_id started = time.perf_counter() try: response = await call_next(request) except Exception: log.exception("unhandled error request_id=%s", request_id) response = error_response(request_id, 500, "internal_error", "Внутренняя ошибка сервера") response.headers["X-Request-Id"] = request_id # в лог идут только метод, путь и код ответа: тела запросов, пароли и токены не пишем log.info( "%s %s status=%d duration_ms=%.1f request_id=%s", request.method, request.url.path, response.status_code, (time.perf_counter() - started) * 1000, request_id, ) return response @app.exception_handler(ApiError) async def on_api_error(request: Request, exc: ApiError): return error_response(request.state.request_id, exc.status, exc.code, exc.message, exc.headers) @app.exception_handler(RequestValidationError) async def on_validation_error(request: Request, exc: RequestValidationError): first = exc.errors()[0] where = ".".join(str(part) for part in first["loc"]) return error_response(request.state.request_id, 400, "invalid_request", f"{where}: {first['msg']}") @app.exception_handler(HTTPException) async def on_http_error(request: Request, exc: HTTPException): # сюда попадают ошибки самого фреймворка: неизвестный путь, неподдерживаемый метод if exc.status_code == 404: code, message = "not_found", "Объект не найден" else: code, message = "invalid_request", "Запрос не поддерживается" return error_response(request.state.request_id, exc.status_code, code, message, exc.headers) # OperationalError — нет связи с PostgreSQL, не дождались соединения из пула или сработал statement_timeout @app.exception_handler(psycopg.OperationalError) async def on_database_down(request: Request, exc: Exception): log.warning("postgres unavailable: %s request_id=%s", type(exc).__name__, request.state.request_id) return error_response(request.state.request_id, 503, "unavailable", "Сервис временно недоступен") @app.exception_handler(redis.RedisError) async def on_cache_down(request: Request, exc: Exception): log.warning("redis unavailable: %s request_id=%s", type(exc).__name__, request.state.request_id) return error_response(request.state.request_id, 503, "unavailable", "Сервис временно недоступен") @dataclass class Session: user_id: str token: str def current_session(request: Request) -> Session: # X-User-Id из lab1 здесь не читается вообще, Basic на бизнес-запросах тоже не принимается token = security.parse_bearer(request.headers.get("Authorization")) if token is None: raise unauthorized() # если Redis недоступен, здесь будет исключение и ответ 503: без проверки сессии запрос дальше не идёт user_id = sessions.user_id(token) if user_id is None: raise unauthorized() return Session(user_id, token) def encode_cursor(scope: str, created_at: str, item_id: str) -> str: raw = json.dumps([scope, created_at, item_id]) return base64.urlsafe_b64encode(raw.encode()).decode() def decode_cursor(scope: str, cursor): """Возвращает ключ (created_at, id) последней выданной записи или None для первой страницы.""" if cursor is None: return None try: # validate=True: символ вне алфавита base64 — ошибка, а не пропускается молча cursor_scope, created_at, item_id = json.loads(base64.b64decode(cursor, altchars=b"-_", validate=True)) # время и id принимаются только в том виде, в котором их выдаёт сам сервер moment = datetime.strptime(created_at, TIME_FORMAT).replace(tzinfo=timezone.utc) time_ok = moment.strftime(TIME_FORMAT) == created_at id_ok = str(UUID(item_id)) == item_id except (TypeError, ValueError, AttributeError): raise invalid("Некорректный cursor") # cursor действует только для того списка, в котором был выдан if cursor_scope != scope or not time_ok or not id_ok: raise invalid("Некорректный cursor") # у одной позиции есть ровно одна запись cursor: другое оформление JSON или base64 не принимается if encode_cursor(scope, created_at, item_id) != cursor: raise invalid("Некорректный cursor") return [moment, item_id] def page(scope: str, items: list, has_more: bool) -> dict: next_cursor = encode_cursor(scope, items[-1]["created_at"], items[-1]["id"]) if has_more else None return {"items": items, "next_cursor": next_cursor} @app.get("/health/live") def liveness(): return {"status": "ok"} @app.get("/health/ready") def readiness(): # без PostgreSQL и Redis обязательные запросы не выполнить, поэтому обе зависимости критичны store.ping() sessions.ping() return {"status": "ok"} @app.post("/api/v1/users", status_code=201) def register_user(body: CreateUser): try: return store.create_user(body.username, body.display_name, security.hash_password(body.password)) except UsernameTaken: raise ApiError(409, "conflict", "Такой username уже занят") @app.post("/api/v1/auth/sessions", status_code=201) def create_session(request: Request): credentials = security.parse_basic(request.headers.get("Authorization")) if credentials is None: raise bad_credentials() username, password = credentials user, password_hash = None, None # username, который не мог быть зарегистрирован, в БД не ищем, но пароль всё равно сверяем с пустышкой if USERNAME.fullmatch(username): user, password_hash = store.get_credentials(username) if not security.verify_password(password_hash, password): raise bad_credentials() token = sessions.create(user["id"]) expires_at = datetime.now(timezone.utc) + timedelta(seconds=config.SESSION_TTL_SECONDS) return {"token": token, "token_type": "Bearer", "expires_at": timestamp(expires_at), "user": user} @app.delete("/api/v1/auth/sessions/current", status_code=204) def revoke_session(session: Session = Depends(current_session)): sessions.revoke(session.token) return Response(status_code=204) @app.get("/api/v1/users/me") def get_me(session: Session = Depends(current_session)): user = store.get_user(session.user_id) if user is None: raise unauthorized() return user @app.post("/api/v1/chats", status_code=201) def create_chat(body: CreateChat, session: Session = Depends(current_session)): member_ids = [str(member) for member in body.member_ids] if len(set(member_ids)) != len(member_ids): raise invalid("member_ids содержит повторы") if session.user_id not in member_ids: raise invalid("Создатель чата должен быть в member_ids") try: return store.create_chat(body.title, member_ids) except UnknownMember: raise invalid("В member_ids есть несуществующий пользователь") @app.get("/api/v1/chats") def list_chats( limit: int = Query(50, ge=1, le=100), cursor: str | None = Query(None, min_length=1), session: Session = Depends(current_session), ): scope = "chats:" + session.user_id items, has_more = store.list_chats(session.user_id, decode_cursor(scope, cursor), limit) return page(scope, items, has_more) @app.get("/api/v1/chats/{chat_id}") def get_chat(chat_id: UUID, session: Session = Depends(current_session)): chat = store.get_chat(str(chat_id), session.user_id) if chat is None: raise not_found() return chat @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) def send_message(chat_id: UUID, body: CreateMessage, session: Session = Depends(current_session)): # отправитель берётся из сессии, в теле запроса его нет message = store.add_message(str(chat_id), session.user_id, body.text) if message is None: raise not_found() return message @app.get("/api/v1/chats/{chat_id}/messages") def list_messages( chat_id: UUID, limit: int = Query(50, ge=1, le=100), cursor: str | None = Query(None, min_length=1), session: Session = Depends(current_session), ): scope = "messages:" + str(chat_id) result = store.list_messages(str(chat_id), session.user_id, decode_cursor(scope, cursor), limit) if result is None: raise not_found() items, has_more = result return page(scope, items, has_more) if __name__ == "__main__": uvicorn.run( app, host=config.HOST, port=config.PORT, log_level=config.LOG_LEVEL, access_log=False, timeout_graceful_shutdown=config.SHUTDOWN_TIMEOUT, )