11import asyncio
2- from importlib import import_module
32
43from dependency_injector import containers , providers
54from dependency_injector .providers import Callable , Factory , Singleton
65from httpx import AsyncClient , Limits
7- from pybotx import Bot
6+ from pybotx import Bot , HandlerCollector
87from redis import asyncio as aioredis
98
109from app .application .use_cases .record_use_cases import SampleRecordUseCases
2019 WriteSampleRecordUnitOfWork ,
2120)
2221from app .logger import logger
23-
2422from app .presentation .bot .error_handlers .internal_error_handler import (
2523 internal_error_handler ,
2624)
@@ -81,12 +79,12 @@ def __call__(self) -> asyncio.Task:
8179 return self ._get_task ()
8280
8381
84- class ApplicationStartupContainer (containers .DeclarativeContainer ):
85- """Container for application startup dependencies ."""
82+ class BaseStartupContainer (containers .DeclarativeContainer ):
83+ """Общий контейнер для старта бота ."""
8684
87- redis_client = Singleton (lambda : aioredis .from_url (settings .REDIS_DSN ))
85+ redis_client = providers . Singleton (lambda : aioredis .from_url (settings .REDIS_DSN ))
8886
89- redis_repo = Factory (
87+ redis_repo = providers . Factory (
9088 RedisRepo ,
9189 redis = redis_client ,
9290 prefix = strings .BOT_PROJECT_NAME ,
@@ -107,16 +105,8 @@ class ApplicationStartupContainer(containers.DeclarativeContainer):
107105 {} if not settings .RAISE_BOT_EXCEPTIONS else {Exception : internal_error_handler }
108106 )
109107
110- # Ленивая загрузка коллекторов
111- @staticmethod
112- def get_collectors ():
113- common = import_module ("app.presentation.bot.commands.common" )
114- sample_record = import_module ("app.presentation.bot.commands.sample_record" )
115- return [common .collector , sample_record .collector ]
116-
117108 bot = providers .Singleton (
118109 Bot ,
119- collectors = Callable (get_collectors ),
120110 bot_accounts = settings .BOT_CREDENTIALS ,
121111 exception_handlers = exception_handlers , # type: ignore
122112 default_callback_timeout = settings .BOTX_CALLBACK_TIMEOUT_IN_SECONDS ,
@@ -128,54 +118,40 @@ def get_collectors():
128118 callback_repo = callback_repo ,
129119 )
130120
131- # Используем менеджер задач для ленивой инициализации
121+
122+ class ApplicationStartupContainer (BaseStartupContainer ):
123+ """Контейнер приложения с ленивой загрузкой collectors."""
124+
125+ @staticmethod
126+ def get_collectors () -> list [HandlerCollector ]:
127+ from app .presentation .bot .commands .common import collector as common_collector
128+ from app .presentation .bot .commands .sample_record import collector as sample_record_collector
129+ return [common_collector , sample_record_collector ]
130+
131+ bot = providers .Singleton (
132+ Bot ,
133+ collectors = providers .Callable (get_collectors ),
134+ ** BaseStartupContainer .bot .kwargs ,
135+ )
136+
132137 callback_task_manager = providers .Singleton (
133138 CallbackTaskManager ,
134- callback_repo ,
139+ BaseStartupContainer . callback_repo ,
135140 )
136141
137- # Провайдер который возвращает задачу через менеджер
138142 process_callbacks_task = providers .Callable (
139143 lambda manager : manager (),
140144 callback_task_manager ,
141145 )
142146
143147
144- class WorkerStartupContainer (containers .DeclarativeContainer ):
145- redis_client = Singleton (lambda : aioredis .from_url (settings .REDIS_DSN ))
146-
147- redis_repo = Factory (
148- RedisRepo ,
149- redis = redis_client ,
150- prefix = strings .BOT_PROJECT_NAME ,
151- )
152-
153- async_client = providers .Singleton (
154- AsyncClient ,
155- timeout = settings .BOT_ASYNC_CLIENT_TIMEOUT_IN_SECONDS ,
156- limits = Limits (max_keepalive_connections = None , max_connections = None ),
157- )
148+ class WorkerStartupContainer (BaseStartupContainer ):
149+ """Контейнер воркера с прямым импортом collectors."""
158150
159- callback_repo = providers .Singleton (
160- CallbackRedisRepo ,
161- redis = redis_client ,
162- )
163151 from app .presentation .bot .commands import common , sample_record
164152
165- exception_handlers = (
166- {} if not settings .RAISE_BOT_EXCEPTIONS else {Exception : internal_error_handler }
167- )
168-
169153 bot = providers .Singleton (
170154 Bot ,
171- collectors = [common .collector , sample_record .collector ],
172- bot_accounts = settings .BOT_CREDENTIALS ,
173- exception_handlers = exception_handlers , # type: ignore
174- default_callback_timeout = settings .BOTX_CALLBACK_TIMEOUT_IN_SECONDS ,
175- httpx_client = async_client ,
176- middlewares = [
177- smart_logger_middleware ,
178- answer_error_middleware ,
179- ],
180- callback_repo = callback_repo ,
181- )
155+ collectors = [common .collector , sample_record .collector ], # type:ignore
156+ ** BaseStartupContainer .bot .kwargs ,
157+ )
0 commit comments