forked from mtusi2026/mtusi2026lab4
Добавить приватное хранилище вложений и отдачу файла через API.
Байты лежат в SeaweedFS, метаданные в Postgres. Другая реплика скачивает тот же объект, потому что локальный диск API не является источником файла.
This commit is contained in:
+58
-11
@@ -37,12 +37,16 @@ def chat_dict(row, member_ids: List[str]) -> dict:
|
||||
|
||||
|
||||
def message_dict(row) -> dict:
|
||||
raw_ids = row["attachment_ids"] if "attachment_ids" in row.keys() else []
|
||||
if raw_ids is None:
|
||||
raw_ids = []
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
"attachment_ids": [str(item) for item in raw_ids],
|
||||
}
|
||||
|
||||
|
||||
@@ -192,10 +196,10 @@ async def list_chats(user_id: str, limit: int, after: Optional[Tuple[str, str]]
|
||||
return items, next_key
|
||||
|
||||
|
||||
def _canonical_message(text: str) -> str:
|
||||
def _canonical_message(text: str, attachment_ids: List[str]) -> str:
|
||||
# Missing attachment_ids and [] are the same message. Key order does not matter.
|
||||
return json.dumps(
|
||||
{"attachment_ids": [], "text": text},
|
||||
{"attachment_ids": attachment_ids, "text": text},
|
||||
sort_keys=True,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
@@ -208,13 +212,15 @@ async def add_message(
|
||||
text: str,
|
||||
idem_key: str,
|
||||
path: str,
|
||||
attachment_ids: Optional[List[str]] = None,
|
||||
) -> Tuple[Optional[dict], Optional[str]]:
|
||||
"""Insert one message or replay the stored 201. The row and the result commit together.
|
||||
|
||||
Same user+method+path+key is serialized with a Postgres advisory lock so two
|
||||
replicas cannot insert two messages. A failed transaction stores nothing.
|
||||
"""
|
||||
digest = hashlib.sha256(_canonical_message(text).encode("utf-8")).hexdigest()
|
||||
attachment_ids = list(attachment_ids or [])
|
||||
digest = hashlib.sha256(_canonical_message(text, attachment_ids).encode("utf-8")).hexdigest()
|
||||
lock_key = f"{sender_id}|POST|{path}|{idem_key}"
|
||||
payload: Optional[dict] = None
|
||||
created_new = False
|
||||
@@ -262,6 +268,24 @@ async def add_message(
|
||||
path,
|
||||
idem_key,
|
||||
)
|
||||
resolved: List[str] = []
|
||||
if attachment_ids:
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT id, chat_id, status
|
||||
FROM attachments
|
||||
WHERE id = ANY($1::uuid[])
|
||||
""",
|
||||
[UUID(item) for item in attachment_ids],
|
||||
)
|
||||
found = {str(row["id"]): row for row in rows}
|
||||
if len(found) != len(attachment_ids) or any(
|
||||
str(found[item]["chat_id"]) != chat_id for item in attachment_ids
|
||||
):
|
||||
return None, "not_found"
|
||||
if any(found[item]["status"] != "ready" for item in attachment_ids):
|
||||
return None, "not_ready"
|
||||
resolved = attachment_ids
|
||||
message_id = uuid4()
|
||||
created = datetime.now(timezone.utc)
|
||||
await conn.execute(
|
||||
@@ -275,6 +299,14 @@ async def add_message(
|
||||
text,
|
||||
created,
|
||||
)
|
||||
if resolved:
|
||||
await conn.executemany(
|
||||
"""
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES ($1, $2, $3)
|
||||
""",
|
||||
[(message_id, UUID(item), index) for index, item in enumerate(resolved)],
|
||||
)
|
||||
payload = message_dict(
|
||||
{
|
||||
"id": message_id,
|
||||
@@ -282,6 +314,7 @@ async def add_message(
|
||||
"sender_id": UUID(sender_id),
|
||||
"text": text,
|
||||
"created_at": created,
|
||||
"attachment_ids": resolved,
|
||||
}
|
||||
)
|
||||
await conn.execute(
|
||||
@@ -323,10 +356,17 @@ async def list_messages(chat_id: str, user_id: str, limit: int, after: Optional[
|
||||
rows = await _run(
|
||||
_fetch(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
COALESCE(
|
||||
array_agg(ma.attachment_id ORDER BY ma.position)
|
||||
FILTER (WHERE ma.attachment_id IS NOT NULL),
|
||||
ARRAY[]::uuid[]
|
||||
) AS attachment_ids
|
||||
FROM messages m
|
||||
LEFT JOIN message_attachments ma ON ma.message_id = m.id
|
||||
WHERE m.chat_id = $1
|
||||
GROUP BY m.id
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2
|
||||
""",
|
||||
UUID(chat_id),
|
||||
@@ -337,10 +377,17 @@ async def list_messages(chat_id: str, user_id: str, limit: int, after: Optional[
|
||||
rows = await _run(
|
||||
_fetch(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
COALESCE(
|
||||
array_agg(ma.attachment_id ORDER BY ma.position)
|
||||
FILTER (WHERE ma.attachment_id IS NOT NULL),
|
||||
ARRAY[]::uuid[]
|
||||
) AS attachment_ids
|
||||
FROM messages m
|
||||
LEFT JOIN message_attachments ma ON ma.message_id = m.id
|
||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
||||
GROUP BY m.id
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
""",
|
||||
UUID(chat_id),
|
||||
|
||||
Reference in New Issue
Block a user