forked from mtusi2026/mtusi2026lab5
Carry over the lab 4 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack, HAProxy, k6 and RustFS configuration, migrations, hooks, evidence and scenario scripts and the CI job from the lab 4 solution commit d2744bc, merge the lab 4 Makefile targets into the lab 5 skeleton Makefile without touching its targets, and append the lab 4 solution variables to the skeleton .env.example. The package and the application follow the contract version 1.5.0, and the image and the throwaway test containers are tagged lab5 so they do not collide with a lab 4 stand on the same host. This is the starting point of the lab 5 cycle: lint, own tests and the offline skeleton check pass before any lab 5 change. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
1210dd899c
commit
540fcb35ba
@@ -0,0 +1,124 @@
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.ports import EventPublisher, Logger, UnitOfWork
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
type CommandHandler = Callable[[Any], Awaitable[Any]]
|
||||
type EventHandler[EventT: DomainEvent] = Callable[[EventT], Awaitable[None]]
|
||||
|
||||
|
||||
class CommandBus:
|
||||
__slots__ = ("_handlers", "_publisher", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
handlers: Mapping[type[Command], CommandHandler],
|
||||
uow: UnitOfWork,
|
||||
publisher: EventPublisher,
|
||||
) -> None:
|
||||
self._handlers = handlers
|
||||
self._uow = uow
|
||||
self._publisher = publisher
|
||||
|
||||
async def execute(self, command: Command) -> Any:
|
||||
handler = self._handlers.get(type(command))
|
||||
if handler is None:
|
||||
raise LookupError(f"нет обработчика для команды {type(command).__name__}")
|
||||
try:
|
||||
return await handler(command)
|
||||
finally:
|
||||
events = self._uow.collect_new_events()
|
||||
if events:
|
||||
await self._publisher.publish(events)
|
||||
|
||||
|
||||
class EventBus:
|
||||
__slots__ = ("_deferred", "_dropped", "_logger", "_projections", "_queue", "_worker")
|
||||
|
||||
def __init__(self, logger: Logger, *, max_queue: int = 10_000) -> None:
|
||||
self._logger = logger
|
||||
self._queue: asyncio.Queue[DomainEvent] = asyncio.Queue(maxsize=max_queue)
|
||||
self._projections: dict[type[DomainEvent], list[Any]] = {}
|
||||
self._deferred: dict[type[DomainEvent], list[Any]] = {}
|
||||
self._worker: asyncio.Task[None] | None = None
|
||||
self._dropped = 0
|
||||
|
||||
def project[EventT: DomainEvent](
|
||||
self, event_type: type[EventT], handler: EventHandler[EventT]
|
||||
) -> None:
|
||||
self._projections.setdefault(event_type, []).append(handler)
|
||||
|
||||
def subscribe[EventT: DomainEvent](
|
||||
self, event_type: type[EventT], handler: EventHandler[EventT]
|
||||
) -> None:
|
||||
self._deferred.setdefault(event_type, []).append(handler)
|
||||
|
||||
async def emit(self, event: DomainEvent) -> bool:
|
||||
await self._run(self._projections.get(type(event), []), event, "projection")
|
||||
if not self._deferred.get(type(event)):
|
||||
return True
|
||||
try:
|
||||
self._queue.put_nowait(event)
|
||||
except asyncio.QueueFull:
|
||||
self._dropped += 1
|
||||
self._logger.warning(
|
||||
"event.dropped", event_name=event.name, dropped_total=self._dropped
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
@property
|
||||
def dropped(self) -> int:
|
||||
return self._dropped
|
||||
|
||||
@property
|
||||
def pending(self) -> int:
|
||||
return self._queue.qsize()
|
||||
|
||||
def start(self) -> None:
|
||||
if self._worker is None:
|
||||
self._worker = asyncio.create_task(self._drain())
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._worker is None:
|
||||
return
|
||||
await self._queue.join()
|
||||
self._worker.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._worker
|
||||
self._worker = None
|
||||
|
||||
async def _drain(self) -> None:
|
||||
while True:
|
||||
event = await self._queue.get()
|
||||
try:
|
||||
await self._run(self._deferred.get(type(event), []), event, "subscriber")
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
async def _run(self, handlers: Sequence[Any], event: DomainEvent, kind: str) -> None:
|
||||
for handler in handlers:
|
||||
try:
|
||||
await handler(event)
|
||||
except Exception as error:
|
||||
self._logger.error(
|
||||
"event.handler_failed",
|
||||
event_name=event.name,
|
||||
reason=kind,
|
||||
error=type(error).__name__,
|
||||
)
|
||||
|
||||
|
||||
class InMemoryEventPublisher:
|
||||
__slots__ = ("_bus",)
|
||||
|
||||
def __init__(self, bus: EventBus) -> None:
|
||||
self._bus = bus
|
||||
|
||||
async def publish(self, events: Sequence[DomainEvent]) -> None:
|
||||
for event in events:
|
||||
await self._bus.emit(event)
|
||||
Reference in New Issue
Block a user