Lab2
This commit is contained in:
+379
-141
@@ -2,158 +2,396 @@ 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;
|
||||
function basicAuthorization(username, password) {
|
||||
const encoded = btoa(
|
||||
new TextEncoder()
|
||||
.encode(`${username}:${password}`)
|
||||
.reduce((value, byte) => value + String.fromCharCode(byte), "")
|
||||
);
|
||||
|
||||
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 `Basic ${encoded}`;
|
||||
}
|
||||
return data;
|
||||
|
||||
async function apiFetch(
|
||||
path,
|
||||
{
|
||||
method = "GET",
|
||||
token,
|
||||
basicCredentials,
|
||||
body,
|
||||
} = {}
|
||||
) {
|
||||
const headers = {
|
||||
Accept: "application/json",
|
||||
};
|
||||
|
||||
if (body !== undefined) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
if (basicCredentials) {
|
||||
headers.Authorization = basicAuthorization(
|
||||
basicCredentials.username,
|
||||
basicCredentials.password
|
||||
);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
const requestId = response.headers.get("X-Request-Id");
|
||||
|
||||
const raw = await response.text();
|
||||
const data = raw ? JSON.parse(raw) : null;
|
||||
|
||||
if (!response.ok) {
|
||||
const message = data?.error?.message || `HTTP ${response.status}`;
|
||||
throw new Error(`${message} (request_id: ${requestId || "unknown"})`);
|
||||
}
|
||||
|
||||
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("");
|
||||
const [username, setUsername] = useState("");
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [password, setPassword] = 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);
|
||||
}
|
||||
}
|
||||
const [session, setSession] = useState(null);
|
||||
const [chat, setChat] = useState(null);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
const [memberIdsInput, setMemberIdsInput] = useState("");
|
||||
const [chatTitle, setChatTitle] = useState("");
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
const [text, setText] = useState("");
|
||||
const [messages, setMessages] = useState([]);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 480, margin: "2rem auto", fontFamily: "sans-serif" }}>
|
||||
<h1>Lab1 Messenger — демо-клиент</h1>
|
||||
{error && <p style={{ color: "red" }}>{error}</p>}
|
||||
const me = session?.user ?? null;
|
||||
const token = session?.token ?? null;
|
||||
|
||||
{!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>
|
||||
)}
|
||||
async function handleRegister() {
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
{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>
|
||||
)}
|
||||
try {
|
||||
await apiFetch("/users", {
|
||||
method: "POST",
|
||||
body: {
|
||||
username,
|
||||
display_name: displayName,
|
||||
password,
|
||||
},
|
||||
});
|
||||
|
||||
{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>
|
||||
);
|
||||
const createdSession = await apiFetch("/auth/sessions", {
|
||||
method: "POST",
|
||||
basicCredentials: {
|
||||
username,
|
||||
password,
|
||||
},
|
||||
});
|
||||
|
||||
setSession(createdSession);
|
||||
setPassword("");
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateChat() {
|
||||
if (!me || !token) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const enteredMemberIds = memberIdsInput
|
||||
.split(",")
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const uniqueMemberIds = [...new Set([me.id, ...enteredMemberIds])];
|
||||
|
||||
const created = await apiFetch("/chats", {
|
||||
method: "POST",
|
||||
token,
|
||||
body: {
|
||||
title: chatTitle,
|
||||
member_ids: uniqueMemberIds,
|
||||
},
|
||||
});
|
||||
|
||||
setChat(created);
|
||||
setMessages([]);
|
||||
setText("");
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendMessage() {
|
||||
if (!chat || !token) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const message = await apiFetch(`/chats/${chat.id}/messages`, {
|
||||
method: "POST",
|
||||
token,
|
||||
body: { text },
|
||||
});
|
||||
|
||||
setMessages((previous) => [...previous, message]);
|
||||
setText("");
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLoadHistory() {
|
||||
if (!chat || !token) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const page = await apiFetch(`/chats/${chat.id}/messages?limit=100`, {
|
||||
token,
|
||||
});
|
||||
|
||||
setMessages(page.items);
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await apiFetch("/auth/sessions/current", {
|
||||
method: "DELETE",
|
||||
token,
|
||||
});
|
||||
|
||||
setSession(null);
|
||||
setChat(null);
|
||||
setMessages([]);
|
||||
setText("");
|
||||
setMemberIdsInput("");
|
||||
setChatTitle("");
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
|
||||
// Если token уже истёк или был отозван, локальная сессия всё равно
|
||||
// недействительна, поэтому её следует очистить.
|
||||
if (
|
||||
requestError.message.includes("Authentication") ||
|
||||
requestError.message.includes("401")
|
||||
) {
|
||||
setSession(null);
|
||||
setChat(null);
|
||||
setMessages([]);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
maxWidth: 560,
|
||||
margin: "2rem auto",
|
||||
fontFamily: "sans-serif",
|
||||
}}
|
||||
>
|
||||
<h1>Lab2 Messenger — демо-клиент</h1>
|
||||
|
||||
{error && (
|
||||
<p
|
||||
role="alert"
|
||||
style={{
|
||||
color: "#b00020",
|
||||
background: "#ffe7eb",
|
||||
padding: "0.75rem",
|
||||
borderRadius: "0.25rem",
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!me && (
|
||||
<section>
|
||||
<h2>Регистрация и вход</h2>
|
||||
|
||||
<p>
|
||||
После регистрации клиент автоматически создаст сессию через Basic
|
||||
authentication и начнёт использовать Bearer-token.
|
||||
</p>
|
||||
|
||||
<input
|
||||
placeholder="username: a-z, 0-9, _"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
autoComplete="username"
|
||||
/>
|
||||
|
||||
<input
|
||||
placeholder="display name"
|
||||
value={displayName}
|
||||
onChange={(event) => setDisplayName(event.target.value)}
|
||||
autoComplete="name"
|
||||
/>
|
||||
|
||||
<input
|
||||
type="password"
|
||||
placeholder="пароль: 12–128 символов"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRegister}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Выполняется…" : "Зарегистрироваться и войти"}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{me && !chat && (
|
||||
<section>
|
||||
<p>
|
||||
Вошли как <b>{me.username}</b>
|
||||
</p>
|
||||
|
||||
<p style={{ overflowWrap: "anywhere" }}>
|
||||
ID пользователя: {me.id}
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLogout}
|
||||
disabled={loading}
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
|
||||
<h2>Создать чат</h2>
|
||||
|
||||
<input
|
||||
placeholder="название чата"
|
||||
value={chatTitle}
|
||||
onChange={(event) => setChatTitle(event.target.value)}
|
||||
/>
|
||||
|
||||
<input
|
||||
placeholder="UUID других участников через запятую"
|
||||
value={memberIdsInput}
|
||||
onChange={(event) => setMemberIdsInput(event.target.value)}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCreateChat}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Создаётся…" : "Создать чат"}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{me && chat && (
|
||||
<section>
|
||||
<p>
|
||||
Вошли как <b>{me.username}</b>
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLogout}
|
||||
disabled={loading}
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
|
||||
<h2>Чат: {chat.title}</h2>
|
||||
|
||||
<p>
|
||||
Участники: {chat.member_ids.length}
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLoadHistory}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Загружается…" : "Обновить историю"}
|
||||
</button>
|
||||
|
||||
<ul>
|
||||
{messages.map((message) => (
|
||||
<li key={message.id}>
|
||||
<b>
|
||||
{message.sender_id === me.id
|
||||
? "Я"
|
||||
: message.sender_id}
|
||||
:
|
||||
</b>{" "}
|
||||
{message.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<input
|
||||
placeholder="текст сообщения"
|
||||
value={text}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSendMessage}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Отправляется…" : "Отправить"}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
"""Valkey session cache.
|
||||
|
||||
PostgreSQL is the source of truth for sessions. Valkey only keeps a short
|
||||
lived copy of "token hash -> user" to avoid a SQL lookup on every request:
|
||||
|
||||
- key: messenger:session:<sha256(token)>, the raw token is never stored;
|
||||
- value TTL: min(SESSION_CACHE_TTL_SECONDS, remaining session lifetime),
|
||||
and expires_at is checked again on every read;
|
||||
- logout writes a "revoked" tombstone (SET ... EX, overwrite), while cache
|
||||
population uses SET ... NX, so a concurrent request cannot resurrect a
|
||||
revoked session in the cache;
|
||||
- any Valkey error or timeout is a cache miss: requests go to PostgreSQL and
|
||||
the cache is skipped for CACHE_RETRY_AFTER_SECONDS. After such an error the
|
||||
cache is flushed before its next use, because an invalidation may have
|
||||
been lost while Valkey was unreachable.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import ConnectionPool, Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
logger = logging.getLogger("messenger.cache")
|
||||
|
||||
KEY_PREFIX = "messenger:session:"
|
||||
REVOKED = "revoked"
|
||||
|
||||
|
||||
class Revoked:
|
||||
"""Marker returned when the cache knows the session was revoked."""
|
||||
|
||||
|
||||
REVOKED_SESSION = Revoked()
|
||||
|
||||
|
||||
def _key(token_hash: str) -> str:
|
||||
return KEY_PREFIX + token_hash
|
||||
|
||||
|
||||
def _serialize(user: dict[str, Any], expires_at: datetime) -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"id": str(user["id"]),
|
||||
"username": user["username"],
|
||||
"display_name": user["display_name"],
|
||||
"created_at": user["created_at"].isoformat(),
|
||||
"expires_at": expires_at.isoformat(),
|
||||
},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
|
||||
|
||||
def _deserialize(raw: str) -> tuple[dict[str, Any], datetime]:
|
||||
payload = json.loads(raw)
|
||||
user = {
|
||||
"id": UUID(payload["id"]),
|
||||
"username": payload["username"],
|
||||
"display_name": payload["display_name"],
|
||||
"created_at": datetime.fromisoformat(payload["created_at"]),
|
||||
}
|
||||
return user, datetime.fromisoformat(payload["expires_at"])
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url: str | None) -> None:
|
||||
self._client: Redis | None = None
|
||||
self._unavailable_until = 0.0
|
||||
self._needs_flush = False
|
||||
|
||||
if url:
|
||||
pool = ConnectionPool.from_url(
|
||||
url,
|
||||
max_connections=settings.cache_max_connections,
|
||||
socket_timeout=settings.cache_timeout_seconds,
|
||||
socket_connect_timeout=settings.cache_timeout_seconds,
|
||||
decode_responses=True,
|
||||
)
|
||||
self._client = Redis(connection_pool=pool)
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self._client is not None
|
||||
|
||||
async def _run(self, operation):
|
||||
"""Run one cache operation; return (ok, result)."""
|
||||
if self._client is None:
|
||||
return False, None
|
||||
|
||||
if time.monotonic() < self._unavailable_until:
|
||||
return False, None
|
||||
|
||||
try:
|
||||
async with asyncio.timeout(settings.cache_timeout_seconds * 2):
|
||||
if self._needs_flush:
|
||||
await self._client.flushdb()
|
||||
self._needs_flush = False
|
||||
logger.warning("session cache recovered and was flushed")
|
||||
return True, await operation(self._client)
|
||||
except (RedisError, OSError, TimeoutError) as exc:
|
||||
self._unavailable_until = (
|
||||
time.monotonic() + settings.cache_retry_after_seconds
|
||||
)
|
||||
self._needs_flush = True
|
||||
logger.warning(
|
||||
"session cache unavailable, falling back to PostgreSQL: %s",
|
||||
type(exc).__name__,
|
||||
)
|
||||
return False, None
|
||||
|
||||
async def get(
|
||||
self,
|
||||
token_hash: str,
|
||||
) -> dict[str, Any] | Revoked | None:
|
||||
ok, raw = await self._run(lambda client: client.get(_key(token_hash)))
|
||||
|
||||
if not ok or raw is None:
|
||||
return None
|
||||
|
||||
if raw == REVOKED:
|
||||
return REVOKED_SESSION
|
||||
|
||||
try:
|
||||
user, expires_at = _deserialize(raw)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return None
|
||||
|
||||
if expires_at <= datetime.now(timezone.utc):
|
||||
return None
|
||||
|
||||
return user
|
||||
|
||||
async def put(
|
||||
self,
|
||||
token_hash: str,
|
||||
user: dict[str, Any],
|
||||
expires_at: datetime,
|
||||
) -> None:
|
||||
remaining = (expires_at - datetime.now(timezone.utc)).total_seconds()
|
||||
ttl = min(settings.session_cache_ttl_seconds, math.floor(remaining))
|
||||
|
||||
if ttl < 1:
|
||||
return
|
||||
|
||||
value = _serialize(user, expires_at)
|
||||
await self._run(
|
||||
lambda client: client.set(_key(token_hash), value, ex=ttl, nx=True)
|
||||
)
|
||||
|
||||
async def revoke(self, token_hash: str) -> None:
|
||||
await self._run(
|
||||
lambda client: client.set(
|
||||
_key(token_hash),
|
||||
REVOKED,
|
||||
ex=settings.session_cache_ttl_seconds,
|
||||
)
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._client is not None:
|
||||
await self._client.aclose()
|
||||
|
||||
|
||||
session_cache = SessionCache(settings.cache_url)
|
||||
+88
-15
@@ -1,19 +1,92 @@
|
||||
"""
|
||||
Конфигурация из окружения (переменные среды), как того требует задание Lab1:
|
||||
"конфигурация приходит из окружения".
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
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
|
||||
def read_value(name: str, default: str | None = None) -> str:
|
||||
file_name = os.getenv(f"{name}_FILE")
|
||||
|
||||
HOST = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
PORT = _int_env("APP_PORT", 8080)
|
||||
LOG_LEVEL = os.environ.get("LOG_LEVEL", "info")
|
||||
if file_name:
|
||||
return Path(file_name).read_text(encoding="utf-8").strip()
|
||||
|
||||
value = os.getenv(name, default)
|
||||
|
||||
if value is None:
|
||||
raise RuntimeError(f"{name} is required.")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def read_positive_int(name: str, default: str) -> int:
|
||||
value = int(os.getenv(name, default))
|
||||
|
||||
if value < 1:
|
||||
raise RuntimeError(f"{name} must be positive.")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def read_positive_float(name: str, default: str) -> float:
|
||||
value = float(os.getenv(name, default))
|
||||
|
||||
if value <= 0:
|
||||
raise RuntimeError(f"{name} must be positive.")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
app_host: str
|
||||
app_port: int
|
||||
database_url: str
|
||||
session_ttl_seconds: int
|
||||
# PostgreSQL connection pool and timeouts.
|
||||
db_pool_size: int
|
||||
db_max_overflow: int
|
||||
db_pool_timeout_seconds: float
|
||||
db_connect_timeout_seconds: float
|
||||
db_statement_timeout_ms: int
|
||||
# Valkey is a session cache; PostgreSQL stays the source of truth.
|
||||
cache_url: str | None
|
||||
session_cache_ttl_seconds: int
|
||||
cache_timeout_seconds: float
|
||||
cache_max_connections: int
|
||||
cache_retry_after_seconds: float
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
session_store = os.getenv("SESSION_STORE", "postgres").lower()
|
||||
|
||||
if session_store not in {"postgres", "valkey", "redis"}:
|
||||
raise RuntimeError("SESSION_STORE must be postgres, valkey or redis.")
|
||||
|
||||
cache_url = None
|
||||
if session_store != "postgres":
|
||||
cache_url = read_value("CACHE_URL")
|
||||
|
||||
return Settings(
|
||||
app_host=os.getenv("APP_HOST", "0.0.0.0"),
|
||||
app_port=int(os.getenv("APP_PORT", "8080")),
|
||||
database_url=read_value("DATABASE_URL"),
|
||||
session_ttl_seconds=read_positive_int("SESSION_TTL_SECONDS", "3600"),
|
||||
db_pool_size=read_positive_int("DB_POOL_SIZE", "10"),
|
||||
db_max_overflow=int(os.getenv("DB_MAX_OVERFLOW", "5")),
|
||||
db_pool_timeout_seconds=read_positive_float("DB_POOL_TIMEOUT_SECONDS", "3"),
|
||||
db_connect_timeout_seconds=read_positive_float(
|
||||
"DB_CONNECT_TIMEOUT_SECONDS", "3"
|
||||
),
|
||||
db_statement_timeout_ms=read_positive_int("DB_STATEMENT_TIMEOUT_MS", "5000"),
|
||||
cache_url=cache_url,
|
||||
session_cache_ttl_seconds=read_positive_int(
|
||||
"SESSION_CACHE_TTL_SECONDS", "60"
|
||||
),
|
||||
cache_timeout_seconds=read_positive_float("CACHE_TIMEOUT_SECONDS", "0.25"),
|
||||
cache_max_connections=read_positive_int("CACHE_MAX_CONNECTIONS", "20"),
|
||||
cache_retry_after_seconds=read_positive_float(
|
||||
"CACHE_RETRY_AFTER_SECONDS", "5"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
settings = load_settings()
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
database_url = settings.database_url.replace(
|
||||
"postgresql://",
|
||||
"postgresql+asyncpg://",
|
||||
1,
|
||||
)
|
||||
|
||||
# Bounded pool: at most db_pool_size + db_max_overflow connections per API
|
||||
# process. Waiting for a free connection, connecting and every statement are
|
||||
# limited, so an unavailable database produces a fast 503 instead of a hang.
|
||||
engine = create_async_engine(
|
||||
database_url,
|
||||
pool_pre_ping=True,
|
||||
pool_size=settings.db_pool_size,
|
||||
max_overflow=settings.db_max_overflow,
|
||||
pool_timeout=settings.db_pool_timeout_seconds,
|
||||
pool_recycle=1800,
|
||||
connect_args={
|
||||
"timeout": settings.db_connect_timeout_seconds,
|
||||
"command_timeout": settings.db_statement_timeout_ms / 1000 + 1,
|
||||
"server_settings": {
|
||||
"statement_timeout": str(settings.db_statement_timeout_ms),
|
||||
"idle_in_transaction_session_timeout": "10000",
|
||||
"application_name": "messenger-api",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
SessionLocal = async_sessionmaker(
|
||||
bind=engine,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with SessionLocal() as session:
|
||||
yield session
|
||||
|
||||
|
||||
async def check_database_ready() -> bool:
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.exec_driver_sql("SELECT 1")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
+47
-17
@@ -1,27 +1,57 @@
|
||||
"""
|
||||
Зависимости FastAPI: проверка X-User-Id (учебная идентификация Lab1)
|
||||
и разбор query-параметров пагинации.
|
||||
FastAPI dependencies for Lab2:
|
||||
- Bearer authentication;
|
||||
- pagination query parameters.
|
||||
"""
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Header, Query
|
||||
from fastapi import Depends, Query, Request, Security
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBearer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.errors import ApiError
|
||||
from app.storage import storage
|
||||
from app.db import get_db
|
||||
from app.errors import Unauthorized
|
||||
from app.services import current_user_from_bearer_token
|
||||
|
||||
|
||||
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
|
||||
# Security schemes make the "Authorize" button in /docs send real
|
||||
# Authorization headers. Errors keep the contract format: auto_error=False
|
||||
# and our own 401 responses.
|
||||
bearer_scheme = HTTPBearer(
|
||||
scheme_name="Bearer",
|
||||
auto_error=False,
|
||||
description="Opaque session token from POST /api/v1/auth/sessions.",
|
||||
)
|
||||
|
||||
|
||||
class BasicForDocs(HTTPBasic):
|
||||
"""Documents Basic auth; the header is parsed by app.security."""
|
||||
|
||||
async def __call__(self, request: Request) -> None: # type: ignore[override]
|
||||
return None
|
||||
|
||||
|
||||
basic_scheme = BasicForDocs(
|
||||
scheme_name="Basic",
|
||||
auto_error=False,
|
||||
description="Only for POST /api/v1/auth/sessions.",
|
||||
)
|
||||
|
||||
|
||||
async def require_user(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Security(
|
||||
bearer_scheme
|
||||
),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict:
|
||||
if credentials is None or not credentials.credentials.strip():
|
||||
raise Unauthorized("Bearer")
|
||||
|
||||
return await current_user_from_bearer_token(
|
||||
db,
|
||||
credentials.credentials.strip(),
|
||||
)
|
||||
|
||||
|
||||
def pagination_params(
|
||||
|
||||
+60
-40
@@ -1,59 +1,79 @@
|
||||
"""
|
||||
Единый формат ошибок согласно 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",
|
||||
}
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status_code: int, message: str, code: str | None = None):
|
||||
def __init__(
|
||||
self,
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
self.status_code = status_code
|
||||
self.code = code or ALLOWED_CODES.get(status_code, "internal_error")
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def _request_id(request: Request) -> str:
|
||||
return getattr(request.state, "request_id", "unknown")
|
||||
class InvalidRequest(ApiError):
|
||||
def __init__(self, message: str = "Invalid request.") -> None:
|
||||
super().__init__(400, "invalid_request", message)
|
||||
|
||||
|
||||
def build_error_body(request: Request, code: str, message: str) -> dict:
|
||||
return {"error": {"code": code, "message": message, "request_id": _request_id(request)}}
|
||||
class Unauthorized(ApiError):
|
||||
def __init__(self, scheme: str = "Bearer") -> None:
|
||||
if scheme == "Basic":
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"'
|
||||
else:
|
||||
challenge = 'Bearer realm="messenger"'
|
||||
|
||||
super().__init__(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Authentication is required.",
|
||||
{"WWW-Authenticate": challenge},
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
class NotFound(ApiError):
|
||||
def __init__(self, message: str = "Object not found.") -> None:
|
||||
super().__init__(404, "not_found", message)
|
||||
|
||||
|
||||
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)})
|
||||
class Conflict(ApiError):
|
||||
def __init__(self, message: str = "Conflict.") -> None:
|
||||
super().__init__(409, "conflict", message)
|
||||
|
||||
|
||||
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)})
|
||||
class Unavailable(ApiError):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(503, "unavailable", "Service is unavailable.")
|
||||
|
||||
def request_id(request: Request) -> str:
|
||||
return getattr(request.state, "request_id", str(uuid4()))
|
||||
|
||||
|
||||
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)})
|
||||
async def api_error_handler(
|
||||
request: Request,
|
||||
exc: ApiError,
|
||||
) -> JSONResponse:
|
||||
rid = request_id(request)
|
||||
|
||||
headers = {
|
||||
"X-Request-Id": rid,
|
||||
**exc.headers,
|
||||
}
|
||||
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": exc.code,
|
||||
"message": exc.message,
|
||||
"request_id": rid,
|
||||
}
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
+285
-160
@@ -1,40 +1,20 @@
|
||||
"""
|
||||
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
|
||||
from __future__ import annotations
|
||||
|
||||
Конфигурация (host/port/log-level) приходит из окружения — см. app/config.py.
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
Запуск через 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 import Depends, FastAPI, Request, Response, Security
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy import exc as sa_exc
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
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.cache import session_cache
|
||||
from app.db import check_database_ready, engine, get_db
|
||||
from app.deps import basic_scheme, pagination_params, require_user
|
||||
from app.errors import ApiError, Unavailable, api_error_handler
|
||||
from app.models import (
|
||||
Chat,
|
||||
ChatPage,
|
||||
@@ -44,161 +24,306 @@ from app.models import (
|
||||
Health,
|
||||
Message,
|
||||
MessagePage,
|
||||
Session,
|
||||
User,
|
||||
)
|
||||
from app.storage import storage
|
||||
from pathlib import Path
|
||||
from app.services import (
|
||||
create_chat,
|
||||
create_message,
|
||||
create_user_session,
|
||||
get_chat,
|
||||
list_chats,
|
||||
list_messages,
|
||||
logout_current_session,
|
||||
register_user,
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
yield
|
||||
await session_cache.close()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger — лабораторная 2",
|
||||
version="1.2.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
request.state.request_id = str(uuid.uuid4())
|
||||
request.state.request_id = (
|
||||
request.headers.get("X-Request-Id")
|
||||
or str(uuid4())
|
||||
)
|
||||
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
return response
|
||||
|
||||
# ---------- Health ----------
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(
|
||||
request: Request,
|
||||
exc: Exception,
|
||||
) -> JSONResponse:
|
||||
if not isinstance(exc, ApiError):
|
||||
raise exc
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
async def liveness():
|
||||
return Health(status="ok")
|
||||
return await api_error_handler(request, exc)
|
||||
|
||||
|
||||
@app.get("/health/ready", response_model=Health)
|
||||
async def readiness():
|
||||
# В Lab1 нет внешних зависимостей (БД появится в Lab2), поэтому
|
||||
# процесс всегда готов, если он успешно поднялся.
|
||||
return Health(status="ok")
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(
|
||||
request: Request,
|
||||
_exc: RequestValidationError,
|
||||
) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", str(uuid4()))
|
||||
|
||||
@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
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={
|
||||
"error": {
|
||||
"code": "invalid_request",
|
||||
"message": "Invalid request.",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers={
|
||||
"X-Request-Id": request_id,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
async def current_user(user: dict = Depends(require_user)):
|
||||
return user
|
||||
logger = logging.getLogger("messenger.api")
|
||||
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def is_dependency_failure(exc: Exception) -> bool:
|
||||
"""PostgreSQL is unreachable, restarting, overloaded or timed out."""
|
||||
if isinstance(
|
||||
exc,
|
||||
(
|
||||
sa_exc.OperationalError,
|
||||
sa_exc.InterfaceError,
|
||||
sa_exc.TimeoutError, # connection pool exhausted
|
||||
OSError,
|
||||
TimeoutError,
|
||||
),
|
||||
):
|
||||
return True
|
||||
|
||||
@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
|
||||
return isinstance(exc, sa_exc.DBAPIError) and exc.connection_invalidated
|
||||
|
||||
|
||||
@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),
|
||||
async def dependency_error_handler(
|
||||
request: Request,
|
||||
exc: Exception,
|
||||
) -> JSONResponse:
|
||||
if not is_dependency_failure(exc):
|
||||
return await unexpected_error_handler(request, exc)
|
||||
|
||||
logger.warning("database unavailable: %s", type(exc).__name__)
|
||||
return await api_error_handler(request, Unavailable())
|
||||
|
||||
|
||||
for _exc_class in (sa_exc.DBAPIError, sa_exc.TimeoutError, OSError, TimeoutError):
|
||||
app.add_exception_handler(_exc_class, dependency_error_handler)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unexpected_error_handler(
|
||||
request: Request,
|
||||
exc: Exception,
|
||||
) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", str(uuid4()))
|
||||
# Only the type: SQL parameters and headers may contain secrets.
|
||||
logger.error("unexpected error: %s", type(exc).__name__)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"error": {
|
||||
"code": "internal_error",
|
||||
"message": "Internal server error.",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers={
|
||||
"X-Request-Id": request_id,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/health/live",
|
||||
response_model=Health,
|
||||
)
|
||||
async def liveness() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get(
|
||||
"/health/ready",
|
||||
response_model=Health,
|
||||
)
|
||||
async def readiness() -> dict[str, str]:
|
||||
if not await check_database_ready():
|
||||
raise Unavailable()
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/users",
|
||||
status_code=201,
|
||||
response_model=User,
|
||||
)
|
||||
async def register_user_route(
|
||||
payload: CreateUser,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
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)
|
||||
return await register_user(
|
||||
db,
|
||||
username=payload.username,
|
||||
display_name=payload.display_name,
|
||||
password=payload.password,
|
||||
)
|
||||
|
||||
|
||||
@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),
|
||||
@app.post(
|
||||
"/api/v1/auth/sessions",
|
||||
status_code=201,
|
||||
response_model=Session,
|
||||
)
|
||||
async def login(
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_basic: None = Security(basic_scheme),
|
||||
):
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "chat_id must be a valid UUID.")
|
||||
return await create_user_session(
|
||||
db,
|
||||
request.headers.get("Authorization"),
|
||||
)
|
||||
|
||||
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)
|
||||
@app.delete(
|
||||
"/api/v1/auth/sessions/current",
|
||||
status_code=204,
|
||||
)
|
||||
async def logout(
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_current_user: dict = Depends(require_user),
|
||||
) -> Response:
|
||||
_, _, token = request.headers["Authorization"].partition(" ")
|
||||
|
||||
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
|
||||
await logout_current_session(
|
||||
db,
|
||||
token.strip(),
|
||||
)
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
return Response(status_code=204)
|
||||
|
||||
uvicorn.run(app, host=config.HOST, port=config.PORT, log_level=config.LOG_LEVEL)
|
||||
|
||||
@app.get(
|
||||
"/api/v1/users/me",
|
||||
response_model=User,
|
||||
)
|
||||
async def current_user_route(
|
||||
current_user: dict = Depends(require_user),
|
||||
):
|
||||
return current_user
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats",
|
||||
status_code=201,
|
||||
response_model=Chat,
|
||||
)
|
||||
async def create_chat_route(
|
||||
payload: CreateChat,
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await create_chat(
|
||||
db,
|
||||
title=payload.title,
|
||||
member_ids=payload.member_ids,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats",
|
||||
response_model=ChatPage,
|
||||
)
|
||||
async def list_chats_route(
|
||||
page: tuple[int, str | None] = Depends(pagination_params),
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
limit, cursor = page
|
||||
|
||||
return await list_chats(
|
||||
db,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats/{chat_id}",
|
||||
response_model=Chat,
|
||||
)
|
||||
async def get_chat_route(
|
||||
chat_id: UUID,
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await get_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
status_code=201,
|
||||
response_model=Message,
|
||||
)
|
||||
async def create_message_route(
|
||||
chat_id: UUID,
|
||||
payload: CreateMessage,
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await create_message(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
text_value=payload.text,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
response_model=MessagePage,
|
||||
)
|
||||
async def list_messages_route(
|
||||
chat_id: UUID,
|
||||
page: tuple[int, str | None] = Depends(pagination_params),
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
limit, cursor = page
|
||||
|
||||
return await list_messages(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
current_user=current_user,
|
||||
)
|
||||
+100
-80
@@ -1,128 +1,148 @@
|
||||
|
||||
"""
|
||||
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 datetime import datetime, timezone
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
USERNAME_PATTERN = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
# Пользователи
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
class ApiModel(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)
|
||||
|
||||
class CreateUser(ApiModel):
|
||||
username: str = Field(
|
||||
min_length=3,
|
||||
max_length=32,
|
||||
pattern=r"^[a-z0-9_]{3,32}$",
|
||||
)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@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
|
||||
def username_is_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("username must not contain only spaces.")
|
||||
return value
|
||||
|
||||
@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
|
||||
def display_name_is_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError(
|
||||
"display_name must not contain only spaces."
|
||||
)
|
||||
return value
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def password_is_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("password must not contain only spaces.")
|
||||
return value
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
id: uuid.UUID
|
||||
class User(ApiModel):
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
@field_validator("created_at")
|
||||
@classmethod
|
||||
def user_time_is_utc(cls, value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("created_at must include UTC timezone.")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
# Чаты
|
||||
|
||||
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)
|
||||
class CreateChat(ApiModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
member_ids: list[UUID] = Field(min_length=1)
|
||||
|
||||
@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
|
||||
def title_is_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("title must not contain only spaces.")
|
||||
return value
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
id: uuid.UUID
|
||||
class Chat(ApiModel):
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: List[uuid.UUID]
|
||||
member_ids: list[UUID]
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
@field_validator("created_at")
|
||||
@classmethod
|
||||
def chat_time_is_utc(cls, value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("created_at must include UTC timezone.")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
# Сообщения
|
||||
class ChatPage(ApiModel):
|
||||
items: list[Chat]
|
||||
next_cursor: str | None = None
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: str = Field(..., min_length=1, max_length=4000)
|
||||
class CreateMessage(ApiModel):
|
||||
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
|
||||
def text_is_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("text must not contain only spaces.")
|
||||
return value
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
sender_id: uuid.UUID
|
||||
class Message(ApiModel):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
@field_validator("created_at")
|
||||
@classmethod
|
||||
def message_time_is_utc(cls, value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("created_at must include UTC timezone.")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
# Health / ошибки
|
||||
|
||||
class Health(BaseModel):
|
||||
status: str = "ok"
|
||||
class MessagePage(ApiModel):
|
||||
items: list[Message]
|
||||
next_cursor: str | None = None
|
||||
|
||||
|
||||
class ErrorBody(BaseModel):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
class Session(ApiModel):
|
||||
token: str = Field(min_length=1)
|
||||
token_type: Literal["Bearer"]
|
||||
expires_at: datetime
|
||||
user: User
|
||||
|
||||
@field_validator("expires_at")
|
||||
@classmethod
|
||||
def expiry_time_is_utc(cls, value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("expires_at must include UTC timezone.")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
error: ErrorBody
|
||||
class Health(ApiModel):
|
||||
status: Literal["ok"]
|
||||
|
||||
|
||||
class ErrorInner(ApiModel):
|
||||
code: str = Field(min_length=1)
|
||||
message: str = Field(min_length=1)
|
||||
request_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class Error(ApiModel):
|
||||
error: ErrorInner
|
||||
@@ -0,0 +1,358 @@
|
||||
"""PostgreSQL repository functions for MTUSI Messenger Lab2."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def create_user(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
username: str,
|
||||
display_name: str,
|
||||
password_hash: str,
|
||||
) -> dict[str, Any] | None:
|
||||
user_id = uuid4()
|
||||
try:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES (:id, :username, :display_name, :password_hash)
|
||||
RETURNING id, username, display_name, created_at
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": user_id,
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"password_hash": password_hash,
|
||||
},
|
||||
)
|
||||
await db.commit()
|
||||
return dict(result.mappings().one())
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
return None
|
||||
|
||||
|
||||
async def get_user_by_username(
|
||||
db: AsyncSession,
|
||||
username: str,
|
||||
) -> dict[str, Any] | None:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = :username
|
||||
"""
|
||||
),
|
||||
{"username": username},
|
||||
)
|
||||
row = result.mappings().first()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
async def get_user_by_id(
|
||||
db: AsyncSession,
|
||||
user_id: UUID,
|
||||
) -> dict[str, Any] | None:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = :user_id
|
||||
"""
|
||||
),
|
||||
{"user_id": user_id},
|
||||
)
|
||||
row = result.mappings().first()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
async def user_ids_that_exist(
|
||||
db: AsyncSession,
|
||||
member_ids: Iterable[UUID],
|
||||
) -> set[UUID]:
|
||||
values = list(member_ids)
|
||||
if not values:
|
||||
return set()
|
||||
|
||||
result = await db.execute(
|
||||
text("SELECT id FROM users WHERE id = ANY(CAST(:member_ids AS uuid[]))"),
|
||||
{"member_ids": values},
|
||||
)
|
||||
return {row.id for row in result}
|
||||
|
||||
|
||||
async def create_session(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: UUID,
|
||||
token_hash: str,
|
||||
expires_at: datetime,
|
||||
) -> None:
|
||||
await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO sessions (id, user_id, token_hash, expires_at)
|
||||
VALUES (:id, :user_id, :token_hash, :expires_at)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": uuid4(),
|
||||
"user_id": user_id,
|
||||
"token_hash": token_hash,
|
||||
"expires_at": expires_at,
|
||||
},
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def get_active_session_user(
|
||||
db: AsyncSession,
|
||||
token_hash: str,
|
||||
) -> dict[str, Any] | None:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
s.id AS session_id,
|
||||
s.token_hash,
|
||||
s.expires_at,
|
||||
u.id,
|
||||
u.username,
|
||||
u.display_name,
|
||||
u.created_at
|
||||
FROM sessions AS s
|
||||
JOIN users AS u ON u.id = s.user_id
|
||||
WHERE s.token_hash = :token_hash
|
||||
AND s.revoked_at IS NULL
|
||||
AND s.expires_at > now()
|
||||
"""
|
||||
),
|
||||
{"token_hash": token_hash},
|
||||
)
|
||||
row = result.mappings().first()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
async def revoke_active_session(
|
||||
db: AsyncSession,
|
||||
token_hash: str,
|
||||
) -> bool:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET revoked_at = now()
|
||||
WHERE token_hash = :token_hash
|
||||
AND revoked_at IS NULL
|
||||
AND expires_at > now()
|
||||
"""
|
||||
),
|
||||
{"token_hash": token_hash},
|
||||
)
|
||||
await db.commit()
|
||||
return result.rowcount == 1
|
||||
|
||||
|
||||
async def create_chat_with_members(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
title: str,
|
||||
member_ids: Iterable[UUID],
|
||||
) -> dict[str, Any]:
|
||||
chat_id = uuid4()
|
||||
members = list(member_ids)
|
||||
|
||||
try:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO chats (id, title)
|
||||
VALUES (:id, :title)
|
||||
RETURNING id, title, created_at
|
||||
"""
|
||||
),
|
||||
{"id": chat_id, "title": title},
|
||||
)
|
||||
chat = dict(result.mappings().one())
|
||||
|
||||
await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
VALUES (:chat_id, :user_id)
|
||||
"""
|
||||
),
|
||||
[{"chat_id": chat_id, "user_id": user_id} for user_id in members],
|
||||
)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
|
||||
chat["member_ids"] = members
|
||||
return chat
|
||||
|
||||
|
||||
async def get_accessible_chat(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dict[str, Any] | None:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats AS c
|
||||
JOIN chat_members AS own_membership
|
||||
ON own_membership.chat_id = c.id
|
||||
AND own_membership.user_id = :user_id
|
||||
WHERE c.id = :chat_id
|
||||
"""
|
||||
),
|
||||
{"chat_id": chat_id, "user_id": user_id},
|
||||
)
|
||||
chat_row = result.mappings().first()
|
||||
if chat_row is None:
|
||||
return None
|
||||
|
||||
members_result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = :chat_id
|
||||
ORDER BY user_id ASC
|
||||
"""
|
||||
),
|
||||
{"chat_id": chat_id},
|
||||
)
|
||||
chat = dict(chat_row)
|
||||
chat["member_ids"] = [row.user_id for row in members_result]
|
||||
return chat
|
||||
|
||||
|
||||
async def list_chats_for_user(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: UUID,
|
||||
limit: int,
|
||||
cursor_created_at: datetime | None,
|
||||
cursor_id: UUID | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
query = """
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats AS c
|
||||
JOIN chat_members AS own_membership
|
||||
ON own_membership.chat_id = c.id
|
||||
AND own_membership.user_id = :user_id \
|
||||
"""
|
||||
params: dict[str, Any] = {
|
||||
"user_id": user_id,
|
||||
"limit_plus_one": limit + 1,
|
||||
}
|
||||
|
||||
if cursor_created_at is not None and cursor_id is not None:
|
||||
query += """
|
||||
WHERE (c.created_at, c.id) > (:cursor_created_at, :cursor_id)
|
||||
"""
|
||||
params["cursor_created_at"] = cursor_created_at
|
||||
params["cursor_id"] = cursor_id
|
||||
|
||||
query += " ORDER BY c.created_at ASC, c.id ASC LIMIT :limit_plus_one"
|
||||
|
||||
result = await db.execute(text(query), params)
|
||||
chats = [dict(row) for row in result.mappings().all()]
|
||||
if not chats:
|
||||
return []
|
||||
|
||||
chat_ids = [chat["id"] for chat in chats]
|
||||
members_result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT chat_id, user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ANY(CAST(:chat_ids AS uuid[]))
|
||||
ORDER BY chat_id ASC, user_id ASC
|
||||
"""
|
||||
),
|
||||
{"chat_ids": chat_ids},
|
||||
)
|
||||
|
||||
members_by_chat: dict[UUID, list[UUID]] = {chat_id: [] for chat_id in chat_ids}
|
||||
for row in members_result:
|
||||
members_by_chat[row.chat_id].append(row.user_id)
|
||||
|
||||
for chat in chats:
|
||||
chat["member_ids"] = members_by_chat[chat["id"]]
|
||||
|
||||
return chats
|
||||
|
||||
|
||||
async def create_message(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text_value: str,
|
||||
) -> dict[str, Any]:
|
||||
message_id = uuid4()
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES (:id, :chat_id, :sender_id, :text)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": message_id,
|
||||
"chat_id": chat_id,
|
||||
"sender_id": sender_id,
|
||||
"text": text_value,
|
||||
},
|
||||
)
|
||||
await db.commit()
|
||||
return dict(result.mappings().one())
|
||||
|
||||
|
||||
async def list_messages_keyset(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
cursor_created_at: datetime | None,
|
||||
cursor_id: UUID | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
query = """
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = :chat_id \
|
||||
"""
|
||||
params: dict[str, Any] = {
|
||||
"chat_id": chat_id,
|
||||
"limit_plus_one": limit + 1,
|
||||
}
|
||||
|
||||
if cursor_created_at is not None and cursor_id is not None:
|
||||
query += """
|
||||
AND (created_at, id) > (:cursor_created_at, :cursor_id)
|
||||
"""
|
||||
params["cursor_created_at"] = cursor_created_at
|
||||
params["cursor_id"] = cursor_id
|
||||
|
||||
query += " ORDER BY created_at ASC, id ASC LIMIT :limit_plus_one"
|
||||
result = await db.execute(text(query), params)
|
||||
return [dict(row) for row in result.mappings().all()]
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerifyMismatchError
|
||||
|
||||
|
||||
password_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return password_hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return password_hasher.verify(password_hash, password)
|
||||
except (VerifyMismatchError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def generate_session_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_session_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def parse_basic_authorization(value: str | None) -> tuple[str, str] | None:
|
||||
if value is None or not value.startswith("Basic "):
|
||||
return None
|
||||
|
||||
try:
|
||||
encoded_credentials = value[len("Basic "):]
|
||||
decoded = base64.b64decode(
|
||||
encoded_credentials,
|
||||
validate=True,
|
||||
).decode("utf-8")
|
||||
|
||||
username, password = decoded.split(":", 1)
|
||||
except (
|
||||
ValueError,
|
||||
UnicodeDecodeError,
|
||||
binascii.Error,
|
||||
):
|
||||
return None
|
||||
|
||||
if not username or not username.isascii():
|
||||
return None
|
||||
|
||||
return username, password
|
||||
|
||||
|
||||
def _encode_cursor_payload(payload: dict[str, str]) -> str:
|
||||
raw = json.dumps(
|
||||
payload,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
).encode("utf-8")
|
||||
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
|
||||
def _decode_cursor_payload(cursor: str) -> dict[str, str] | None:
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor.encode("ascii"))
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
|
||||
return payload
|
||||
except (
|
||||
ValueError,
|
||||
TypeError,
|
||||
UnicodeDecodeError,
|
||||
binascii.Error,
|
||||
):
|
||||
return None
|
||||
|
||||
|
||||
def _utc_timestamp(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("Cursor datetime must be timezone-aware.")
|
||||
|
||||
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def encode_chat_cursor(
|
||||
created_at: datetime,
|
||||
chat_id: UUID,
|
||||
) -> str:
|
||||
return _encode_cursor_payload(
|
||||
{
|
||||
"kind": "chat",
|
||||
"created_at": _utc_timestamp(created_at),
|
||||
"id": str(chat_id),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def decode_chat_cursor(
|
||||
cursor: str,
|
||||
) -> tuple[datetime, UUID] | None:
|
||||
payload = _decode_cursor_payload(cursor)
|
||||
|
||||
if payload is None or payload.get("kind") != "chat":
|
||||
return None
|
||||
|
||||
try:
|
||||
created_at = datetime.fromisoformat(
|
||||
payload["created_at"].replace("Z", "+00:00")
|
||||
)
|
||||
chat_id = UUID(payload["id"])
|
||||
except (KeyError, ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
return created_at, chat_id
|
||||
|
||||
|
||||
def encode_message_cursor(
|
||||
chat_id: UUID,
|
||||
created_at: datetime,
|
||||
message_id: UUID,
|
||||
) -> str:
|
||||
return _encode_cursor_payload(
|
||||
{
|
||||
"kind": "message",
|
||||
"chat_id": str(chat_id),
|
||||
"created_at": _utc_timestamp(created_at),
|
||||
"id": str(message_id),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def decode_message_cursor(
|
||||
cursor: str,
|
||||
) -> tuple[UUID, datetime, UUID] | None:
|
||||
payload = _decode_cursor_payload(cursor)
|
||||
|
||||
if payload is None or payload.get("kind") != "message":
|
||||
return None
|
||||
|
||||
try:
|
||||
chat_id = UUID(payload["chat_id"])
|
||||
created_at = datetime.fromisoformat(
|
||||
payload["created_at"].replace("Z", "+00:00")
|
||||
)
|
||||
message_id = UUID(payload["id"])
|
||||
except (KeyError, ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
return chat_id, created_at, message_id
|
||||
+372
@@ -0,0 +1,372 @@
|
||||
"""Business rules for MTUSI Messenger Lab2."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app import repositories
|
||||
from app.cache import REVOKED_SESSION, session_cache
|
||||
from app.config import settings
|
||||
from app.errors import ApiError
|
||||
from app.security import (
|
||||
decode_chat_cursor,
|
||||
decode_message_cursor,
|
||||
encode_chat_cursor,
|
||||
encode_message_cursor,
|
||||
generate_session_token,
|
||||
hash_password,
|
||||
hash_session_token,
|
||||
parse_basic_authorization,
|
||||
verify_password,
|
||||
)
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _to_user(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def _to_chat(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"title": row["title"],
|
||||
"member_ids": row["member_ids"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def _to_message(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"chat_id": row["chat_id"],
|
||||
"sender_id": row["sender_id"],
|
||||
"text": row["text"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def _bearer_unauthorized() -> ApiError:
|
||||
return ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Authentication is required.",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Bearer realm="messenger"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _basic_unauthorized() -> ApiError:
|
||||
return ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Invalid credentials.",
|
||||
headers={
|
||||
"WWW-Authenticate": (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _invalid_request(message: str) -> ApiError:
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def _not_found() -> ApiError:
|
||||
return ApiError(404, "not_found", "Object not found.")
|
||||
|
||||
|
||||
async def register_user(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
username: str,
|
||||
display_name: str,
|
||||
password: str,
|
||||
) -> dict[str, Any]:
|
||||
user = await repositories.create_user(
|
||||
db,
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
password_hash=hash_password(password),
|
||||
)
|
||||
|
||||
if user is None:
|
||||
raise ApiError(
|
||||
409,
|
||||
"conflict",
|
||||
"Username is already taken.",
|
||||
)
|
||||
|
||||
return _to_user(user)
|
||||
|
||||
|
||||
async def create_user_session(
|
||||
db: AsyncSession,
|
||||
authorization: str | None,
|
||||
) -> dict[str, Any]:
|
||||
credentials = parse_basic_authorization(authorization)
|
||||
|
||||
if credentials is None:
|
||||
raise _basic_unauthorized()
|
||||
|
||||
username, password = credentials
|
||||
user = await repositories.get_user_by_username(db, username)
|
||||
|
||||
if user is None or not verify_password(
|
||||
user["password_hash"],
|
||||
password,
|
||||
):
|
||||
raise _basic_unauthorized()
|
||||
|
||||
token = generate_session_token()
|
||||
expires_at = _utc_now() + timedelta(
|
||||
seconds=settings.session_ttl_seconds
|
||||
)
|
||||
|
||||
await repositories.create_session(
|
||||
db,
|
||||
user_id=user["id"],
|
||||
token_hash=hash_session_token(token),
|
||||
expires_at=expires_at,
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at,
|
||||
"user": _to_user(user),
|
||||
}
|
||||
|
||||
|
||||
async def current_user_from_bearer_token(
|
||||
db: AsyncSession,
|
||||
token: str,
|
||||
) -> dict[str, Any]:
|
||||
token_hash = hash_session_token(token)
|
||||
cached = await session_cache.get(token_hash)
|
||||
|
||||
if cached is REVOKED_SESSION:
|
||||
raise _bearer_unauthorized()
|
||||
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
# Cache miss or cache unavailable: PostgreSQL decides.
|
||||
session_user = await repositories.get_active_session_user(db, token_hash)
|
||||
|
||||
if session_user is None:
|
||||
raise _bearer_unauthorized()
|
||||
|
||||
user = _to_user(session_user)
|
||||
await session_cache.put(token_hash, user, session_user["expires_at"])
|
||||
return user
|
||||
|
||||
|
||||
async def logout_current_session(
|
||||
db: AsyncSession,
|
||||
token: str,
|
||||
) -> None:
|
||||
token_hash = hash_session_token(token)
|
||||
revoked = await repositories.revoke_active_session(db, token_hash)
|
||||
|
||||
if not revoked:
|
||||
raise _bearer_unauthorized()
|
||||
|
||||
# Invalidate after COMMIT in the source of truth.
|
||||
await session_cache.revoke(token_hash)
|
||||
|
||||
|
||||
async def create_chat(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
title: str,
|
||||
member_ids: list[UUID],
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
unique_member_ids = set(member_ids)
|
||||
|
||||
if len(unique_member_ids) != len(member_ids):
|
||||
raise _invalid_request(
|
||||
"member_ids must not contain duplicates."
|
||||
)
|
||||
|
||||
if current_user["id"] not in unique_member_ids:
|
||||
raise _invalid_request(
|
||||
"The current user must be included in member_ids."
|
||||
)
|
||||
|
||||
existing_ids = await repositories.user_ids_that_exist(
|
||||
db,
|
||||
unique_member_ids,
|
||||
)
|
||||
|
||||
if existing_ids != unique_member_ids:
|
||||
raise _invalid_request(
|
||||
"One or more member_ids do not exist."
|
||||
)
|
||||
|
||||
chat = await repositories.create_chat_with_members(
|
||||
db,
|
||||
title=title,
|
||||
member_ids=member_ids,
|
||||
)
|
||||
|
||||
return _to_chat(chat)
|
||||
|
||||
|
||||
async def get_chat(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
user_id=current_user["id"],
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
return _to_chat(chat)
|
||||
|
||||
|
||||
async def list_chats(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
cursor_created_at: datetime | None = None
|
||||
cursor_id: UUID | None = None
|
||||
|
||||
if cursor is not None:
|
||||
decoded = decode_chat_cursor(cursor)
|
||||
|
||||
if decoded is None:
|
||||
raise _invalid_request("Invalid cursor.")
|
||||
|
||||
cursor_created_at, cursor_id = decoded
|
||||
|
||||
rows = await repositories.list_chats_for_user(
|
||||
db,
|
||||
user_id=current_user["id"],
|
||||
limit=limit,
|
||||
cursor_created_at=cursor_created_at,
|
||||
cursor_id=cursor_id,
|
||||
)
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_chat_cursor(
|
||||
last["created_at"],
|
||||
last["id"],
|
||||
)
|
||||
|
||||
return {
|
||||
"items": [_to_chat(row) for row in page],
|
||||
"next_cursor": next_cursor,
|
||||
}
|
||||
|
||||
|
||||
async def create_message(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
text_value: str,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
user_id=current_user["id"],
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
message = await repositories.create_message(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
sender_id=current_user["id"],
|
||||
text_value=text_value,
|
||||
)
|
||||
|
||||
return _to_message(message)
|
||||
|
||||
|
||||
async def list_messages(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
user_id=current_user["id"],
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
cursor_created_at: datetime | None = None
|
||||
cursor_id: UUID | None = None
|
||||
|
||||
if cursor is not None:
|
||||
decoded = decode_message_cursor(cursor)
|
||||
|
||||
if decoded is None:
|
||||
raise _invalid_request("Invalid cursor.")
|
||||
|
||||
cursor_chat_id, cursor_created_at, cursor_id = decoded
|
||||
|
||||
if cursor_chat_id != chat_id:
|
||||
raise _invalid_request(
|
||||
"Cursor belongs to another chat."
|
||||
)
|
||||
|
||||
rows = await repositories.list_messages_keyset(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
limit=limit,
|
||||
cursor_created_at=cursor_created_at,
|
||||
cursor_id=cursor_id,
|
||||
)
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_message_cursor(
|
||||
chat_id,
|
||||
last["created_at"],
|
||||
last["id"],
|
||||
)
|
||||
|
||||
return {
|
||||
"items": [_to_message(row) for row in page],
|
||||
"next_cursor": next_cursor,
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
"""
|
||||
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
@@ -1,232 +0,0 @@
|
||||
"""
|
||||
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