Brings the system changes of lab 2 from 8cddb09..102579e onto the lab 3 code, resolving each conflict by meaning: - the request pipeline counts the body bytes actually received, so a chunked body over the limit gets 413 instead of reaching the app; - logout revokes through a SessionRevocations port and withdraws the mark when PostgreSQL rejects the delete, so 503 means the session still works; PostgresSessionDirectory loses its no-op invalidate; - an empty cursor is 400 on history and on the chat list; - EventBus.project and the test that allowed importing an event across zones are gone, the config rules speak of the schema foreign key; - the worker waits one second less than the rest of the shutdown budget, so it cancels a stuck request with 500 and exits 0 instead of being killed by the gunicorn master. Lab 3 keeps 3 s after the drain window for the database timeouts, so SHUTDOWN_TIMEOUT_SECONDS becomes 6 s and the stop hooks wait 7 s, still under the 8 s grace; - the lab 3 single statement post already locks the chat only for a member, so lab 2's LOCK_CHAT edit is not needed; its test is kept; - lab 2 tests come along with Idempotency-Key where lab 3 needs it; the short TTL after restart runs without api-shortttl by shortening the session in the database; test_drain adds a stuck request; - make validate uses .venv with openapi-spec-validator, PYTEST_ARGS, faults-evidence, down with the bench profile, the image is tagged by the compose project, start probes every 200 ms, cache evidence fails without a tombstone and checks the key expiry, kdf.txt shows the seed stub apart. The track 2 tooling of lab 2 (track.py, postgres-restore and the database argument of migrate) and its evidence scripts stay out. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
113 lines
3.5 KiB
Python
113 lines
3.5 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_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)
|