feat: перенос логики с 4лабф
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
from uuid import UUID
|
||||
|
||||
import asyncpg
|
||||
|
||||
from domain import IdempotencyKeySchema, MessageSchema, PageKey
|
||||
from domain.errors import ConflictError, NotFoundError
|
||||
from infrastructure.utils import Pool, repository_logs, transaction
|
||||
from interfaces import MessageRepository
|
||||
|
||||
# Пространство ключей advisory lock: (namespace, hashtext(chat_id))
|
||||
CHAT_LOCK_NAMESPACE = 2
|
||||
|
||||
# Вложения сообщения в порядке attachment_ids запроса
|
||||
MESSAGE_ATTACHMENT_IDS = """
|
||||
ARRAY(
|
||||
SELECT link.attachment_id
|
||||
FROM message_attachments link
|
||||
WHERE link.message_id = message.id
|
||||
ORDER BY link.position
|
||||
) AS attachment_ids
|
||||
"""
|
||||
|
||||
|
||||
class PostgresMessageRepository(MessageRepository):
|
||||
def __init__(self, pool: Pool) -> None:
|
||||
self._pool = pool
|
||||
|
||||
@repository_logs
|
||||
async def create(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
attachment_ids: list[UUID],
|
||||
idempotency: IdempotencyKeySchema,
|
||||
) -> tuple[MessageSchema, bool]:
|
||||
"""
|
||||
Блокировка чата, проверка ключа, вставка сообщения и ключа — одна
|
||||
транзакция; lock снимается на COMMIT.
|
||||
|
||||
Запись в один чат сериализуется, записи в разные чаты не мешают друг другу.
|
||||
Ключ идемпотентности привязан к чату, поэтому та же блокировка
|
||||
сериализует и одновременные повторы с одним ключом с разных реплик:
|
||||
второй ждёт COMMIT первого и находит его ключ
|
||||
|
||||
created_at строго больше последнего в чате, даже если часы ушли назад:
|
||||
порядок коммитов совпадает с порядком (created_at, id), и читатель
|
||||
с cursor не пропустит сообщение. MAX берётся из индекса
|
||||
(chat_id, created_at, id) — Index Only Scan Backward, а не проход по истории.
|
||||
|
||||
Вложения связываются одним INSERT ... SELECT только с готовыми
|
||||
вложениями этого чата; если связано меньше, чем передано, — 404
|
||||
и откат всей транзакции, сообщение не появляется. Составной FK
|
||||
(attachment_id, chat_id) дублирует проверку чата на уровне БД.
|
||||
"""
|
||||
lock_query = """
|
||||
SELECT pg_advisory_xact_lock($1, hashtext($2::uuid::text));
|
||||
"""
|
||||
find_key_query = f"""
|
||||
SELECT
|
||||
idem.request_hash,
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text,
|
||||
message.created_at,
|
||||
{MESSAGE_ATTACHMENT_IDS}
|
||||
FROM message_idempotency_keys idem
|
||||
JOIN messages message ON message.id = idem.message_id
|
||||
WHERE
|
||||
idem.sender_id = $1
|
||||
AND idem.chat_id = $2
|
||||
AND idem.idempotency_key = $3
|
||||
AND idem.expires_at > clock_timestamp();
|
||||
"""
|
||||
insert_query = """
|
||||
INSERT INTO messages
|
||||
(
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
)
|
||||
SELECT
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
GREATEST(clock_timestamp(), MAX(created_at) + interval '1 microsecond')
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
RETURNING id, chat_id, sender_id, text, created_at;
|
||||
"""
|
||||
attachments_query = """
|
||||
INSERT INTO message_attachments
|
||||
(
|
||||
message_id,
|
||||
chat_id,
|
||||
attachment_id,
|
||||
position
|
||||
)
|
||||
SELECT
|
||||
$1,
|
||||
$2,
|
||||
attachment.id,
|
||||
item.ordinality - 1
|
||||
FROM unnest($3::uuid[]) WITH ORDINALITY AS item(attachment_id, ordinality)
|
||||
JOIN attachments attachment
|
||||
ON attachment.id = item.attachment_id
|
||||
AND attachment.chat_id = $2
|
||||
AND attachment.status = 'ready';
|
||||
"""
|
||||
|
||||
save_key_query = """
|
||||
INSERT INTO message_idempotency_keys
|
||||
(
|
||||
sender_id,
|
||||
chat_id,
|
||||
idempotency_key,
|
||||
request_hash,
|
||||
message_id,
|
||||
expires_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
clock_timestamp() + make_interval(secs => $6::integer)
|
||||
)
|
||||
ON CONFLICT (sender_id, chat_id, idempotency_key) DO UPDATE
|
||||
SET
|
||||
request_hash = EXCLUDED.request_hash,
|
||||
message_id = EXCLUDED.message_id,
|
||||
created_at = EXCLUDED.created_at,
|
||||
expires_at = EXCLUDED.expires_at;
|
||||
"""
|
||||
async with transaction(self._pool) as conn:
|
||||
await conn.execute(lock_query, CHAT_LOCK_NAMESPACE, chat_id)
|
||||
stored = await conn.fetchrow(
|
||||
find_key_query, sender_id, chat_id, idempotency.key
|
||||
)
|
||||
if stored is not None:
|
||||
if stored["request_hash"] != idempotency.request_hash:
|
||||
raise ConflictError(
|
||||
"Idempotency-Key уже использован с другим телом запроса"
|
||||
)
|
||||
return self._row_to_message(stored), False
|
||||
row = await conn.fetchrow(insert_query, chat_id, sender_id, text)
|
||||
assert row is not None
|
||||
if attachment_ids:
|
||||
status = await conn.execute(
|
||||
attachments_query, row["id"], chat_id, attachment_ids
|
||||
)
|
||||
if int(status.split()[-1]) != len(attachment_ids):
|
||||
raise NotFoundError("Вложение не найдено")
|
||||
await conn.execute(
|
||||
save_key_query,
|
||||
sender_id,
|
||||
chat_id,
|
||||
idempotency.key,
|
||||
idempotency.request_hash,
|
||||
row["id"],
|
||||
idempotency.ttl_seconds,
|
||||
)
|
||||
return self._row_to_message(row, attachment_ids), True
|
||||
|
||||
@repository_logs
|
||||
async def list_for_chat(
|
||||
self, chat_id: UUID, after: PageKey | None, limit: int
|
||||
) -> list[MessageSchema]:
|
||||
"""
|
||||
История по (created_at, id). Со второй страницы Index Cond по
|
||||
(chat_id, created_at, id) начинает чтение сразу после cursor
|
||||
и останавливается после LIMIT строк.
|
||||
"""
|
||||
first_page_query = f"""
|
||||
SELECT
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text,
|
||||
message.created_at,
|
||||
{MESSAGE_ATTACHMENT_IDS}
|
||||
FROM messages message
|
||||
WHERE message.chat_id = $1
|
||||
ORDER BY message.created_at, message.id
|
||||
LIMIT $2;
|
||||
"""
|
||||
next_page_query = f"""
|
||||
SELECT
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text,
|
||||
message.created_at,
|
||||
{MESSAGE_ATTACHMENT_IDS}
|
||||
FROM messages message
|
||||
WHERE
|
||||
message.chat_id = $1
|
||||
AND (message.created_at, message.id) > ($2, $3)
|
||||
ORDER BY message.created_at, message.id
|
||||
LIMIT $4;
|
||||
"""
|
||||
async with self._pool.acquire() as conn:
|
||||
if after is None:
|
||||
rows = await conn.fetch(first_page_query, chat_id, limit)
|
||||
else:
|
||||
rows = await conn.fetch(
|
||||
next_page_query, chat_id, after.created_at, after.id, limit
|
||||
)
|
||||
return [self._row_to_message(row) for row in rows]
|
||||
|
||||
@staticmethod
|
||||
def _row_to_message(
|
||||
row: asyncpg.Record, attachment_ids: list[UUID] | None = None
|
||||
) -> MessageSchema:
|
||||
"""attachment_ids — из запроса для только что вставленного сообщения"""
|
||||
return MessageSchema(
|
||||
id=row["id"],
|
||||
chat_id=row["chat_id"],
|
||||
sender_id=row["sender_id"],
|
||||
text=row["text"],
|
||||
created_at=row["created_at"],
|
||||
attachment_ids=(
|
||||
attachment_ids if attachment_ids is not None else row["attachment_ids"]
|
||||
),
|
||||
)
|
||||
Reference in New Issue
Block a user