Exemplo n.º 1
0
    def start(self, args: OrderedDict) -> None:
        key = validators.string(args["key"])
        config_path = validators.string(args["config"])

        self.logger.info("Starting %s.", key)

        config_file = Path(abspath(config_path))

        print(f"Loading configuration from {config_file}.")

        if config_file.exists():
            with open(config_file) as f:
                config = Configuration()
                config.from_dict(json.load(f))

                features = filter(lambda c: isinstance(c, Feature),
                                  self.components)

                for feature in features:
                    self.logger.info("Configuring feature %s.",
                                     type(feature).__name__)

                    # noinspection PyBroadException
                    try:
                        cast(Feature, feature).config(config)
                    except BaseException as e:
                        self.logger.error("Failed to initialise feature.",
                                          exc_info=e)

        def except_hook(tpe, value, traceback):
            if tpe != KeyboardInterrupt:
                self.logger.exception("Unhandled error occurred:",
                                      exc_info=value,
                                      stack_info=traceback)

            sys.__excepthook__(tpe, value, traceback)

        # noinspection SpellCheckingInspection
        sys.excepthook = except_hook

        for callback in _initializers:
            try:
                callback()
            except Exception as e:
                self.logger.exception(e, exc_info=True)

        global _initialized

        _initialized = True
        _initializers.clear()

        self.logger.info("Bootstrap has completed successfully.")
Exemplo n.º 2
0
class DumpContainer(DeclarativeContainer):
    config = Configuration()
    write_factory = Factory(FileWriteFactory, path=config.path)
    format_factory = Factory(JsonFormatFactory, matrix=config.matrix)
    dumper = Factory(MatrixDump,
                     write_factory=write_factory,
                     format_factory=format_factory)
Exemplo n.º 3
0
class RootContainer(DeclarativeContainer):
    """Application IoC container"""

    config = Configuration('config')
    loop = Singleton(get_event_loop)

    # Remote services
    engine = Singleton(_create_engine_wrapper, config.db.connect_string,
                       config.db.options)

    http = Factory(ClientSession, loop=loop, raise_for_status=True)

    sessionmaker = Singleton(_sessionmaker, bind=engine)

    scoped_session = Singleton(_scoped_session,
                               sessionmaker,
                               scopefunc=event_context.get)

    context_factory = DelegatedFactory(Context, scoped_session=scoped_session)

    bot = Singleton(Bot,
                    command_prefix=config.cmd_prefix,
                    context_factory=context_factory,
                    default_game=config.default_game,
                    loop=loop,
                    scoped_session=scoped_session)

    # Main
    run_bot = Callable(Bot.run, bot, config.token)
class Container(DeclarativeContainer):
    config = Configuration(default={"cell": 0.0, "shape": (2, 2)})
    matrix = Factory(Mock,
                     ABCMinimalMatrix,
                     get_cell=Mock(return_value=config.cell()),
                     get_shape=Mock(return_value=config.shape()))
    formatter = Factory(JsonFormat, matrix=matrix)
class HandleContainer(DeclarativeContainer):
    config = Configuration()
    base_file_handler = Factory(BaseFileHandler, write=config.write)
    txt_handler = Factory(LoggingHandler,
                          logger=config.logger,
                          next_handler=base_file_handler,
                          name="txt")
    csv_handler = Factory(LoggingHandler,
                          logger=config.logger,
                          next_handler=base_file_handler,
                          name="csv")
    json_handler = Factory(LoggingHandler,
                           logger=config.logger,
                           next_handler=base_file_handler,
                           name="json")
    xml_handler = Factory(LoggingHandler,
                          logger=config.logger,
                          next_handler=base_file_handler,
                          name="xml")
    routing_map = Factory(dict,
                          txt=txt_handler,
                          csv=csv_handler,
                          json=json_handler,
                          xml=xml_handler)
    routing_table = Factory(SimpleRoutingTable, routing_map=routing_map)
    routing_handler = Factory(RoutingHandler, routing_table=routing_table)
Exemplo n.º 6
0
class SummarizeContainer(DeclarativeContainer):
    config = Configuration()
    matrix_factory = Factory(MinimalMatrixFactory)
    summarize_pair_factory = Factory(SummarizePairFactory,
                                     matrix_factory=matrix_factory)
    summarize = Factory(Summarize,
                        matrices=config.matrices,
                        summarize_pair_factory=summarize_pair_factory)
Exemplo n.º 7
0
class FileLoadContainer(DeclarativeContainer):
    config = Configuration()
    read_factory = Factory(FileReadFactory, path=config.path)
    parser_factory = Factory(JsonParserFactory)
    matrix_factory = Factory(MinimalMatrixFactory)
    loader = Factory(FileLoadMatrices,
                     read_factory=read_factory,
                     parser_factory=parser_factory,
                     matrix_factory=matrix_factory)
