55fc99d5ec175a293a381d5fc69ab23f60328fbf
[pti/o2.git] / o2ims / bootstrap.py
1 # Copyright (C) 2021 Wind River Systems, Inc.
2 #
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
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import inspect
16 from typing import Callable
17 from o2ims.adapter import orm, redis_eventpublisher
18 from o2ims.adapter.notifications import AbstractNotifications,\
19     SmoO2Notifications
20
21 from o2ims.service import handlers, messagebus, unit_of_work
22 from o2ims.adapter.unit_of_work import SqlAlchemyUnitOfWork
23 from o2ims.adapter.clients import orm_stx
24
25
26 def bootstrap(
27     start_orm: bool = True,
28     uow: unit_of_work.AbstractUnitOfWork = SqlAlchemyUnitOfWork(),
29     notifications: AbstractNotifications = None,
30     publish: Callable = redis_eventpublisher.publish,
31 ) -> messagebus.MessageBus:
32
33     if notifications is None:
34         notifications = SmoO2Notifications()
35
36     if start_orm:
37         orm.start_o2ims_mappers()
38         orm_stx.start_o2ims_stx_mappers(uow)
39
40     dependencies = {"uow": uow, "notifications": notifications,
41                     "publish": publish}
42     injected_event_handlers = {
43         event_type: [
44             inject_dependencies(handler, dependencies)
45             for handler in event_handlers
46         ]
47         for event_type, event_handlers in handlers.EVENT_HANDLERS.items()
48     }
49     injected_command_handlers = {
50         command_type: inject_dependencies(handler, dependencies)
51         for command_type, handler in handlers.COMMAND_HANDLERS.items()
52     }
53
54     return messagebus.MessageBus(
55         uow=uow,
56         event_handlers=injected_event_handlers,
57         command_handlers=injected_command_handlers,
58     )
59
60
61 def inject_dependencies(handler, dependencies):
62     params = inspect.signature(handler).parameters
63     deps = {
64         name: dependency
65         for name, dependency in dependencies.items()
66         if name in params
67     }
68     return lambda message: handler(message, **deps)