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 o2ims.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]
32 uow: unit_of_work.AbstractUnitOfWork,
33 event_handlers: Dict[Type[events.Event], List[Callable]],
34 command_handlers: Dict[Type[commands.Command], Callable],
37 self.event_handlers = event_handlers
38 self.command_handlers = command_handlers
40 def handle(self, message: Message):
41 self.queue = [message]
43 message = self.queue.pop(0)
44 if isinstance(message, events.Event):
45 self.handle_event(message)
46 elif isinstance(message, commands.Command):
47 self.handle_command(message)
49 raise Exception(f"{message} was not an Event or Command")
51 def handle_event(self, event: events.Event):
52 for handler in self.event_handlers[type(event)]:
54 logger.debug("handling event %s with handler %s",
57 self.queue.extend(self.uow.collect_new_events())
59 logger.exception("Exception handling event %s", event)
62 def handle_command(self, command: commands.Command):
63 logger.debug("handling command %s", command)
65 handler = self.command_handlers[type(command)]
67 self.queue.extend(self.uow.collect_new_events())
69 logger.exception("Exception handling command %s", command)