Разработала необходимый код
This commit is contained in:
+58
-3
@@ -1,8 +1,10 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
||||
from ..models.schemas import CreateMessage, Message, MessagePage, User
|
||||
from ..storage.postgres import storage
|
||||
from .security import current_user
|
||||
@@ -33,6 +35,17 @@ def _decode_cursor(chat_id: UUID, cursor: str) -> tuple:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
def _canonical_body_hash(payload: CreateMessage) -> str:
|
||||
"""sha256 канонизированного JSON. Отсутствующий attachment_ids == [].
|
||||
Порядок ключей не важен (sort_keys). Это ровно то, что требует контракт:
|
||||
'порядок ключей JSON и отсутствующий attachment_ids вместо [] семантически равны'.
|
||||
"""
|
||||
data = payload.model_dump(exclude_none=True)
|
||||
data.setdefault("attachment_ids", [])
|
||||
canonical = json.dumps(data, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/{chat_id}/messages",
|
||||
summary="Отправить сообщение в чат",
|
||||
@@ -43,11 +56,53 @@ def create_message(
|
||||
chat_id: UUID,
|
||||
payload: CreateMessage,
|
||||
user: User = Depends(current_user),
|
||||
idempotency_key: str = Header(..., alias="Idempotency-Key"),
|
||||
) -> Message:
|
||||
# Контракт: ключ ASCII [A-Za-z0-9._:-]{1,128}.
|
||||
if not (1 <= len(idempotency_key) <= 128):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if not all(c.isalnum() or c in "._:-" for c in idempotency_key):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
_require_member(chat_id, user.id)
|
||||
if not payload.text.strip():
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
return storage.add_message(chat_id, user.id, payload.text)
|
||||
|
||||
method = "POST"
|
||||
path = "/api/v1/chats/%s/messages" % chat_id
|
||||
body_hash = _canonical_body_hash(payload)
|
||||
|
||||
# 1) Атомарно бронируем ключ. Ровно один поток (или реплика) получит
|
||||
# право создать сообщение, остальные уйдут в replay.
|
||||
while True:
|
||||
state, info = storage.reserve_idempotency(
|
||||
user.id, method, path, idempotency_key, body_hash
|
||||
)
|
||||
if state == "reserved":
|
||||
break
|
||||
if state == "retry":
|
||||
time.sleep(0.05)
|
||||
continue
|
||||
# state == "replay"
|
||||
if info["body_hash"] != body_hash:
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
if info["response_status"] == 0:
|
||||
# Победитель ещё не записал финальный ответ — ждём.
|
||||
time.sleep(0.05)
|
||||
continue
|
||||
return Message.model_validate(info["response_body"])
|
||||
|
||||
# 2) Мы выиграли гонку: создаём сообщение и фиксируем результат.
|
||||
message = storage.add_message(chat_id, user.id, payload.text)
|
||||
storage.complete_idempotency(
|
||||
user_id=user.id,
|
||||
method=method,
|
||||
path=path,
|
||||
key=idempotency_key,
|
||||
response_status=201,
|
||||
response_body=json.loads(message.model_dump_json()),
|
||||
)
|
||||
return message
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -61,7 +116,7 @@ def list_messages(
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> MessagePage:
|
||||
"""Keyset-пагинация в SQL: (created_at, id) по возрастанию, без полного scan истории."""
|
||||
"""Keyset-пагинация в SQL: (created_at, id) по возрастанию"""
|
||||
_require_member(chat_id, user.id)
|
||||
after = _decode_cursor(chat_id, cursor) if cursor else None
|
||||
# Берём limit+1, чтобы понять, есть ли следующая страница
|
||||
|
||||
Reference in New Issue
Block a user