Exemplo n.º 8
0
class ControlActionReportContainer(DeclarativeContainer):
    config = Configuration(strict=True)

    control_action_repository = Dependency()

    control_action_report_service = Factory(
        ControlActionReportService,
        timestamp_report_pattern_v1=config.timestamp_report_pattern_v1,
        control_action_repository=control_action_repository)
Exemplo n.º 9
0
class Core(DeclarativeContainer):
    config = Configuration(strict=True)

    # Для применения настроек логгирования необходимо инициализироватьь ресурс,
    # т.к. он напрямую нигде не вызывается.
    # Для инициализации необходимо вызвать core.init_resources() у экземпляра контенера.
    logging = Resource(
        logging.config.dictConfig,
        config=config.logging,
    )
Exemplo n.º 10
0
class Container(DeclarativeContainer):
    config = Configuration(default={"matrix_count": 2})

    reader = Factory(Mock, ABCRead, return_value=config.content)
    read_factory = Factory(Mock, ABCReadFactory, return_value=reader)

    matrix_like = Factory(Mock, ArrayLike)
    matrix_like_list = Factory(lambda matrix_like_factory, matrix_count: [matrix_like_factory() for i in range(0, matrix_count)], matrix_like.provider, config.matrix_count)
    parser = Factory(Mock, ABCParser, return_value=matrix_like_list)
    parser_factory = Factory(Mock, ABCParserFactory, return_value=parser)

    matrix = Factory(Mock, ABCMinimalMatrix, get_cell=Mock(return_value=config.cell), get_shape=Mock(return_value=config.shape))
    matrix_factory = Factory(Mock, ABCMinimalMatrixFactory, return_value=matrix)

    load = Factory(FileLoadMatrices, read_factory=read_factory, parser_factory=parser_factory, matrix_factory=matrix_factory)
Exemplo n.º 11
0
class WSGI(DeclarativeContainer):
    config = Configuration(strict=True)

    app = Resource(FastAPIApp,
                   api_routers=Object([
                       api_v1.api_router, api_v2.api_router, api_v3.api_router
                   ]))

    server = Singleton(
        uvicorn.Server,
        config=Factory(
            uvicorn.Config,
            app=app,
            host=config.host,
            port=config.port,
            # log_config=None
        ))
Exemplo n.º 12
0
class Container(DeclarativeContainer):
    config = Configuration(default={"matrix_count": 2})
    matrix = Factory(Mock,
                     ABCMinimalMatrix,
                     get_cell=Mock(return_value=config.cell),
                     get_shape=Mock(return_value=config.shape))
    matrices = Factory(
        lambda matrix_factory, matrix_count:
        [matrix_factory() for i in range(0, matrix_count)], matrix.provider,
        config.matrix_count)
    summarize_pair = Factory(Mock, ABCSummarize, return_value=matrix)
    summarize_pair_factory = Factory(Mock,
                                     ABCSummarizePairFactory,
                                     return_value=summarize_pair)
    summarize = Factory(Summarize,
                        matrices=matrices,
                        summarize_pair_factory=summarize_pair_factory)
Exemplo n.º 13
0
class Gateways(DeclarativeContainer):
    config = Configuration(strict=True)

    temp_graph_reader = Factory(SoftMSyncTempGraphJSONReader)
    temp_graph_loader = Factory(SoftMAsyncTempGraphOnlineLoader,
                                reader=temp_graph_reader)

    weather_forecast_timezone = Callable(
        gettz, config.weather_forecast_loader.weather_server_timezone)
    weather_forecast_reader = Factory(
        SoftMSyncWeatherForecastJSONReader,
        weather_data_timezone=weather_forecast_timezone)
    weather_forecast_loader = Factory(SoftMAsyncWeatherForecastOnlineLoader,
                                      reader=weather_forecast_reader)

    time_delta_loader = Factory(
        SyncTimedeltaFileLoader,
        filepath=config.time_delta_loader.heating_objects_time_delta_path,
        reader=Factory(SyncTimedeltaCSVReader, separator=","))
Exemplo n.º 14
0
class UpdateContainer(DeclarativeContainer):
    config = Configuration(strict=True)

    control_actions_predictor = Dependency()
    temp_graph_updater = Dependency()
    weather_forecast_updater = Dependency()

    control_actions_predictor.enable_async_mode()
    temp_graph_updater.enable_async_mode()
    weather_forecast_updater.enable_async_mode()

    temp_graph_updatable_item = Singleton(
        TempGraphUpdatableItem,
        provider=temp_graph_updater.provider,
        update_interval=Callable(
            pd.Timedelta,
            seconds=config.update_intervals.temp_graph
        )
    )

    weather_forecast_updatable_item = Singleton(
        WeatherForecastUpdatableItem,
        provider=weather_forecast_updater.provider,
        update_interval=Callable(
            pd.Timedelta,
            seconds=config.update_intervals.weather_forecast
        )
    )

    control_action_updatable_item = Singleton(
        ControlActionUpdatableItem,
        provider=control_actions_predictor.provider,
        dependencies=List(
            temp_graph_updatable_item,
            weather_forecast_updatable_item
        )
    )

    updater_service = Singleton(
        SimpleUpdaterService,
        item_to_update=control_action_updatable_item
    )
