Files
mtusi2026labs/src/messenger/messaging/entrypoints/http.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

90 lines
2.4 KiB
Python

from typing import Annotated
from uuid import UUID
from dishka.integrations.fastapi import FromDishka, inject
from fastapi import APIRouter, Query, status
from messenger.messaging.application.bus import MessagingCommandBus
from messenger.messaging.application.commands import CreateChat, PostMessage
from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory
from messenger.messaging.entrypoints.schemas import (
ChatOut,
CreateChatRequest,
CreateMessageRequest,
IdempotencyKey,
MessageOut,
PageOut,
PageQuery,
)
from messenger.shared.entrypoints.actor import Actor
chats_router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
messages_router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
@chats_router.post("", status_code=status.HTTP_201_CREATED)
@inject
async def create_chat(
actor: Actor,
body: CreateChatRequest,
bus: FromDishka[MessagingCommandBus],
) -> ChatOut:
chat = await bus.execute(
CreateChat(creator_id=actor, title=body.title, member_ids=body.member_ids)
)
return ChatOut.of(chat)
@chats_router.get("")
@inject
async def list_chats(
actor: Actor,
page: Annotated[PageQuery, Query()],
query: FromDishka[ListChats],
) -> PageOut[ChatOut]:
chats = await query(actor, limit=page.limit, cursor=page.cursor)
return PageOut[ChatOut].of(chats, ChatOut.of)
@chats_router.get("/{chat_id}")
@inject
async def read_chat(
chat_id: UUID,
actor: Actor,
query: FromDishka[GetChat],
) -> ChatOut:
return ChatOut.of(await query(chat_id, actor))
@messages_router.post("", status_code=status.HTTP_201_CREATED)
@inject
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,
key=key,
fingerprint=body.fingerprint(),
)
)
return MessageOut.of(message)
@messages_router.get("")
@inject
async def read_history(
chat_id: UUID,
actor: Actor,
page: Annotated[PageQuery, Query()],
query: FromDishka[ReadHistory],
) -> PageOut[MessageOut]:
messages = await query(chat_id, actor, limit=page.limit, cursor=page.cursor)
return PageOut[MessageOut].of(messages, MessageOut.of)