Skip to content

Commit 3eeb3cd

Browse files
committed
messagebus now does events and commands differently [new_messagebus]
1 parent 9ba670b commit 3eeb3cd

1 file changed

Lines changed: 39 additions & 13 deletions

File tree

‎src/allocation/messagebus.py‎

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,49 @@
11
from __future__ import annotations
2-
from typing import List, Dict, Callable, Type, TYPE_CHECKING
3-
from allocation import events, handlers
2+
import traceback
3+
from typing import List, Dict, Callable, Type, Union, TYPE_CHECKING
4+
from allocation import commands, events, handlers
5+
46
if TYPE_CHECKING:
57
from allocation import unit_of_work
68

9+
Message = Union[commands.Command, events.Event]
710

8-
def handle(event: events.Event, uow: unit_of_work.AbstractUnitOfWork):
9-
results = []
10-
for handler in HANDLERS[type(event)]:
11-
r = handler(event, uow=uow)
12-
results.append(r)
13-
return results
1411

12+
def handle(message: Message, uow: unit_of_work.AbstractUnitOfWork):
13+
if isinstance(message, events.Event):
14+
handle_event(message, uow)
15+
elif isinstance(message, commands.Command):
16+
return handle_command(message, uow)
17+
else:
18+
raise Exception(f'{message} was not an Event or Command')
1519

1620

17-
HANDLERS = {
18-
events.BatchCreated: [handlers.add_batch],
19-
events.BatchQuantityChanged: [handlers.change_batch_quantity],
20-
events.AllocationRequired: [handlers.allocate],
21-
events.OutOfStock: [handlers.send_out_of_stock_notification],
21+
def handle_event(event: events.Event, uow: unit_of_work.AbstractUnitOfWork):
22+
for handler in EVENT_HANDLERS[type(event)]:
23+
try:
24+
print('handling event', event, 'with handler', handler, flush=True)
25+
handler(event, uow=uow)
26+
except:
27+
print(f'Exception handling event {event}\n:{traceback.format_exc()}')
28+
continue
29+
30+
31+
def handle_command(command, uow: unit_of_work.AbstractUnitOfWork):
32+
print('handling command', command, flush=True)
33+
try:
34+
handler = COMMAND_HANDLERS[type(command)]
35+
return handler(command, uow=uow)
36+
except Exception as e:
37+
print(f'Exception handling command {command}: {e}')
38+
raise e
2239

40+
41+
EVENT_HANDLERS = {
42+
events.OutOfStock: [handlers.send_out_of_stock_notification],
2343
} # type: Dict[Type[events.Event], List[Callable]]
44+
45+
COMMAND_HANDLERS = {
46+
commands.Allocate: handlers.allocate,
47+
commands.CreateBatch: handlers.add_batch,
48+
commands.ChangeBatchQuantity: handlers.change_batch_quantity,
49+
} # type: Dict[Type[commands.Command], Callable]

0 commit comments

Comments
 (0)