1 # Copyright (C) 2021 Wind River Systems, Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # pylint: disable=broad-except, attribute-defined-outside-init
16 from __future__ import annotations
17 from typing import Callable, Dict, List, Union, Type, TYPE_CHECKING
18 from o2common.domain import commands, events
21 from . import unit_of_work
23 from o2common.helper import o2logging
24 logger = o2logging.get_logger(__name__)
26 Message = Union[commands.Command, events.Event]
30 __instance: MessageBus = None
33 def set_instance(instance: MessageBus):
34 MessageBus.__instance = instance
37 def get_instance() -> MessageBus:
38 return MessageBus.__instance
42 uow: unit_of_work.AbstractUnitOfWork,
43 event_handlers: Dict[Type[events.Event], List[Callable]],
44 command_handlers: Dict[Type[commands.Command], Callable],
47 self.event_handlers = event_handlers
48 self.command_handlers = command_handlers
50 def handle(self, message: Message):
51 self.queue = [message]
53 message = self.queue.pop(0)
56 elif isinstance(message, events.Event):
57 self.handle_event(message)
58 elif isinstance(message, commands.Command):
59 self.handle_command(message)
61 raise Exception(f"{message} was not an Event or Command")
63 def handle_event(self, event: events.Event):
64 for handler in self.event_handlers[type(event)]:
66 logger.debug("handling event %s with handler %s",
69 self.queue.extend(self.uow.collect_new_events())
71 logger.exception("Exception handling event %s", event)
74 def handle_command(self, command: commands.Command):
75 logger.debug("handling command %s", command)
77 handler = self.command_handlers[type(command)]
79 self.queue.extend(self.uow.collect_new_events())
80 except Exception as ex:
81 logger.exception("Exception handling command %s", command)