-
-
Notifications
You must be signed in to change notification settings - Fork 331
Add support for async generator injections #900
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,18 @@ | ||
from typing import Any, Awaitable, Callable, Dict, Tuple, TypeVar | ||
from typing import Any, Dict | ||
|
||
from .providers import Provider | ||
|
||
T = TypeVar("T") | ||
class DependencyResolver: | ||
def __init__( | ||
self, | ||
kwargs: Dict[str, Any], | ||
injections: Dict[str, Provider[Any]], | ||
closings: Dict[str, Provider[Any]], | ||
/, | ||
) -> None: ... | ||
def __enter__(self) -> Dict[str, Any]: ... | ||
def __exit__(self, *exc_info: Any) -> None: ... | ||
async def __aenter__(self) -> Dict[str, Any]: ... | ||
async def __aexit__(self, *exc_info: Any) -> None: ... | ||
|
||
def _sync_inject( | ||
fn: Callable[..., T], | ||
args: Tuple[Any, ...], | ||
kwargs: Dict[str, Any], | ||
injections: Dict[str, Provider[Any]], | ||
closings: Dict[str, Provider[Any]], | ||
/, | ||
) -> T: ... | ||
async def _async_inject( | ||
fn: Callable[..., Awaitable[T]], | ||
args: Tuple[Any, ...], | ||
kwargs: Dict[str, Any], | ||
injections: Dict[str, Provider[Any]], | ||
closings: Dict[str, Provider[Any]], | ||
/, | ||
) -> T: ... | ||
def _isawaitable(instance: Any) -> bool: ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,83 +1,110 @@ | ||
"""Wiring optimizations module.""" | ||
|
||
import asyncio | ||
import collections.abc | ||
import inspect | ||
import types | ||
from asyncio import gather | ||
from collections.abc import Awaitable | ||
from inspect import CO_ITERABLE_COROUTINE | ||
from types import CoroutineType, GeneratorType | ||
|
||
from .providers cimport Provider, Resource, NULL_AWAITABLE | ||
from .wiring import _Marker | ||
|
||
from .providers cimport Provider, Resource | ||
cimport cython | ||
|
||
|
||
def _sync_inject(object fn, tuple args, dict kwargs, dict injections, dict closings, /): | ||
cdef object result | ||
@cython.internal | ||
@cython.no_gc | ||
cdef class KWPair: | ||
cdef str name | ||
cdef object value | ||
|
||
def __cinit__(self, str name, object value, /): | ||
self.name = name | ||
self.value = value | ||
|
||
|
||
cdef inline bint _is_injectable(dict kwargs, str name): | ||
return name not in kwargs or isinstance(kwargs[name], _Marker) | ||
|
||
|
||
cdef class DependencyResolver: | ||
cdef dict kwargs | ||
cdef dict to_inject | ||
cdef object arg_key | ||
cdef Provider provider | ||
cdef dict injections | ||
cdef dict closings | ||
|
||
to_inject = kwargs.copy() | ||
for arg_key, provider in injections.items(): | ||
if arg_key not in kwargs or isinstance(kwargs[arg_key], _Marker): | ||
to_inject[arg_key] = provider() | ||
def __init__(self, dict kwargs, dict injections, dict closings, /): | ||
self.kwargs = kwargs | ||
self.to_inject = kwargs.copy() | ||
self.injections = injections | ||
self.closings = closings | ||
|
||
result = fn(*args, **to_inject) | ||
async def _await_injection(self, kw_pair: KWPair, /) -> None: | ||
self.to_inject[kw_pair.name] = await kw_pair.value | ||
|
||
if closings: | ||
for arg_key, provider in closings.items(): | ||
if arg_key in kwargs and not isinstance(kwargs[arg_key], _Marker): | ||
continue | ||
if not isinstance(provider, Resource): | ||
continue | ||
provider.shutdown() | ||
cdef object _await_injections(self, to_await: list): | ||
return gather(*map(self._await_injection, to_await)) | ||
|
||
return result | ||
cdef void _handle_injections_sync(self): | ||
cdef Provider provider | ||
|
||
for name, provider in self.injections.items(): | ||
if _is_injectable(self.kwargs, name): | ||
self.to_inject[name] = provider() | ||
|
||
async def _async_inject(object fn, tuple args, dict kwargs, dict injections, dict closings, /): | ||
cdef object result | ||
cdef dict to_inject | ||
cdef list to_inject_await = [] | ||
cdef list to_close_await = [] | ||
cdef object arg_key | ||
cdef Provider provider | ||
|
||
to_inject = kwargs.copy() | ||
for arg_key, provider in injections.items(): | ||
if arg_key not in kwargs or isinstance(kwargs[arg_key], _Marker): | ||
provide = provider() | ||
if provider.is_async_mode_enabled(): | ||
to_inject_await.append((arg_key, provide)) | ||
elif _isawaitable(provide): | ||
to_inject_await.append((arg_key, provide)) | ||
else: | ||
to_inject[arg_key] = provide | ||
|
||
if to_inject_await: | ||
async_to_inject = await asyncio.gather(*(provide for _, provide in to_inject_await)) | ||
for provide, (injection, _) in zip(async_to_inject, to_inject_await): | ||
to_inject[injection] = provide | ||
|
||
result = await fn(*args, **to_inject) | ||
|
||
if closings: | ||
for arg_key, provider in closings.items(): | ||
if arg_key in kwargs and isinstance(kwargs[arg_key], _Marker): | ||
continue | ||
if not isinstance(provider, Resource): | ||
continue | ||
shutdown = provider.shutdown() | ||
if _isawaitable(shutdown): | ||
to_close_await.append(shutdown) | ||
|
||
await asyncio.gather(*to_close_await) | ||
|
||
return result | ||
cdef list _handle_injections_async(self): | ||
cdef list to_await = [] | ||
cdef Provider provider | ||
|
||
for name, provider in self.injections.items(): | ||
if _is_injectable(self.kwargs, name): | ||
provide = provider() | ||
|
||
if provider.is_async_mode_enabled() or _isawaitable(provide): | ||
to_await.append(KWPair(name, provide)) | ||
else: | ||
self.to_inject[name] = provide | ||
|
||
return to_await | ||
|
||
cdef void _handle_closings_sync(self): | ||
cdef Provider provider | ||
|
||
for name, provider in self.closings.items(): | ||
if _is_injectable(self.kwargs, name) and isinstance(provider, Resource): | ||
provider.shutdown() | ||
|
||
cdef list _handle_closings_async(self): | ||
cdef list to_await = [] | ||
cdef Provider provider | ||
|
||
for name, provider in self.closings.items(): | ||
if _is_injectable(self.kwargs, name) and isinstance(provider, Resource): | ||
if _isawaitable(shutdown := provider.shutdown()): | ||
to_await.append(shutdown) | ||
|
||
return to_await | ||
|
||
def __enter__(self): | ||
self._handle_injections_sync() | ||
return self.to_inject | ||
|
||
def __exit__(self, *_): | ||
self._handle_closings_sync() | ||
|
||
async def __aenter__(self): | ||
if to_await := self._handle_injections_async(): | ||
await self._await_injections(to_await) | ||
return self.to_inject | ||
|
||
def __aexit__(self, *_): | ||
if to_await := self._handle_closings_async(): | ||
return gather(*to_await) | ||
return NULL_AWAITABLE | ||
|
||
|
||
cdef bint _isawaitable(object instance): | ||
"""Return true if object can be passed to an ``await`` expression.""" | ||
return (isinstance(instance, types.CoroutineType) or | ||
isinstance(instance, types.GeneratorType) and | ||
bool(instance.gi_code.co_flags & inspect.CO_ITERABLE_COROUTINE) or | ||
isinstance(instance, collections.abc.Awaitable)) | ||
return (isinstance(instance, CoroutineType) or | ||
isinstance(instance, GeneratorType) and | ||
bool(instance.gi_code.co_flags & CO_ITERABLE_COROUTINE) or | ||
isinstance(instance, Awaitable)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.