from datetime import timedelta from dishka import Provider, Scope, provide from messenger.messaging.application.bus import MessagingCommandBus from messenger.messaging.application.commands import CreateChat, PostMessage from messenger.messaging.application.handlers import CreateChatHandler, PostMessageHandler from messenger.messaging.application.ports import ( AttachmentStates, ChatDirectory, CursorCodec, MessageLog, MessagingUnitOfWork, ) from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory from messenger.messaging.config import MessagingSettings from messenger.messaging.infrastructure.cursor import SignedCursorCodec from messenger.messaging.infrastructure.postgres import ( PostgresChatDirectory, PostgresMessageLog, PostgresMessagingUnitOfWork, ) from messenger.shared.application.commands import Command from messenger.shared.application.messagebus import CommandHandler from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator from messenger.shared.infrastructure.postgres import Database class MessagingProvider(Provider): def __init__(self, settings: MessagingSettings) -> None: super().__init__() self._settings = settings @provide(scope=Scope.APP) def settings(self) -> MessagingSettings: return self._settings @provide(scope=Scope.APP) def directory(self, database: Database) -> ChatDirectory: return PostgresChatDirectory(database) @provide(scope=Scope.APP) def log(self, database: Database, attachments: AttachmentStates) -> MessageLog: return PostgresMessageLog(database, attachments) @provide(scope=Scope.APP) def cursors(self, settings: MessagingSettings) -> CursorCodec: return SignedCursorCodec(settings.cursor_secret.get_secret_value().encode()) @provide(scope=Scope.REQUEST) def unit_of_work(self, database: Database) -> MessagingUnitOfWork: return PostgresMessagingUnitOfWork(database) @provide(scope=Scope.REQUEST) def chat(self, directory: ChatDirectory) -> GetChat: return GetChat(directory) @provide(scope=Scope.REQUEST) def chat_list(self, directory: ChatDirectory, cursors: CursorCodec) -> ListChats: return ListChats(directory, cursors) @provide(scope=Scope.REQUEST) def history(self, directory: ChatDirectory, cursors: CursorCodec) -> ReadHistory: return ReadHistory(directory, cursors) @provide(scope=Scope.REQUEST) def command_bus( self, uow: MessagingUnitOfWork, log: MessageLog, directory: ChatDirectory, publisher: EventPublisher, clock: Clock, ids: IdGenerator, settings: MessagingSettings, ) -> MessagingCommandBus: ttl = timedelta(seconds=settings.idempotency_ttl_seconds) handlers: dict[type[Command], CommandHandler] = { CreateChat: CreateChatHandler(uow, clock, ids), PostMessage: PostMessageHandler(uow, log, directory, clock, ids, ttl=ttl), } return MessagingCommandBus(handlers, uow, publisher)