pydico 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pydico/__init__.py +73 -0
- pydico/_context.py +23 -0
- pydico/_dependencies.py +233 -0
- pydico/_disposal.py +43 -0
- pydico/_typing.py +8 -0
- pydico/_validation.py +181 -0
- pydico/collection.py +249 -0
- pydico/descriptors.py +18 -0
- pydico/exceptions.py +238 -0
- pydico/identifiers.py +16 -0
- pydico/injection.py +89 -0
- pydico/lifecycle.py +18 -0
- pydico/lifetimes.py +7 -0
- pydico/metadata.py +19 -0
- pydico/provider.py +376 -0
- pydico/py.typed +0 -0
- pydico/resolver.py +16 -0
- pydico/scope.py +287 -0
- pydico/validation.py +38 -0
- pydico-0.1.1.dist-info/METADATA +761 -0
- pydico-0.1.1.dist-info/RECORD +23 -0
- pydico-0.1.1.dist-info/WHEEL +4 -0
- pydico-0.1.1.dist-info/licenses/LICENSE +21 -0
pydico/__init__.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Public package API for pydico."""
|
|
2
|
+
|
|
3
|
+
from pydico.collection import ServiceCollection
|
|
4
|
+
from pydico.descriptors import ServiceDescriptor
|
|
5
|
+
from pydico.exceptions import (
|
|
6
|
+
AbstractTypeRegistrationError,
|
|
7
|
+
AsyncDisposalRequiredError,
|
|
8
|
+
CircularDependencyError,
|
|
9
|
+
CloseDuringResolutionError,
|
|
10
|
+
CollectionMaterializationError,
|
|
11
|
+
ConflictingInjectKeyError,
|
|
12
|
+
ConflictingRegistrationError,
|
|
13
|
+
DisposalError,
|
|
14
|
+
ImplementationTypeMismatchError,
|
|
15
|
+
InjectionError,
|
|
16
|
+
InstanceTypeMismatchError,
|
|
17
|
+
MissingTypeAnnotationError,
|
|
18
|
+
NoActiveScopeError,
|
|
19
|
+
ProviderClosedError,
|
|
20
|
+
PydicoError,
|
|
21
|
+
RegistrationError,
|
|
22
|
+
ResolutionError,
|
|
23
|
+
ScopeClosedError,
|
|
24
|
+
ScopeRequiredError,
|
|
25
|
+
ServiceNotRegisteredError,
|
|
26
|
+
UnsupportedTypeAnnotationError,
|
|
27
|
+
)
|
|
28
|
+
from pydico.identifiers import ServiceIdentifier
|
|
29
|
+
from pydico.injection import inject
|
|
30
|
+
from pydico.lifecycle import SupportsAsyncClose, SupportsClose
|
|
31
|
+
from pydico.lifetimes import ServiceLifetime
|
|
32
|
+
from pydico.metadata import InjectKey
|
|
33
|
+
from pydico.provider import ServiceProvider
|
|
34
|
+
from pydico.resolver import ServiceResolver
|
|
35
|
+
from pydico.scope import ServiceScope
|
|
36
|
+
from pydico.validation import ServiceProviderValidationError, ValidationIssue
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"AbstractTypeRegistrationError",
|
|
40
|
+
"AsyncDisposalRequiredError",
|
|
41
|
+
"CircularDependencyError",
|
|
42
|
+
"CloseDuringResolutionError",
|
|
43
|
+
"CollectionMaterializationError",
|
|
44
|
+
"ConflictingInjectKeyError",
|
|
45
|
+
"ConflictingRegistrationError",
|
|
46
|
+
"DisposalError",
|
|
47
|
+
"ImplementationTypeMismatchError",
|
|
48
|
+
"InjectionError",
|
|
49
|
+
"InjectKey",
|
|
50
|
+
"InstanceTypeMismatchError",
|
|
51
|
+
"MissingTypeAnnotationError",
|
|
52
|
+
"NoActiveScopeError",
|
|
53
|
+
"PydicoError",
|
|
54
|
+
"ProviderClosedError",
|
|
55
|
+
"RegistrationError",
|
|
56
|
+
"ResolutionError",
|
|
57
|
+
"ScopeClosedError",
|
|
58
|
+
"ScopeRequiredError",
|
|
59
|
+
"ServiceCollection",
|
|
60
|
+
"ServiceDescriptor",
|
|
61
|
+
"ServiceIdentifier",
|
|
62
|
+
"ServiceLifetime",
|
|
63
|
+
"ServiceNotRegisteredError",
|
|
64
|
+
"ServiceProvider",
|
|
65
|
+
"ServiceProviderValidationError",
|
|
66
|
+
"ServiceResolver",
|
|
67
|
+
"ServiceScope",
|
|
68
|
+
"SupportsClose",
|
|
69
|
+
"SupportsAsyncClose",
|
|
70
|
+
"UnsupportedTypeAnnotationError",
|
|
71
|
+
"ValidationIssue",
|
|
72
|
+
"inject",
|
|
73
|
+
]
|
pydico/_context.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Internal context-local resolver state used by scopes and injection."""
|
|
2
|
+
|
|
3
|
+
from contextvars import ContextVar, Token
|
|
4
|
+
|
|
5
|
+
from pydico.resolver import ServiceResolver
|
|
6
|
+
|
|
7
|
+
_current_resolver: ContextVar[ServiceResolver | None] = ContextVar(
|
|
8
|
+
"pydico_current_resolver", default=None
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def current_resolver() -> ServiceResolver | None:
|
|
13
|
+
return _current_resolver.get()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def activate_resolver(
|
|
17
|
+
resolver: ServiceResolver,
|
|
18
|
+
) -> Token[ServiceResolver | None]:
|
|
19
|
+
return _current_resolver.set(resolver)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def restore_resolver(token: Token[ServiceResolver | None]) -> None:
|
|
23
|
+
_current_resolver.reset(token)
|
pydico/_dependencies.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Shared dependency analysis for constructor and function injection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
from collections.abc import Callable, Hashable, Iterable, Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import Enum, auto
|
|
9
|
+
from threading import RLock
|
|
10
|
+
from typing import Annotated, Any, cast, get_args, get_origin, get_type_hints
|
|
11
|
+
|
|
12
|
+
from pydico.exceptions import (
|
|
13
|
+
CollectionMaterializationError,
|
|
14
|
+
ConflictingInjectKeyError,
|
|
15
|
+
InjectionError,
|
|
16
|
+
MissingTypeAnnotationError,
|
|
17
|
+
ServiceNotRegisteredError,
|
|
18
|
+
UnsupportedTypeAnnotationError,
|
|
19
|
+
)
|
|
20
|
+
from pydico.metadata import InjectKey
|
|
21
|
+
from pydico.resolver import ServiceResolver
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class DependencyRequest:
|
|
26
|
+
"""A single, unambiguous dependency required by a callable."""
|
|
27
|
+
|
|
28
|
+
parameter_name: str
|
|
29
|
+
service_type: type[object]
|
|
30
|
+
positional_only: bool
|
|
31
|
+
key: Hashable | None
|
|
32
|
+
collection_kind: CollectionKind | None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class CollectionKind(Enum):
|
|
36
|
+
"""Internal representation of a requested collection shape."""
|
|
37
|
+
|
|
38
|
+
LIST = auto()
|
|
39
|
+
TUPLE = auto()
|
|
40
|
+
SET = auto()
|
|
41
|
+
FROZENSET = auto()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class DependencyPlan:
|
|
45
|
+
"""Lazily parse and cache the injectable parameters of a callable."""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
callable_target: Callable[..., object],
|
|
50
|
+
*,
|
|
51
|
+
error_target: object | None = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
self.callable_target = callable_target
|
|
54
|
+
self.error_target = callable_target if error_target is None else error_target
|
|
55
|
+
self.signature = inspect.signature(callable_target)
|
|
56
|
+
self._raw_annotations = dict(getattr(callable_target, "__annotations__", {}))
|
|
57
|
+
self._resolved_annotations: dict[str, object] = {}
|
|
58
|
+
self._type_hints_lock = RLock()
|
|
59
|
+
|
|
60
|
+
def required_parameters(self) -> tuple[inspect.Parameter, ...]:
|
|
61
|
+
"""Return required parameters that are candidates for injection."""
|
|
62
|
+
return tuple(
|
|
63
|
+
parameter
|
|
64
|
+
for parameter in self.signature.parameters.values()
|
|
65
|
+
if parameter.name not in ("self", "cls")
|
|
66
|
+
and parameter.default is inspect.Parameter.empty
|
|
67
|
+
and parameter.kind
|
|
68
|
+
not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def requests(
|
|
72
|
+
self, parameters: Sequence[inspect.Parameter]
|
|
73
|
+
) -> tuple[DependencyRequest, ...]:
|
|
74
|
+
"""Validate parameters and convert them to dependency requests."""
|
|
75
|
+
if not parameters:
|
|
76
|
+
return ()
|
|
77
|
+
|
|
78
|
+
requests: list[DependencyRequest] = []
|
|
79
|
+
for parameter in parameters:
|
|
80
|
+
if parameter.name not in self._raw_annotations:
|
|
81
|
+
raise MissingTypeAnnotationError(self.error_target, parameter.name)
|
|
82
|
+
|
|
83
|
+
annotation = self._get_type_hint(parameter.name)
|
|
84
|
+
service_type, key, collection_kind = _parse_dependency_annotation(
|
|
85
|
+
annotation,
|
|
86
|
+
target=self.error_target,
|
|
87
|
+
parameter_name=parameter.name,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
requests.append(
|
|
91
|
+
DependencyRequest(
|
|
92
|
+
parameter_name=parameter.name,
|
|
93
|
+
service_type=service_type,
|
|
94
|
+
positional_only=parameter.kind is inspect.Parameter.POSITIONAL_ONLY,
|
|
95
|
+
key=key,
|
|
96
|
+
collection_kind=collection_kind,
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
return tuple(requests)
|
|
100
|
+
|
|
101
|
+
def _get_type_hint(self, parameter_name: str) -> object:
|
|
102
|
+
with self._type_hints_lock:
|
|
103
|
+
if parameter_name in self._resolved_annotations:
|
|
104
|
+
return self._resolved_annotations[parameter_name]
|
|
105
|
+
|
|
106
|
+
holder = type("_AnnotationHolder", (), {})
|
|
107
|
+
holder.__annotations__ = {
|
|
108
|
+
parameter_name: self._raw_annotations[parameter_name]
|
|
109
|
+
}
|
|
110
|
+
globalns = getattr(self.callable_target, "__globals__", None)
|
|
111
|
+
localns: dict[str, object] | None = None
|
|
112
|
+
if isinstance(self.error_target, type):
|
|
113
|
+
localns = dict(vars(self.error_target))
|
|
114
|
+
localns[self.error_target.__name__] = self.error_target
|
|
115
|
+
try:
|
|
116
|
+
annotation = get_type_hints(
|
|
117
|
+
holder,
|
|
118
|
+
globalns=globalns,
|
|
119
|
+
localns=localns,
|
|
120
|
+
include_extras=True,
|
|
121
|
+
)[parameter_name]
|
|
122
|
+
except Exception as error:
|
|
123
|
+
name = getattr(
|
|
124
|
+
self.error_target, "__qualname__", repr(self.error_target)
|
|
125
|
+
)
|
|
126
|
+
raise InjectionError(
|
|
127
|
+
f"Cannot resolve type annotations for {name}: parameter "
|
|
128
|
+
f"{parameter_name!r}."
|
|
129
|
+
) from error
|
|
130
|
+
|
|
131
|
+
self._resolved_annotations[parameter_name] = annotation
|
|
132
|
+
return annotation
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _parse_dependency_annotation(
|
|
136
|
+
annotation: object,
|
|
137
|
+
*,
|
|
138
|
+
target: object,
|
|
139
|
+
parameter_name: str,
|
|
140
|
+
) -> tuple[type[object], Hashable | None, CollectionKind | None]:
|
|
141
|
+
dependency_annotation = annotation
|
|
142
|
+
key: Hashable | None = None
|
|
143
|
+
|
|
144
|
+
if get_origin(annotation) is Annotated:
|
|
145
|
+
dependency_annotation, *metadata = get_args(annotation)
|
|
146
|
+
inject_keys = tuple(
|
|
147
|
+
item.key for item in metadata if isinstance(item, InjectKey)
|
|
148
|
+
)
|
|
149
|
+
if len(inject_keys) > 1:
|
|
150
|
+
raise ConflictingInjectKeyError(target, parameter_name, inject_keys)
|
|
151
|
+
if inject_keys:
|
|
152
|
+
key = inject_keys[0]
|
|
153
|
+
|
|
154
|
+
origin: Any = get_origin(dependency_annotation)
|
|
155
|
+
collection_kind = _collection_kind(origin)
|
|
156
|
+
if collection_kind is not None:
|
|
157
|
+
arguments = get_args(dependency_annotation)
|
|
158
|
+
if origin is tuple:
|
|
159
|
+
valid_shape = len(arguments) == 2 and arguments[1] is Ellipsis
|
|
160
|
+
else:
|
|
161
|
+
valid_shape = len(arguments) == 1
|
|
162
|
+
|
|
163
|
+
if not valid_shape:
|
|
164
|
+
raise UnsupportedTypeAnnotationError(target, parameter_name, annotation)
|
|
165
|
+
|
|
166
|
+
service_type = arguments[0]
|
|
167
|
+
if not isinstance(service_type, type) or service_type is Any:
|
|
168
|
+
raise UnsupportedTypeAnnotationError(target, parameter_name, annotation)
|
|
169
|
+
return service_type, key, collection_kind
|
|
170
|
+
|
|
171
|
+
if not isinstance(dependency_annotation, type) or dependency_annotation is Any:
|
|
172
|
+
raise UnsupportedTypeAnnotationError(target, parameter_name, annotation)
|
|
173
|
+
|
|
174
|
+
return dependency_annotation, key, None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _collection_kind(origin: Any) -> CollectionKind | None:
|
|
178
|
+
if origin is list:
|
|
179
|
+
return CollectionKind.LIST
|
|
180
|
+
if origin is tuple or origin is Sequence or origin is Iterable:
|
|
181
|
+
return CollectionKind.TUPLE
|
|
182
|
+
if origin is set:
|
|
183
|
+
return CollectionKind.SET
|
|
184
|
+
if origin is frozenset:
|
|
185
|
+
return CollectionKind.FROZENSET
|
|
186
|
+
return None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def resolve_dependency(
|
|
190
|
+
request: DependencyRequest,
|
|
191
|
+
*,
|
|
192
|
+
resolver: ServiceResolver,
|
|
193
|
+
target: object,
|
|
194
|
+
) -> object:
|
|
195
|
+
"""Resolve one request and turn a missing registration into an injection error."""
|
|
196
|
+
if request.collection_kind is not None:
|
|
197
|
+
services = resolver.get_services(request.service_type, key=request.key)
|
|
198
|
+
try:
|
|
199
|
+
return _materialize_collection(services, request.collection_kind)
|
|
200
|
+
except TypeError as error:
|
|
201
|
+
raise CollectionMaterializationError(
|
|
202
|
+
target,
|
|
203
|
+
request.parameter_name,
|
|
204
|
+
_collection_type(request.collection_kind),
|
|
205
|
+
) from error
|
|
206
|
+
|
|
207
|
+
dependency = resolver.get_service(request.service_type, key=request.key)
|
|
208
|
+
if dependency is None:
|
|
209
|
+
raise ServiceNotRegisteredError(
|
|
210
|
+
request.service_type,
|
|
211
|
+
key=request.key,
|
|
212
|
+
target=target,
|
|
213
|
+
parameter_name=request.parameter_name,
|
|
214
|
+
)
|
|
215
|
+
return dependency
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _materialize_collection(
|
|
219
|
+
services: tuple[object, ...], kind: CollectionKind
|
|
220
|
+
) -> object:
|
|
221
|
+
return _COLLECTION_FACTORIES[kind](services)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _collection_type(kind: CollectionKind) -> type[object]:
|
|
225
|
+
return cast(type[object], _COLLECTION_FACTORIES[kind])
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
_COLLECTION_FACTORIES: dict[CollectionKind, Callable[[Iterable[object]], object]] = {
|
|
229
|
+
CollectionKind.LIST: list,
|
|
230
|
+
CollectionKind.TUPLE: tuple,
|
|
231
|
+
CollectionKind.SET: set,
|
|
232
|
+
CollectionKind.FROZENSET: frozenset,
|
|
233
|
+
}
|
pydico/_disposal.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from collections.abc import Iterable
|
|
2
|
+
|
|
3
|
+
from pydico.exceptions import AsyncDisposalRequiredError, DisposalError
|
|
4
|
+
from pydico.lifecycle import OwnedResource, SupportsAsyncClose, SupportsClose
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def ensure_sync_disposable(instances: Iterable[OwnedResource]) -> None:
|
|
8
|
+
async_only = tuple(
|
|
9
|
+
instance
|
|
10
|
+
for instance in instances
|
|
11
|
+
if isinstance(instance, SupportsAsyncClose)
|
|
12
|
+
and not isinstance(instance, SupportsClose)
|
|
13
|
+
)
|
|
14
|
+
if async_only:
|
|
15
|
+
raise AsyncDisposalRequiredError(async_only)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def close_instances(instances: Iterable[OwnedResource]) -> None:
|
|
19
|
+
instances = tuple(instances)
|
|
20
|
+
ensure_sync_disposable(instances)
|
|
21
|
+
errors: list[Exception] = []
|
|
22
|
+
for instance in instances:
|
|
23
|
+
try:
|
|
24
|
+
if isinstance(instance, SupportsClose):
|
|
25
|
+
instance.close()
|
|
26
|
+
except Exception as error:
|
|
27
|
+
errors.append(error)
|
|
28
|
+
if errors:
|
|
29
|
+
raise DisposalError(errors) from errors[0]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def aclose_instances(instances: Iterable[OwnedResource]) -> None:
|
|
33
|
+
errors: list[Exception] = []
|
|
34
|
+
for instance in instances:
|
|
35
|
+
try:
|
|
36
|
+
if isinstance(instance, SupportsAsyncClose):
|
|
37
|
+
await instance.aclose()
|
|
38
|
+
else:
|
|
39
|
+
instance.close()
|
|
40
|
+
except Exception as error:
|
|
41
|
+
errors.append(error)
|
|
42
|
+
if errors:
|
|
43
|
+
raise DisposalError(errors) from errors[0]
|
pydico/_typing.py
ADDED
pydico/_validation.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Static validation of service descriptors without creating services."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
|
|
7
|
+
from pydico._dependencies import DependencyPlan, DependencyRequest
|
|
8
|
+
from pydico.descriptors import ServiceDescriptor
|
|
9
|
+
from pydico.exceptions import (
|
|
10
|
+
CircularDependencyError,
|
|
11
|
+
InjectionError,
|
|
12
|
+
PydicoError,
|
|
13
|
+
ResolutionError,
|
|
14
|
+
ServiceNotRegisteredError,
|
|
15
|
+
)
|
|
16
|
+
from pydico.identifiers import ServiceIdentifier
|
|
17
|
+
from pydico.validation import ValidationIssue
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def validate_descriptors(
|
|
21
|
+
descriptors: Sequence[ServiceDescriptor[object]],
|
|
22
|
+
) -> tuple[ValidationIssue, ...]:
|
|
23
|
+
"""Return deterministic issues from every statically visible graph."""
|
|
24
|
+
return _ServiceGraphValidator(descriptors).validate()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _ServiceGraphValidator:
|
|
28
|
+
def __init__(self, descriptors: Sequence[ServiceDescriptor[object]]) -> None:
|
|
29
|
+
self._descriptors = tuple(descriptors)
|
|
30
|
+
self._issues: list[ValidationIssue] = []
|
|
31
|
+
self._processed: set[int] = set()
|
|
32
|
+
self._stack: list[ServiceDescriptor[object]] = []
|
|
33
|
+
self._plans: dict[type[object], DependencyPlan] = {}
|
|
34
|
+
self._reported_cycles: set[tuple[int, ...]] = set()
|
|
35
|
+
|
|
36
|
+
def validate(self) -> tuple[ValidationIssue, ...]:
|
|
37
|
+
for descriptor in self._descriptors:
|
|
38
|
+
self._validate_descriptor(descriptor)
|
|
39
|
+
return tuple(self._issues)
|
|
40
|
+
|
|
41
|
+
def _validate_descriptor(self, descriptor: ServiceDescriptor[object]) -> None:
|
|
42
|
+
descriptor_id = id(descriptor)
|
|
43
|
+
if descriptor_id in self._processed:
|
|
44
|
+
return
|
|
45
|
+
|
|
46
|
+
for index, active in enumerate(self._stack):
|
|
47
|
+
if active is descriptor:
|
|
48
|
+
cycle_descriptors = (*self._stack[index:], descriptor)
|
|
49
|
+
cycle_key = _normalize_cycle(
|
|
50
|
+
tuple(id(item) for item in cycle_descriptors[:-1])
|
|
51
|
+
)
|
|
52
|
+
if cycle_key in self._reported_cycles:
|
|
53
|
+
return
|
|
54
|
+
self._reported_cycles.add(cycle_key)
|
|
55
|
+
cycle = tuple(
|
|
56
|
+
ServiceIdentifier(item.service_type, item.key)
|
|
57
|
+
for item in cycle_descriptors
|
|
58
|
+
)
|
|
59
|
+
self._issues.append(
|
|
60
|
+
ValidationIssue(
|
|
61
|
+
CircularDependencyError(cycle),
|
|
62
|
+
(
|
|
63
|
+
*self._current_path(),
|
|
64
|
+
ServiceIdentifier(descriptor.service_type, descriptor.key),
|
|
65
|
+
),
|
|
66
|
+
)
|
|
67
|
+
)
|
|
68
|
+
return
|
|
69
|
+
|
|
70
|
+
self._stack.append(descriptor)
|
|
71
|
+
try:
|
|
72
|
+
if descriptor.factory is not None or descriptor.instance is not None:
|
|
73
|
+
return
|
|
74
|
+
|
|
75
|
+
implementation_type = descriptor.implementation_type
|
|
76
|
+
if implementation_type is None:
|
|
77
|
+
self._add_issue(
|
|
78
|
+
ResolutionError(
|
|
79
|
+
f"Service type {descriptor.service_type} has no "
|
|
80
|
+
"implementation, factory, or instance."
|
|
81
|
+
)
|
|
82
|
+
)
|
|
83
|
+
return
|
|
84
|
+
|
|
85
|
+
plan = self._get_plan(implementation_type)
|
|
86
|
+
if plan is None:
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
for parameter in plan.required_parameters():
|
|
90
|
+
try:
|
|
91
|
+
request = plan.requests((parameter,))[0]
|
|
92
|
+
except PydicoError as error:
|
|
93
|
+
self._add_issue(error)
|
|
94
|
+
if type(error) is InjectionError and error.__cause__ is not None:
|
|
95
|
+
break
|
|
96
|
+
continue
|
|
97
|
+
self._validate_request(request, implementation_type)
|
|
98
|
+
finally:
|
|
99
|
+
self._stack.pop()
|
|
100
|
+
self._processed.add(descriptor_id)
|
|
101
|
+
|
|
102
|
+
def _get_plan(self, implementation_type: type[object]) -> DependencyPlan | None:
|
|
103
|
+
plan = self._plans.get(implementation_type)
|
|
104
|
+
if plan is not None:
|
|
105
|
+
return plan
|
|
106
|
+
try:
|
|
107
|
+
plan = DependencyPlan(
|
|
108
|
+
implementation_type.__init__, error_target=implementation_type
|
|
109
|
+
)
|
|
110
|
+
except (TypeError, ValueError) as error:
|
|
111
|
+
injection_error = InjectionError(
|
|
112
|
+
f"Cannot inspect constructor for {implementation_type.__qualname__}."
|
|
113
|
+
)
|
|
114
|
+
injection_error.__cause__ = error
|
|
115
|
+
self._add_issue(injection_error)
|
|
116
|
+
return None
|
|
117
|
+
self._plans[implementation_type] = plan
|
|
118
|
+
return plan
|
|
119
|
+
|
|
120
|
+
def _validate_request(
|
|
121
|
+
self,
|
|
122
|
+
request: DependencyRequest,
|
|
123
|
+
target: type[object],
|
|
124
|
+
) -> None:
|
|
125
|
+
matches = tuple(
|
|
126
|
+
descriptor
|
|
127
|
+
for descriptor in self._descriptors
|
|
128
|
+
if descriptor.service_type is request.service_type
|
|
129
|
+
and descriptor.key == request.key
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
if request.collection_kind is not None:
|
|
133
|
+
for descriptor in matches:
|
|
134
|
+
self._validate_descriptor(descriptor)
|
|
135
|
+
return
|
|
136
|
+
|
|
137
|
+
if request.key is None and _is_builtin_service(request.service_type):
|
|
138
|
+
return
|
|
139
|
+
|
|
140
|
+
if not matches:
|
|
141
|
+
dependency = ServiceIdentifier(request.service_type, request.key)
|
|
142
|
+
self._issues.append(
|
|
143
|
+
ValidationIssue(
|
|
144
|
+
ServiceNotRegisteredError(
|
|
145
|
+
request.service_type,
|
|
146
|
+
key=request.key,
|
|
147
|
+
target=target,
|
|
148
|
+
parameter_name=request.parameter_name,
|
|
149
|
+
),
|
|
150
|
+
(*self._current_path(), dependency),
|
|
151
|
+
)
|
|
152
|
+
)
|
|
153
|
+
return
|
|
154
|
+
|
|
155
|
+
self._validate_descriptor(matches[-1])
|
|
156
|
+
|
|
157
|
+
def _add_issue(self, error: PydicoError) -> None:
|
|
158
|
+
self._issues.append(ValidationIssue(error, self._current_path()))
|
|
159
|
+
|
|
160
|
+
def _current_path(self) -> tuple[ServiceIdentifier, ...]:
|
|
161
|
+
return tuple(
|
|
162
|
+
ServiceIdentifier(descriptor.service_type, descriptor.key)
|
|
163
|
+
for descriptor in self._stack
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _is_builtin_service(service_type: type[object]) -> bool:
|
|
168
|
+
# Imported lazily to avoid collection/provider/scope import cycles.
|
|
169
|
+
from pydico.provider import ServiceProvider
|
|
170
|
+
from pydico.resolver import ServiceResolver
|
|
171
|
+
from pydico.scope import ServiceScope
|
|
172
|
+
|
|
173
|
+
return service_type in (ServiceProvider, ServiceResolver, ServiceScope)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _normalize_cycle(descriptor_ids: tuple[int, ...]) -> tuple[int, ...]:
|
|
177
|
+
rotations = tuple(
|
|
178
|
+
descriptor_ids[index:] + descriptor_ids[:index]
|
|
179
|
+
for index in range(len(descriptor_ids))
|
|
180
|
+
)
|
|
181
|
+
return min(rotations)
|