forked from mtusi2026/mtusi2026lab2
Перенос lab1
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""MTUSI Messenger — лабораторная 1 (in-memory)."""
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Единый формат ошибок API и исключение ApiError."""
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
"""Ошибка, которую нужно вернуть клиенту в формате контракта."""
|
||||
|
||||
def __init__(self, status: int, code: str, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
def error_body(code: str, message: str, request_id: str) -> dict[str, Any]:
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
"""HTTP-обработчики FastAPI для lab1."""
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Body, Header, Query, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .errors import ApiError
|
||||
from .store import Store
|
||||
from .validation import (
|
||||
encode_cursor,
|
||||
parse_cursor,
|
||||
parse_limit,
|
||||
validate_chat_id,
|
||||
validate_create_chat,
|
||||
validate_create_message,
|
||||
validate_create_user,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def get_store(request: Request) -> Store:
|
||||
return request.app.state.store
|
||||
|
||||
|
||||
def current_user_id(request: Request, x_user_id: str | None) -> str:
|
||||
"""lab1: X-User-Id — идентификатор существующего пользователя."""
|
||||
if not x_user_id:
|
||||
raise ApiError(401, "unauthorized", "Требуется X-User-Id")
|
||||
store = get_store(request)
|
||||
if store.get_user(x_user_id) is None:
|
||||
raise ApiError(401, "unauthorized", "Неизвестный пользователь")
|
||||
return x_user_id
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
def health_live() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
def health_ready() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/api/v1/users", status_code=201)
|
||||
def register_user(request: Request, body: Any = Body(...)) -> JSONResponse:
|
||||
username, display_name = validate_create_user(body)
|
||||
store = get_store(request)
|
||||
user = store.create_user(username, display_name)
|
||||
if user is None:
|
||||
raise ApiError(409, "conflict", "username уже занят")
|
||||
return JSONResponse(user, status_code=201)
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me")
|
||||
def current_user(request: Request, x_user_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
user_id = current_user_id(request, x_user_id)
|
||||
user = get_store(request).get_user(user_id)
|
||||
assert user is not None
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/api/v1/chats", status_code=201)
|
||||
def create_chat(
|
||||
request: Request,
|
||||
body: Any = Body(...),
|
||||
x_user_id: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
title, member_ids = validate_create_chat(body, caller)
|
||||
store = get_store(request)
|
||||
for mid in member_ids:
|
||||
if store.get_user(mid) is None:
|
||||
raise ApiError(400, "invalid_request", "Неизвестный участник чата")
|
||||
chat = store.create_chat(title, member_ids)
|
||||
return JSONResponse(chat, status_code=201)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats")
|
||||
def list_chats(
|
||||
request: Request,
|
||||
limit: str | None = Query(default=None),
|
||||
cursor: str | None = Query(default=None),
|
||||
x_user_id: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
page_size = parse_limit(limit)
|
||||
scope = f"chats:{caller}"
|
||||
after = parse_cursor(cursor, scope)
|
||||
items = get_store(request).list_chats_for(caller)
|
||||
if after is not None:
|
||||
items = [c for c in items if (c["created_at"], c["id"]) > after]
|
||||
page = items[:page_size]
|
||||
next_cursor = None
|
||||
if len(items) > page_size and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(last["created_at"], last["id"], scope)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
x_user_id: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
chat_id = validate_chat_id(chat_id)
|
||||
chat = get_store(request).get_chat(chat_id)
|
||||
if chat is None or caller not in chat["member_ids"]:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return chat
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
body: Any = Body(...),
|
||||
x_user_id: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
chat_id = validate_chat_id(chat_id)
|
||||
store = get_store(request)
|
||||
chat = store.get_chat(chat_id)
|
||||
if chat is None or caller not in chat["member_ids"]:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
text = validate_create_message(body)
|
||||
message = store.add_message(chat_id, caller, text)
|
||||
return JSONResponse(message, status_code=201)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
limit: str | None = Query(default=None),
|
||||
cursor: str | None = Query(default=None),
|
||||
x_user_id: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
chat_id = validate_chat_id(chat_id)
|
||||
store = get_store(request)
|
||||
chat = store.get_chat(chat_id)
|
||||
if chat is None or caller not in chat["member_ids"]:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
page_size = parse_limit(limit)
|
||||
scope = f"messages:{chat_id}"
|
||||
after = parse_cursor(cursor, scope)
|
||||
items = store.list_messages(chat_id)
|
||||
if after is not None:
|
||||
items = [m for m in items if (m["created_at"], m["id"]) > after]
|
||||
page = items[:page_size]
|
||||
next_cursor = None
|
||||
if len(items) > page_size and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(last["created_at"], last["id"], scope)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
"""Точка входа: FastAPI-приложение, middleware и обработка ошибок."""
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .errors import ApiError, error_body
|
||||
from .handlers import router
|
||||
from .store import Store
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.1.0")
|
||||
app.state.store = Store()
|
||||
app.include_router(router)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except ApiError as exc:
|
||||
response = JSONResponse(
|
||||
error_body(exc.code, exc.message, request_id),
|
||||
status_code=exc.status,
|
||||
)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return JSONResponse(
|
||||
error_body(exc.code, exc.message, request_id),
|
||||
status_code=exc.status,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return JSONResponse(
|
||||
error_body("invalid_request", "Некорректный запрос", request_id),
|
||||
status_code=400,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_error_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
||||
"""Ошибки разбора тела (невалидный JSON/байты) FastAPI отдаёт как HTTPException 400."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
if exc.status_code == 400:
|
||||
return JSONResponse(
|
||||
error_body("invalid_request", "Некорректный запрос", request_id),
|
||||
status_code=400,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
return JSONResponse(
|
||||
error_body("not_found" if exc.status_code == 404 else "internal_error",
|
||||
str(exc.detail), request_id),
|
||||
status_code=exc.status_code,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.exception("unhandled error request_id=%s", request_id)
|
||||
return JSONResponse(
|
||||
error_body("internal_error", "Внутренняя ошибка", request_id),
|
||||
status_code=500,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import uvicorn
|
||||
|
||||
host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
port = int(os.environ.get("APP_PORT", "8080"))
|
||||
uvicorn.run(app, host=host, port=port, log_level="info")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Потокобезопасное in-memory хранилище пользователей, чатов и сообщений."""
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
"""RFC 3339 UTC с суффиксом Z, секунды — как в примерах контракта."""
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
class Store:
|
||||
"""Все данные живут в памяти одного процесса и исчезают при рестарте."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
self.users: dict[str, dict[str, Any]] = {}
|
||||
self.usernames: dict[str, str] = {}
|
||||
self.chats: dict[str, dict[str, Any]] = {}
|
||||
self.messages: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
# --- пользователи -----------------------------------------------------
|
||||
def create_user(self, username: str, display_name: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
if username in self.usernames:
|
||||
return None # сигнал конфликта
|
||||
user = {
|
||||
"id": new_id(),
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"created_at": utc_now(),
|
||||
}
|
||||
self.users[user["id"]] = user
|
||||
self.usernames[username] = user["id"]
|
||||
return dict(user)
|
||||
|
||||
def get_user(self, user_id: str) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
user = self.users.get(user_id)
|
||||
return dict(user) if user else None
|
||||
|
||||
# --- чаты -------------------------------------------------------------
|
||||
def create_chat(self, title: str, member_ids: list[str]) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
chat = {
|
||||
"id": new_id(),
|
||||
"title": title,
|
||||
"member_ids": list(member_ids),
|
||||
"created_at": utc_now(),
|
||||
}
|
||||
self.chats[chat["id"]] = chat
|
||||
self.messages[chat["id"]] = []
|
||||
return dict(chat)
|
||||
|
||||
def get_chat(self, chat_id: str) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
chat = self.chats.get(chat_id)
|
||||
return dict(chat) if chat else None
|
||||
|
||||
def list_chats_for(self, user_id: str) -> list[dict[str, Any]]:
|
||||
with self._lock:
|
||||
items = [dict(c) for c in self.chats.values() if user_id in c["member_ids"]]
|
||||
items.sort(key=lambda c: (c["created_at"], c["id"]))
|
||||
return items
|
||||
|
||||
# --- сообщения --------------------------------------------------------
|
||||
def add_message(self, chat_id: str, sender_id: str, text: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
message = {
|
||||
"id": new_id(),
|
||||
"chat_id": chat_id,
|
||||
"sender_id": sender_id,
|
||||
"text": text,
|
||||
"created_at": utc_now(),
|
||||
}
|
||||
self.messages.setdefault(chat_id, []).append(message)
|
||||
return dict(message)
|
||||
|
||||
def list_messages(self, chat_id: str) -> list[dict[str, Any]]:
|
||||
with self._lock:
|
||||
items = [dict(m) for m in self.messages.get(chat_id, [])]
|
||||
items.sort(key=lambda m: (m["created_at"], m["id"]))
|
||||
return items
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Валидация тел запросов и параметров вручную, без pydantic-моделей контракта."""
|
||||
import base64
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from .errors import ApiError
|
||||
|
||||
USERNAME_RE = re.compile(r"\A[a-z0-9_]{3,32}\Z")
|
||||
|
||||
# Уникальный идентификатор жизни процесса: cursors, выданные до рестарта,
|
||||
# становятся недействительными.
|
||||
CURSOR_EPOCH = uuid.uuid4().hex
|
||||
|
||||
|
||||
def _is_blank(value: str) -> bool:
|
||||
return value.strip() == ""
|
||||
|
||||
|
||||
def require_object(body: Any) -> dict[str, Any]:
|
||||
if not isinstance(body, dict):
|
||||
raise ApiError(400, "invalid_request", "Тело запроса должно быть JSON-объектом")
|
||||
return body
|
||||
|
||||
|
||||
def reject_extra(body: dict[str, Any], allowed: set[str]) -> None:
|
||||
if set(body) - allowed:
|
||||
raise ApiError(400, "invalid_request", "Неизвестные поля в теле запроса")
|
||||
|
||||
|
||||
def validate_create_user(body: Any) -> tuple[str, str]:
|
||||
body = require_object(body)
|
||||
reject_extra(body, {"username", "display_name"})
|
||||
username = body.get("username")
|
||||
display_name = body.get("display_name")
|
||||
if not isinstance(username, str) or not USERNAME_RE.match(username):
|
||||
raise ApiError(400, "invalid_request", "Некорректный username")
|
||||
if not isinstance(display_name, str) or not (1 <= len(display_name) <= 100) or _is_blank(display_name):
|
||||
raise ApiError(400, "invalid_request", "Некорректный display_name")
|
||||
return username, display_name
|
||||
|
||||
|
||||
def validate_create_chat(body: Any, caller_id: str) -> tuple[str, list[str]]:
|
||||
body = require_object(body)
|
||||
reject_extra(body, {"title", "member_ids"})
|
||||
title = body.get("title")
|
||||
member_ids = body.get("member_ids")
|
||||
if not isinstance(title, str) or not (1 <= len(title) <= 100) or _is_blank(title):
|
||||
raise ApiError(400, "invalid_request", "Некорректный title")
|
||||
if not isinstance(member_ids, list) or not (1 <= len(member_ids) <= 100):
|
||||
raise ApiError(400, "invalid_request", "member_ids должен быть непустым массивом")
|
||||
seen: set[str] = set()
|
||||
for mid in member_ids:
|
||||
if not isinstance(mid, str):
|
||||
raise ApiError(400, "invalid_request", "member_ids содержит не строку")
|
||||
try:
|
||||
uuid.UUID(mid)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "member_ids содержит не UUID")
|
||||
if mid in seen:
|
||||
raise ApiError(400, "invalid_request", "member_ids содержит дубликаты")
|
||||
seen.add(mid)
|
||||
if caller_id not in seen:
|
||||
raise ApiError(400, "invalid_request", "Вызывающий должен входить в member_ids")
|
||||
return title, list(member_ids)
|
||||
|
||||
|
||||
def validate_create_message(body: Any) -> str:
|
||||
body = require_object(body)
|
||||
reject_extra(body, {"text"})
|
||||
text = body.get("text")
|
||||
if not isinstance(text, str) or not (1 <= len(text) <= 4000) or _is_blank(text):
|
||||
raise ApiError(400, "invalid_request", "Некорректный text")
|
||||
return text
|
||||
|
||||
|
||||
def validate_chat_id(raw: str) -> str:
|
||||
"""chat_id в пути должен быть UUID, иначе 400 invalid_request."""
|
||||
try:
|
||||
uuid.UUID(raw)
|
||||
except (ValueError, TypeError):
|
||||
raise ApiError(400, "invalid_request", "Некорректный chat_id")
|
||||
return raw
|
||||
|
||||
|
||||
def parse_limit(raw: str | None, default: int = 50) -> int:
|
||||
if raw is None:
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ApiError(400, "invalid_request", "limit должен быть целым числом")
|
||||
if not (1 <= value <= 100):
|
||||
raise ApiError(400, "invalid_request", "limit вне диапазона 1..100")
|
||||
return value
|
||||
|
||||
|
||||
def parse_cursor(raw: str | None, scope: str) -> tuple[str, str] | None:
|
||||
"""Cursor — непрозрачная строка base64url от 'epoch|scope|created_at|id'.
|
||||
|
||||
Cursor привязан к ресурсу (scope) и к жизни процесса (epoch).
|
||||
"""
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
decoded = base64.urlsafe_b64decode(raw.encode("ascii")).decode("utf-8")
|
||||
except Exception:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
parts = decoded.split("|")
|
||||
if len(parts) != 4:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
epoch, cursor_scope, created_at, item_id = parts
|
||||
if epoch != CURSOR_EPOCH or cursor_scope != scope:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
if not created_at or not item_id:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
return created_at, item_id
|
||||
|
||||
|
||||
def encode_cursor(created_at: str, item_id: str, scope: str) -> str:
|
||||
raw = "|".join([CURSOR_EPOCH, scope, created_at, item_id]).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
Reference in New Issue
Block a user