Exemplo n.º 15
0
class Services(DeclarativeContainer):
    config = Configuration(strict=True)

    temp_graph_loader = Dependency()
    weather_forecast_loader = Dependency()

    dynamic_settings_repository = Dependency()
    temp_graph_repository = Dependency()
    time_delta_loader = Dependency()
    weather_forecast_repository = Dependency()
    control_actions_repository = Dependency()

    dynamic_settings_pkg = Container(
        DynamicSettingsContainer,
        config=config.dynamic_settings,
        settings_repository=dynamic_settings_repository)
    temp_graph_pkg = Container(TempGraphContainer,
                               temp_graph_loader=temp_graph_loader,
                               temp_graph_repository=temp_graph_repository)
    weather_forecast_pkg = Container(
        WeatherForecastContainer,
        weather_forecast_loader=weather_forecast_loader,
        weather_forecast_repository=weather_forecast_repository)
    control_action_pkg = Container(
        ControlActionContainer,
        config=config.control_action_predictor,
        time_delta_loader=time_delta_loader,
        temp_graph_repository=temp_graph_repository,
        weather_forecast_repository=weather_forecast_repository,
        control_actions_repository=control_actions_repository,
        dynamic_settings_repository=dynamic_settings_repository)
    control_action_report_pkg = Container(
        ControlActionReportContainer,
        config=config.control_action_reporter,
        control_action_repository=control_actions_repository)
    updater_pkg = Container(
        UpdateContainer,
        config=config.updater,
        control_actions_predictor=control_action_pkg.temp_prediction_service,
        temp_graph_updater=temp_graph_pkg.temp_graph_update_service,
        weather_forecast_updater=weather_forecast_pkg.weather_forecast_service)
Exemplo n.º 16
0
class Application(DeclarativeContainer):
    config = Configuration(strict=True)

    repositories = Container(Repositories, config=config.repositories)

    gateways = Container(Gateways, config=config.gateways)

    services = Container(
        Services,
        config=config.services,
        temp_graph_loader=gateways.temp_graph_loader,
        weather_forecast_loader=gateways.weather_forecast_loader,
        time_delta_loader=gateways.time_delta_loader,
        dynamic_settings_repository=repositories.dynamic_settings_repository,
        temp_graph_repository=repositories.temp_graph_repository,
        weather_forecast_repository=repositories.weather_forecast_repository,
        control_actions_repository=repositories.control_actions_repository)

    core = Container(Core, config=config.core)

    wsgi = Container(WSGI, config=config.server)
Exemplo n.º 17
0
class CogsContainer(DeclarativeContainer):
    root = DependenciesContainer()
    # Accessing a Configuration through a DependenciesContainer does not work, so do it manually
    config = Configuration('config.cogs')

    anilist = Singleton(Anilist, http=root.http)

    botadmin = Singleton(BotAdmin, http=root.http)

    channels = Singleton(Channels)

    jisho = Singleton(Jisho, http=root.http)

    moderation = Singleton(Moderation)

    mute = Singleton(Mute,
                     bot=root.bot,
                     loop=root.loop,
                     scoped_session=root.scoped_session,
                     sessionmaker=root.sessionmaker)

    newbie = Singleton(Newbies,
                       bot=root.bot,
                       loop=root.loop,
                       scoped_session=root.scoped_session,
                       sessionmaker=root.sessionmaker)

    notifications = Singleton(Notifications,
                              scoped_session=root.scoped_session)

    roles = Singleton(Roles)

    saucenao = Singleton(SauceNAO,
                         http=root.http,
                         api_key=config.saucenao.api_key)

    stop = Singleton(Stop)

    whitelist = Singleton(Whitelisting)
Exemplo n.º 18
0
class Repositories(DeclarativeContainer):
    config = Configuration(strict=True)

    temp_graph_repository = Singleton(SyncTempGraphInMemoryDumperLoader)
    weather_forecast_repository = Singleton(
        WeatherForecastRepository,
        filter_algorithm=Factory(FullClosedTimestampFilterAlgorithm))
    control_actions_repository = Singleton(ControlActionsRepository)
    dynamic_settings_repository = Resource(
        DynamicSettingsRepositoryResource,
        session_factory=Resource(AsyncSettingsDBSessionFactory,
                                 db_engine=Resource(
                                     AsyncSettingsDBEngine,
                                     db_url=config.db_settings_url)),
        dtype_converters=Object([
            dtype_converters.BooleanDTypeConverter(),
            dtype_converters.DatetimeDTypeConverter(),
            dtype_converters.FloatDTypeConverter(),
            dtype_converters.IntDTypeConverter(),
            dtype_converters.StrDTypeConverter(),
            dtype_converters.NoneDTypeConverter(),
            dtype_converters.TimedeltaDTypeConverter()
        ]),
        default_settings=Object(default_config.DICT))
