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

lagom.experimental.context_based   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 229
Duplicated Lines 0 %

Test Coverage

Coverage 97.25%

Importance

Changes 0
Metric Value
eloc 159
dl 0
loc 229
ccs 106
cts 109
cp 0.9725
rs 9.36
c 0
b 0
f 0
wmc 38

16 Methods

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