forked from mtusi2026/mtusi2026lab4
Bring the system changes of lab 3 from 61c0c28..72a1e57 onto the lab 4 code, resolving each conflict by meaning and keeping everything lab 4 added: - a message is posted with one SQL statement under the chat row lock, and the attachment links go into the same statement; a foreign key violation on the attachment link still answers 404 and leaves nothing behind. Text and the attachment list are checked before the write, an outsider gets 404 for both, as before the carry over; - the request pipeline counts the body bytes actually received against the limit of the route, so a chunked body over 1 MiB gets 413 and the upload route keeps its MAX_UPLOAD_BYTES limit; - a request cancelled at shutdown gets 503 unavailable in the contract format, the worker waits a second less than the rest of the shutdown budget, SHUTDOWN_TIMEOUT_SECONDS becomes 6 s and the stop hooks 7 s; - readiness sits behind a Readiness port with the draining flag in shared infrastructure, and the drain window is logged through Logger; - logout revokes through SessionRevocations and withdraws the mark when PostgreSQL rejects the delete; an empty cursor is 400; - EventBus.project is gone, the sweep test subscribes and waits on a queue; domain tests check attachment_list instead of Chat.post; - make up waits for every replica in the balancer, BASE_URL follows the lb port, the image is tagged by the compose project, retry-check and faults-evidence are added, detection runs three times, failover-each and rolling-update record the stand usage, CI checks numeric uids. down also takes the tools and reconcile profiles of lab 4. Track 1 tooling of lab 3 (scaling.py, its samplers, tools/ and the CPU pinning of api, lb, valkey and k6) stays out; stand-usage.sh queries the database size itself instead of the track 1 sampler. 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)
|