"""In-process domain event bus. Events are delivered after the transaction commits.""" from collections import defaultdict from collections.abc import Callable from typing import Any from django.db import transaction _handlers: dict[type, list[Callable[[Any], None]]] = defaultdict(list) def subscribe(event_type: type, handler: Callable[[Any], None]) -> None: """Register a handler; call from ``AppConfig.ready()``.""" if handler not in _handlers[event_type]: _handlers[event_type].append(handler) def _dispatch(event: object) -> None: for handler in list(_handlers[type(event)]): handler(event) class DjangoEventPublisher: def publish(self, event: object) -> None: transaction.on_commit(lambda: _dispatch(event))