Files
mtusi2026labs/src/messenger/messaging/entrypoints/schemas.py
T
ArtyomandClaude Opus 5.5 7bf28fc6ed Make message posts idempotent with Idempotency-Key
POST /api/v1/chats/{chat_id}/messages now requires the header, checked
at the HTTP boundary (1-128 of [A-Za-z0-9._:-], else 400). The handler
keeps the lab 2 order under the chat row lock: membership, then text,
then the receipt for (chat, sender, key) younger than
IDEMPOTENCY_TTL_SECONDS. A receipt with the same fingerprint replays
the stored message, a different one is 409 conflict; without a
receipt one statement inserts the message, the key row and the chat
mark, so both commit or neither does. Concurrent retries wait on the
same row lock and then read the committed receipt. The fingerprint is
SHA-256 of the canonical JSON of the parsed body, so layout does not
matter, and only 201 answers are ever stored.

A lock timeout now counts as a dependency failure and answers 503
instead of 500, so a retry with the same key is safe.

Own tests cover replay, a different layout of the same JSON, conflict,
missing and malformed keys, rejected attempts that leave the key free,
scope by user and chat, revalidation after logout and for outsiders,
expiry, and eight concurrent retries through two app instances
sharing one PostgreSQL. Every earlier message post sends a fresh key.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 11:36:15 +03:00

83 lines
2.0 KiB
Python

from collections.abc import Callable
from datetime import datetime
from hashlib import sha256
from typing import Annotated, Self
from uuid import UUID
from fastapi import Header
from pydantic import BaseModel, ConfigDict, Field
from messenger.messaging.application.queries import Page
from messenger.messaging.domain.models import Chat, Message
STRICT = ConfigDict(extra="forbid", strict=True)
type IdempotencyKey = Annotated[
str,
Header(alias="Idempotency-Key", min_length=1, max_length=128, pattern=r"^[A-Za-z0-9._:-]+$"),
]
class CreateChatRequest(BaseModel):
model_config = STRICT
title: str
member_ids: list[Annotated[UUID, Field(strict=False)]]
class CreateMessageRequest(BaseModel):
model_config = STRICT
text: str
def fingerprint(self) -> bytes:
return sha256(self.model_dump_json().encode()).digest()
class PageQuery(BaseModel):
limit: int = Field(default=50, ge=1, le=100)
cursor: str | None = None
class ChatOut(BaseModel):
id: UUID
title: str
member_ids: tuple[UUID, ...]
created_at: datetime
@classmethod
def of(cls, chat: Chat) -> ChatOut:
return cls(
id=chat.id,
title=chat.title.value,
member_ids=chat.member_ids,
created_at=chat.created_at,
)
class MessageOut(BaseModel):
id: UUID
chat_id: UUID
sender_id: UUID
text: str
created_at: datetime
@classmethod
def of(cls, message: Message) -> MessageOut:
return cls(
id=message.id,
chat_id=message.chat_id,
sender_id=message.sender_id,
text=message.text.value,
created_at=message.created_at,
)
class PageOut[ItemT](BaseModel):
items: list[ItemT]
next_cursor: str | None
@classmethod
def of[SourceT](cls, page: Page[SourceT], view: Callable[[SourceT], ItemT]) -> Self:
return cls(items=[view(item) for item in page.items], next_cursor=page.next_cursor)