Make message retries idempotent across replicas
This commit is contained in:
+29
-1
@@ -2,6 +2,7 @@
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
@@ -205,19 +206,46 @@ class Store:
|
||||
items = [chat_view(row) for row in rows[:limit]]
|
||||
return {"items": items, "next_cursor": encode_cursor(f"chats:{actor_id}", items[-1]) if len(rows) > limit else None}
|
||||
|
||||
def create_message(self, actor_id: str, chat_id: str, text: str) -> dict:
|
||||
def create_message(self, actor_id: str, chat_id: str, text: str, key: str) -> dict:
|
||||
chat_uuid, actor_uuid = UUID(chat_id), UUID(actor_id)
|
||||
request_hash = hashlib.sha256(json.dumps({"text": text}, ensure_ascii=False, sort_keys=True).encode()).digest()
|
||||
with connection() as conn:
|
||||
member = conn.execute(
|
||||
"SELECT 1 FROM memberships WHERE chat_id=%s AND user_id=%s", (chat_uuid, actor_uuid)
|
||||
).fetchone()
|
||||
if member is None:
|
||||
raise HTTPException(404)
|
||||
conn.execute(
|
||||
"DELETE FROM message_replays WHERE user_id=%s AND chat_id=%s AND request_key=%s "
|
||||
"AND created_at<clock_timestamp()-interval '24 hours'",
|
||||
(actor_uuid, chat_uuid, key),
|
||||
)
|
||||
reserved = conn.execute(
|
||||
"INSERT INTO message_replays (user_id,chat_id,request_key,request_hash) VALUES (%s,%s,%s,%s) "
|
||||
"ON CONFLICT DO NOTHING RETURNING request_key",
|
||||
(actor_uuid, chat_uuid, key, request_hash),
|
||||
).fetchone()
|
||||
if reserved is None:
|
||||
replay = conn.execute(
|
||||
"SELECT r.request_hash,m.id,m.chat_id,m.sender_id,m.text,m.created_at "
|
||||
"FROM message_replays r JOIN messages m ON m.id=r.message_id "
|
||||
"WHERE r.user_id=%s AND r.chat_id=%s AND r.request_key=%s",
|
||||
(actor_uuid, chat_uuid, key),
|
||||
).fetchone()
|
||||
if replay is None:
|
||||
raise HTTPException(503)
|
||||
if replay["request_hash"] != request_hash:
|
||||
raise HTTPException(409)
|
||||
return message_view(replay)
|
||||
row = 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_uuid, actor_uuid, text),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"UPDATE message_replays SET message_id=%s WHERE user_id=%s AND chat_id=%s AND request_key=%s",
|
||||
(row["id"], actor_uuid, chat_uuid, key),
|
||||
)
|
||||
return message_view(row)
|
||||
|
||||
def list_messages(self, actor_id: str, chat_id: str, limit: int, cursor: str | None) -> dict:
|
||||
|
||||
Reference in New Issue
Block a user