add code for level 3
This commit is contained in:
@@ -1,2 +1,2 @@
|
||||
"""Слой in-memory хранения для приложения первой лабораторной работы."""
|
||||
|
||||
"""Persistent storage adapters."""
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from threading import RLock
|
||||
from uuid import uuid4
|
||||
|
||||
from ..errors import ApiError
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class User:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Chat:
|
||||
id: str
|
||||
title: str
|
||||
member_ids: tuple[str, ...]
|
||||
created_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Message:
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class MemoryStore:
|
||||
def __init__(self) -> None:
|
||||
self._users_by_id: dict[str, User] = {}
|
||||
self._user_ids_by_username: dict[str, str] = {}
|
||||
self._chats_by_id: dict[str, Chat] = {}
|
||||
self._messages_by_chat_id: dict[str, list[Message]] = {}
|
||||
self._lock = RLock()
|
||||
|
||||
@staticmethod
|
||||
def _now() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
|
||||
@staticmethod
|
||||
def _message_sort_key(message: Message) -> tuple[datetime, str]:
|
||||
"""Возвращает ключ порядка сообщений, заданный API-контрактом."""
|
||||
|
||||
return message.created_at, message.id
|
||||
|
||||
@classmethod
|
||||
def _insert_message_in_order(
|
||||
cls, messages: list[Message], message: Message
|
||||
) -> None:
|
||||
"""Вставляет сообщение в отсортированную историю без сортировки при чтении."""
|
||||
|
||||
message_key = cls._message_sort_key(message)
|
||||
left, right = 0, len(messages)
|
||||
while left < right:
|
||||
middle = (left + right) // 2
|
||||
if cls._message_sort_key(messages[middle]) <= message_key:
|
||||
left = middle + 1
|
||||
else:
|
||||
right = middle
|
||||
messages.insert(left, message)
|
||||
|
||||
def create_user(self, username: str, display_name: str) -> User:
|
||||
with self._lock:
|
||||
if username in self._user_ids_by_username:
|
||||
raise ApiError(409, "conflict", "Username уже занят")
|
||||
|
||||
user = User(
|
||||
id=str(uuid4()),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=self._now(),
|
||||
)
|
||||
self._users_by_id[user.id] = user
|
||||
self._user_ids_by_username[user.username] = user.id
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: str) -> User | None:
|
||||
"""Возвращает пользователя по ID, если он существует."""
|
||||
|
||||
with self._lock:
|
||||
return self._users_by_id.get(user_id)
|
||||
|
||||
def create_chat(
|
||||
self, creator_id: str, title: str, member_ids: list[str] | tuple[str, ...]
|
||||
) -> Chat:
|
||||
members = tuple(member_ids)
|
||||
with self._lock:
|
||||
if len(members) != len(set(members)):
|
||||
raise ApiError(400, "invalid_request", "Список участников содержит повторяющиеся ID")
|
||||
if creator_id not in members:
|
||||
raise ApiError(400, "invalid_request", "Создатель должен входить в список участников")
|
||||
if any(member_id not in self._users_by_id for member_id in members):
|
||||
raise ApiError(400, "invalid_request", "Один или несколько участников не существуют")
|
||||
|
||||
chat = Chat(
|
||||
id=str(uuid4()),
|
||||
title=title,
|
||||
member_ids=members,
|
||||
created_at=self._now(),
|
||||
)
|
||||
self._chats_by_id[chat.id] = chat
|
||||
self._messages_by_chat_id[chat.id] = []
|
||||
return chat
|
||||
|
||||
def get_chat_for_member(self, chat_id: str, user_id: str) -> Chat:
|
||||
with self._lock:
|
||||
chat = self._chats_by_id.get(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return chat
|
||||
|
||||
def list_chats_for_member(self, user_id: str) -> tuple[Chat, ...]:
|
||||
with self._lock:
|
||||
chats = (
|
||||
chat for chat in self._chats_by_id.values() if user_id in chat.member_ids
|
||||
)
|
||||
return tuple(sorted(chats, key=lambda chat: (chat.created_at, chat.id)))
|
||||
|
||||
def create_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
||||
with self._lock:
|
||||
chat = self._chats_by_id.get(chat_id)
|
||||
if chat is None or sender_id not in chat.member_ids:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
|
||||
message = Message(
|
||||
id=str(uuid4()),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=self._now(),
|
||||
)
|
||||
self._insert_message_in_order(self._messages_by_chat_id[chat_id], message)
|
||||
return message
|
||||
|
||||
def list_messages_for_member(
|
||||
self, chat_id: str, user_id: str
|
||||
) -> tuple[Message, ...]:
|
||||
with self._lock:
|
||||
chat = self._chats_by_id.get(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return tuple(self._messages_by_chat_id[chat_id])
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
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()
|
||||
|
||||
|
||||
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 asyncpg.PostgresError 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"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
async def ready(self) -> None:
|
||||
try:
|
||||
await self.pool.fetchval("SELECT 1")
|
||||
except asyncpg.PostgresError 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 asyncpg.PostgresError as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row)
|
||||
|
||||
async def get_user(self, user_id: UUID) -> dict | None:
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = $1", user_id
|
||||
)
|
||||
except asyncpg.PostgresError as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row) if row else None
|
||||
|
||||
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 asyncpg.PostgresError 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 asyncpg.PostgresError 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:
|
||||
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 asyncpg.PostgresError 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 asyncpg.PostgresError 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 asyncpg.PostgresError 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 asyncpg.PostgresError 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 asyncpg.PostgresError as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return [self._chat(row) for row in rows]
|
||||
|
||||
async def create_message(self, chat_id: UUID, sender_id: UUID, text: str) -> dict:
|
||||
await self.get_chat_for_member(chat_id, sender_id)
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at",
|
||||
uuid4(),
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
)
|
||||
except asyncpg.PostgresError 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, 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 asyncpg.PostgresError as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return [self._message(row) for row in rows]
|
||||
Reference in New Issue
Block a user