11import functools
22import typing as t
33
4+ from ellar .cache import CacheModule
45from ellar .common import IExecutionContext , IModuleSetup , Module
6+ from ellar .common .exceptions import ImproperConfiguration
57from ellar .core import Config , ModuleSetup
6- from ellar .core .modules import DynamicModule , ModuleBase
8+ from ellar .core .modules import DynamicModule , ModuleBase , ModuleRefBase
79from ellar .di import ProviderConfig
810
911from ellar_throttler .interfaces import IThrottleModel , IThrottlerStorage
1012from ellar_throttler .throttler_module_options import ThrottlerModuleOptions
11- from ellar_throttler .throttler_service import ThrottlerStorageService
13+ from ellar_throttler .throttler_service import (
14+ CacheThrottlerStorageService ,
15+ ThrottlerStorageService ,
16+ )
1217
1318
1419class _Config (t .TypedDict ):
@@ -19,8 +24,23 @@ class _Config(t.TypedDict):
1924 skip_if : t .Optional [t .Callable [[IExecutionContext ], bool ]]
2025
2126
22- @Module ()
27+ @Module (name = "ThrottlerModule" , exports = [ IThrottlerStorage , ThrottlerModuleOptions ] )
2328class ThrottlerModule (ModuleBase , IModuleSetup ):
29+ @classmethod
30+ def post_build (cls , module_ref : "ModuleRefBase" ) -> None :
31+ storage = module_ref .providers .get (IThrottlerStorage )
32+ if storage .use_class and ( # type:ignore[union-attr]
33+ storage .use_class == CacheThrottlerStorageService # type:ignore[union-attr]
34+ or issubclass (storage .use_class , CacheThrottlerStorageService ) # type:ignore[union-attr]
35+ ):
36+ try :
37+ module_ref .tree_manager .add_module_dependency (cls , CacheModule )
38+ except ValueError :
39+ raise ImproperConfiguration (
40+ f"Using { CacheThrottlerStorageService } as storage type requires { CacheModule } setup. "
41+ f"See https://python-ellar.github.io/ellar/security/rate-limit/"
42+ ) from None
43+
2444 @classmethod
2545 def setup (
2646 cls ,
@@ -66,7 +86,7 @@ def register_setup(cls, **override_config: t.Any) -> ModuleSetup:
6686
6787 @staticmethod
6888 def __register_setup_factory (
69- module : t . Type [ "ThrottlerModule" ] ,
89+ module_ref : ModuleRefBase ,
7090 config : Config ,
7191 override_config : t .Dict [str , t .Any ],
7292 ) -> DynamicModule :
@@ -81,7 +101,7 @@ def __register_setup_factory(
81101 schema = ThrottlerModuleOptions .model_validate (
82102 defined_config , from_attributes = True
83103 )
84-
104+ module = t . cast ( t . Type [ ThrottlerModule ], module_ref . module )
85105 return module .__setup_module (schema , storage )
86106 raise RuntimeError (
87107 "Could not find `ELLAR_THROTTLER_CONFIG` in application config."
0 commit comments