From 6bc82eaa2a18bd8c2eb14b740a6c44ab6a0eb332 Mon Sep 17 00:00:00 2001 From: masha Date: Thu, 24 Sep 2026 16:27:50 +0300 Subject: [PATCH] Lab2: starting --- Dockerfile | 24 ++ Dockerfile.example | 8 - app/App.js | 159 ++++++++++++++ app/__init__.py | 0 app/config.py | 19 ++ app/deps.py | 31 +++ app/errors.py | 59 +++++ app/main.py | 204 +++++++++++++++++ app/models.py | 128 +++++++++++ app/requirements | 0 app/smoke_test.py | 113 ++++++++++ app/storage.py | 232 ++++++++++++++++++++ compose.example.yaml | 10 - compose.yaml | 36 +++ scripts/restart.sh | 0 student-tests/experiment_cursor.py | 337 +++++++++++++++++++++++++++++ student-tests/extra.py | 227 +++++++++++++++++++ student-tests/log_safety.py | 103 +++++++++ student-tests/race_100.py | 212 ++++++++++++++++++ 19 files changed, 1884 insertions(+), 18 deletions(-) create mode 100644 Dockerfile delete mode 100644 Dockerfile.example create mode 100644 app/App.js create mode 100644 app/__init__.py create mode 100644 app/config.py create mode 100644 app/deps.py create mode 100644 app/errors.py create mode 100644 app/main.py create mode 100644 app/models.py create mode 100644 app/requirements create mode 100644 app/smoke_test.py create mode 100644 app/storage.py delete mode 100644 compose.example.yaml create mode 100644 compose.yaml create mode 100644 scripts/restart.sh create mode 100644 student-tests/experiment_cursor.py create mode 100644 student-tests/extra.py create mode 100644 student-tests/log_safety.py create mode 100644 student-tests/race_100.py diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..adefc536 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM python:3.12.7-slim + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY app/ ./app/ + +RUN useradd --create-home --shell /usr/sbin/nologin appuser \ + && chown -R appuser:appuser /app + +USER appuser + +ENV APP_HOST=0.0.0.0 +ENV APP_PORT=8080 +ENV LOG_LEVEL=info + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD python -c "import sys, urllib.request; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/live', timeout=2).status == 200 else 1)" + +CMD ["sh", "-c", "exec uvicorn app.main:app --host ${APP_HOST} --port ${APP_PORT} --log-level ${LOG_LEVEL}"] \ No newline at end of file diff --git a/Dockerfile.example b/Dockerfile.example deleted file mode 100644 index e333a12e..00000000 --- a/Dockerfile.example +++ /dev/null @@ -1,8 +0,0 @@ -# Teaching outline, not a runnable Dockerfile. Implement your own Dockerfile. -# 1. Choose a runtime/toolchain version and pin the base image tag/digest. -# 2. Copy dependency manifests first; install from the language lockfile. -# 3. Copy source and build. For compiled languages use a separate runtime stage. -# 4. Run the HTTP process as PID 1; listen on 0.0.0.0:8080. -# 5. Add non-root, signals and healthcheck according to the current rubric. -# 6. Pass runtime config/secrets at startup, never COPY .env or secret files. -# This file deliberately has no FROM/CMD: selecting/implementing them is the task. diff --git a/app/App.js b/app/App.js new file mode 100644 index 00000000..a1143a90 --- /dev/null +++ b/app/App.js @@ -0,0 +1,159 @@ +import { useState } from "react"; + +const API_BASE = "http://localhost:8080/api/v1"; + +async function apiFetch(path, { method = "GET", userId, body } = {}) { + const headers = { "Content-Type": "application/json" }; +if (userId) headers["X-User-Id"] = userId; + +const res = await fetch(`${API_BASE}${path}`, { + method, + headers, + body: body ? JSON.stringify(body) : undefined, +}); + +const requestId = res.headers.get("X-Request-Id"); +const data = await res.json().catch(() => null); + +if (!res.ok) { +const message = data?.error?.message || `HTTP ${res.status}`; +throw new Error(`${message} (request_id: ${requestId})`); +} +return data; +} + +export default function App() { +const [username, setUsername] = useState(""); +const [displayName, setDisplayName] = useState(""); +const [me, setMe] = useState(null); +const [chat, setChat] = useState(null); +const [memberIdsInput, setMemberIdsInput] = useState(""); +const [chatTitle, setChatTitle] = useState(""); +const [text, setText] = useState(""); +const [messages, setMessages] = useState([]); +const [error, setError] = useState(""); + +async function handleRegister() { + setError(""); +try { +const user = await apiFetch("/users", { +method: "POST", +body: { username, display_name: displayName }, +}); +setMe(user); +} catch (e) { + setError(e.message); +} +} + +async function handleCreateChat() { +setError(""); +try { +const memberIds = memberIdsInput +.split(",") +.map((s) => s.trim()) +.filter(Boolean); +const created = await apiFetch("/chats", { +method: "POST", +userId: me.id, +body: { title: chatTitle, member_ids: [me.id, ...memberIds] }, +}); +setChat(created); +setMessages([]); +} catch (e) { + setError(e.message); +} +} + +async function handleSendMessage() { +setError(""); +try { +const msg = await apiFetch(`/chats/${chat.id}/messages`, { +method: "POST", +userId: me.id, +body: { text }, +}); +setMessages((prev) => [...prev, msg]); +setText(""); +} catch (e) { + setError(e.message); +} +} + +async function handleLoadHistory() { +setError(""); +try { +const page = await apiFetch(`/chats/${chat.id}/messages`, { +method: "GET", +userId: me.id, +}); +setMessages(page.items); +} catch (e) { + setError(e.message); +} +} + +return ( +
+

Lab1 Messenger — демо-клиент

