Done Track 4
This commit is contained in:
+24
-13
@@ -1,4 +1,4 @@
|
||||
"""Business rules for MTUSI Messenger Lab3."""
|
||||
"""Business rules for MTUSI Messenger Lab4 (users, chats, messages)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -58,6 +58,7 @@ def _to_message(row: dict[str, Any]) -> dict[str, Any]:
|
||||
"sender_id": row["sender_id"],
|
||||
"text": row["text"],
|
||||
"created_at": row["created_at"],
|
||||
"attachment_ids": list(row.get("attachment_ids") or []),
|
||||
}
|
||||
|
||||
|
||||
@@ -299,10 +300,15 @@ async def list_chats(
|
||||
}
|
||||
|
||||
|
||||
def _request_fingerprint(text_value: str) -> str:
|
||||
"""Hash of the validated body: key order and whitespace do not matter."""
|
||||
def _request_fingerprint(text_value: str, attachment_ids: list[UUID]) -> str:
|
||||
"""Hash of the validated body: key order and whitespace do not matter,
|
||||
a missing attachment_ids equals []. Without attachments the canonical
|
||||
form is the lab3 one, so keys stored by lab3 still replay correctly."""
|
||||
body: dict[str, Any] = {"text": text_value}
|
||||
if attachment_ids:
|
||||
body["attachment_ids"] = [str(item) for item in attachment_ids]
|
||||
canonical = json.dumps(
|
||||
{"text": text_value},
|
||||
body,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
@@ -315,6 +321,7 @@ async def create_message(
|
||||
*,
|
||||
chat_id: UUID,
|
||||
text_value: str,
|
||||
attachment_ids: list[UUID],
|
||||
idempotency_key: str | None,
|
||||
current_user: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], bool]:
|
||||
@@ -339,15 +346,19 @@ async def create_message(
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
result = await repositories.create_message_idempotent(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
sender_id=current_user["id"],
|
||||
text_value=text_value,
|
||||
idempotency_key=idempotency_key,
|
||||
request_hash=_request_fingerprint(text_value),
|
||||
ttl_seconds=settings.idempotency_ttl_seconds,
|
||||
)
|
||||
try:
|
||||
result = await repositories.create_message_idempotent(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
sender_id=current_user["id"],
|
||||
text_value=text_value,
|
||||
attachment_ids=attachment_ids,
|
||||
idempotency_key=idempotency_key,
|
||||
request_hash=_request_fingerprint(text_value, attachment_ids),
|
||||
ttl_seconds=settings.idempotency_ttl_seconds,
|
||||
)
|
||||
except repositories.AttachmentsNotFound:
|
||||
raise _not_found() from None
|
||||
|
||||
if result is None:
|
||||
raise ApiError(
|
||||
|
||||
Reference in New Issue
Block a user