Перенос lab1

This commit is contained in:
Evgeny Bushkov
2026-10-23 18:02:07 +03:00
parent 65003b6119
commit 3e152d4175
8 changed files with 762 additions and 0 deletions
+1
View File
@@ -30,3 +30,4 @@ coverage/
.vscode/
# Keep small, sanitized evidence summaries in evidence/ under version control.
# Inspect git diff --cached: ignore rules are not a secret scanner.
.aider*
+1
View File
@@ -0,0 +1 @@
"""MTUSI Messenger — лабораторная 1 (in-memory)."""
+16
View File
@@ -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
View File
@@ -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
View File
@@ -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()
+88
View File
@@ -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
+122
View File
@@ -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")
+276
View File
@@ -0,0 +1,276 @@
#!/usr/bin/env python3
"""Собственные тесты уровня 4: негативные сценарии и конкурентная запись.
Запуск: python3 tests/test_unit.py
Требует запущенный сервер (по умолчанию http://localhost:8080).
"""
import argparse
import base64
import json
import os
import sys
import threading
import unittest
import urllib.error
import urllib.request
import uuid
_parser = argparse.ArgumentParser(description="Собственные тесты уровня 4")
_parser.add_argument("--base-url", default=None)
_args, _unknown = _parser.parse_known_args()
# unittest.main() читает sys.argv сам и не знает про --base-url — убираем его.
sys.argv = [sys.argv[0]] + _unknown
BASE_URL = (
_args.base_url
or os.environ.get("BASE_URL")
or "http://localhost:8080"
).rstrip("/")
def request(method, path, body=None, user_id=None, raw=None, content_type="application/json"):
headers = {"Accept": "application/json"}
if user_id:
headers["X-User-Id"] = user_id
data = None
if raw is not None:
data = raw
headers["Content-Type"] = content_type
elif body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(BASE_URL + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
payload = resp.read()
return resp.status, json.loads(payload) if payload else None
except urllib.error.HTTPError as err:
payload = err.read()
return err.code, json.loads(payload) if payload else None
def make_user(label):
username = "u_" + label + "_" + uuid.uuid4().hex[:10]
status, user = request("POST", "/api/v1/users", {"username": username, "display_name": "Тест " + label})
assert status == 201, (status, user)
return user
class MessengerTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.alice = make_user("alice")
cls.bob = make_user("bob")
cls.eve = make_user("eve")
status, chat = request(
"POST",
"/api/v1/chats",
{"title": "Тестовый чат", "member_ids": [cls.alice["id"], cls.bob["id"]]},
user_id=cls.alice["id"],
)
assert status == 201, (status, chat)
cls.chat = chat
def test_invalid_json(self):
status, body = request(
"POST",
"/api/v1/chats/" + self.chat["id"] + "/messages",
raw=b"{not json",
user_id=self.alice["id"],
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
def test_foreign_chat_returns_404(self):
status, body = request("GET", "/api/v1/chats/" + self.chat["id"], user_id=self.eve["id"])
self.assertEqual(status, 404)
self.assertEqual(body["error"]["code"], "not_found")
def test_empty_message_rejected(self):
status, body = request(
"POST",
"/api/v1/chats/" + self.chat["id"] + "/messages",
{"text": " "},
user_id=self.alice["id"],
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
def test_duplicate_username(self):
username = "u_dup_" + uuid.uuid4().hex[:10]
first = request("POST", "/api/v1/users", {"username": username, "display_name": "Первый"})
self.assertEqual(first[0], 201)
second = request("POST", "/api/v1/users", {"username": username, "display_name": "Второй"})
self.assertEqual(second[0], 409)
self.assertEqual(second[1]["error"]["code"], "conflict")
def test_pagination_walks_all_pages(self):
chat = request(
"POST",
"/api/v1/chats",
{"title": "Пагинация", "member_ids": [self.alice["id"], self.bob["id"]]},
user_id=self.alice["id"],
)[1]
sent = []
for i in range(7):
status, msg = request(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
{"text": "msg-%d" % i},
user_id=self.alice["id"],
)
self.assertEqual(status, 201)
sent.append(msg["id"])
collected = []
cursor = None
while True:
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=2"
if cursor:
path += "&cursor=" + cursor
status, page = request("GET", path, user_id=self.bob["id"])
self.assertEqual(status, 200)
collected.extend(m["id"] for m in page["items"])
cursor = page["next_cursor"]
if not cursor:
break
self.assertEqual(collected, sent)
def test_cursor_bound_to_resource(self):
chat_a = request(
"POST",
"/api/v1/chats",
{"title": "Cursor A", "member_ids": [self.alice["id"], self.bob["id"]]},
user_id=self.alice["id"],
)[1]
chat_b = request(
"POST",
"/api/v1/chats",
{"title": "Cursor B", "member_ids": [self.alice["id"], self.bob["id"]]},
user_id=self.alice["id"],
)[1]
for i in range(3):
request(
"POST",
"/api/v1/chats/" + chat_a["id"] + "/messages",
{"text": "a-%d" % i},
user_id=self.alice["id"],
)
status, page = request(
"GET",
"/api/v1/chats/" + chat_a["id"] + "/messages?limit=1",
user_id=self.alice["id"],
)
self.assertEqual(status, 200)
cursor = page["next_cursor"]
self.assertIsNotNone(cursor)
status, body = request(
"GET",
"/api/v1/chats/" + chat_b["id"] + "/messages?limit=1&cursor=" + cursor,
user_id=self.alice["id"],
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
def test_cursor_bound_to_endpoint(self):
status, page = request(
"GET", "/api/v1/chats?limit=1", user_id=self.alice["id"]
)
self.assertEqual(status, 200)
cursor = page["next_cursor"]
self.assertIsNotNone(cursor)
status, body = request(
"GET",
"/api/v1/chats/" + self.chat["id"] + "/messages?limit=1&cursor=" + cursor,
user_id=self.alice["id"],
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
def test_cursor_garbage_rejected(self):
garbage = base64.urlsafe_b64encode(b"x|y").decode("ascii")
status, body = request(
"GET",
"/api/v1/chats/" + self.chat["id"] + "/messages?cursor=" + garbage,
user_id=self.alice["id"],
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
def test_invalid_chat_id_returns_400(self):
status, body = request("GET", "/api/v1/chats/not-a-uuid", user_id=self.alice["id"])
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
status, body = request(
"POST",
"/api/v1/chats/not-a-uuid/messages",
{"text": "hi"},
user_id=self.alice["id"],
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
status, body = request(
"GET", "/api/v1/chats/not-a-uuid/messages", user_id=self.alice["id"]
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
def test_username_with_trailing_newline_rejected(self):
status, body = request(
"POST",
"/api/v1/users",
{"username": "abc\n", "display_name": "Имя"},
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
def test_invalid_body_bytes_contract_error(self):
status, body = request(
"POST",
"/api/v1/users",
raw=b"\xff",
user_id=self.alice["id"],
)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
self.assertIn("message", body["error"])
self.assertIn("request_id", body["error"])
def test_concurrent_writes_are_unique(self):
chat = request(
"POST",
"/api/v1/chats",
{"title": "Конкурентность", "member_ids": [self.alice["id"], self.bob["id"]]},
user_id=self.alice["id"],
)[1]
errors = []
lock = threading.Lock()
def worker(worker_id):
for i in range(10):
status, body = request(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
{"text": "w%d-%d" % (worker_id, i)},
user_id=self.alice["id"],
)
if status != 201:
with lock:
errors.append((status, body))
threads = [threading.Thread(target=worker, args=(w,)) for w in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
self.assertEqual(errors, [])
status, page = request(
"GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", user_id=self.alice["id"]
)
self.assertEqual(status, 200)
ids = [m["id"] for m in page["items"]]
self.assertEqual(len(ids), 100)
self.assertEqual(len(set(ids)), 100)
if __name__ == "__main__":
unittest.main(verbosity=2)