Exemplo n.º 19
0
class ControlActionContainer(DeclarativeContainer):
    config = Configuration(strict=True)

    temp_graph_repository = Dependency()
    weather_forecast_repository = Dependency()
    control_actions_repository = Dependency()
    dynamic_settings_repository = Dependency()
    time_delta_loader = Dependency()

    # TODO: перевести на репозиторий
    temp_correlation_table = Resource(
        TempCorrelationTable,
        config.temp_correlation_table_path
    )

    # TODO: перевести на репозиторий
    time_delta_df = Resource(
        HeatingObjTimedeltaResource,
        loader=time_delta_loader
    )

    model_requirements = Factory(
        TimedeltaModelRequirementsWithoutHistory,
        time_delta_df
    )

    timestamp_round_algo = Factory(
        CeilTimestampRoundAlgorithm,
        round_step=TIME_TICK
    )

    temp_constrains = Factory(
        SingleTypeHeatingObjOnWeatherConstraint,
        temp_requirements_predictor=Factory(
            TempGraphRequirementsPredictor,
            temp_graph=temp_graph_repository.provided.load_temp_graph.call(),
            weather_temp_round_algorithm=Factory(ArithmeticFloatRoundAlgorithm)
        ),
        timestamp_round_algo=timestamp_round_algo,
        temp_requirements_coefficient=Coroutine(
            get_one_setting,
            dynamic_settings_repository,
            config_names.APARTMENT_HOUSE_MIN_TEMP_COEFFICIENT
        ),
        min_model_error=Coroutine(
            get_one_setting,
            dynamic_settings_repository,
            config_names.MODEL_ERROR_SIZE
        )
    )

    heating_system_model = Factory(
        CorrTableHeatingSystemModel,
        temp_correlation_df=temp_correlation_table,
        timedelta_df=time_delta_df,
    )

    control_action_predictor = Factory(
        SingleCircuitControlActionPredictor,
        heating_system_model=heating_system_model,
        temp_requirements_constraint=temp_constrains,
        min_boiler_temp=Coroutine(
            get_one_setting,
            dynamic_settings_repository,
            config_names.MIN_BOILER_TEMP
        ),
        max_boiler_temp=Coroutine(
            get_one_setting,
            dynamic_settings_repository,
            config_names.MAX_BOILER_TEMP
        ),
        min_regulation_step=0.3
    )

    temp_prediction_service = Factory(
        ControlActionPredictionService,
        weather_forecast_repository=weather_forecast_repository,
        control_actions_repository=control_actions_repository,
        control_action_predictor=control_action_predictor,
        model_requirements=model_requirements,
        timestamp_round_algo=timestamp_round_algo,
        timedelta=TIME_TICK,
        timedelta_predict_forward=pd.Timedelta(seconds=3600),
        executor=None
    )
Exemplo n.º 20
0
class Container(DeclarativeContainer):
    config = Configuration()
    writer = Factory(FileWrite, path=config.path, content=config.content)
Exemplo n.º 21
0
class IocContainer(DeclarativeContainer):
    """
    IOC Container for Dependency Injection for reusable services
    """
    config = Configuration('config')
Exemplo n.º 22
0
class Container(DeclarativeContainer):
    config = Configuration()
    json_format = Factory(MatrixPairJsonFormat,
                          matrix1=config.matrix1,
                          matrix2=config.matrix2)
class Container(DeclarativeContainer):
    config = Configuration()
    summarize_adapter = Factory(SummarizeAdapter,
                                input_path=config.input_path,
                                output_path=config.output_path)
class Container(DeclarativeContainer):
    config = Configuration()
    matrix_factory = Factory(MinimalMatrixFactory)
    generate = Factory(GenerateZeroMatrix,
                       shape=config.shape,
                       matrix_factory=matrix_factory)
class Container(DeclarativeContainer):
    config = Configuration()
    parser = Factory(JsonParser, content=config.content)
Exemplo n.º 26
0
class Core(DeclarativeContainer):
    main_config = Configuration('main')
    network_config = Configuration('network_config')

    logger = Factory(logging.Logger)\
        .add_kwargs(name="core")
Exemplo n.º 27
0
class OutputContainer(DeclarativeContainer):
    config = Configuration()
    write = Factory(FileAppend, path=config.path)
class Container(DeclarativeContainer):
    config = Configuration()
    reader = Factory(FileRead, path=config.path)