Files
mtusi2026lab3/src/messenger/main.py
T
ArtyomandClaude Opus 5.5 a59e3a39a8 Carry over the lab 2 fixes made after 8cddb09
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
2026-10-30 02:32:49 +03:00

105 lines
4.3 KiB
Python

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dishka import make_async_container
from dishka.integrations.fastapi import FastapiProvider, setup_dishka
from fastapi import FastAPI
from messenger.identity.config import IdentitySettings
from messenger.identity.domain.events import SessionClosed, SessionOpened, UserRegistered
from messenger.identity.entrypoints.authentication import challenge_for, guard
from messenger.identity.entrypoints.errors import ERROR_CODES as IDENTITY_ERRORS
from messenger.identity.entrypoints.http import router as users_router
from messenger.identity.entrypoints.http import sessions_router
from messenger.identity.entrypoints.ioc import IdentityProvider
from messenger.identity.entrypoints.journal import LOG_FIELDS as IDENTITY_FIELDS
from messenger.identity.entrypoints.journal import IdentityJournal
from messenger.messaging.config import MessagingSettings
from messenger.messaging.domain.events import ChatCreated, MessagePosted
from messenger.messaging.entrypoints.errors import ERROR_CODES as MESSAGING_ERRORS
from messenger.messaging.entrypoints.http import chats_router, messages_router
from messenger.messaging.entrypoints.ioc import MessagingProvider
from messenger.messaging.entrypoints.journal import LOG_FIELDS as MESSAGING_FIELDS
from messenger.messaging.entrypoints.journal import MessagingJournal
from messenger.shared.application.messagebus import EventBus
from messenger.shared.application.ports import Logger
from messenger.shared.config import PlatformSettings
from messenger.shared.entrypoints import errors, health
from messenger.shared.entrypoints.config import TransportSettings
from messenger.shared.entrypoints.ioc import PlatformProvider
from messenger.shared.entrypoints.pipeline import RequestPipeline
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
TRANSPORT_FIELDS = frozenset({"dropped_total"})
LOG_FIELDS = PLATFORM_FIELDS | TRANSPORT_FIELDS | IDENTITY_FIELDS | MESSAGING_FIELDS
ERROR_CODES = {**IDENTITY_ERRORS, **MESSAGING_ERRORS}
def wire_events(bus: EventBus, logger: Logger) -> None:
identity = IdentityJournal(logger)
bus.subscribe(UserRegistered, identity.on_user_registered)
bus.subscribe(SessionOpened, identity.on_session_opened)
bus.subscribe(SessionClosed, identity.on_session_closed)
messaging = MessagingJournal(logger)
bus.subscribe(ChatCreated, messaging.on_chat_created)
bus.subscribe(MessagePosted, messaging.on_message_posted)
def create_app(
platform: PlatformSettings | None = None,
transport: TransportSettings | None = None,
identity: IdentitySettings | None = None,
messaging: MessagingSettings | None = None,
) -> FastAPI:
platform = platform or PlatformSettings()
transport = transport or TransportSettings()
identity = identity or IdentitySettings()
messaging = messaging or MessagingSettings()
logger = StructlogLogger(level=platform.log_level, allowed_fields=LOG_FIELDS)
container = make_async_container(
PlatformProvider(platform, logger),
IdentityProvider(identity),
MessagingProvider(messaging),
FastapiProvider(),
)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
bus = await container.get(EventBus)
wire_events(bus, logger)
bus.start()
logger.info("service.started")
try:
yield
finally:
await bus.stop()
await container.close()
logger.info("service.stopped")
app = FastAPI(
title="MTUSI Messenger",
version="1.3.0",
lifespan=lifespan,
docs_url="/docs" if transport.docs else None,
redoc_url=None,
openapi_url="/openapi.json" if transport.docs else None,
)
app.add_middleware(
RequestPipeline,
logger=logger,
max_bytes=transport.max_body_bytes,
timeout=transport.request_timeout_seconds,
guard=guard,
instance=platform.instance_id,
)
errors.install(app, logger, ERROR_CODES, challenge_for, platform.instance_id)
app.include_router(health.router)
app.include_router(users_router)
app.include_router(sessions_router)
app.include_router(chats_router)
app.include_router(messages_router)
setup_dishka(container, app)
return app