Lab2: starting
This commit is contained in:
+159
@@ -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 (
|
||||
<div style={{ maxWidth: 480, margin: "2rem auto", fontFamily: "sans-serif" }}>
|
||||
<h1>Lab1 Messenger — демо-клиент</h1>
|
||||
{error && <p style={{ color: "red" }}>{error}</p>}
|
||||
|
||||
{!me && (
|
||||
<section>
|
||||
<h2>Регистрация</h2>
|
||||
<input
|
||||
placeholder="username (a-z0-9_)"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
placeholder="display name"
|
||||
value={displayName}
|
||||
onChange={(e) => setDisplayName(e.target.value)}
|
||||
/>
|
||||
<button onClick={handleRegister}>Зарегистрироваться</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{me && !chat && (
|
||||
<section>
|
||||
<p>
|
||||
Вошли как <b>{me.username}</b> (id: {me.id})
|
||||
</p>
|
||||
<h2>Создать чат</h2>
|
||||
<input
|
||||
placeholder="название чата"
|
||||
value={chatTitle}
|
||||
onChange={(e) => setChatTitle(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
placeholder="ID других участников через запятую"
|
||||
value={memberIdsInput}
|
||||
onChange={(e) => setMemberIdsInput(e.target.value)}
|
||||
/>
|
||||
<button onClick={handleCreateChat}>Создать</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{me && chat && (
|
||||
<section>
|
||||
<h2>Чат: {chat.title}</h2>
|
||||
<button onClick={handleLoadHistory}>Обновить историю</button>
|
||||
<ul>
|
||||
{messages.map((m) => (
|
||||
<li key={m.id}>
|
||||
<b>{m.sender_id === me.id ? "Я" : m.sender_id}:</b> {m.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<input
|
||||
placeholder="текст сообщения"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
/>
|
||||
<button onClick={handleSendMessage}>Отправить</button>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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")
|
||||
+31
@@ -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
|
||||
@@ -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)})
|
||||
+204
@@ -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)
|
||||
+128
@@ -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
|
||||
@@ -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()
|
||||
+232
@@ -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()
|
||||
Reference in New Issue
Block a user