+ {error &&

{error}

} + + {!me && ( +
+

Регистрация

+ setUsername(e.target.value)} +/> + setDisplayName(e.target.value)} +/> + +
+)} + +{me && !chat && ( +
+

+ Вошли как {me.username} (id: {me.id}) +

+

Создать чат

+ setChatTitle(e.target.value)} +/> + setMemberIdsInput(e.target.value)} +/> + +
+)} + +{me && chat && ( +
+

Чат: {chat.title}

+ +
    + {messages.map((m) => ( +
  • + {m.sender_id === me.id ? "Я" : m.sender_id}: {m.text} +
  • +))} +
+ setText(e.target.value)} +/> + +
+)} +
+); +} \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/config.py b/app/config.py new file mode 100644 index 00000000..cf9616f0 --- /dev/null +++ b/app/config.py @@ -0,0 +1,19 @@ +""" +Конфигурация из окружения (переменные среды), как того требует задание Lab1: +"конфигурация приходит из окружения". +""" +import os + + +def _int_env(name: str, default: int) -> int: + raw = os.environ.get(name) + if raw is None or raw == "": + return default + try: + return int(raw) + except ValueError: + return default + +HOST = os.environ.get("APP_HOST", "0.0.0.0") +PORT = _int_env("APP_PORT", 8080) +LOG_LEVEL = os.environ.get("LOG_LEVEL", "info") \ No newline at end of file diff --git a/app/deps.py b/app/deps.py new file mode 100644 index 00000000..9681eee8 --- /dev/null +++ b/app/deps.py @@ -0,0 +1,31 @@ +""" +Зависимости FastAPI: проверка X-User-Id (учебная идентификация Lab1) +и разбор query-параметров пагинации. +""" +import uuid +from typing import Optional + +from fastapi import Header, Query + +from app.errors import ApiError +from app.storage import storage + + +def require_user(x_user_id: Optional[str] = Header(default=None, alias="X-User-Id")) -> dict: + if not x_user_id: + raise ApiError(401, "X-User-Id header is required.") + try: + uuid.UUID(x_user_id) + except ValueError: + raise ApiError(401, "X-User-Id must be a valid UUID.") + user = storage.get_user(x_user_id) + if user is None: + raise ApiError(401, "Unknown user.") + return user + + +def pagination_params( + limit: int = Query(default=50, ge=1, le=100), + cursor: Optional[str] = Query(default=None, min_length=1), +) -> tuple[int, Optional[str]]: + return limit, cursor \ No newline at end of file diff --git a/app/errors.py b/app/errors.py new file mode 100644 index 00000000..1b3ae2af --- /dev/null +++ b/app/errors.py @@ -0,0 +1,59 @@ +""" +Единый формат ошибок согласно contracts/README.md: +{"error": {"code": "...", "message": "...", "request_id": "..."}} +""" +from fastapi import Request +from fastapi.responses import JSONResponse +from fastapi.exceptions import RequestValidationError +from starlette.exceptions import HTTPException as StarletteHTTPException + +ALLOWED_CODES = { + 400: "invalid_request", + 401: "unauthorized", + 404: "not_found", + 409: "conflict", + 413: "payload_too_large", + 415: "unsupported_media_type", + 429: "rate_limited", + 500: "internal_error", + 503: "unavailable", +} + + +class ApiError(Exception): + def __init__(self, status_code: int, message: str, code: str | None = None): + self.status_code = status_code + self.code = code or ALLOWED_CODES.get(status_code, "internal_error") + self.message = message + + +def _request_id(request: Request) -> str: + return getattr(request.state, "request_id", "unknown") + + +def build_error_body(request: Request, code: str, message: str) -> dict: + return {"error": {"code": code, "message": message, "request_id": _request_id(request)}} + + +async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse: + body = build_error_body(request, exc.code, exc.message) + headers = {"X-Request-Id": _request_id(request)} + if exc.status_code == 401: + headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"' + return JSONResponse(status_code=exc.status_code, content=body, headers=headers) + + +async def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse: + body = build_error_body(request, "invalid_request", "Request body failed validation.") + return JSONResponse(status_code=400, content=body, headers={"X-Request-Id": _request_id(request)}) + + +async def http_error_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse: + code = ALLOWED_CODES.get(exc.status_code, "internal_error") + body = build_error_body(request, code, str(exc.detail)) + return JSONResponse(status_code=exc.status_code, content=body, headers={"X-Request-Id": _request_id(request)}) + + +async def unhandled_error_handler(request: Request, exc: Exception) -> JSONResponse: + body = build_error_body(request, "internal_error", "Internal server error.") + return JSONResponse(status_code=500, content=body, headers={"X-Request-Id": _request_id(request)}) \ No newline at end of file diff --git a/app/main.py b/app/main.py new file mode 100644 index 00000000..410704d0 --- /dev/null +++ b/app/main.py @@ -0,0 +1,204 @@ +""" +Lab1: In-memory API мессенджера. +Реализует 7 обязательных эндпоинтов по contracts/openapi.json: + GET /health/live + GET /health/ready + POST /api/v1/users + GET /api/v1/users/me + POST /api/v1/chats + GET /api/v1/chats + GET /api/v1/chats/{chat_id} + POST /api/v1/chats/{chat_id}/messages + GET /api/v1/chats/{chat_id}/messages + +Конфигурация (host/port/log-level) приходит из окружения — см. app/config.py. + +Запуск через Docker (см. Dockerfile): + uvicorn app.main:app --host ${APP_HOST} --port ${APP_PORT} + +Запуск напрямую (для локальной отладки без контейнера): + python -m app.main +""" +import uuid +from typing import Optional + +from fastapi import Depends, FastAPI, Request +from fastapi.exceptions import RequestValidationError +from starlette.exceptions import HTTPException as StarletteHTTPException + +from app import config +from app.deps import pagination_params, require_user +from app.errors import ( + ApiError, + api_error_handler, + http_error_handler, + unhandled_error_handler, + validation_error_handler, +) +from app.models import ( + Chat, + ChatPage, + CreateChat, + CreateMessage, + CreateUser, + Health, + Message, + MessagePage, + User, +) +from app.storage import storage +from pathlib import Path + +app = FastAPI(title="MTUSI Messenger Lab1", version="1.0.0") +app.add_exception_handler(ApiError, api_error_handler) +app.add_exception_handler(RequestValidationError, validation_error_handler) +app.add_exception_handler(StarletteHTTPException, http_error_handler) +app.add_exception_handler(Exception, unhandled_error_handler) + + +@app.middleware("http") +async def add_request_id(request: Request, call_next): + request.state.request_id = str(uuid.uuid4()) + response = await call_next(request) + response.headers["X-Request-Id"] = request.state.request_id + return response + +# ---------- Health ---------- + +@app.get("/health/live", response_model=Health) +async def liveness(): + return Health(status="ok") + + +@app.get("/health/ready", response_model=Health) +async def readiness(): + # В Lab1 нет внешних зависимостей (БД появится в Lab2), поэтому + # процесс всегда готов, если он успешно поднялся. + return Health(status="ok") + +@app.get("/internal/metrics") +async def internal_metrics(): + return { + "rss_bytes": process_rss_bytes(), + **storage.counts(), + } + +def process_rss_bytes() -> int: + try: + for line in Path("/proc/self/status").read_text(encoding="utf-8").splitlines(): + if line.startswith("VmRSS:"): + return int(line.split()[1]) * 1024 + except OSError: + pass + return 0 + +# ---------- Пользователи ---------- + +@app.post("/api/v1/users", response_model=User, status_code=201) +async def register_user(payload: CreateUser): + user = storage.create_user(payload.username, payload.display_name) + if user is None: + raise ApiError(409, "Username is already taken.") + return user + + +@app.get("/api/v1/users/me", response_model=User) +async def current_user(user: dict = Depends(require_user)): + return user + + +# ---------- Чаты ---------- + +@app.post("/api/v1/chats", response_model=Chat, status_code=201) +async def create_chat(payload: CreateChat, user: dict = Depends(require_user)): + member_ids = [str(m) for m in payload.member_ids] + + if user["id"] not in member_ids: + raise ApiError(400, "Caller must be included in member_ids.") + + for member_id in member_ids: + if storage.get_user(member_id) is None: + raise ApiError(400, f"Unknown member_id: {member_id}") + + chat = storage.create_chat(payload.title, member_ids) + return chat + + +@app.get("/api/v1/chats", response_model=ChatPage) +async def list_chats( + user: dict = Depends(require_user), + pagination: tuple[int, Optional[str]] = Depends(pagination_params), +): + limit, cursor = pagination + try: + items, next_cursor = storage.list_chats_for_user(user["id"], limit, cursor) + except ValueError: + raise ApiError(400, "Invalid cursor.") + return ChatPage(items=items, next_cursor=next_cursor) + + +@app.get("/api/v1/chats/{chat_id}", response_model=Chat) +async def get_chat(chat_id: str, user: dict = Depends(require_user)): + try: + uuid.UUID(chat_id) + except ValueError: + raise ApiError(400, "chat_id must be a valid UUID.") + + chat = storage.get_chat(chat_id) + if chat is None or user["id"] not in chat["member_ids"]: + raise ApiError(404, "Chat not found.") + return chat + + +# ---------- Сообщения ---------- + +@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201) +async def create_message(chat_id: str, payload: CreateMessage, user: dict = Depends(require_user)): + try: + uuid.UUID(chat_id) + except ValueError: + raise ApiError(400, "chat_id must be a valid UUID.") + + chat = storage.get_chat(chat_id) + if chat is None or user["id"] not in chat["member_ids"]: + raise ApiError(404, "Chat not found.") + + message = storage.create_message(chat_id, user["id"], payload.text) + return message + + +@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage) +async def list_messages( + chat_id: str, + user: dict = Depends(require_user), + pagination: tuple[int, Optional[str]] = Depends(pagination_params), +): + try: + uuid.UUID(chat_id) + except ValueError: + raise ApiError(400, "chat_id must be a valid UUID.") + + chat = storage.get_chat(chat_id) + if chat is None or user["id"] not in chat["member_ids"]: + raise ApiError(404, "Chat not found.") + + limit, cursor = pagination + try: + items, next_cursor = storage.list_messages(chat_id, limit, cursor) + except ValueError: + raise ApiError(400, "Invalid cursor.") + return MessagePage(items=items, next_cursor=next_cursor) + +def process_rss_bytes() -> int: + try: + for line in Path("/proc/self/status").read_text(encoding="utf-8").splitlines(): + if line.startswith("VmRSS:"): + return int(line.split()[1]) * 1024 + except OSError: + pass + return 0 + +if __name__ == "__main__": + import uvicorn + + uvicorn.run(app, host=config.HOST, port=config.PORT, log_level=config.LOG_LEVEL) \ No newline at end of file diff --git a/app/models.py b/app/models.py new file mode 100644 index 00000000..efdc7208 --- /dev/null +++ b/app/models.py @@ -0,0 +1,128 @@ + +""" +Pydantic-схемы запросов/ответов согласно contracts/openapi.json. + +ВАЖНО: все модели запросов (Create*) используют extra="forbid" - контракт +явно требует 400 на JSON с лишними полями, а Pydantic по умолчанию такие +поля молча игнорирует. Без extra="forbid" лишнее поле вроде "password" +в CreateUser проходило бы валидацию незамеченным. +""" +from __future__ import annotations + +import re +import uuid +from datetime import datetime +from typing import List, Optional + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +USERNAME_PATTERN = re.compile(r"^[a-z0-9_]{3,32}$") + + +# Пользователи + +class CreateUser(BaseModel): + model_config = ConfigDict(extra="forbid") + + username: str = Field(..., min_length=3, max_length=32) + display_name: str = Field(..., min_length=1, max_length=100) + + @field_validator("username") + @classmethod + def check_username(cls, v: str) -> str: + if not USERNAME_PATTERN.match(v): + raise ValueError("username must match [a-z0-9_]{3,32}") + return v + + @field_validator("display_name") + @classmethod + def check_display_name(cls, v: str) -> str: + if not v.strip(): + raise ValueError("display_name must not be blank") + return v + + +class User(BaseModel): + id: uuid.UUID + username: str + display_name: str + created_at: datetime + + +# Чаты + +class CreateChat(BaseModel): + model_config = ConfigDict(extra="forbid") + + title: str = Field(..., min_length=1, max_length=100) + member_ids: List[uuid.UUID] = Field(..., min_length=1, max_length=100) + + @field_validator("title") + @classmethod + def check_title(cls, v: str) -> str: + if not v.strip(): + raise ValueError("title must not be blank") + return v + + @field_validator("member_ids") + @classmethod + def check_unique(cls, v: List[uuid.UUID]) -> List[uuid.UUID]: + if len(set(v)) != len(v): + raise ValueError("member_ids must be unique") + return v + + +class Chat(BaseModel): + id: uuid.UUID + title: str + member_ids: List[uuid.UUID] + created_at: datetime + + +class ChatPage(BaseModel): + items: List[Chat] + next_cursor: Optional[str] = None + + +# Сообщения + +class CreateMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + + text: str = Field(..., min_length=1, max_length=4000) + + @field_validator("text") + @classmethod + def check_text(cls, v: str) -> str: + if not v.strip(): + raise ValueError("text must not be blank/whitespace-only") + return v + + +class Message(BaseModel): + id: uuid.UUID + chat_id: uuid.UUID + sender_id: uuid.UUID + text: str + created_at: datetime + + +class MessagePage(BaseModel): + items: List[Message] + next_cursor: Optional[str] = None + + +# Health / ошибки + +class Health(BaseModel): + status: str = "ok" + + +class ErrorBody(BaseModel): + code: str + message: str + request_id: str + + +class ErrorResponse(BaseModel): + error: ErrorBody \ No newline at end of file diff --git a/app/requirements b/app/requirements new file mode 100644 index 00000000..e69de29b diff --git a/app/smoke_test.py b/app/smoke_test.py new file mode 100644 index 00000000..8132dd06 --- /dev/null +++ b/app/smoke_test.py @@ -0,0 +1,113 @@ +""" +HTTP smoke-тест для Lab1. Проверяет всю цепочку "живьём" по сети: +health -> регистрация двух пользователей -> создание чата -> +отправка сообщения -> чтение истории -> проверка отказа доступа для +постороннего -> проверка формата ошибок. + +Запуск (сервер должен быть уже поднят, например через docker run): + python smoke_test.py http://localhost:8080 +""" +import sys +import uuid + +import httpx + +BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080" + + +def check(condition: bool, message: str) -> None: + if not condition: + raise AssertionError(f"FAILED: {message}") + print(f"OK: {message}") + + +def main() -> None: + client = httpx.Client(base_url=BASE_URL, timeout=10.0) + + # 1. Health + r = client.get("/health/live") + check(r.status_code == 200, "GET /health/live -> 200") + check(r.json() == {"status": "ok"}, "health/live body") + check(bool(r.headers.get("X-Request-Id")), "health/live has X-Request-Id") + + r = client.get("/health/ready") + check(r.status_code == 200, "GET /health/ready -> 200") + + # 2. Регистрация двух пользователей + uname_a = f"alice_{uuid.uuid4().hex[:8]}" + r = client.post("/api/v1/users", json={"username": uname_a, "display_name": "Алиса"}) + check(r.status_code == 201, "POST /api/v1/users (alice) -> 201") + alice = r.json() + check("password" not in alice and "password_hash" not in alice, "no password leaked in User") + + uname_b = f"bob_{uuid.uuid4().hex[:8]}" + r = client.post("/api/v1/users", json={"username": uname_b, "display_name": "Боб"}) + check(r.status_code == 201, "POST /api/v1/users (bob) -> 201") + bob = r.json() + + # Повторная регистрация с тем же username -> 409 + r = client.post("/api/v1/users", json={"username": uname_a, "display_name": "Дубликат"}) + check(r.status_code == 409, "duplicate username -> 409") + check(r.json()["error"]["code"] == "conflict", "error.code == conflict") + check(r.json()["error"]["request_id"] == r.headers["X-Request-Id"], "error.request_id matches header") + + # 3. GET /users/me без заголовка -> 401 + r = client.get("/api/v1/users/me") + check(r.status_code == 401, "GET /users/me without X-User-Id -> 401") + + r = client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}) + check(r.status_code == 200, "GET /users/me with valid X-User-Id -> 200") + check(r.json()["username"] == uname_a, "me returns correct user") + + # 4. Создание чата (caller должен быть среди участников) + r = client.post( + "/api/v1/chats", + headers={"X-User-Id": alice["id"]}, + json={"title": "Lab1 smoke chat", "member_ids": [alice["id"], bob["id"]]}, + ) + check(r.status_code == 201, "POST /api/v1/chats -> 201") + chat = r.json() + + # caller не включён в member_ids -> 400 + r = client.post( + "/api/v1/chats", + headers={"X-User-Id": alice["id"]}, + json={"title": "Bad chat", "member_ids": [bob["id"]]}, + ) + check(r.status_code == 400, "chat without caller in member_ids -> 400") + + # 5. Отправка сообщения + r = client.post( + f"/api/v1/chats/{chat['id']}/messages", + headers={"X-User-Id": alice["id"]}, + json={"text": "Привет, Боб!"}, + ) + check(r.status_code == 201, "POST message -> 201") + message = r.json() + check(message["sender_id"] == alice["id"], "sender_id inferred from X-User-Id") + + # Пустой/пробельный текст -> 400 + r = client.post( + f"/api/v1/chats/{chat['id']}/messages", + headers={"X-User-Id": alice["id"]}, + json={"text": " "}, + ) + check(r.status_code == 400, "whitespace-only text -> 400") + + # 6. Чтение истории + r = client.get(f"/api/v1/chats/{chat['id']}/messages", headers={"X-User-Id": bob["id"]}) + check(r.status_code == 200, "GET history as bob (member) -> 200") + check(len(r.json()["items"]) == 1, "history contains 1 message") + + # 7. Посторонний не должен видеть чат: 404, не 403 + uname_c = f"carol_{uuid.uuid4().hex[:8]}" + r = client.post("/api/v1/users", json={"username": uname_c, "display_name": "Кэрол"}) + carol = r.json() + r = client.get(f"/api/v1/chats/{chat['id']}", headers={"X-User-Id": carol["id"]}) + check(r.status_code == 404, "stranger gets 404, not 403, for foreign chat") + + print("\nALL SMOKE CHECKS PASSED") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/app/storage.py b/app/storage.py new file mode 100644 index 00000000..fc189caa --- /dev/null +++ b/app/storage.py @@ -0,0 +1,232 @@ +""" +In-memory хранилище для Lab1. Никакой БД — только dict/list в памяти процесса. +Данные пропадают при перезапуске, это ожидаемо для уровня 3 этой лабы. + +Порядок истории задаётся монотонным счётчиком _seq. UUID случайны и не +сохраняют порядок создания, а created_at может совпадать у нескольких записей. +_seq не попадает в API-ответы: это внутренний ключ порядка и cursor. + +Для эксперимента уровня 5 используется message_index_by_seq: +chat_id -> {message_seq -> position_in_chat_messages}. Он позволяет находить +начало следующей страницы истории по cursor за O(1), вместо линейного обхода +списка сообщений O(N). Цена оптимизации — дополнительная память O(N). +""" +import base64 +import itertools +import threading +import uuid +from datetime import datetime, timezone +from typing import Dict, List, Optional, Tuple + + +def now_iso() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _strip_seq(obj: dict) -> dict: + """Убирает внутреннее поле _seq перед отдачей объекта наружу через API.""" + return {key: value for key, value in obj.items() if key != "_seq"} + + +def _encode_cursor(seq: int) -> str: + return base64.urlsafe_b64encode(str(seq).encode()).decode() + + +def _decode_cursor(cursor: str) -> Optional[int]: + try: + return int(base64.urlsafe_b64decode(cursor.encode()).decode()) + except Exception: + return None + + +def _encode_message_cursor(chat_id: str, seq: int) -> str: + raw = f"{chat_id}|{seq}" + return base64.urlsafe_b64encode(raw.encode()).decode() + + +def _decode_message_cursor(cursor: str) -> Optional[Tuple[str, int]]: + try: + raw = base64.urlsafe_b64decode(cursor.encode()).decode() + chat_id, seq = raw.split("|", 1) + return chat_id, int(seq) + except Exception: + return None + + +class Storage: + def __init__(self) -> None: + self._lock = threading.Lock() + self._seq = itertools.count(1) + + self.users: Dict[str, dict] = {} + self.usernames: Dict[str, str] = {} + + self.chats: Dict[str, dict] = {} + self.chat_order: List[str] = [] + + self.messages: Dict[str, List[dict]] = {} + self.message_index_by_seq: Dict[str, Dict[int, int]] = {} + + # Пользователи + + def create_user(self, username: str, display_name: str) -> Optional[dict]: + with self._lock: + if username in self.usernames: + return None + + user_id = str(uuid.uuid4()) + user = { + "id": user_id, + "username": username, + "display_name": display_name, + "created_at": now_iso(), + } + + self.users[user_id] = user + self.usernames[username] = user_id + return user + + def get_user(self, user_id: str) -> Optional[dict]: + return self.users.get(user_id) + + # Чаты + + def create_chat(self, title: str, member_ids: List[str]) -> dict: + with self._lock: + chat_id = str(uuid.uuid4()) + chat = { + "id": chat_id, + "title": title, + "member_ids": list(member_ids), + "created_at": now_iso(), + "_seq": next(self._seq), + } + + self.chats[chat_id] = chat + self.chat_order.append(chat_id) + + self.messages[chat_id] = [] + self.message_index_by_seq[chat_id] = {} + + return _strip_seq(chat) + + def get_chat(self, chat_id: str) -> Optional[dict]: + chat = self.chats.get(chat_id) + return _strip_seq(chat) if chat else None + + def list_chats_for_user( + self, + user_id: str, + limit: int, + cursor: Optional[str], + ) -> Tuple[List[dict], Optional[str]]: + visible = sorted( + ( + self.chats[chat_id] + for chat_id in self.chat_order + if user_id in self.chats[chat_id]["member_ids"] + ), + key=lambda chat: chat["_seq"], + ) + + start_idx = 0 + + if cursor is not None: + last_seq = _decode_cursor(cursor) + if last_seq is None: + raise ValueError("bad cursor") + + start_idx = next( + ( + index + for index, chat in enumerate(visible) + if chat["_seq"] > last_seq + ), + len(visible), + ) + + window = visible[start_idx:start_idx + limit + 1] + has_more = len(window) > limit + page = window[:limit] + + next_cursor = ( + _encode_cursor(page[-1]["_seq"]) + if has_more and page + else None + ) + + return [_strip_seq(chat) for chat in page], next_cursor + + # ---------- Сообщения ---------- + + def create_message(self, chat_id: str, sender_id: str, text: str) -> dict: + with self._lock: + msg_id = str(uuid.uuid4()) + msg = { + "id": msg_id, + "chat_id": chat_id, + "sender_id": sender_id, + "text": text, + "created_at": now_iso(), + "_seq": next(self._seq), + } + + chat_messages = self.messages[chat_id] + position = len(chat_messages) + + chat_messages.append(msg) + self.message_index_by_seq[chat_id][msg["_seq"]] = position + + return _strip_seq(msg) + + def list_messages( + self, + chat_id: str, + limit: int, + cursor: Optional[str], + ) -> Tuple[List[dict], Optional[str]]: + all_msgs = self.messages.get(chat_id, []) + start_idx = 0 + + if cursor is not None: + decoded = _decode_message_cursor(cursor) + if decoded is None: + raise ValueError("bad cursor") + + cur_chat_id, last_seq = decoded + if cur_chat_id != chat_id: + raise ValueError("cursor belongs to another chat") + + position = self.message_index_by_seq.get(chat_id, {}).get(last_seq) + if position is None: + raise ValueError("unknown cursor sequence") + + start_idx = position + 1 + + window = all_msgs[start_idx:start_idx + limit + 1] + has_more = len(window) > limit + page = window[:limit] + + next_cursor = ( + _encode_message_cursor(chat_id, page[-1]["_seq"]) + if has_more and page + else None + ) + + return [_strip_seq(message) for message in page], next_cursor + + # Диагностика уровня 5 + + def counts(self) -> dict: + with self._lock: + return { + "users": len(self.users), + "chats": len(self.chats), + "messages": sum( + len(chat_messages) + for chat_messages in self.messages.values() + ), + } + + +storage = Storage() \ No newline at end of file diff --git a/compose.example.yaml b/compose.example.yaml deleted file mode 100644 index 52524b0c..00000000 --- a/compose.example.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# Topology worksheet, deliberately NOT a runnable stack (no application supplied). -# Implement compose.yaml or stack.yaml; do not submit this empty file as deployment. -# Service names below are logical roles, not imposed container names. -x-lab-number: 2 -x-required-roles: - - api - - postgres -# TODO: implement real images/builds, network wiring, volumes, healthchecks, -# credentials and bootstrap. Details: contracts/infrastructure.json and README.md. -services: {} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..261001c7 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,36 @@ +services: + postgres: + image: postgres:16.4-alpine + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 5s + restart: unless-stopped + + api: + build: + context: . + dockerfile: Dockerfile + environment: + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + LOG_LEVEL: info + DATABASE_URL: postgresql+psycopg://messenger:${POSTGRES_PASSWORD}@postgres:5432/messenger + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + ports: + - "8080:8080" + depends_on: + postgres: + condition: service_healthy + restart: unless-stopped + +volumes: + postgres_data: \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..e69de29b diff --git a/student-tests/experiment_cursor.py b/student-tests/experiment_cursor.py new file mode 100644 index 00000000..55ab39ba --- /dev/null +++ b/student-tests/experiment_cursor.py @@ -0,0 +1,337 @@ +import argparse +import json +import math +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +from pathlib import Path + +import httpx + + +def percentile(values: list[float], percent: float) -> float: + if not values: + return 0.0 + ordered = sorted(values) + index = math.ceil(len(ordered) * percent / 100) - 1 + index = max(0, min(index, len(ordered) - 1)) + return round(ordered[index], 3) + + +def require_json(response: httpx.Response, expected_status: int) -> dict: + if response.status_code != expected_status: + raise RuntimeError( + f"{response.request.method} {response.request.url} returned " + f"{response.status_code}, expected {expected_status}: {response.text}" + ) + return response.json() + + +def create_fixture( + base_url: str, + history_size: int, +) -> tuple[str, str]: + suffix = uuid.uuid4().hex[:12] + + with httpx.Client(base_url=base_url, timeout=30.0) as client: + user = require_json( + client.post( + "/api/v1/users", + json={ + "username": f"bench_{suffix}", + "display_name": "Benchmark User", + }, + ), + 201, + ) + user_id = user["id"] + + chat = require_json( + client.post( + "/api/v1/chats", + headers={"X-User-Id": user_id}, + json={ + "title": "Benchmark chat", + "member_ids": [user_id], + }, + ), + 201, + ) + chat_id = chat["id"] + + headers = {"X-User-Id": user_id, "Connection": "close"} + + for number in range(history_size): + last_error = None + + for attempt in range(3): + try: + with httpx.Client(base_url=base_url, timeout=30.0) as client: + response = client.post( + f"/api/v1/chats/{chat_id}/messages", + headers=headers, + json={"text": f"synthetic-{number:06d}"}, + ) + + if response.status_code == 201: + break + + last_error = RuntimeError( + f"message {number}: got {response.status_code}: {response.text}" + ) + + except httpx.HTTPError as error: + last_error = error + + time.sleep(0.05 * (attempt + 1)) + else: + raise RuntimeError( + f"fixture failed at message {number} after 3 attempts: {last_error}" + ) + + if (number + 1) % 1000 == 0 or number + 1 == history_size: + print(f"fixture progress: {number + 1}/{history_size}") + + return user_id, chat_id + +def get_metrics(base_url: str) -> dict: + with httpx.Client(base_url=base_url, timeout=10.0) as client: + return require_json(client.get("/internal/metrics"), 200) + + +def prepare_deep_cursor( + base_url: str, + user_id: str, + chat_id: str, + history_size: int, + page_limit: int, + depth_fraction: float, +) -> str: + pages_before_cursor = max( + 1, + int(history_size * depth_fraction) // page_limit, + ) + + cursor = None + headers = {"X-User-Id": user_id} + + with httpx.Client(base_url=base_url, timeout=30.0) as client: + for _ in range(pages_before_cursor): + params = {"limit": page_limit} + if cursor is not None: + params["cursor"] = cursor + + body = require_json( + client.get( + f"/api/v1/chats/{chat_id}/messages", + headers=headers, + params=params, + ), + 200, + ) + cursor = body["next_cursor"] + + if cursor is None: + raise RuntimeError( + "history ended before requested cursor depth; " + "start with a fresh container" + ) + + return cursor + + +def run_requests( + base_url: str, + user_id: str, + chat_id: str, + cursor: str, + page_limit: int, + concurrency: int, + seconds: int, + record_latencies: bool, +) -> tuple[int, int, list[float], dict[str, int]]: + deadline = time.perf_counter() + seconds + lock = threading.Lock() + + successes = 0 + failures = 0 + latencies: list[float] = [] + status_counts: dict[str, int] = {} + + def worker() -> None: + nonlocal successes, failures + + headers = {"X-User-Id": user_id} + with httpx.Client(base_url=base_url, timeout=10.0) as client: + while time.perf_counter() < deadline: + started = time.perf_counter() + try: + response = client.get( + f"/api/v1/chats/{chat_id}/messages", + headers=headers, + params={"limit": page_limit, "cursor": cursor}, + ) + elapsed_ms = (time.perf_counter() - started) * 1000 + + with lock: + key = str(response.status_code) + status_counts[key] = status_counts.get(key, 0) + 1 + + if response.status_code == 200: + successes += 1 + if record_latencies: + latencies.append(elapsed_ms) + else: + failures += 1 + + except httpx.HTTPError: + with lock: + failures += 1 + status_counts["transport_error"] = ( + status_counts.get("transport_error", 0) + 1 + ) + + with ThreadPoolExecutor(max_workers=concurrency) as executor: + futures = [executor.submit(worker) for _ in range(concurrency)] + for future in futures: + future.result() + + return successes, failures, latencies, status_counts + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Track 1: deep cursor benchmark for in-memory message history." + ) + parser.add_argument("--base-url", required=True) + parser.add_argument("--history-size", type=int, required=True) + parser.add_argument("--concurrency", type=int, required=True) + parser.add_argument("--warmup-seconds", type=int, default=5) + parser.add_argument("--duration-seconds", type=int, default=15) + parser.add_argument("--page-limit", type=int, default=100) + parser.add_argument("--depth-fraction", type=float, default=0.8) + parser.add_argument("--implementation", required=True) + parser.add_argument("--git-commit", required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + + if args.history_size < args.page_limit * 2: + raise SystemExit("history-size must contain at least two pages") + if args.concurrency < 1: + raise SystemExit("concurrency must be >= 1") + if not 0.1 <= args.depth_fraction < 1.0: + raise SystemExit("depth-fraction must be in [0.1, 1.0)") + + print( + f"fixture: history={args.history_size}, " + f"concurrency={args.concurrency}, " + f"deep cursor={args.depth_fraction:.0%}" + ) + + user_id, chat_id = create_fixture(args.base_url, args.history_size) + + metrics_before = get_metrics(args.base_url) + if metrics_before["messages"] != args.history_size: + raise RuntimeError( + f"expected exactly {args.history_size} messages, got " + f"{metrics_before['messages']}. " + "Run each scenario in a fresh container." + ) + + cursor = prepare_deep_cursor( + args.base_url, + user_id, + chat_id, + args.history_size, + args.page_limit, + args.depth_fraction, + ) + + print(f"warmup: {args.warmup_seconds}s") + run_requests( + args.base_url, + user_id, + chat_id, + cursor, + args.page_limit, + args.concurrency, + args.warmup_seconds, + record_latencies=False, + ) + + print(f"measurement: {args.duration_seconds}s") + started_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + successes, failures, latencies, status_counts = run_requests( + args.base_url, + user_id, + chat_id, + cursor, + args.page_limit, + args.concurrency, + args.duration_seconds, + record_latencies=True, + ) + + metrics_after = get_metrics(args.base_url) + attempted = successes + failures + + result = { + "experiment": "track1-inmemory-deep-cursor", + "timestamp_utc": started_at, + "implementation": args.implementation, + "git_commit": args.git_commit, + "container_limits": { + "cpus": 2, + "memory": "512m", + }, + "workload": { + "endpoint": "GET /api/v1/chats/{chat_id}/messages", + "history_size": args.history_size, + "page_limit": args.page_limit, + "cursor_depth_fraction": args.depth_fraction, + "concurrency": args.concurrency, + "warmup_seconds": args.warmup_seconds, + "duration_seconds": args.duration_seconds, + "writes_during_measurement": False, + "client": "httpx synchronous client; one instance per worker", + }, + "results": { + "attempted_requests": attempted, + "successful_requests": successes, + "failed_requests": failures, + "error_rate_percent": round( + (failures / attempted * 100) if attempted else 0.0, + 4, + ), + "successful_rps": round(successes / args.duration_seconds, 3), + "latency_ms": { + "p50": percentile(latencies, 50), + "p95": percentile(latencies, 95), + "p99": percentile(latencies, 99), + }, + "status_counts": status_counts, + "rss_before_bytes": metrics_before["rss_bytes"], + "rss_after_bytes": metrics_after["rss_bytes"], + "rss_after_mib": round( + metrics_after["rss_bytes"] / (1024 * 1024), + 3, + ), + "messages_after": metrics_after["messages"], + }, + } + + output = Path(args.output) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text( + json.dumps(result, ensure_ascii=False, indent=2), + encoding="utf-8", + ) + + print(json.dumps(result["results"], ensure_ascii=False, indent=2)) + print(f"saved: {output}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/student-tests/extra.py b/student-tests/extra.py new file mode 100644 index 00000000..547b99fb --- /dev/null +++ b/student-tests/extra.py @@ -0,0 +1,227 @@ +from __future__ import annotations + +import argparse +import json +import sys +import urllib.error +import urllib.parse +import urllib.request +import uuid + + +def request( + base_url: str, + method: str, + path: str, + body: bytes | None = None, + headers: dict[str, str] | None = None, +) -> tuple[int, dict, dict[str, str]]: + request_headers = {"Accept": "application/json"} + if headers: + request_headers.update(headers) + + req = urllib.request.Request( + f"{base_url.rstrip('/')}{path}", + data=body, + headers=request_headers, + method=method, + ) + + try: + with urllib.request.urlopen(req, timeout=10) as response: + raw = response.read().decode("utf-8") + return response.status, json.loads(raw) if raw else {}, dict(response.headers.items()) + except urllib.error.HTTPError as exc: + raw = exc.read().decode("utf-8") + return exc.code, json.loads(raw) if raw else {}, dict(exc.headers.items()) + + +def json_request( + base_url: str, + method: str, + path: str, + payload: dict, + user_id: str | None = None, +) -> tuple[int, dict, dict[str, str]]: + headers = {"Content-Type": "application/json"} + if user_id: + headers["X-User-Id"] = user_id + return request( + base_url, + method, + path, + json.dumps(payload).encode("utf-8"), + headers, + ) + + +def expect_error(status: int, body: dict, expected_status: int, expected_code: str) -> None: + assert status == expected_status, f"expected HTTP {expected_status}, got {status}: {body}" + assert body.get("error", {}).get("code") == expected_code, ( + f"expected error.code={expected_code!r}, got {body}" + ) + assert body.get("error", {}).get("request_id"), f"missing error request_id: {body}" + +def create_user(base_url: str, suffix: str) -> dict: + status, body, _ = json_request( + base_url, + "POST", + "/api/v1/users", + { + "username": f"u_{suffix}", + "display_name": f"User {suffix}", + }, + ) + assert status == 201, f"create user failed: {status}, {body}" + return body + +def create_chat(base_url: str, owner_id: str, member_ids: list[str], suffix: str) -> dict: + status, body, _ = json_request( + base_url, + "POST", + "/api/v1/chats", + { + "title": f"Extra tests {suffix}", + "member_ids": member_ids, + }, + owner_id, + ) + assert status == 201, f"create chat failed: {status}, {body}" + return body + + +def test_malformed_json(base_url: str) -> None: + status, body, _ = request( + base_url, + "POST", + "/api/v1/users", + b'{"username": "bad_json",', + {"Content-Type": "application/json"}, + ) + expect_error(status, body, 400, "invalid_request") + + +def test_foreign_chat(base_url: str, owner: dict, outsider: dict, suffix: str) -> None: + chat = create_chat(base_url, owner["id"], [owner["id"]], suffix) + status, body, _ = request( + base_url, + "GET", + f"/api/v1/chats/{chat['id']}/messages", + headers={"X-User-Id": outsider["id"]}, + ) + expect_error(status, body, 404, "not_found") + + +def test_empty_message(base_url: str, owner: dict, suffix: str) -> None: + chat = create_chat(base_url, owner["id"], [owner["id"]], suffix) + status, body, _ = json_request( + base_url, + "POST", + f"/api/v1/chats/{chat['id']}/messages", + {"text": " "}, + owner["id"], + ) + expect_error(status, body, 400, "invalid_request") + + +def test_duplicate_username(base_url: str, suffix: str) -> None: + username = f"dup_{suffix}" + + status, body, _ = json_request( + base_url, + "POST", + "/api/v1/users", + {"username": username, "display_name": "Original"}, + ) + assert status == 201, f"first user creation failed: {status}, {body}" + + status, body, _ = json_request( + base_url, + "POST", + "/api/v1/users", + {"username": username, "display_name": "Duplicate"}, + ) + expect_error(status, body, 409, "conflict") + + +def test_message_pagination(base_url: str, owner: dict, suffix: str) -> None: + chat = create_chat(base_url, owner["id"], [owner["id"]], suffix) + expected_texts = [f"page_{suffix}_{index}" for index in range(7)] + + for text in expected_texts: + status, body, _ = json_request( + base_url, + "POST", + f"/api/v1/chats/{chat['id']}/messages", + {"text": text}, + owner["id"], + ) + assert status == 201, f"message creation failed: {status}, {body}" + + received = [] + cursor = None + + while True: + query = {"limit": "3"} + if cursor: + query["cursor"] = cursor + + status, body, _ = request( + base_url, + "GET", + f"/api/v1/chats/{chat['id']}/messages?{urllib.parse.urlencode(query)}", + headers={"X-User-Id": owner["id"]}, + ) + assert status == 200, f"history request failed: {status}, {body}" + + received.extend(body["items"]) + cursor = body["next_cursor"] + if cursor is None: + break + + received_ids = [message["id"] for message in received] + received_texts = [message["text"] for message in received] + + assert len(received) == len(expected_texts), ( + f"expected {len(expected_texts)} messages, got {len(received)}" + ) + assert len(set(received_ids)) == len(expected_texts), "pagination returned duplicate message IDs" + assert received_texts == expected_texts, ( + f"unexpected message order/content: {received_texts}" + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + args = parser.parse_args() + + suffix = uuid.uuid4().hex[:12] + owner = create_user(args.base_url, f"owner_{suffix}") + outsider = create_user(args.base_url, f"outsider_{suffix}") + + tests = [ + ("malformed JSON -> 400 invalid_request", lambda: test_malformed_json(args.base_url)), + ("foreign chat -> 404 not_found", lambda: test_foreign_chat(args.base_url, owner, outsider, suffix)), + ("empty message -> 400 invalid_request", lambda: test_empty_message(args.base_url, owner, suffix)), + ("duplicate username -> 409 conflict", lambda: test_duplicate_username(args.base_url, suffix)), + ("message pagination across pages", lambda: test_message_pagination(args.base_url, owner, suffix)), + ] + + for name, test in tests: + test() + print(f"PASS: {name}") + + print("PASS: extra lab1 scenarios (5/5)") + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except AssertionError as exc: + print(f"FAIL: {exc}", file=sys.stderr) + raise SystemExit(1) + except Exception as exc: + print(f"FAIL: unexpected error: {type(exc).__name__}: {exc}", file=sys.stderr) + raise SystemExit(1) \ No newline at end of file diff --git a/student-tests/log_safety.py b/student-tests/log_safety.py new file mode 100644 index 00000000..6b712ad3 --- /dev/null +++ b/student-tests/log_safety.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import argparse +import json +import sys +import urllib.error +import urllib.request +import uuid + + +CONTROL_TEXT = "CONTROL_SECRET_MESSAGE_MUST_NOT_BE_IN_LOGS" + + +def request( + base_url: str, + method: str, + path: str, + payload: dict | None = None, + user_id: str | None = None, +) -> tuple[int, dict]: + headers = {"Accept": "application/json"} + data = None + + if payload is not None: + data = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + + if user_id is not None: + headers["X-User-Id"] = user_id + + req = urllib.request.Request( + f"{base_url.rstrip('/')}{path}", + data=data, + headers=headers, + method=method, + ) + + try: + with urllib.request.urlopen(req, timeout=10) as response: + raw = response.read().decode("utf-8") + return response.status, json.loads(raw) if raw else {} + except urllib.error.HTTPError as exc: + raw = exc.read().decode("utf-8") + return exc.code, json.loads(raw) if raw else {} + + +def require(status: int, body: dict, expected: int, action: str) -> None: + assert status == expected, f"{action}: expected HTTP {expected}, got {status}: {body}" + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + args = parser.parse_args() + + suffix = uuid.uuid4().hex[:12] + + status, user = request( + args.base_url, + "POST", + "/api/v1/users", + { + "username": f"log_{suffix}", + "display_name": "Log safety test", + }, + ) + require(status, user, 201, "create user") + + status, chat = request( + args.base_url, + "POST", + "/api/v1/chats", + { + "title": "Log safety test", + "member_ids": [user["id"]], + }, + user["id"], + ) + require(status, chat, 201, "create chat") + + status, message = request( + args.base_url, + "POST", + f"/api/v1/chats/{chat['id']}/messages", + {"text": CONTROL_TEXT}, + user["id"], + ) + require(status, message, 201, "create control message") + + print("PASS: control message accepted with HTTP 201") + print(f"CONTROL_TEXT={CONTROL_TEXT}") + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except AssertionError as exc: + print(f"FAIL: {exc}", file=sys.stderr) + raise SystemExit(1) + except Exception as exc: + print(f"FAIL: unexpected error: {type(exc).__name__}: {exc}", file=sys.stderr) + raise SystemExit(1) \ No newline at end of file diff --git a/student-tests/race_100.py b/student-tests/race_100.py new file mode 100644 index 00000000..8eee918e --- /dev/null +++ b/student-tests/race_100.py @@ -0,0 +1,212 @@ +from __future__ import annotations + +import argparse +import concurrent.futures +import json +import sys +import urllib.error +import urllib.parse +import urllib.request +import uuid + + +TOTAL_CLIENTS = 10 +MESSAGES_PER_CLIENT = 10 +EXPECTED_MESSAGES = TOTAL_CLIENTS * MESSAGES_PER_CLIENT + + +def request( + base_url: str, + method: str, + path: str, + payload: dict | None = None, + user_id: str | None = None, +) -> tuple[int, dict]: + headers = {"Accept": "application/json"} + + data = None + if payload is not None: + data = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + + if user_id is not None: + headers["X-User-Id"] = user_id + + req = urllib.request.Request( + f"{base_url.rstrip('/')}{path}", + data=data, + headers=headers, + method=method, + ) + + try: + with urllib.request.urlopen(req, timeout=15) as response: + raw = response.read().decode("utf-8") + return response.status, json.loads(raw) if raw else {} + except urllib.error.HTTPError as exc: + raw = exc.read().decode("utf-8") + return exc.code, json.loads(raw) if raw else {} + + +def require_status(status: int, body: dict, expected: int, action: str) -> None: + assert status == expected, f"{action}: expected HTTP {expected}, got {status}: {body}" + + +def create_user(base_url: str, suffix: str, index: int) -> dict: + status, body = request( + base_url, + "POST", + "/api/v1/users", + { + "username": f"race_{suffix}_{index}", + "display_name": f"Race client {index}", + }, + ) + require_status(status, body, 201, f"create user {index}") + return body + + +def create_chat(base_url: str, owner_id: str, member_ids: list[str], suffix: str) -> dict: + status, body = request( + base_url, + "POST", + "/api/v1/chats", + { + "title": f"Race test {suffix}", + "member_ids": member_ids, + }, + owner_id, + ) + require_status(status, body, 201, "create chat") + return body + + +def send_message( + base_url: str, + chat_id: str, + user_id: str, + client_index: int, + message_index: int, + suffix: str, +) -> dict: + text = f"race_{suffix}_client_{client_index}_message_{message_index}" + status, body = request( + base_url, + "POST", + f"/api/v1/chats/{chat_id}/messages", + {"text": text}, + user_id, + ) + require_status( + status, + body, + 201, + f"send client={client_index}, message={message_index}", + ) + return body + + +def read_all_messages(base_url: str, chat_id: str, user_id: str) -> list[dict]: + items: list[dict] = [] + cursor: str | None = None + + while True: + query = {"limit": "100"} + if cursor is not None: + query["cursor"] = cursor + + status, body = request( + base_url, + "GET", + f"/api/v1/chats/{chat_id}/messages?{urllib.parse.urlencode(query)}", + user_id=user_id, + ) + require_status(status, body, 200, "read messages") + + items.extend(body["items"]) + cursor = body["next_cursor"] + if cursor is None: + return items + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Race test: 10 clients × 10 messages, then verify 100 unique messages." + ) + parser.add_argument("--base-url", default="http://localhost:8080") + args = parser.parse_args() + + suffix = uuid.uuid4().hex[:12] + + users = [ + create_user(args.base_url, suffix, index) + for index in range(TOTAL_CLIENTS) + ] + chat = create_chat( + args.base_url, + users[0]["id"], + [user["id"] for user in users], + suffix, + ) + + jobs = [ + ( + args.base_url, + chat["id"], + users[client_index]["id"], + client_index, + message_index, + suffix, + ) + for client_index in range(TOTAL_CLIENTS) + for message_index in range(MESSAGES_PER_CLIENT) + ] + + with concurrent.futures.ThreadPoolExecutor(max_workers=TOTAL_CLIENTS) as executor: + created = list(executor.map(lambda job: send_message(*job), jobs)) + + created_ids = [message["id"] for message in created] + assert len(created) == EXPECTED_MESSAGES, ( + f"POST result count: expected {EXPECTED_MESSAGES}, got {len(created)}" + ) + assert len(set(created_ids)) == EXPECTED_MESSAGES, ( + f"POST returned duplicate IDs: {len(set(created_ids))}/{EXPECTED_MESSAGES} unique" + ) + + messages = read_all_messages(args.base_url, chat["id"], users[0]["id"]) + ids = [message["id"] for message in messages] + texts = [message["text"] for message in messages] + + expected_texts = { + f"race_{suffix}_client_{client_index}_message_{message_index}" + for client_index in range(TOTAL_CLIENTS) + for message_index in range(MESSAGES_PER_CLIENT) + } + + assert len(messages) == EXPECTED_MESSAGES, ( + f"history count: expected {EXPECTED_MESSAGES}, got {len(messages)}" + ) + assert len(set(ids)) == EXPECTED_MESSAGES, ( + f"history contains duplicate IDs: {len(set(ids))}/{EXPECTED_MESSAGES} unique" + ) + assert set(texts) == expected_texts, ( + "history is missing or contains unexpected messages" + ) + + print(f"PASS: parallel POST requests: {len(created)}/{EXPECTED_MESSAGES}") + print(f"PASS: unique IDs returned by POST: {len(set(created_ids))}/{EXPECTED_MESSAGES}") + print(f"PASS: history items after writes: {len(messages)}/{EXPECTED_MESSAGES}") + print(f"PASS: unique IDs in history: {len(set(ids))}/{EXPECTED_MESSAGES}") + print("PASS: race test (10 clients x 10 messages = 100 unique messages)") + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except AssertionError as exc: + print(f"FAIL: {exc}", file=sys.stderr) + raise SystemExit(1) + except Exception as exc: + print(f"FAIL: unexpected error: {type(exc).__name__}: {exc}", file=sys.stderr) + raise SystemExit(1) \ No newline at end of file