Add framework and apiserver
[pti/o2.git] / src / 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, SmoO2Notifications
19
20 from o2ims.service import handlers, messagebus, unit_of_work
21
22
23 def bootstrap(
24     start_orm: bool = True,
25     uow: unit_of_work.AbstractUnitOfWork = unit_of_work.SqlAlchemyUnitOfWork(),
26     notifications: AbstractNotifications = None,
27     publish: Callable = redis_eventpublisher.publish,
28 ) -> messagebus.MessageBus:
29
30     if notifications is None:
31         notifications = SmoO2Notifications()
32
33     if start_orm:
34         orm.start_o2ims_mappers()
35
36     dependencies = {"uow": uow, "notifications": notifications, "publish": publish}
37     injected_event_handlers = {
38         event_type: [
39             inject_dependencies(handler, dependencies)
40             for handler in event_handlers
41         ]
42         for event_type, event_handlers in handlers.EVENT_HANDLERS.items()
43     }
44     injected_command_handlers = {
45         command_type: inject_dependencies(handler, dependencies)
46         for command_type, handler in handlers.COMMAND_HANDLERS.items()
47     }
48
49     return messagebus.MessageBus(
50         uow=uow,
51         event_handlers=injected_event_handlers,
52         command_handlers=injected_command_handlers,
53     )
54
55
56 def inject_dependencies(handler, dependencies):
57     params = inspect.signature(handler).parameters
58     deps = {
59         name: dependency
60         for name, dependency in dependencies.items()
61         if name in params
62     }
63     return lambda message: handler(message, **deps)