import boto3 from anydi import Container, Module, Provider, provider from fansifter_common import context from fansifter_common.adapters.aws.secretsmanager import SecretsManager from owsclient import M2MTokenManager, OwsClient from app.adapters.aws.s3 import S3Client from app.adapters.ows_dmp import OwsDmpClient from app.adapters.ows_notifications import OwsNotificationsClient from app.config.settings import Settings from app.handlers import ExportAudienceFileHandler from app.utils import get_random_string class AppModule(Module): @provider(scope="singleton") def aws_session(self, settings: Settings) -> boto3.Session: return boto3.Session(region_name=settings.aws_region_name) @provider(scope="singleton") def secrets_manager( self, session: boto3.Session, settings: Settings ) -> SecretsManager: return SecretsManager(session=session, region_name=settings.aws_region_name) @provider(scope="singleton") def s3_client(self, session: boto3.Session, settings: Settings) -> S3Client: return S3Client(session=session, region_name=settings.aws_region_name) @provider(scope="singleton") def m2m_token_manager( self, settings: Settings, secrets_manager: SecretsManager ) -> M2MTokenManager: return M2MTokenManager( secrets_manager=secrets_manager, environment=settings.environment, service_name=settings.service_name, ) @provider(scope="singleton") def ows_client( self, settings: Settings, m2m_token_manager: M2MTokenManager ) -> OwsClient: return OwsClient( environment=settings.environment, service_name=settings.service_name, m2m_token_manager=m2m_token_manager, correlation_id_getter=context.get_correlation_id, request_context_getter=context.get_request_context, ) @provider(scope="singleton") def ows_dmp(self, ows_client: OwsClient) -> OwsDmpClient: return OwsDmpClient(ows_client=ows_client) @provider(scope="singleton") def ows_notifications(self, ows_client: OwsClient) -> OwsNotificationsClient: return OwsNotificationsClient(ows_client=ows_client) @provider(scope="singleton") def handler( self, settings: Settings, s3_client: S3Client, ows_dmp: OwsDmpClient, ows_notifications: OwsNotificationsClient, ) -> ExportAudienceFileHandler: return ExportAudienceFileHandler( s3_client=s3_client, ows_dmp_client=ows_dmp, ows_notifications_client=ows_notifications, tmp_dir=settings.tmp_dir, generate_password_func=lambda: get_random_string( length=settings.password_length, allowed_chars=settings.password_allowed_chars, ), ) def initialize_container(settings: Settings) -> Container: """Configure DI container.""" return Container( providers={ Settings: Provider(obj=lambda: settings, scope="singleton"), }, modules=[AppModule], )