forked from mtusi2026/mtusi2026lab4
реализация 4 лабы
This commit is contained in:
+25
-10
@@ -24,7 +24,12 @@ def public_chat(row):
|
||||
|
||||
def public_message(row):
|
||||
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]),
|
||||
"text": row["text"], "created_at": utc(row["created_at"])}
|
||||
"text": row["text"], "created_at": utc(row["created_at"]),
|
||||
"attachment_ids": [str(value) for value in row.get("attachment_ids", [])]}
|
||||
|
||||
|
||||
MESSAGE_ATTACHMENTS = """ARRAY(SELECT attachment_id FROM message_attachments
|
||||
WHERE message_id=m.id ORDER BY position) AS attachment_ids"""
|
||||
|
||||
|
||||
def create_user(username, display_name, password_hash):
|
||||
@@ -98,28 +103,38 @@ def list_chats(user_id, limit, cursor):
|
||||
return pagination.page([public_chat(row) for row in rows], size, scope)
|
||||
|
||||
|
||||
def create_message(user_id, chat_id, text, key):
|
||||
def create_message(user_id, chat_id, text, key, attachment_ids=()):
|
||||
attachment_ids = [UUID(value) for value in attachment_ids]
|
||||
with db.connection() as conn:
|
||||
require_member(conn, user_id, chat_id)
|
||||
# Одна блокировка на область ключа во всех API-процессах.
|
||||
# Побочный эффект и результат повтора фиксируются одной транзакцией.
|
||||
scope = user_id + ":POST:/api/v1/chats/" + chat_id + "/messages:" + key
|
||||
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (scope,))
|
||||
previous = conn.execute("""SELECT m.*, i.request_text FROM message_idempotency i
|
||||
previous = conn.execute("SELECT m.*, i.request_text, i.request_attachment_ids, " + MESSAGE_ATTACHMENTS + """ FROM message_idempotency i
|
||||
JOIN messages m ON m.id=i.message_id
|
||||
WHERE i.user_id=%s AND i.chat_id=%s AND i.key=%s AND i.expires_at>clock_timestamp()""",
|
||||
(UUID(user_id), UUID(chat_id), key)).fetchone()
|
||||
if previous:
|
||||
if previous["request_text"] != text:
|
||||
if previous["request_text"] != text or previous["request_attachment_ids"] != attachment_ids:
|
||||
raise ApiError(409, "conflict", "Этот ключ уже использован с другим сообщением")
|
||||
return public_message(previous)
|
||||
if attachment_ids:
|
||||
available = conn.execute("SELECT id FROM attachments WHERE chat_id=%s AND id=ANY(%s)",
|
||||
(UUID(chat_id), attachment_ids)).fetchall()
|
||||
if len(available) != len(attachment_ids):
|
||||
raise ApiError(404, "not_found", "Вложение не найдено в этом чате")
|
||||
conn.execute("DELETE FROM message_idempotency WHERE user_id=%s AND chat_id=%s AND key=%s",
|
||||
(UUID(user_id), UUID(chat_id), key))
|
||||
row = conn.execute("""INSERT INTO messages(id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s)
|
||||
RETURNING *""", (uuid4(), UUID(chat_id), UUID(user_id), text)).fetchone()
|
||||
conn.execute("""INSERT INTO message_idempotency(user_id, chat_id, key, request_text, message_id, expires_at)
|
||||
VALUES (%s, %s, %s, %s, %s, clock_timestamp() + %s * interval '1 second')""",
|
||||
(UUID(user_id), UUID(chat_id), key, text, row["id"], IDEMPOTENCY_TTL))
|
||||
for position, attachment_id in enumerate(attachment_ids):
|
||||
conn.execute("INSERT INTO message_attachments(message_id, attachment_id, position) VALUES (%s, %s, %s)",
|
||||
(row["id"], attachment_id, position))
|
||||
conn.execute("""INSERT INTO message_idempotency(user_id, chat_id, key, request_text, request_attachment_ids, message_id, expires_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, clock_timestamp() + %s * interval '1 second')""",
|
||||
(UUID(user_id), UUID(chat_id), key, text, attachment_ids, row["id"], IDEMPOTENCY_TTL))
|
||||
row["attachment_ids"] = attachment_ids
|
||||
result = public_message(row)
|
||||
return result
|
||||
|
||||
@@ -133,7 +148,7 @@ def list_messages(user_id, chat_id, limit, cursor):
|
||||
found = conn.execute("SELECT 1 FROM messages WHERE chat_id=%s AND (created_at, id)=(%s, %s)", (UUID(chat_id), *anchor)).fetchone()
|
||||
if not found:
|
||||
raise ApiError(400, "invalid_request", "Неверный cursor")
|
||||
condition = "AND (created_at, id) > (%s, %s)" if anchor else ""
|
||||
rows = conn.execute("SELECT * FROM messages WHERE chat_id=%s " + condition +
|
||||
" ORDER BY created_at, id LIMIT %s", (UUID(chat_id), *(anchor or ()), size + 1)).fetchall()
|
||||
condition = "AND (m.created_at, m.id) > (%s, %s)" if anchor else ""
|
||||
rows = conn.execute("SELECT m.*, " + MESSAGE_ATTACHMENTS + " FROM messages m WHERE m.chat_id=%s " + condition +
|
||||
" ORDER BY m.created_at, m.id LIMIT %s", (UUID(chat_id), *(anchor or ()), size + 1)).fetchall()
|
||||
return pagination.page([public_message(row) for row in rows], size, scope)
|
||||
|
||||
Reference in New Issue
Block a user