In Memory Message Bus¶
in_memory_message_bus
¶
In-memory message bus implementation for intra-process message routing.
Provides a simple synchronous dispatch mechanism that routes messages
to registered handlers based on message type.
InMemoryMessageBus
¶
Bases: MessageBusPort[MessageType, MessageBusResultType]
In-memory message bus that routes messages to registered handlers.
Handlers are registered by message type and invoked directly when a
message of that type is dispatched. Suitable for testing, prototyping,
and simple intra-process communication.
Usage::
bus = InMemoryMessageBus[Command[object], None]()
bus.register(MyCommand, my_handler)
await bus.dispatch(MyCommand())
Source code in src/forging_blocks/infrastructure/message_bus/in_memory_message_bus.py
__init__() -> None
¶
Initialize the message bus with an empty handler registry.
register(message_type: type[MT], handler: Callable[[MT], object]) -> None
¶
Register a handler for a specific message type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_type
|
type[MT]
|
The message type to handle. |
required |
handler
|
Callable[[MT], object]
|
A callable that processes the message. It should accept |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the message type is already registered. |
Source code in src/forging_blocks/infrastructure/message_bus/in_memory_message_bus.py
dispatch(message: MessageType) -> MessageBusResultType
async
¶
Dispatch a message to the registered handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
MessageType
|
The message instance to dispatch. |
required |
Returns:
| Type | Description |
|---|---|
MessageBusResultType
|
The result from the handler. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no handler is registered for the message type. |