chore: перенос решения lab1 (src, student-tests, Dockerfile, lock) без изменений

Исходная точка lab2: код из solution/bvt2302-bodanyuk лабы 1, коммит 472c1bd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alexey Bodanyuk
2026-10-12 19:05:00 +03:00
co-authored by Claude Opus 5.5
parent 65003b6119
commit 893beaa79a
20 changed files with 1696 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
"""In-memory messenger for lab 1 (MTUSI, «Высоконагруженные приложения»)."""
__version__ = "1.0.0"
+64
View File
@@ -0,0 +1,64 @@
"""Entry point: `python -m messenger`. The HTTP server is the main process (PID 1 in Docker).
Shutdown sequence on SIGTERM/SIGINT:
1. readiness flips to 503 (`app.state.draining = True`);
2. uvicorn closes the listening socket, so new connections are refused;
3. in-flight requests get up to SHUTDOWN_TIMEOUT_SECONDS (default 8 s < Docker's 10 s) to finish;
4. the process exits with code 0. In-memory data is lost by design.
"""
from __future__ import annotations
import logging
import sys
from types import FrameType
import uvicorn
from . import __version__, logging_setup
from .app import create_app
from .config import ConfigError, Settings
log = logging.getLogger("messenger")
class GracefulServer(uvicorn.Server):
"""uvicorn.Server that marks the app as draining before the normal graceful stop."""
def handle_exit(self, sig: int, frame: FrameType | None) -> None:
if not self.should_exit:
log.info("shutdown_requested", extra={"fields": {"signal": sig, "timeout_s": self.config.timeout_graceful_shutdown}})
self.config.app.state.draining = True # config.app is our Starlette instance
super().handle_exit(sig, frame)
def main() -> int:
try:
settings = Settings.from_env()
except ConfigError as exc:
print(f"configuration error: {exc}", file=sys.stderr)
return 2
logging_setup.configure(settings.log_level)
app = create_app(settings)
config = uvicorn.Config(
app,
host=settings.host,
port=settings.port,
log_config=None,
access_log=False,
server_header=False,
proxy_headers=False,
lifespan="off",
timeout_graceful_shutdown=settings.shutdown_timeout,
)
server = GracefulServer(config)
log.info("starting", extra={"fields": {
"version": __version__, "env": settings.env, "host": settings.host, "port": settings.port,
"python": sys.version.split()[0], "storage": "in-memory (single process)",
}})
server.run()
log.info("stopped", extra={"fields": {"state": app.state.store.counts(), "note": "in-memory data discarded"}})
return 0
if __name__ == "__main__":
sys.exit(main())
+271
View File
@@ -0,0 +1,271 @@
"""HTTP layer: Starlette routes, request-id/logging middleware and error mapping."""
from __future__ import annotations
import asyncio
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
from starlette.routing import Route
from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Send
from . import cursor, docs, validation
from .config import Settings
from .errors import ApiError, InvalidRequest, PayloadTooLarge, Unauthorized, Unavailable
from .store import Store, User
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)
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 store_of(request: Request) -> Store:
return request.app.state.store
def current_user(request: Request) -> User:
"""Lab 1 identification: X-User-Id must be the UUID of an existing user, otherwise 401."""
raw = request.headers.get("x-user-id")
if raw is None or validation.UUID_RE.fullmatch(raw) is None:
raise Unauthorized()
user = store_of(request).get_user(raw.lower())
if user is None:
raise Unauthorized()
return user
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:
# The only critical dependency is process memory; while draining after
# SIGTERM the instance reports 503 so no new traffic is routed to it.
if request.app.state.draining:
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"})
username = validation.username_field(data)
display_name = validation.text_field(data, "display_name", 100)
user = store_of(request).create_user(username, display_name)
log.info("user_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}})
return ok(user.to_json(), 201)
async def me(request: Request) -> JSONResponse:
return ok(current_user(request).to_json())
async def create_chat(request: Request) -> JSONResponse:
user = current_user(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 = store_of(request).create_chat(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 = current_user(request)
limit, raw_cursor = page_params(request)
after = cursor.decode(raw_cursor, cursor.CHATS, user.id) if raw_cursor else None
items, has_more = store_of(request).list_chats(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 = current_user(request)
chat_id = path_uuid(request, "chat_id")
return ok(store_of(request).get_chat(user.id, chat_id).to_json())
async def create_message(request: Request) -> JSONResponse:
user = current_user(request)
chat_id = path_uuid(request, "chat_id")
store = store_of(request)
store.get_chat(user.id, chat_id) # access check before reading the body: outsiders get 404
data = await read_json(request)
validation.check_fields(data, {"text"})
text = validation.text_field(data, "text", 4000)
# sender_id is derived from the identification, never taken from the body.
message = store.add_message(user.id, chat_id, text)
return ok(message.to_json(), 201)
async def list_messages(request: Request) -> JSONResponse:
user = current_user(request)
chat_id = path_uuid(request, "chat_id")
store = store_of(request)
store.get_chat(user.id, chat_id) # 404 for outsiders before any 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 = store.list_messages(user.id, 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, store: Store | None = None) -> Starlette:
settings = settings or Settings.from_env()
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/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},
)
app.add_middleware(RequestContextMiddleware)
app.state.settings = settings
app.state.store = store or Store()
app.state.draining = False
return app
+76
View File
@@ -0,0 +1,76 @@
"""Runtime configuration read from environment variables (12-factor style).
Every variable has a safe default, so `docker run` works from a clean clone
even without an .env file. Invalid values stop the process at startup with a
clear message instead of failing later under traffic.
"""
from __future__ import annotations
import os
from dataclasses import dataclass
class ConfigError(ValueError):
pass
def _int(name: str, default: int, low: int, high: int) -> int:
raw = os.environ.get(name)
if raw is None or raw.strip() == "":
return default
try:
value = int(raw.strip())
except ValueError:
raise ConfigError(f"{name} must be an integer, got {raw!r}") from None
if not low <= value <= high:
raise ConfigError(f"{name} must be in [{low}, {high}], got {value}")
return value
def _float(name: str, default: float, low: float, high: float) -> float:
raw = os.environ.get(name)
if raw is None or raw.strip() == "":
return default
try:
value = float(raw.strip())
except ValueError:
raise ConfigError(f"{name} must be a number, got {raw!r}") from None
if not low <= value <= high:
raise ConfigError(f"{name} must be in [{low}, {high}], got {value}")
return value
def _bool(name: str, default: bool) -> bool:
raw = os.environ.get(name, "").strip().lower()
if raw == "":
return default
if raw not in {"true", "false", "1", "0"}:
raise ConfigError(f"{name} must be true/false, got {raw!r}")
return raw in {"true", "1"}
@dataclass(frozen=True)
class Settings:
host: str
port: int
env: str
log_level: str
shutdown_timeout: float
max_body_bytes: int
docs_enabled: bool = True
@classmethod
def from_env(cls) -> "Settings":
log_level = os.environ.get("LOG_LEVEL", "info").strip().lower() or "info"
if log_level not in {"debug", "info", "warning", "error"}:
raise ConfigError(f"LOG_LEVEL must be debug/info/warning/error, got {log_level!r}")
return cls(
host=os.environ.get("APP_HOST", "0.0.0.0").strip() or "0.0.0.0",
port=_int("APP_PORT", 8080, 1, 65535),
env=os.environ.get("APP_ENV", "lab").strip() or "lab",
log_level=log_level,
# Docker sends SIGKILL 10 s after SIGTERM by default; finish earlier.
shutdown_timeout=_float("SHUTDOWN_TIMEOUT_SECONDS", 8.0, 0.0, 9.0),
max_body_bytes=_int("MAX_BODY_BYTES", 64 * 1024, 1024, 1024 * 1024),
docs_enabled=_bool("DOCS_ENABLED", True),
)
+51
View File
@@ -0,0 +1,51 @@
"""Opaque keyset cursors.
A cursor encodes the sort key `(created_at, id)` of the last item on the page
plus the resource it belongs to, e.g. `v1|m|<chat_id>|<ts_us>|<message_id>`,
packed in URL-safe base64. The client treats it as an opaque string; the server
rejects cursors of another chat/user (400) and any non-canonical encoding.
"""
from __future__ import annotations
import base64
import re
from .errors import InvalidRequest
from .validation import UUID_RE
B64_RE = re.compile(r"[A-Za-z0-9_-]{1,512}")
TS_RE = re.compile(r"[0-9]{1,19}")
MESSAGES = "m"
CHATS = "c"
SortKey = tuple[int, str]
def encode(scope: str, owner_id: str, key: SortKey) -> str:
ts, item_id = key
raw = f"v1|{scope}|{owner_id}|{ts}|{item_id}".encode("ascii")
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def decode(cursor: str, scope: str, owner_id: str) -> SortKey:
"""Return the sort key stored in the cursor or raise InvalidRequest."""
bad = InvalidRequest("Неверный cursor")
if B64_RE.fullmatch(cursor) is None:
raise bad
try:
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)).decode("ascii")
except (ValueError, UnicodeDecodeError):
raise bad from None
parts = raw.split("|")
if len(parts) != 5 or parts[0] != "v1":
raise bad
_, got_scope, got_owner, ts, item_id = parts
if TS_RE.fullmatch(ts) is None or UUID_RE.fullmatch(item_id) is None or item_id != item_id.lower():
raise bad
key = (int(ts), item_id)
if encode(got_scope, got_owner, key) != cursor:
raise bad # only the canonical form produced by the server is accepted
if got_scope != scope or got_owner != owner_id:
raise InvalidRequest("cursor относится к другому ресурсу")
return key
+57
View File
@@ -0,0 +1,57 @@
"""Swagger UI for manual experiments: http://127.0.0.1:8080/docs
The page shows the course contract contracts/openapi.json as is (it is not
generated from our code). Only `servers` is replaced with "/" so that the
"Try it out" requests go to the same host the page was opened from.
Swagger UI itself (JS/CSS) is loaded by the browser from the jsDelivr CDN.
Disable with DOCS_ENABLED=false.
"""
from __future__ import annotations
import json
from functools import lru_cache
from pathlib import Path
from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse
SPEC_PATH = Path(__file__).resolve().parents[2] / "contracts" / "openapi.json"
SWAGGER_UI = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.33.0"
PAGE = f"""<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Messenger lab1 — Swagger UI</title>
<link rel="stylesheet" href="{SWAGGER_UI}/swagger-ui.css">
</head>
<body>
<div id="swagger-ui"></div>
<script src="{SWAGGER_UI}/swagger-ui-bundle.js"></script>
<script>
window.ui = SwaggerUIBundle({{
url: "/openapi.json",
dom_id: "#swagger-ui",
tryItOutEnabled: true, // fields are editable right away
persistAuthorization: true, // X-User-Id from "Authorize" survives page reload
displayRequestDuration: true,
}});
</script>
</body>
</html>
"""
@lru_cache(maxsize=1)
def _spec() -> dict:
spec = json.loads(SPEC_PATH.read_text(encoding="utf-8"))
spec["servers"] = [{"url": "/", "description": "этот сервер"}]
return spec
async def swagger_page(request: Request) -> HTMLResponse:
return HTMLResponse(PAGE)
async def openapi_json(request: Request) -> JSONResponse:
return JSONResponse(_spec())
+48
View File
@@ -0,0 +1,48 @@
"""Domain errors mapped 1:1 to the contract error codes (contracts/README.md)."""
from __future__ import annotations
class ApiError(Exception):
status = 500
code = "internal_error"
default_message = "Внутренняя ошибка сервера"
def __init__(self, message: str | None = None):
self.message = message or self.default_message
super().__init__(self.message)
class InvalidRequest(ApiError):
status = 400
code = "invalid_request"
default_message = "Неверный запрос"
class Unauthorized(ApiError):
status = 401
code = "unauthorized"
default_message = "Требуется X-User-Id существующего пользователя"
class NotFound(ApiError):
status = 404
code = "not_found"
default_message = "Объект не найден"
class Conflict(ApiError):
status = 409
code = "conflict"
default_message = "Конфликт"
class PayloadTooLarge(ApiError):
status = 413
code = "payload_too_large"
default_message = "Тело запроса слишком большое"
class Unavailable(ApiError):
status = 503
code = "unavailable"
default_message = "Сервис временно недоступен"
+19
View File
@@ -0,0 +1,19 @@
"""Docker HEALTHCHECK probe without curl/wget in the image: `python -m messenger.healthcheck`."""
from __future__ import annotations
import os
import sys
import urllib.request
def main() -> int:
port = os.environ.get("APP_PORT", "8080").strip() or "8080"
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/health/ready", timeout=2) as response:
return 0 if response.status == 200 else 1
except Exception:
return 1
if __name__ == "__main__":
sys.exit(main())
+36
View File
@@ -0,0 +1,36 @@
"""JSON-lines logging to stdout. Logs never contain message texts or request bodies."""
from __future__ import annotations
import datetime as dt
import json
import logging
import sys
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
entry = {
"ts": dt.datetime.fromtimestamp(record.created, dt.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
"level": record.levelname.lower(),
"logger": record.name,
"event": record.getMessage(),
}
fields = getattr(record, "fields", None)
if fields:
entry.update(fields)
if record.exc_info:
# Stack traces go only to the server log, never to the HTTP client.
entry["exception"] = self.formatException(record.exc_info)
return json.dumps(entry, ensure_ascii=False)
def configure(level: str) -> None:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
root = logging.getLogger()
root.handlers[:] = [handler]
root.setLevel(level.upper())
# uvicorn's own access log is disabled; our middleware writes one line per request.
for name in ("uvicorn", "uvicorn.error"):
logging.getLogger(name).handlers[:] = []
logging.getLogger(name).propagate = True
+191
View File
@@ -0,0 +1,191 @@
"""In-memory state of the messenger: the single source of truth for lab 1.
Concurrency model
-----------------
All data lives in ordinary dicts/lists of ONE process. Every public method
takes `self._lock` for its whole critical section, so each operation is atomic
and readers never see a half-built chat or message.
The server runs coroutines on one asyncio event loop, and store methods never
`await`, so on the event loop they are already atomic. The lock additionally
protects the store when it is used from several threads (student-tests start
10 threads that write concurrently) and documents the invariant explicitly.
Ordering invariant
------------------
`created_at` is assigned INSIDE the same critical section that appends the
object, from a strictly increasing clock (`_next_ts`). Therefore the append
order of every list equals the contract order `(created_at, id)` even under
concurrent writes and even if the wall clock jumps backwards.
"""
from __future__ import annotations
import bisect
import datetime as dt
import operator
import threading
import time
import uuid
from dataclasses import dataclass
from typing import Callable
from .cursor import SortKey
from .errors import Conflict, InvalidRequest, NotFound
_EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)
# (created_at, id) of a Chat/Message as a C-level getter: cheap to call inside bisect.
_sort_key = operator.attrgetter("ts", "id")
def format_ts(ts_us: int) -> str:
"""RFC 3339 UTC with fixed microsecond precision, e.g. 2026-09-25T12:00:00.000001Z."""
return (_EPOCH + dt.timedelta(microseconds=ts_us)).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
@dataclass(slots=True, frozen=True)
class User:
id: str
username: str
display_name: str
ts: int
created_at: str
def to_json(self) -> dict:
return {"id": self.id, "username": self.username, "display_name": self.display_name, "created_at": self.created_at}
@dataclass(slots=True, frozen=True)
class Chat:
id: str
title: str
member_ids: tuple[str, ...]
members: frozenset[str]
ts: int
created_at: str
@property
def key(self) -> SortKey:
return (self.ts, self.id)
def to_json(self) -> dict:
return {"id": self.id, "title": self.title, "member_ids": list(self.member_ids), "created_at": self.created_at}
@dataclass(slots=True, frozen=True)
class Message:
id: str
chat_id: str
sender_id: str
text: str
ts: int
created_at: str
@property
def key(self) -> SortKey:
return (self.ts, self.id)
def to_json(self) -> dict:
return {"id": self.id, "chat_id": self.chat_id, "sender_id": self.sender_id, "text": self.text, "created_at": self.created_at}
def _page_after(items: list, after: SortKey | None, limit: int) -> tuple[list, bool]:
"""Keyset page: up to `limit` items strictly after `after`, plus "has more".
`items` is always sorted by (created_at, id) (see the ordering invariant), so
the page start is found by binary search in O(log n) instead of scanning the
history from the beginning (O(n)); only the page itself is copied.
"""
start = 0 if after is None else bisect.bisect_right(items, after, key=_sort_key)
page = items[start:start + limit + 1]
return page[:limit], len(page) > limit
class Store:
def __init__(self, clock_ns: Callable[[], int] = time.time_ns):
self._lock = threading.Lock()
self._clock_ns = clock_ns
self._last_ts = 0
self._users: dict[str, User] = {}
self._user_ids_by_name: dict[str, str] = {}
self._chats: dict[str, Chat] = {}
self._chats_by_user: dict[str, list[Chat]] = {}
self._messages: dict[str, list[Message]] = {}
# -- helpers (caller holds the lock) ---------------------------------
def _next_ts(self) -> tuple[int, str]:
"""Strictly increasing server time in microseconds; must be called under the lock."""
ts = max(self._clock_ns() // 1000, self._last_ts + 1)
self._last_ts = ts
return ts, format_ts(ts)
def _chat_for_member(self, user_id: str, chat_id: str) -> Chat:
chat = self._chats.get(chat_id)
# A missing chat and a foreign chat are indistinguishable: both 404.
if chat is None or user_id not in chat.members:
raise NotFound("Чат не найден")
return chat
# -- users -----------------------------------------------------------
def create_user(self, username: str, display_name: str) -> User:
with self._lock:
if username in self._user_ids_by_name:
raise Conflict("Имя пользователя уже занято")
ts, created_at = self._next_ts()
user = User(str(uuid.uuid4()), username, display_name, ts, created_at)
self._users[user.id] = user
self._user_ids_by_name[username] = user.id
self._chats_by_user[user.id] = []
return user
def get_user(self, user_id: str) -> User | None:
with self._lock:
return self._users.get(user_id)
# -- chats -----------------------------------------------------------
def create_chat(self, creator_id: str, title: str, member_ids: list[str]) -> Chat:
with self._lock:
if creator_id not in member_ids:
raise InvalidRequest("member_ids должен включать текущего пользователя")
if any(member not in self._users for member in member_ids):
raise InvalidRequest("member_ids содержит несуществующих пользователей")
ts, created_at = self._next_ts()
chat = Chat(str(uuid.uuid4()), title, tuple(member_ids), frozenset(member_ids), ts, created_at)
# All indexes are updated in one critical section: the chat is created atomically.
self._chats[chat.id] = chat
self._messages[chat.id] = []
for member in member_ids:
self._chats_by_user[member].append(chat)
return chat
def get_chat(self, user_id: str, chat_id: str) -> Chat:
with self._lock:
return self._chat_for_member(user_id, chat_id)
def list_chats(self, user_id: str, after: SortKey | None, limit: int) -> tuple[list[Chat], bool]:
"""Page of the user's chats ordered by (created_at, id); returns (items, has_more)."""
with self._lock:
return _page_after(self._chats_by_user[user_id], after, limit)
# -- messages --------------------------------------------------------
def add_message(self, user_id: str, chat_id: str, text: str) -> Message:
with self._lock:
chat = self._chat_for_member(user_id, chat_id)
ts, created_at = self._next_ts()
message = Message(str(uuid.uuid4()), chat.id, user_id, text, ts, created_at)
self._messages[chat.id].append(message)
return message
def list_messages(self, user_id: str, chat_id: str, after: SortKey | None, limit: int) -> tuple[list[Message], bool]:
"""Page of history strictly after `after` in (created_at, id) order; returns (items, has_more)."""
with self._lock:
chat = self._chat_for_member(user_id, chat_id)
return _page_after(self._messages[chat.id], after, limit)
# -- diagnostics -----------------------------------------------------
def counts(self) -> dict[str, int]:
with self._lock:
return {
"users": len(self._users),
"chats": len(self._chats),
"messages": sum(len(h) for h in self._messages.values()),
}
+103
View File
@@ -0,0 +1,103 @@
"""Strict request validation according to contracts/openapi.json + contracts/README.md.
Written by hand instead of a schema library so that every rule is visible:
extra fields, wrong JSON types, whitespace-only strings and lengths counted in
Unicode code points all produce 400 invalid_request.
"""
from __future__ import annotations
import json
import re
from typing import Any
from .errors import InvalidRequest
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}")
# Canonical textual UUID (8-4-4-4-12 hex). Case-insensitive, normalised to lower case.
UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
LIMIT_RE = re.compile(r"[0-9]{1,3}")
SURROGATES_RE = re.compile("[\ud800-\udfff]")
DEFAULT_LIMIT = 50
MAX_LIMIT = 100
def _reject_constant(name: str) -> Any:
# Python's json accepts NaN/Infinity, which are not valid JSON.
raise ValueError(f"invalid JSON constant {name}")
def parse_json_object(body: bytes) -> dict[str, Any]:
"""Decode a UTF-8 JSON object or raise InvalidRequest (malformed JSON -> 400)."""
try:
text = body.decode("utf-8")
value = json.loads(text, parse_constant=_reject_constant)
except (UnicodeDecodeError, ValueError):
raise InvalidRequest("Тело запроса должно быть корректным JSON в UTF-8") from None
if not isinstance(value, dict):
raise InvalidRequest("Тело запроса должно быть JSON-объектом")
return value
def check_fields(data: dict[str, Any], required: set[str], optional: frozenset[str] = frozenset()) -> None:
extra = set(data) - required - optional
if extra:
raise InvalidRequest("Неизвестные поля: " + ", ".join(sorted(extra)))
missing = required - set(data)
if missing:
raise InvalidRequest("Отсутствуют обязательные поля: " + ", ".join(sorted(missing)))
def text_field(data: dict[str, Any], name: str, max_len: int, *, min_len: int = 1) -> str:
value = data[name]
if not isinstance(value, str):
raise InvalidRequest(f"Поле {name} должно быть строкой")
if SURROGATES_RE.search(value):
# "\ud800" escapes decode to lone surrogates that cannot be encoded as UTF-8.
raise InvalidRequest(f"Поле {name} содержит недопустимые символы")
# len() of a Python str is the number of Unicode code points, as the contract requires.
if not min_len <= len(value) <= max_len:
raise InvalidRequest(f"Длина поля {name} должна быть от {min_len} до {max_len} символов")
if value.strip() == "":
raise InvalidRequest(f"Поле {name} не может состоять только из пробелов")
return value
def username_field(data: dict[str, Any]) -> str:
value = data["username"]
if not isinstance(value, str) or USERNAME_RE.fullmatch(value) is None:
raise InvalidRequest("username должен соответствовать [a-z0-9_]{3,32}")
return value
def parse_uuid(value: Any, what: str = "UUID") -> str:
if not isinstance(value, str) or UUID_RE.fullmatch(value) is None:
raise InvalidRequest(f"Неверный {what}")
return value.lower()
def member_ids_field(data: dict[str, Any]) -> list[str]:
value = data["member_ids"]
if not isinstance(value, list):
raise InvalidRequest("member_ids должен быть массивом")
if not 1 <= len(value) <= 100:
raise InvalidRequest("member_ids должен содержать от 1 до 100 элементов")
ids = [parse_uuid(item, "UUID участника") for item in value]
if len(set(ids)) != len(ids):
raise InvalidRequest("member_ids содержит дубликаты")
return ids
def single_query_param(query: list[tuple[str, str]], name: str) -> str | None:
values = [v for k, v in query if k == name]
if len(values) > 1:
raise InvalidRequest(f"Параметр {name} указан несколько раз")
return values[0] if values else None
def parse_limit(raw: str | None) -> int:
if raw is None:
return DEFAULT_LIMIT
if LIMIT_RE.fullmatch(raw) is None or not 1 <= int(raw) <= MAX_LIMIT:
raise InvalidRequest(f"limit должен быть целым числом от 1 до {MAX_LIMIT}")
return int(raw)