Passed
Pull Request — master (#226)
by Steve
03:02
created

_AsyncContextBoundFunction.__call__()   A

Complexity

Conditions 2

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nop 3
dl 0
loc 3
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1 1
import inspect
2 1
import logging
3 1
from asyncio import Lock
4 1
from contextlib import AsyncExitStack
5 1
from copy import copy
6 1
from typing import (
7
    Optional,
8
    Type,
9
    TypeVar,
10
    Awaitable,
11
    Generic,
12
    Collection,
13
    Union,
14
    ContextManager,
15
    AsyncContextManager,
16
    Iterator,
17
    Generator,
18
    AsyncGenerator,
19
    Callable,
20
    List,
21
)
22
23 1
from lagom.container import Container
24 1
from lagom.definitions import Alias, ConstructionWithContainer, SingletonWrapper
25 1
from lagom.exceptions import InvalidDependencyDefinition, MissingFeature
26 1
from lagom.experimental.definitions import AsyncConstructionWithContainer
27 1
from lagom.interfaces import (
28
    ReadableContainer,
29
    SpecialDepDefinition,
30
    CallTimeContainerUpdate,
31
    ContainerBoundFunction,
32
)
33
34 1
T = TypeVar("T")
35 1
X = TypeVar("X")
36
37
38 1
class AwaitableSingleton(Generic[T]):
39 1
    instance: Optional[T]
40 1
    constructor: ConstructionWithContainer[Awaitable[T]]
41 1
    container: Container
42 1
    _lock: Lock
43
44 1
    def __init__(self, constructor: ConstructionWithContainer, container: Container):
45 1
        self.instance = None
46 1
        self.constructor = constructor  # type: ignore
47 1
        self.container = container
48 1
        self._lock = Lock()
49
50 1
    async def get(self) -> T:
51 1
        if not self.instance:
52 1
            async with self._lock:
53 1
                if not self.instance:
54 1
                    self.instance = await self.constructor.get_instance(self.container)
55 1
        return self.instance
56
57
58 1
class _AsyncContextBoundFunction(ContainerBoundFunction[X]):
59
    """
60
    Represents an instance of a function bound to an async context container
61
    """
62
63 1
    async_context_container: "AsyncContextContainer"
64 1
    partially_bound_function: ContainerBoundFunction
65
66 1
    def __init__(
67
        self,
68
        async_context_container: "AsyncContextContainer",
69
        partially_bound_function: ContainerBoundFunction,
70
    ):
71 1
        self.async_context_container = async_context_container
72 1
        self.partially_bound_function = partially_bound_function
73
74 1
    async def __call__(self, *args, **kwargs) -> X:  # type: ignore # TODO: figure out what this should be for async
75 1
        async with self.async_context_container as c:
76 1
            return await self.partially_bound_function.rebind(c)(*args, **kwargs)
77
78 1
    def rebind(self, container: ReadableContainer) -> "ContainerBoundFunction[X]":
79
        return _AsyncContextBoundFunction(
80
            self.async_context_container,
81
            self.partially_bound_function.rebind(container),
82
        )
83
84
85 1
class AsyncContextContainer(Container):
86 1
    async_exit_stack: Optional[AsyncExitStack] = None
87 1
    _context_types: Collection[Type]
88 1
    _context_singletons: Collection[Type]
89 1
    _root_context: bool = True
90
91 1
    def __init__(
92
        self,
93
        container: Container,
94
        context_types: Collection[Type],
95
        context_singletons: Collection[Type] = tuple(),
96
        log_undefined_deps: Union[bool, logging.Logger] = False,
97
    ):
98 1
        super().__init__(container, log_undefined_deps)
99 1
        self._context_types = set(context_types)
100 1
        self._context_singletons = set(context_singletons)
101
102 1
    def clone(self) -> "AsyncContextContainer":
103
        """returns a copy of the container
104
        :return:
105
        """
106 1
        return AsyncContextContainer(
107
            self,
108
            context_types=self._context_types,
109
            context_singletons=self._context_singletons,
110
            log_undefined_deps=self._undefined_logger,
111
        )
112
113 1
    async def __aenter__(self):
114 1
        if not self.async_exit_stack and self._root_context:
115 1
            self.async_exit_stack = AsyncExitStack()
116
117 1
        if self.async_exit_stack and self._root_context:
118
            # All actual context definitions happen on a clone so that there's isolation between invocations
119 1
            in_context = self.clone()
120 1
            in_context.async_exit_stack = AsyncExitStack()
121 1
            in_context._root_context = False
122
123 1
            for dep_type in self._context_types:
124 1
                managed_dep = self._context_type_def(dep_type)
125 1
                key = Awaitable[dep_type] if isinstance(managed_dep, AsyncConstructionWithContainer) else dep_type  # type: ignore
126 1
                in_context[key] = managed_dep  # type: ignore
127 1
            for dep_type in self._context_singletons:
128 1
                managed_singleton = self._singleton_type_def(dep_type)
129 1
                key = AwaitableSingleton[dep_type] if isinstance(managed_singleton, AwaitableSingleton) else dep_type  # type: ignore
130 1
                in_context[key] = managed_singleton  # type: ignore
131
132
            # The parent context manager keeps track of the inner clone
133 1
            await self.async_exit_stack.enter_async_context(in_context)
134 1
            return in_context
135 1
        return self
136
137 1
    async def __aexit__(self, exc_type, exc_val, exc_tb):
138 1
        if self.async_exit_stack:
139 1
            await self.async_exit_stack.aclose()
140 1
            self.async_exit_stack = None
141
142 1
    def partial(
143
        self,
144
        func: Callable[..., X],
145
        shared: Optional[List[Type]] = None,
146
        container_updater: Optional[CallTimeContainerUpdate] = None,
147
    ) -> ContainerBoundFunction[X]:
148 1
        if not inspect.iscoroutinefunction(func):
149
            raise MissingFeature(
150
                "AsyncContextManager currently can only deal with async functions"
151
            )
152 1
        base_partial = super(AsyncContextContainer, self).partial(
153
            func, shared, container_updater
154
        )
155
156 1
        return _AsyncContextBoundFunction(self, base_partial)
157
158 1
    def magic_partial(
159
        self,
160
        func: Callable[..., X],
161
        shared: Optional[List[Type]] = None,
162
        keys_to_skip: Optional[List[str]] = None,
163
        skip_pos_up_to: int = 0,
164
        container_updater: Optional[CallTimeContainerUpdate] = None,
165
    ) -> ContainerBoundFunction[X]:
166 1
        if not inspect.iscoroutinefunction(func):
167
            raise MissingFeature(
168
                "AsyncContextManager currently can only deal with async functions"
169
            )
170 1
        base_partial = super(AsyncContextContainer, self).magic_partial(
171
            func, shared, keys_to_skip, skip_pos_up_to, container_updater
172
        )
173
174 1
        return _AsyncContextBoundFunction(self, base_partial)
175
176 1
    def _context_type_def(self, dep_type: Type):
177 1
        type_def = self.get_definition(ContextManager[dep_type]) or self.get_definition(Iterator[dep_type]) or self.get_definition(Generator[dep_type, None, None]) or self.get_definition(AsyncGenerator[dep_type, None]) or self.get_definition(AsyncContextManager[dep_type])  # type: ignore
178 1
        if type_def is None:
179 1
            raise InvalidDependencyDefinition(
180
                f"A ContextManager[{dep_type}] should be defined. "
181
                f"This could be an Iterator[{dep_type}] or Generator[{dep_type}, None, None] "
182
                f"with the @contextmanager decorator"
183
            )
184 1
        if isinstance(type_def, Alias):
185
            # Without this we create a definition that points to
186
            # itself.
187 1
            type_def = copy(type_def)
188 1
            type_def.skip_definitions = True
189 1
        if self.get_definition(AsyncGenerator[dep_type, None]) or self.get_definition(AsyncContextManager[dep_type]):  # type: ignore
190 1
            return AsyncConstructionWithContainer(lambda c: self._async_context_resolver(c, type_def))  # type: ignore
191 1
        return ConstructionWithContainer(lambda c: self._context_resolver(c, type_def))  # type: ignore
192
193 1
    def _context_resolver(self, c: ReadableContainer, type_def: SpecialDepDefinition):
194
        """
195
        Takes an existing definition which must be a context manager. Returns
196
        the value of the context manager from __enter__ and then places the
197
        __exit__ in this container's exit stack
198
        """
199 1
        assert self.async_exit_stack, "Types can only be resolved within an async with"
200 1
        context_manager = type_def.get_instance(c)
201 1
        return self.async_exit_stack.enter_context(context_manager)
202
203 1
    def _async_context_resolver(
204
        self, c: ReadableContainer, type_def: SpecialDepDefinition
205
    ):
206
        """
207
        Takes an existing definition which must be a context manager. Returns
208
        the value of the context manager from __aenter__ and then places the
209
        __aexit__ in this container's exit stack
210
        """
211 1
        assert self.async_exit_stack, "Types can only be resolved within an async with"
212 1
        context_manager = type_def.get_instance(c)
213 1
        return self.async_exit_stack.enter_async_context(context_manager)
214
215 1
    def _singleton_type_def(self, dep_type: Type):
216
        """
217
        The same as context_type_def but acts as a singleton within this container
218
        """
219 1
        type_def = self._context_type_def(dep_type)
220 1
        if isinstance(type_def, AsyncConstructionWithContainer):
221 1
            return AwaitableSingleton(type_def, self)
222
        return SingletonWrapper(type_def)
223