-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinjectables.py
More file actions
203 lines (149 loc) · 5.39 KB
/
injectables.py
File metadata and controls
203 lines (149 loc) · 5.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable, MutableMapping
from contextlib import suppress
from dataclasses import dataclass, field
from functools import partial
from typing import (
Any,
AsyncContextManager,
ClassVar,
ContextManager,
NoReturn,
Protocol,
runtime_checkable,
)
from injection._core.common.asynchronous import Caller
from injection._core.common.asynchronous import (
create_semaphore as _create_async_semaphore,
)
from injection._core.scope import Scope, get_active_scopes, get_scope
from injection.exceptions import InjectionError
@runtime_checkable
class Injectable[T](Protocol):
__slots__ = ()
@property
def is_locked(self) -> bool:
return False
def unlock(self) -> None:
return
@abstractmethod
async def aget_instance(self) -> T:
raise NotImplementedError
@abstractmethod
def get_instance(self) -> T:
raise NotImplementedError
@dataclass(repr=False, eq=False, frozen=True, slots=True)
class SimpleInjectable[T](Injectable[T]):
factory: Caller[..., T]
async def aget_instance(self) -> T:
return await self.factory.acall()
def get_instance(self) -> T:
return self.factory.call()
class CacheLogic[T]:
__slots__ = ("__semaphore",)
__semaphore: AsyncContextManager[Any]
def __init__(self) -> None:
self.__semaphore = _create_async_semaphore(1)
async def aget_or_create[K](
self,
cache: MutableMapping[K, T],
key: K,
factory: Callable[..., Awaitable[T]],
) -> T:
async with self.__semaphore:
with suppress(KeyError):
return cache[key]
instance = await factory()
cache[key] = instance
return instance
def get_or_create[K](
self,
cache: MutableMapping[K, T],
key: K,
factory: Callable[..., T],
) -> T:
with suppress(KeyError):
return cache[key]
instance = factory()
cache[key] = instance
return instance
@dataclass(repr=False, eq=False, frozen=True, slots=True)
class SingletonInjectable[T](Injectable[T]):
factory: Caller[..., T]
cache: MutableMapping[str, T] = field(default_factory=dict)
logic: CacheLogic[T] = field(default_factory=CacheLogic)
__key: ClassVar[str] = "$instance"
@property
def is_locked(self) -> bool:
return self.__key in self.cache
async def aget_instance(self) -> T:
return await self.logic.aget_or_create(
self.cache,
self.__key,
self.factory.acall,
)
def get_instance(self) -> T:
return self.logic.get_or_create(self.cache, self.__key, self.factory.call)
def unlock(self) -> None:
self.cache.pop(self.__key, None)
@dataclass(repr=False, eq=False, frozen=True, slots=True)
class ScopedInjectable[R, T](Injectable[T], ABC):
factory: Caller[..., R]
scope_name: str
logic: CacheLogic[T] = field(default_factory=CacheLogic)
@property
def is_locked(self) -> bool:
return any(self in scope.cache for scope in get_active_scopes(self.scope_name))
@abstractmethod
async def abuild(self, scope: Scope) -> T:
raise NotImplementedError
@abstractmethod
def build(self, scope: Scope) -> T:
raise NotImplementedError
async def aget_instance(self) -> T:
scope = self.__get_scope()
factory = partial(self.abuild, scope)
return await self.logic.aget_or_create(scope.cache, self, factory)
def get_instance(self) -> T:
scope = self.__get_scope()
factory = partial(self.build, scope)
return self.logic.get_or_create(scope.cache, self, factory)
def setdefault(self, instance: T) -> T:
scope = self.__get_scope()
return self.logic.get_or_create(scope.cache, self, lambda: instance)
def unlock(self) -> None:
if self.is_locked:
raise RuntimeError(f"To unlock, close the `{self.scope_name}` scope.")
def __get_scope(self) -> Scope:
return get_scope(self.scope_name)
class AsyncCMScopedInjectable[T](ScopedInjectable[AsyncContextManager[T], T]):
__slots__ = ()
async def abuild(self, scope: Scope) -> T:
cm = await self.factory.acall()
return await scope.aenter(cm)
def build(self, scope: Scope) -> NoReturn:
raise RuntimeError("Can't use async context manager synchronously.")
class CMScopedInjectable[T](ScopedInjectable[ContextManager[T], T]):
__slots__ = ()
async def abuild(self, scope: Scope) -> T:
cm = await self.factory.acall()
return scope.enter(cm)
def build(self, scope: Scope) -> T:
cm = self.factory.call()
return scope.enter(cm)
class SimpleScopedInjectable[T](ScopedInjectable[T, T]):
__slots__ = ()
async def abuild(self, scope: Scope) -> T:
return await self.factory.acall()
def build(self, scope: Scope) -> T:
return self.factory.call()
def unlock(self) -> None:
for scope in get_active_scopes(self.scope_name):
scope.cache.pop(self, None)
@dataclass(repr=False, eq=False, frozen=True, slots=True)
class ShouldBeInjectable[T](Injectable[T]):
cls: type[T]
async def aget_instance(self) -> T:
return self.get_instance()
def get_instance(self) -> NoReturn:
raise InjectionError(f"`{self.cls}` should be an injectable.")