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>
125 lines
3.9 KiB
Python
125 lines
3.9 KiB
Python
import asyncio
|
|
from dataclasses import fields
|
|
from datetime import UTC, datetime
|
|
from uuid import uuid4
|
|
|
|
from httpx import ASGITransport, AsyncClient
|
|
|
|
from conftest import keyed, make_chat, register, split_settings
|
|
from fakes import NullLogger
|
|
from messenger.identity.domain.events import UserRegistered
|
|
from messenger.main import create_app
|
|
from messenger.messaging.domain.events import MessagePosted
|
|
from messenger.shared.application.messagebus import EventBus, InMemoryEventPublisher
|
|
|
|
|
|
def posted() -> MessagePosted:
|
|
return MessagePosted(
|
|
message_id=uuid4(),
|
|
chat_id=uuid4(),
|
|
sender_id=uuid4(),
|
|
text_length=5,
|
|
created_at=datetime.now(UTC),
|
|
)
|
|
|
|
|
|
async def test_event_has_no_message_text() -> None:
|
|
names = {field.name for field in fields(posted())}
|
|
assert names == {"name", "message_id", "chat_id", "sender_id", "text_length", "created_at"}
|
|
|
|
|
|
async def test_every_subscriber_receives_event() -> None:
|
|
bus = EventBus(NullLogger())
|
|
seen: list[str] = []
|
|
|
|
async def first(_event: MessagePosted) -> None:
|
|
seen.append("first")
|
|
|
|
async def second(_event: MessagePosted) -> None:
|
|
seen.append("second")
|
|
|
|
bus.subscribe(MessagePosted, first)
|
|
bus.subscribe(MessagePosted, second)
|
|
bus.start()
|
|
await InMemoryEventPublisher(bus).publish([posted()])
|
|
await bus.stop()
|
|
assert sorted(seen) == ["first", "second"]
|
|
|
|
|
|
async def test_failing_subscriber_does_not_block_others() -> None:
|
|
bus = EventBus(NullLogger())
|
|
survived: list[str] = []
|
|
|
|
async def broken(_event: MessagePosted) -> None:
|
|
raise RuntimeError("обработчик упал")
|
|
|
|
async def healthy(_event: MessagePosted) -> None:
|
|
survived.append("ok")
|
|
|
|
bus.subscribe(MessagePosted, broken)
|
|
bus.subscribe(MessagePosted, healthy)
|
|
bus.start()
|
|
await InMemoryEventPublisher(bus).publish([posted()])
|
|
await bus.stop()
|
|
assert survived == ["ok"]
|
|
|
|
|
|
async def test_queue_overflow_drops_events_without_raising() -> None:
|
|
bus = EventBus(NullLogger(), max_queue=16)
|
|
|
|
async def never_called(_event: MessagePosted) -> None:
|
|
raise AssertionError("обработчик не должен вызываться без запущенной шины")
|
|
|
|
bus.subscribe(MessagePosted, never_called)
|
|
publisher = InMemoryEventPublisher(bus)
|
|
await publisher.publish([posted() for _ in range(64)])
|
|
assert bus.dropped > 0
|
|
assert bus.pending <= 16
|
|
|
|
|
|
async def test_projection_runs_before_publish_returns() -> None:
|
|
bus = EventBus(NullLogger())
|
|
seen: list[str] = []
|
|
|
|
async def projection(_event: MessagePosted) -> None:
|
|
seen.append("projected")
|
|
|
|
bus.project(MessagePosted, projection)
|
|
await InMemoryEventPublisher(bus).publish([posted()])
|
|
assert seen == ["projected"]
|
|
|
|
|
|
async def test_publication_does_not_delay_response() -> None:
|
|
app = create_app(**split_settings(log_level="CRITICAL"))
|
|
async with (
|
|
app.router.lifespan_context(app),
|
|
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
|
):
|
|
alice = await register(http, "alice")
|
|
chat = await make_chat(http, alice)
|
|
bus = await app.state.dishka_container.get(EventBus)
|
|
slow = asyncio.Event()
|
|
|
|
async def blocker(_event: MessagePosted) -> None:
|
|
await slow.wait()
|
|
|
|
bus.subscribe(MessagePosted, blocker)
|
|
response = await asyncio.wait_for(
|
|
http.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": "не ждём обработчик"},
|
|
headers=keyed(alice),
|
|
),
|
|
timeout=2,
|
|
)
|
|
assert response.status_code == 201
|
|
slow.set()
|
|
|
|
|
|
async def test_null_logger_hides_everything() -> None:
|
|
logger = NullLogger()
|
|
logger.info("x", route="/")
|
|
logger.warning("x")
|
|
logger.error("x")
|
|
assert isinstance(UserRegistered, type)
|