forked from mtusi2026/mtusi2026lab3
solution
This commit is contained in:
@@ -0,0 +1,358 @@
|
||||
"""Запросы к PostgreSQL: единственное место, где выполняется SQL.
|
||||
|
||||
Все значения передаются bind-параметрами — строки запросов не собираются из
|
||||
данных пользователя. Транзакционную границу задаёт репозиторий: операция,
|
||||
меняющая несколько таблиц, выполняется целиком или не выполняется вовсе.
|
||||
|
||||
Единица работы — неявная транзакция сессии запроса: пишущие методы завершают
|
||||
её `commit`, а незавершённую откатывает закрытие сессии. Поэтому чтение перед
|
||||
записью (проверка доступа → вставка сообщения) идёт в той же транзакции.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy import Row, Select, cast, delete, func, insert, literal, select, text, tuple_
|
||||
from sqlalchemy.dialects.postgresql import TIMESTAMP, UUID as PGUUID
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from .domain import (
|
||||
ChatRecord,
|
||||
IdempotencyConflict,
|
||||
MessageRecord,
|
||||
Position,
|
||||
UnknownMembers,
|
||||
UserRecord,
|
||||
)
|
||||
from .schema import CHAT_MEMBERS, CHATS, MESSAGE_IDEMPOTENCY, MESSAGES, USERS
|
||||
|
||||
FOREIGN_KEY_VIOLATION = "23503"
|
||||
|
||||
# Ключ идемпотентности живёт 24 часа; срок считает PostgreSQL, а не часы
|
||||
# приложения, чтобы реплики с разными часами принимали одинаковое решение.
|
||||
IDEMPOTENCY_FRESH_PREDICATE = MESSAGE_IDEMPOTENCY.c.created_at > (
|
||||
func.now() - text("INTERVAL '24 hours'")
|
||||
)
|
||||
|
||||
|
||||
def _sqlstate(error: IntegrityError) -> str | None:
|
||||
"""Код ошибки PostgreSQL: драйвер кладёт его в исходное исключение."""
|
||||
return getattr(getattr(error, "orig", None), "sqlstate", None)
|
||||
|
||||
|
||||
def _after_predicate(created_at_column, id_column, after: Position):
|
||||
"""Keyset-условие «строго после пары (created_at, id)» одним сравнением строк.
|
||||
|
||||
Сравнение строк целиком — то, что умеет использовать составной индекс;
|
||||
значение приводится к нужному типу явно, чтобы драйвер не угадывал его.
|
||||
"""
|
||||
moment, item_id = after
|
||||
return tuple_(created_at_column, id_column) > tuple_(
|
||||
cast(literal(moment), TIMESTAMP(timezone=True)),
|
||||
cast(literal(item_id), PGUUID(as_uuid=True)),
|
||||
)
|
||||
|
||||
|
||||
def _user_record(row: Row) -> UserRecord:
|
||||
return UserRecord(
|
||||
id=row.id, username=row.username, display_name=row.display_name, created_at=row.created_at
|
||||
)
|
||||
|
||||
|
||||
def _chat_columns() -> tuple:
|
||||
return (CHATS.c.id, CHATS.c.title, CHATS.c.created_at)
|
||||
|
||||
|
||||
def _message_columns() -> tuple:
|
||||
return (
|
||||
MESSAGES.c.id,
|
||||
MESSAGES.c.chat_id,
|
||||
MESSAGES.c.sender_id,
|
||||
MESSAGES.c.text,
|
||||
MESSAGES.c.created_at,
|
||||
)
|
||||
|
||||
|
||||
class Repository:
|
||||
"""Набор операций над PostgreSQL в рамках одной сессии (одного запроса)."""
|
||||
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def ping(self) -> None:
|
||||
"""Дешёвая проверка живости соединения для /health/ready."""
|
||||
await self._session.execute(select(literal(1)))
|
||||
|
||||
async def username_taken(self, username: str) -> bool:
|
||||
"""Дешёвая предпроверка: занятый username отсекается до дорогого KDF."""
|
||||
found = await self._session.scalar(
|
||||
select(USERS.c.id).where(USERS.c.username == username).limit(1)
|
||||
)
|
||||
return found is not None
|
||||
|
||||
async def create_user(
|
||||
self, username: str, display_name: str, password_hash: str
|
||||
) -> UserRecord | None:
|
||||
"""Создаёт пользователя; None — если username уже занят.
|
||||
|
||||
Гонку двух одновременных регистраций закрывает уникальный индекс:
|
||||
`ON CONFLICT DO NOTHING` не поднимает ошибку и не портит транзакцию.
|
||||
"""
|
||||
row = (
|
||||
await self._session.execute(
|
||||
pg_insert(USERS)
|
||||
.values(
|
||||
id=uuid4(),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
password_hash=password_hash,
|
||||
)
|
||||
.on_conflict_do_nothing(index_elements=[USERS.c.username])
|
||||
.returning(*USERS.c)
|
||||
)
|
||||
).first()
|
||||
await self._session.commit()
|
||||
return None if row is None else _user_record(row)
|
||||
|
||||
async def credentials_for(self, username: str) -> tuple[UserRecord, str] | None:
|
||||
"""Пользователь и его хэш пароля для проверки входа."""
|
||||
row = (
|
||||
await self._session.execute(
|
||||
select(USERS.c.id, USERS.c.username, USERS.c.display_name, USERS.c.created_at,
|
||||
USERS.c.password_hash)
|
||||
.where(USERS.c.username == username)
|
||||
.limit(1)
|
||||
)
|
||||
).first()
|
||||
if row is None:
|
||||
return None
|
||||
return _user_record(row), row.password_hash
|
||||
|
||||
async def get_user(self, user_id: UUID) -> UserRecord | None:
|
||||
row = (
|
||||
await self._session.execute(
|
||||
select(USERS.c.id, USERS.c.username, USERS.c.display_name, USERS.c.created_at)
|
||||
.where(USERS.c.id == user_id)
|
||||
.limit(1)
|
||||
)
|
||||
).first()
|
||||
return None if row is None else _user_record(row)
|
||||
|
||||
async def create_chat(self, title: str, member_ids: Sequence[UUID]) -> ChatRecord:
|
||||
"""Чат и его участники появляются одной транзакцией.
|
||||
|
||||
Неизвестный участник нарушает внешний ключ — транзакция откатывается
|
||||
целиком, поэтому «чат без участников» или «чат с чужаком» не возникает.
|
||||
"""
|
||||
chat_id = uuid4()
|
||||
row = (
|
||||
await self._session.execute(
|
||||
insert(CHATS).values(id=chat_id, title=title).returning(*_chat_columns())
|
||||
)
|
||||
).one()
|
||||
try:
|
||||
await self._session.execute(
|
||||
insert(CHAT_MEMBERS),
|
||||
[{"chat_id": chat_id, "user_id": member_id} for member_id in member_ids],
|
||||
)
|
||||
except IntegrityError as error:
|
||||
if _sqlstate(error) != FOREIGN_KEY_VIOLATION:
|
||||
raise
|
||||
# Нарушенный внешний ключ обрывает транзакцию: откат снимает и уже
|
||||
# вставленный чат, поэтому неполного чата в базе не остаётся.
|
||||
await self._session.rollback()
|
||||
raise UnknownMembers(member_ids) from None
|
||||
await self._session.commit()
|
||||
return ChatRecord(
|
||||
id=row.id,
|
||||
title=row.title,
|
||||
member_ids=tuple(sorted(member_ids, key=lambda item: item.int)),
|
||||
created_at=row.created_at,
|
||||
)
|
||||
|
||||
async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> ChatRecord | None:
|
||||
"""Чат глазами участника: чужой чат неотличим от несуществующего (404)."""
|
||||
row = (
|
||||
await self._session.execute(
|
||||
select(*_chat_columns())
|
||||
.select_from(CHATS.join(CHAT_MEMBERS, CHAT_MEMBERS.c.chat_id == CHATS.c.id))
|
||||
.where(CHATS.c.id == chat_id, CHAT_MEMBERS.c.user_id == user_id)
|
||||
.limit(1)
|
||||
)
|
||||
).first()
|
||||
if row is None:
|
||||
return None
|
||||
members = await self._members_of([chat_id])
|
||||
return ChatRecord(
|
||||
id=row.id, title=row.title, member_ids=members[chat_id], created_at=row.created_at
|
||||
)
|
||||
|
||||
async def list_chats(
|
||||
self, user_id: UUID, after: Position | None, limit: int
|
||||
) -> tuple[list[ChatRecord], bool]:
|
||||
"""Страница чатов пользователя в порядке (created_at, id) и признак «есть ещё»."""
|
||||
statement = (
|
||||
select(*_chat_columns())
|
||||
.select_from(CHATS.join(CHAT_MEMBERS, CHAT_MEMBERS.c.chat_id == CHATS.c.id))
|
||||
.where(CHAT_MEMBERS.c.user_id == user_id)
|
||||
)
|
||||
rows = await self._page(statement, CHATS, after, limit)
|
||||
more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
members = await self._members_of([row.id for row in rows])
|
||||
chats = [
|
||||
ChatRecord(
|
||||
id=row.id, title=row.title, member_ids=members[row.id], created_at=row.created_at
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
return chats, more
|
||||
|
||||
async def append_message(self, chat_id: UUID, sender_id: UUID, text: str) -> MessageRecord:
|
||||
"""Время и идентификатор назначает база: ответ возвращает то, что записано."""
|
||||
row = (
|
||||
await self._session.execute(
|
||||
insert(MESSAGES)
|
||||
.values(id=uuid4(), chat_id=chat_id, sender_id=sender_id, text=text)
|
||||
.returning(*_message_columns())
|
||||
)
|
||||
).one()
|
||||
await self._session.commit()
|
||||
return MessageRecord(
|
||||
id=row.id,
|
||||
chat_id=row.chat_id,
|
||||
sender_id=row.sender_id,
|
||||
text=row.text,
|
||||
created_at=row.created_at,
|
||||
)
|
||||
|
||||
async def append_message_idempotent(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
idempotency_key: str,
|
||||
request_hash: str,
|
||||
) -> MessageRecord:
|
||||
"""Создаёт сообщение ровно один раз для ключа (пользователь, чат, ключ).
|
||||
|
||||
Транзакционная блокировка по хэшу ключа сериализует одновременные
|
||||
повторы, пришедшие на разные реплики. Побочный эффект (строка messages)
|
||||
и запись результата (message_idempotency) фиксируются одной транзакцией:
|
||||
клиент либо видит подтверждённое сообщение, либо не видит ничего.
|
||||
"""
|
||||
lock_scope = f'{sender_id}:{chat_id}:{idempotency_key}'
|
||||
await self._session.execute(
|
||||
select(func.pg_advisory_xact_lock(func.hashtextextended(lock_scope, 0)))
|
||||
)
|
||||
fresh = IDEMPOTENCY_FRESH_PREDICATE
|
||||
existing = (
|
||||
await self._session.execute(
|
||||
select(*_message_columns(), MESSAGE_IDEMPOTENCY.c.request_hash, fresh.label('fresh'))
|
||||
.select_from(
|
||||
MESSAGE_IDEMPOTENCY.join(
|
||||
MESSAGES, MESSAGES.c.id == MESSAGE_IDEMPOTENCY.c.message_id
|
||||
)
|
||||
)
|
||||
.where(
|
||||
MESSAGE_IDEMPOTENCY.c.user_id == sender_id,
|
||||
MESSAGE_IDEMPOTENCY.c.chat_id == chat_id,
|
||||
MESSAGE_IDEMPOTENCY.c.idempotency_key == idempotency_key,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
).first()
|
||||
if existing is not None:
|
||||
if existing.fresh and existing.request_hash == request_hash:
|
||||
record = MessageRecord(
|
||||
id=existing.id,
|
||||
chat_id=existing.chat_id,
|
||||
sender_id=existing.sender_id,
|
||||
text=existing.text,
|
||||
created_at=existing.created_at,
|
||||
)
|
||||
await self._session.commit()
|
||||
return record
|
||||
if existing.fresh:
|
||||
await self._session.rollback()
|
||||
raise IdempotencyConflict()
|
||||
# Срок хранения ключа истёк: старый ключ можно использовать снова.
|
||||
await self._session.execute(
|
||||
delete(MESSAGE_IDEMPOTENCY).where(
|
||||
MESSAGE_IDEMPOTENCY.c.user_id == sender_id,
|
||||
MESSAGE_IDEMPOTENCY.c.chat_id == chat_id,
|
||||
MESSAGE_IDEMPOTENCY.c.idempotency_key == idempotency_key,
|
||||
)
|
||||
)
|
||||
message_id = uuid4()
|
||||
row = (
|
||||
await self._session.execute(
|
||||
insert(MESSAGES)
|
||||
.values(id=message_id, chat_id=chat_id, sender_id=sender_id, text=text)
|
||||
.returning(*_message_columns())
|
||||
)
|
||||
).one()
|
||||
await self._session.execute(
|
||||
insert(MESSAGE_IDEMPOTENCY).values(
|
||||
user_id=sender_id,
|
||||
chat_id=chat_id,
|
||||
idempotency_key=idempotency_key,
|
||||
request_hash=request_hash,
|
||||
message_id=message_id,
|
||||
)
|
||||
)
|
||||
await self._session.commit()
|
||||
return MessageRecord(
|
||||
id=row.id,
|
||||
chat_id=row.chat_id,
|
||||
sender_id=row.sender_id,
|
||||
text=row.text,
|
||||
created_at=row.created_at,
|
||||
)
|
||||
|
||||
async def list_messages(
|
||||
self, chat_id: UUID, after: Position | None, limit: int
|
||||
) -> tuple[list[MessageRecord], bool]:
|
||||
"""Страница истории чата от старых к новым и признак «есть ещё»."""
|
||||
statement = select(*_message_columns()).where(MESSAGES.c.chat_id == chat_id)
|
||||
rows = await self._page(statement, MESSAGES, after, limit)
|
||||
more = len(rows) > limit
|
||||
messages = [
|
||||
MessageRecord(
|
||||
id=row.id,
|
||||
chat_id=row.chat_id,
|
||||
sender_id=row.sender_id,
|
||||
text=row.text,
|
||||
created_at=row.created_at,
|
||||
)
|
||||
for row in rows[:limit]
|
||||
]
|
||||
return messages, more
|
||||
|
||||
async def _page(
|
||||
self, statement: Select, table, after: Position | None, limit: int
|
||||
) -> list[Row]:
|
||||
"""Забирает limit+1 строк: лишняя строка и означает «есть ещё»."""
|
||||
if after is not None:
|
||||
statement = statement.where(_after_predicate(table.c.created_at, table.c.id, after))
|
||||
result = await self._session.execute(
|
||||
statement.order_by(table.c.created_at, table.c.id).limit(limit + 1)
|
||||
)
|
||||
return list(result)
|
||||
|
||||
async def _members_of(self, chat_ids: Sequence[UUID]) -> dict[UUID, tuple[UUID, ...]]:
|
||||
"""Состав участников страницы чатов одним запросом, без N+1."""
|
||||
if not chat_ids:
|
||||
return {}
|
||||
rows = await self._session.execute(
|
||||
select(CHAT_MEMBERS.c.chat_id, CHAT_MEMBERS.c.user_id)
|
||||
.where(CHAT_MEMBERS.c.chat_id.in_(chat_ids))
|
||||
.order_by(CHAT_MEMBERS.c.chat_id, CHAT_MEMBERS.c.user_id)
|
||||
)
|
||||
grouped: dict[UUID, list[UUID]] = {}
|
||||
for chat_id, user_id in rows:
|
||||
grouped.setdefault(chat_id, []).append(user_id)
|
||||
return {chat_id: tuple(members) for chat_id, members in grouped.items()}
|
||||
Reference in New Issue
Block a user