Реализация лабораторной работы 4 на 4
This commit is contained in:
@@ -0,0 +1,165 @@
|
||||
from uuid import UUID
|
||||
import asyncpg
|
||||
|
||||
from domain import IdempotencyKeySchema, MessageSchema, PageKey
|
||||
from domain.errors import ConflictError
|
||||
from infrastructure.utils import Pool, repository_logs, transaction
|
||||
from interfaces import MessageRepository
|
||||
|
||||
CHAT_LOCK_NAMESPACE = 2
|
||||
|
||||
|
||||
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_query = """
|
||||
SELECT pg_advisory_xact_lock($1, hashtext($2::uuid::text));
|
||||
"""
|
||||
find_key_query = """
|
||||
SELECT
|
||||
idem.request_hash,
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text,
|
||||
message.attachment_ids,
|
||||
message.created_at
|
||||
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,
|
||||
attachment_ids,
|
||||
created_at
|
||||
)
|
||||
SELECT
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4::uuid[],
|
||||
GREATEST(clock_timestamp(), MAX(created_at) + interval '1 microsecond')
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
RETURNING id, chat_id, sender_id, text, attachment_ids, created_at;
|
||||
"""
|
||||
|
||||
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, attachment_ids)
|
||||
assert row is not None
|
||||
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), True
|
||||
|
||||
@repository_logs
|
||||
async def list_for_chat(
|
||||
self, chat_id: UUID, after: PageKey | None, limit: int
|
||||
) -> list[MessageSchema]:
|
||||
first_page_query = """
|
||||
SELECT
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
attachment_ids,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2;
|
||||
"""
|
||||
next_page_query = """
|
||||
SELECT
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
attachment_ids,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE
|
||||
chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, 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) -> MessageSchema:
|
||||
return MessageSchema(
|
||||
id=row["id"],
|
||||
chat_id=row["chat_id"],
|
||||
sender_id=row["sender_id"],
|
||||
text=row["text"],
|
||||
attachment_ids=list(row["attachment_ids"]) if row["attachment_ids"] is not None else [],
|
||||
created_at=row["created_at"],
|
||||
)
|
||||
Reference in New Issue
Block a user