base.py 795 B

12345678910111213141516171819202122232425262728
  1. from typing import Generic, TypeVar, Any
  2. from contextlib import asynccontextmanager
  3. import asyncio
  4. from ..types import Message, Context
  5. Dep = TypeVar("DepType")
  6. class Injector(Generic[Dep]):
  7. async def inject(self, message: Message, context: Context) -> Dep:
  8. raise NotImplementedError
  9. class InjectorWithCleanup(Injector[Dep]):
  10. async def cleanup(self, dep: Dep):
  11. raise NotImplementedError
  12. @asynccontextmanager
  13. async def inject_all(injectors: list[Injector[Any]], message: Message, context: Context):
  14. deps = await asyncio.gather(*[inj.inject(message, context) for inj in injectors])
  15. try:
  16. yield deps
  17. finally:
  18. for dep, inj in zip(deps, injectors):
  19. if isinstance(inj, InjectorWithCleanup):
  20. await inj.cleanup(dep)