forked from mtusi2026/mtusi2026lab3
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>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a18e7b320b
commit
7bf28fc6ed
@@ -17,3 +17,5 @@ class PostMessage(Command):
|
||||
sender_id: UUID
|
||||
chat_id: UUID
|
||||
text: str
|
||||
key: str
|
||||
fingerprint: bytes
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from messenger.messaging.application.commands import CreateChat, PostMessage
|
||||
from messenger.messaging.application.ports import MessagingUnitOfWork
|
||||
from messenger.messaging.domain.errors import ChatNotFound
|
||||
from messenger.messaging.domain.models import Chat, Message
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.shared.application.ports import Clock, IdGenerator
|
||||
|
||||
|
||||
@@ -28,24 +30,33 @@ class CreateChatHandler:
|
||||
|
||||
|
||||
class PostMessageHandler:
|
||||
__slots__ = ("_clock", "_ids", "_uow")
|
||||
__slots__ = ("_clock", "_ids", "_ttl", "_uow")
|
||||
|
||||
def __init__(self, uow: MessagingUnitOfWork, clock: Clock, ids: IdGenerator) -> None:
|
||||
def __init__(
|
||||
self, uow: MessagingUnitOfWork, clock: Clock, ids: IdGenerator, ttl: timedelta
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._clock = clock
|
||||
self._ids = ids
|
||||
self._ttl = ttl
|
||||
|
||||
async def __call__(self, command: PostMessage) -> Message:
|
||||
async with self._uow.transaction():
|
||||
chat = await self._uow.chats.get(command.chat_id)
|
||||
if chat is None:
|
||||
raise ChatNotFound("чат не найден")
|
||||
now = self._clock.now()
|
||||
message = chat.post(
|
||||
message_id=self._ids.new_id(),
|
||||
sender_id=command.sender_id,
|
||||
text=command.text,
|
||||
now=self._clock.now(),
|
||||
now=now,
|
||||
)
|
||||
await self._uow.chats.append(message)
|
||||
known = await self._uow.chats.receipt(
|
||||
chat.id, command.sender_id, command.key, now - self._ttl
|
||||
)
|
||||
if known is not None:
|
||||
return known.replay(command.fingerprint)
|
||||
await self._uow.chats.append(Receipt(command.key, command.fingerprint, message))
|
||||
await self._uow.commit()
|
||||
return message
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
from datetime import datetime
|
||||
from typing import Protocol, runtime_checkable
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.models import Chat, Message
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.shared.application.ports import UnitOfWork
|
||||
|
||||
|
||||
@@ -19,7 +20,11 @@ class ChatRepository(Protocol):
|
||||
|
||||
async def get(self, chat_id: UUID) -> Chat | None: ...
|
||||
|
||||
async def append(self, message: Message) -> None: ...
|
||||
async def receipt(
|
||||
self, chat_id: UUID, sender_id: UUID, key: str, since: datetime
|
||||
) -> Receipt | None: ...
|
||||
|
||||
async def append(self, receipt: Receipt) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
|
||||
@@ -5,3 +5,4 @@ from messenger.shared.config import Settings
|
||||
|
||||
class MessagingSettings(Settings):
|
||||
cursor_secret: SecretStr = Field(min_length=16)
|
||||
idempotency_ttl_seconds: int = Field(default=86_400, ge=1)
|
||||
|
||||
@@ -19,3 +19,7 @@ class InvalidPageRequest(MessagingError):
|
||||
|
||||
class ChatNotFound(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class IdempotencyConflict(MessagingError):
|
||||
pass
|
||||
|
||||
@@ -3,7 +3,7 @@ from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.messaging.domain.errors import ChatNotFound, InvalidChatData
|
||||
from messenger.messaging.domain.errors import ChatNotFound, IdempotencyConflict, InvalidChatData
|
||||
from messenger.messaging.domain.events import ChatCreated, MessagePosted
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.values import CHAT_MEMBERS_MAX, ChatTitle, MessageText
|
||||
@@ -25,6 +25,18 @@ class Message:
|
||||
return (self.created_at, self.id.int)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Receipt:
|
||||
key: str
|
||||
fingerprint: bytes
|
||||
message: Message
|
||||
|
||||
def replay(self, fingerprint: bytes) -> Message:
|
||||
if fingerprint != self.fingerprint:
|
||||
raise IdempotencyConflict("ключ идемпотентности уже использован с другим телом")
|
||||
return self.message
|
||||
|
||||
|
||||
class Chat:
|
||||
__slots__ = (
|
||||
"_events",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidChatData,
|
||||
InvalidMessageText,
|
||||
InvalidPageRequest,
|
||||
@@ -11,4 +12,5 @@ ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
|
||||
InvalidMessageText: ("invalid_request", 400),
|
||||
InvalidPageRequest: ("invalid_request", 400),
|
||||
ChatNotFound: ("not_found", 404),
|
||||
IdempotencyConflict: ("conflict", 409),
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ from messenger.messaging.entrypoints.schemas import (
|
||||
ChatOut,
|
||||
CreateChatRequest,
|
||||
CreateMessageRequest,
|
||||
IdempotencyKey,
|
||||
MessageOut,
|
||||
PageOut,
|
||||
PageQuery,
|
||||
@@ -61,9 +62,18 @@ async def post_message(
|
||||
chat_id: UUID,
|
||||
actor: Actor,
|
||||
body: CreateMessageRequest,
|
||||
key: IdempotencyKey,
|
||||
bus: FromDishka[MessagingCommandBus],
|
||||
) -> MessageOut:
|
||||
message = await bus.execute(PostMessage(sender_id=actor, chat_id=chat_id, text=body.text))
|
||||
message = await bus.execute(
|
||||
PostMessage(
|
||||
sender_id=actor,
|
||||
chat_id=chat_id,
|
||||
text=body.text,
|
||||
key=key,
|
||||
fingerprint=body.fingerprint(),
|
||||
)
|
||||
)
|
||||
return MessageOut.of(message)
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import Provider, Scope, provide
|
||||
|
||||
from messenger.messaging.application.bus import MessagingCommandBus
|
||||
@@ -57,9 +59,11 @@ class MessagingProvider(Provider):
|
||||
publisher: EventPublisher,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
settings: MessagingSettings,
|
||||
) -> MessagingCommandBus:
|
||||
ttl = timedelta(seconds=settings.idempotency_ttl_seconds)
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
CreateChat: CreateChatHandler(uow, clock, ids),
|
||||
PostMessage: PostMessageHandler(uow, clock, ids),
|
||||
PostMessage: PostMessageHandler(uow, clock, ids, ttl),
|
||||
}
|
||||
return MessagingCommandBus(handlers, uow, publisher)
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
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
|
||||
@@ -10,6 +12,11 @@ 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
|
||||
@@ -23,6 +30,9 @@ class CreateMessageRequest(BaseModel):
|
||||
|
||||
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)
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
|
||||
from messenger.messaging.domain.errors import InvalidChatData
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.models import Chat, Message
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.messaging.domain.values import ChatTitle, MessageText
|
||||
from messenger.shared.infrastructure.postgres import (
|
||||
Connection,
|
||||
@@ -27,11 +28,23 @@ FROM chats c
|
||||
WHERE c.id = $1
|
||||
FOR UPDATE
|
||||
"""
|
||||
RECEIPT = """
|
||||
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.chat_id = $1 AND k.user_id = $2 AND k.key = $3 AND k.created_at > $4
|
||||
"""
|
||||
APPEND_MESSAGE = """
|
||||
WITH message AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING chat_id, created_at
|
||||
RETURNING id, chat_id, sender_id, created_at
|
||||
), receipt AS (
|
||||
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
|
||||
SELECT chat_id, sender_id, $6, $7, id, created_at FROM message
|
||||
ON CONFLICT (chat_id, user_id, key) DO UPDATE
|
||||
SET fingerprint = EXCLUDED.fingerprint,
|
||||
message_id = EXCLUDED.message_id,
|
||||
created_at = EXCLUDED.created_at
|
||||
)
|
||||
UPDATE chats SET last_message_at = message.created_at
|
||||
FROM message
|
||||
@@ -124,7 +137,14 @@ class PostgresChatRepository:
|
||||
self._seen.append(chat)
|
||||
return chat
|
||||
|
||||
async def append(self, message: Message) -> None:
|
||||
async def receipt(
|
||||
self, chat_id: UUID, sender_id: UUID, key: str, since: datetime
|
||||
) -> Receipt | None:
|
||||
row = await self._connection.fetchrow(RECEIPT, chat_id, sender_id, key, since)
|
||||
return None if row is None else Receipt(key, row["fingerprint"], message_of(row))
|
||||
|
||||
async def append(self, receipt: Receipt) -> None:
|
||||
message = receipt.message
|
||||
await self._connection.execute(
|
||||
APPEND_MESSAGE,
|
||||
message.id,
|
||||
@@ -132,6 +152,8 @@ class PostgresChatRepository:
|
||||
message.sender_id,
|
||||
message.text.value,
|
||||
message.created_at,
|
||||
receipt.key,
|
||||
receipt.fingerprint,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ FAILURES = (
|
||||
asyncpg.PostgresConnectionError,
|
||||
asyncpg.exceptions.OperatorInterventionError,
|
||||
asyncpg.exceptions.InsufficientResourcesError,
|
||||
asyncpg.exceptions.LockNotAvailableError,
|
||||
)
|
||||
|
||||
type Connection = asyncpg.Connection
|
||||
|
||||
Reference in New Issue
Block a user