import asyncio from collections.abc import Sequence from contextlib import suppress from dishka import AsyncContainer from messenger.attachments.application.bus import AttachmentsCommandBus from messenger.attachments.application.commands import ( CleanStaging, PublishOutbox, RecoverExpiredLeases, ) from messenger.attachments.config import PipelineSettings from messenger.shared.application.commands import Command from messenger.shared.application.ports import Logger class Relay: __slots__ = ("_container", "_logger", "_settings", "_tasks") def __init__( self, container: AsyncContainer, settings: PipelineSettings, logger: Logger ) -> None: self._container = container self._settings = settings self._logger = logger self._tasks: list[asyncio.Task[None]] = [] def start(self) -> None: settings = self._settings loops: tuple[tuple[float, Sequence[Command]], ...] = ( (settings.outbox_poll_seconds, (PublishOutbox(settings.outbox_batch),)), ( settings.sweep_interval_seconds, (RecoverExpiredLeases(settings.sweep_batch), CleanStaging(settings.sweep_batch)), ), ) self._tasks = [asyncio.create_task(self._every(*loop)) for loop in loops] async def stop(self) -> None: for task in self._tasks: task.cancel() for task in self._tasks: with suppress(asyncio.CancelledError): await task self._tasks = [] async def run(self, command: Command) -> int: async with self._container() as scope: bus = await scope.get(AttachmentsCommandBus) return await bus.execute(command) async def _every(self, interval: float, commands: Sequence[Command]) -> None: while True: for command in commands: try: done = await self.run(command) except Exception as error: self._logger.warning( "relay.pass_failed", reason=type(command).__name__, error=type(error).__name__, ) continue if done: self._logger.info("relay.pass", reason=type(command).__name__, count=done) await asyncio.sleep(interval)