175 lines
5.3 KiB
Python
175 lines
5.3 KiB
Python
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
from uuid import UUID, uuid4
|
|
|
|
from app.db import pool
|
|
from app.errors import ApiError, invalid, not_found
|
|
|
|
|
|
async def create_message_once(
|
|
chat_id: UUID,
|
|
sender_id: UUID,
|
|
text: str,
|
|
key: str,
|
|
attachment_ids: list[UUID] | None = None,
|
|
) -> dict:
|
|
attachment_ids = list(
|
|
attachment_ids if attachment_ids is not None else []
|
|
)
|
|
|
|
if (
|
|
len(attachment_ids) > 10
|
|
or len(set(attachment_ids)) != len(attachment_ids)
|
|
):
|
|
raise invalid("Некорректный список вложений")
|
|
|
|
if not isinstance(text, str) or len(text) > 4000:
|
|
raise invalid("Некорректный текст сообщения")
|
|
|
|
if not text.strip() and not attachment_ids:
|
|
raise invalid("Сообщение должно содержать текст или вложение")
|
|
|
|
scope = json.dumps(
|
|
[
|
|
str(sender_id),
|
|
"POST",
|
|
f"/api/v1/chats/{chat_id}/messages",
|
|
key,
|
|
],
|
|
separators=(",", ":"),
|
|
)
|
|
|
|
lock_id = int.from_bytes(
|
|
hashlib.sha256(scope.encode("utf-8")).digest()[:8],
|
|
byteorder="big",
|
|
signed=True,
|
|
)
|
|
|
|
async with pool.connection() as conn:
|
|
await conn.execute(
|
|
"SELECT pg_advisory_xact_lock(%s)",
|
|
(lock_id,),
|
|
)
|
|
|
|
cursor = await conn.execute(
|
|
"""
|
|
SELECT i.request_text,
|
|
i.request_attachment_ids,
|
|
m.id, m.chat_id, m.sender_id,
|
|
m.text, m.created_at,
|
|
ARRAY(
|
|
SELECT ma.attachment_id
|
|
FROM message_attachments AS ma
|
|
WHERE ma.message_id = m.id
|
|
ORDER BY ma.position
|
|
) AS attachment_ids
|
|
FROM message_idempotency AS i
|
|
JOIN messages AS m ON m.id = i.message_id
|
|
WHERE i.user_id = %s
|
|
AND i.chat_id = %s
|
|
AND i.http_method = 'POST'
|
|
AND i.idempotency_key = %s
|
|
""",
|
|
(sender_id, chat_id, key),
|
|
)
|
|
previous = await cursor.fetchone()
|
|
|
|
if previous is not None:
|
|
if (
|
|
previous["request_text"] != text
|
|
or previous["request_attachment_ids"] != attachment_ids
|
|
):
|
|
raise ApiError(
|
|
409,
|
|
"conflict",
|
|
"Ключ уже использован с другим сообщением",
|
|
)
|
|
|
|
message = {
|
|
field: previous[field]
|
|
for field in (
|
|
"id",
|
|
"chat_id",
|
|
"sender_id",
|
|
"text",
|
|
"created_at",
|
|
"attachment_ids",
|
|
)
|
|
}
|
|
else:
|
|
if attachment_ids:
|
|
cursor = await conn.execute(
|
|
"""
|
|
SELECT id
|
|
FROM attachments
|
|
WHERE id = ANY(%s::uuid[])
|
|
AND chat_id = %s
|
|
AND status = 'ready'
|
|
ORDER BY id
|
|
FOR SHARE
|
|
""",
|
|
(attachment_ids, chat_id),
|
|
)
|
|
available = await cursor.fetchall()
|
|
|
|
if len(available) != len(attachment_ids):
|
|
raise not_found()
|
|
|
|
cursor = await conn.execute(
|
|
"""
|
|
INSERT INTO messages (
|
|
id, chat_id, sender_id, text
|
|
)
|
|
VALUES (%s, %s, %s, %s)
|
|
RETURNING id, chat_id, sender_id,
|
|
text, created_at
|
|
""",
|
|
(uuid4(), chat_id, sender_id, text),
|
|
)
|
|
message = await cursor.fetchone()
|
|
|
|
if attachment_ids:
|
|
async with conn.cursor() as cursor:
|
|
await cursor.executemany(
|
|
"""
|
|
INSERT INTO message_attachments (
|
|
message_id, attachment_id, position
|
|
)
|
|
VALUES (%s, %s, %s)
|
|
""",
|
|
[
|
|
(message["id"], attachment_id, position)
|
|
for position, attachment_id
|
|
in enumerate(attachment_ids)
|
|
],
|
|
)
|
|
|
|
await conn.execute(
|
|
"""
|
|
INSERT INTO message_idempotency (
|
|
user_id,
|
|
chat_id,
|
|
http_method,
|
|
idempotency_key,
|
|
request_text,
|
|
request_attachment_ids,
|
|
message_id
|
|
)
|
|
VALUES (%s, %s, 'POST', %s, %s, %s::uuid[], %s)
|
|
""",
|
|
(
|
|
sender_id,
|
|
chat_id,
|
|
key,
|
|
text,
|
|
attachment_ids,
|
|
message["id"],
|
|
),
|
|
)
|
|
|
|
message["attachment_ids"] = attachment_ids
|
|
|
|
return message
|