forked from mtusi2026/mtusi2026lab4
When the ready commit fails after the object was written, the upload handler now locks the row, keeps it if it turned out ready, and otherwise deletes the object first and the pending row second before answering 503. A ready update that touches no row means the intent was already swept, so it fails as unavailable and the object goes too; a 201 without a row cannot happen. Every worker runs an UploadSweeper that every 30 s removes pending intents older than UPLOAD_GRACE_SECONDS (900 s, at least 60 s) one row at a time under FOR UPDATE SKIP LOCKED over the partial pending index, object first, and logs an audit event for each discard. Bodies are buffered only inside one of UPLOAD_CONCURRENCY slots per worker and released before the ready commit, and a client that disconnects in the middle of a body becomes a 400 instead of an unhandled 500. The tests run against a throwaway PostgreSQL: a trigger rejects the ready commit and the compensation leaves neither row nor object, a row removed during the write gives 503, a failed write stays until the grace ends, fresh intents and an aged ready attachment in a message survive a sweep, two concurrent sweeps share five intents exactly, the background loop runs by itself, a second upload waits for the slot without reading its body, and aborted and stalled bodies leave nothing. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
152 lines
6.3 KiB
Python
152 lines
6.3 KiB
Python
from collections.abc import AsyncIterator, Sequence
|
|
from contextlib import asynccontextmanager
|
|
from uuid import UUID
|
|
|
|
from dishka import Provider, Scope, make_async_container, provide
|
|
from dishka.integrations.fastapi import FastapiProvider, setup_dishka
|
|
from fastapi import FastAPI
|
|
|
|
from messenger.attachments.application.ports import ChatMembership
|
|
from messenger.attachments.config import AttachmentsSettings
|
|
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentStored
|
|
from messenger.attachments.entrypoints.errors import ERROR_CODES as ATTACHMENT_ERRORS
|
|
from messenger.attachments.entrypoints.http import UPLOAD_PATH, attachments_router, uploads_router
|
|
from messenger.attachments.entrypoints.ioc import AttachmentsProvider
|
|
from messenger.attachments.entrypoints.journal import LOG_FIELDS as ATTACHMENT_FIELDS
|
|
from messenger.attachments.entrypoints.journal import AttachmentsJournal
|
|
from messenger.attachments.entrypoints.sweeper import UploadSweeper
|
|
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.application.ports import ChatDirectory
|
|
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", "queue", "instance"})
|
|
|
|
LOG_FIELDS = (
|
|
PLATFORM_FIELDS | TRANSPORT_FIELDS | IDENTITY_FIELDS | MESSAGING_FIELDS | ATTACHMENT_FIELDS
|
|
)
|
|
ERROR_CODES = {**IDENTITY_ERRORS, **MESSAGING_ERRORS, **ATTACHMENT_ERRORS}
|
|
|
|
|
|
class MessagingMembership:
|
|
__slots__ = ("_chats",)
|
|
|
|
def __init__(self, chats: ChatDirectory) -> None:
|
|
self._chats = chats
|
|
|
|
async def is_member(self, chat_id: UUID, user_id: UUID) -> bool:
|
|
return await self._chats.chat_for_member(chat_id, user_id) is not None
|
|
|
|
|
|
class ZoneLinks(Provider):
|
|
@provide(scope=Scope.APP)
|
|
def membership(self, chats: ChatDirectory) -> ChatMembership:
|
|
return MessagingMembership(chats)
|
|
|
|
|
|
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)
|
|
|
|
attachments = AttachmentsJournal(logger)
|
|
bus.subscribe(AttachmentStored, attachments.on_attachment_stored)
|
|
bus.subscribe(AttachmentDiscarded, attachments.on_attachment_discarded)
|
|
|
|
|
|
def create_app(
|
|
*,
|
|
platform: PlatformSettings | None = None,
|
|
transport: TransportSettings | None = None,
|
|
identity: IdentitySettings | None = None,
|
|
messaging: MessagingSettings | None = None,
|
|
attachments: AttachmentsSettings | None = None,
|
|
overrides: Sequence[Provider] = (),
|
|
) -> FastAPI:
|
|
platform = platform or PlatformSettings()
|
|
transport = transport or TransportSettings()
|
|
identity = identity or IdentitySettings()
|
|
messaging = messaging or MessagingSettings()
|
|
attachments = attachments or AttachmentsSettings()
|
|
logger = StructlogLogger(level=platform.log_level, allowed_fields=LOG_FIELDS)
|
|
container = make_async_container(
|
|
PlatformProvider(platform, logger),
|
|
IdentityProvider(identity),
|
|
MessagingProvider(messaging),
|
|
AttachmentsProvider(attachments),
|
|
ZoneLinks(),
|
|
FastapiProvider(),
|
|
*overrides,
|
|
)
|
|
sweeper = UploadSweeper(container, attachments, logger)
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
|
bus = await container.get(EventBus)
|
|
wire_events(bus, logger)
|
|
bus.start()
|
|
sweeper.start()
|
|
logger.info("service.started")
|
|
try:
|
|
yield
|
|
finally:
|
|
await sweeper.stop()
|
|
await bus.stop()
|
|
await container.close()
|
|
logger.info("service.stopped")
|
|
|
|
app = FastAPI(
|
|
title="MTUSI Messenger",
|
|
version="1.4.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,
|
|
limits=((UPLOAD_PATH, attachments.max_upload_bytes),),
|
|
)
|
|
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)
|
|
app.include_router(uploads_router)
|
|
app.include_router(attachments_router)
|
|
setup_dishka(container, app)
|
|
app.state.sweeper = sweeper
|
|
return app
|