lab4 for lab5

This commit is contained in:
Матвей
2026-10-26 10:05:24 +03:00
parent 276dbdad8a
commit 3b67201e5e
40 changed files with 3522 additions and 0 deletions
+352
View File
@@ -0,0 +1,352 @@
from datetime import datetime
from contextlib import asynccontextmanager
from hashlib import sha256
import json
from pathlib import Path
from secrets import token_urlsafe
from uuid import UUID, uuid4
import asyncpg
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
from ..errors import ApiError
ROOT = Path(__file__).resolve().parents[2]
MIGRATIONS = ROOT / "migrations"
PASSWORD_HASHER = PasswordHasher()
DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError, TimeoutError)
class PostgresStore:
def __init__(self, database_url: str) -> None:
self._database_url = database_url
self._pool: asyncpg.Pool | None = None
async def connect(self) -> None:
try:
self._pool = await asyncpg.create_pool(
self._database_url, min_size=1, max_size=10, command_timeout=5
)
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def close(self) -> None:
if self._pool is not None:
await self._pool.close()
@property
def pool(self) -> asyncpg.Pool:
if self._pool is None:
raise RuntimeError("PostgreSQL pool has not been initialized")
return self._pool
async def migrate(self) -> None:
async with self.pool.acquire() as connection:
await connection.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())"
)
for migration in sorted(MIGRATIONS.glob("*.sql")):
applied = await connection.fetchval(
"SELECT 1 FROM schema_migrations WHERE version = $1", migration.name
)
if applied:
continue
async with connection.transaction():
await connection.execute(migration.read_text(encoding="utf-8"))
await connection.execute(
"INSERT INTO schema_migrations (version) VALUES ($1)", migration.name
)
@staticmethod
def _user(row: asyncpg.Record) -> dict:
return {
"id": row["id"],
"username": row["username"],
"display_name": row["display_name"],
"created_at": row["created_at"],
}
@staticmethod
def _chat(row: asyncpg.Record) -> dict:
return {
"id": row["id"],
"title": row["title"],
"member_ids": row["member_ids"],
"created_at": row["created_at"],
}
@staticmethod
def _message(row: asyncpg.Record) -> dict:
return {
"id": row["id"],
"chat_id": row["chat_id"],
"sender_id": row["sender_id"],
"text": row["text"],
"attachment_ids": row["attachment_ids"],
"created_at": row["created_at"],
}
async def ready(self) -> None:
try:
await self.pool.fetchval("SELECT 1")
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
async def create_user(self, username: str, display_name: str, password: str) -> dict:
try:
row = await self.pool.fetchrow(
"INSERT INTO users (id, username, display_name, password_hash) VALUES ($1, $2, $3, $4) RETURNING id, username, display_name, created_at",
uuid4(),
username,
display_name,
PASSWORD_HASHER.hash(password),
)
except asyncpg.UniqueViolationError as error:
raise ApiError(409, "conflict", "Username уже занят") from error
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return self._user(row)
async def authenticate(self, username: str, password: str) -> dict | None:
try:
row = await self.pool.fetchrow(
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1",
username,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
if row is None:
return None
try:
valid = PASSWORD_HASHER.verify(row["password_hash"], password)
except (InvalidHashError, VerificationError):
valid = False
return self._user(row) if valid else None
async def create_session(self, user: dict, ttl_seconds: int) -> dict:
token = token_urlsafe(32)
token_hash = sha256(token.encode("ascii")).hexdigest()
try:
row = await self.pool.fetchrow(
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2, now() + $3 * interval '1 second') RETURNING expires_at",
token_hash,
user["id"],
ttl_seconds,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return {"token": token, "token_type": "Bearer", "expires_at": row["expires_at"], "user": user}
async def user_for_token(self, token: str) -> dict | None:
if not token.isascii():
return None
token_hash = sha256(token.encode("ascii")).hexdigest()
try:
row = await self.pool.fetchrow(
"SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now()",
token_hash,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return self._user(row) if row else None
async def revoke_session(self, token: str) -> None:
try:
await self.pool.execute(
"DELETE FROM sessions WHERE token_hash = $1", sha256(token.encode("ascii")).hexdigest()
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
async def create_chat(self, creator_id: UUID, title: str, member_ids: list[UUID]) -> dict:
if len(member_ids) != len(set(member_ids)) or creator_id not in member_ids:
raise ApiError(400, "invalid_request", "Некорректный список участников")
try:
async with self.pool.acquire() as connection, connection.transaction():
existing = await connection.fetchval(
"SELECT count(*) FROM users WHERE id = ANY($1::uuid[])", member_ids
)
if existing != len(member_ids):
raise ApiError(400, "invalid_request", "Один или несколько участников не существуют")
row = await connection.fetchrow(
"INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at",
uuid4(),
title,
)
await connection.executemany(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
[(row["id"], member_id) for member_id in member_ids],
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return {
"id": row["id"],
"title": row["title"],
"member_ids": member_ids,
"created_at": row["created_at"],
}
async def get_chat_for_member(self, chat_id: UUID, user_id: UUID) -> dict:
try:
row = await self.pool.fetchrow(
"SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids FROM chats c JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $2 JOIN chat_members cm_all ON cm_all.chat_id = c.id WHERE c.id = $1 GROUP BY c.id",
chat_id,
user_id,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
if row is None:
raise ApiError(404, "not_found", "Чат не найден")
return self._chat(row)
async def list_chats_for_member(
self, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int
) -> list[dict]:
query = "SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids FROM chats c JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $1 JOIN chat_members cm_all ON cm_all.chat_id = c.id"
args: list = [user_id]
if after is not None:
query += " WHERE (c.created_at, c.id) > ($2, $3)"
args.extend(after)
query += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT $" + str(len(args) + 1)
args.append(limit + 1)
try:
rows = await self.pool.fetch(query, *args)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return [self._chat(row) for row in rows]
async def create_message_idempotent(
self, chat_id: UUID, sender_id: UUID, text: str, idempotency_key: str, ttl_seconds: int, attachment_ids: list[UUID] | None = None
) -> dict:
"""Создаёт сообщение и фиксирует результат retry в одной транзакции."""
path = f"/api/v1/chats/{chat_id}/messages"
attachment_ids = attachment_ids or []
# Preserve hashes of text-only requests already accepted by lab3.
canonical = {"text": text}
if attachment_ids:
canonical["attachment_ids"] = [str(value) for value in attachment_ids]
request_hash = sha256(
json.dumps(canonical, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
).hexdigest()
try:
async with self.pool.acquire() as connection, connection.transaction():
member = await connection.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_id, sender_id
)
if member is None:
raise ApiError(404, "not_found", "Чат не найден")
await connection.execute(
"DELETE FROM idempotency_records WHERE created_at <= now() - $1 * interval '1 second'", ttl_seconds
)
if attachment_ids:
count = await connection.fetchval(
"SELECT count(*) FROM attachments WHERE chat_id = $1 AND id = ANY($2::uuid[])",
chat_id, attachment_ids,
)
if count != len(attachment_ids):
raise ApiError(404, "not_found", "Вложение не найдено")
claimed = await connection.fetchrow(
"INSERT INTO idempotency_records (user_id, method, path, idempotency_key, request_hash) "
"VALUES ($1, 'POST', $2, $3, $4) ON CONFLICT DO NOTHING RETURNING message_id",
sender_id, path, idempotency_key, request_hash,
)
if claimed is None:
recorded = await connection.fetchrow(
"SELECT request_hash, message_id FROM idempotency_records "
"WHERE user_id = $1 AND method = 'POST' AND path = $2 AND idempotency_key = $3 FOR UPDATE",
sender_id, path, idempotency_key,
)
if recorded is None:
raise ApiError(503, "unavailable", "Не удалось получить результат идемпотентного запроса")
if recorded["request_hash"] != request_hash:
raise ApiError(409, "conflict", "Idempotency-Key использован с другим телом")
if recorded["message_id"] is None:
raise ApiError(503, "unavailable", "Не удалось получить результат идемпотентного запроса")
row = await connection.fetchrow(
"SELECT id, chat_id, sender_id, text, attachment_ids, created_at FROM messages WHERE id = $1", recorded["message_id"]
)
if row is None:
raise ApiError(503, "unavailable", "Не удалось получить сохранённое сообщение")
return self._message(row)
row = await connection.fetchrow(
"INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids) VALUES ($1, $2, $3, $4, $5) "
"RETURNING id, chat_id, sender_id, text, attachment_ids, created_at",
uuid4(), chat_id, sender_id, text, attachment_ids,
)
await connection.execute(
"UPDATE idempotency_records SET message_id = $1 WHERE user_id = $2 AND method = 'POST' "
"AND path = $3 AND idempotency_key = $4",
row["id"], sender_id, path, idempotency_key,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return self._message(row)
async def list_messages_for_member(
self, chat_id: UUID, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int
) -> list[dict]:
await self.get_chat_for_member(chat_id, user_id)
query = "SELECT id, chat_id, sender_id, text, attachment_ids, created_at FROM messages WHERE chat_id = $1"
args: list = [chat_id]
if after is not None:
query += " AND (created_at, id) > ($2, $3)"
args.extend(after)
query += " ORDER BY created_at, id LIMIT $" + str(len(args) + 1)
args.append(limit + 1)
try:
rows = await self.pool.fetch(query, *args)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return [self._message(row) for row in rows]
@asynccontextmanager
async def attachment_transaction(self, *, maintenance=False):
"""Shared writer / exclusive reconciler lock across all API replicas.
Writers hold the transaction from before PUT through metadata COMMIT.
Maintenance holds the exclusive lock through inventory and deletion.
All attachment writers must participate in this protocol.
"""
try:
async with self.pool.acquire() as connection, connection.transaction():
await connection.execute("SET LOCAL lock_timeout = '5s'")
lock = "pg_advisory_xact_lock" if maintenance else "pg_advisory_xact_lock_shared"
await connection.execute(f"SELECT {lock}(41004, 1)")
yield connection
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
async def create_attachment(self, attachment_id, chat_id, owner_id, filename,
content_type, size_bytes, digest, object_key, *, connection=None) -> dict:
try:
row = await (connection or self.pool).fetchrow(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key) "
"VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *",
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, object_key,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return dict(row)
async def attachment_for_member(self, attachment_id: UUID, user_id: UUID) -> dict:
try:
row = await self.pool.fetchrow(
"SELECT a.* FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id "
"WHERE a.id = $1 AND m.user_id = $2", attachment_id, user_id,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
if row is None:
raise ApiError(404, "not_found", "Вложение не найдено")
return dict(row)
async def attachment_keys(self) -> dict[str, UUID]:
"""Inventory used only by the maintenance reconciler."""
try:
rows = await self.pool.fetch("SELECT object_key, id FROM attachments")
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
return {row["object_key"]: row["id"] for row in rows}