pico-ioc 1.5.0__py3-none-any.whl → 2.0.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.
- pico_ioc/__init__.py +82 -57
- pico_ioc/_version.py +1 -1
- pico_ioc/aop.py +281 -0
- pico_ioc/api.py +1137 -198
- pico_ioc/config_runtime.py +289 -0
- pico_ioc/constants.py +10 -0
- pico_ioc/container.py +420 -148
- pico_ioc/event_bus.py +223 -0
- pico_ioc/exceptions.py +72 -0
- pico_ioc/factory.py +48 -0
- pico_ioc/locator.py +53 -0
- pico_ioc/scope.py +155 -39
- pico_ioc-2.0.1.dist-info/METADATA +243 -0
- pico_ioc-2.0.1.dist-info/RECORD +17 -0
- pico_ioc/_state.py +0 -75
- pico_ioc/builder.py +0 -210
- pico_ioc/config.py +0 -332
- pico_ioc/decorators.py +0 -120
- pico_ioc/infra.py +0 -196
- pico_ioc/interceptors.py +0 -76
- pico_ioc/plugins.py +0 -28
- pico_ioc/policy.py +0 -245
- pico_ioc/proxy.py +0 -115
- pico_ioc/public_api.py +0 -76
- pico_ioc/resolver.py +0 -101
- pico_ioc/scanner.py +0 -178
- pico_ioc/utils.py +0 -25
- pico_ioc-1.5.0.dist-info/METADATA +0 -249
- pico_ioc-1.5.0.dist-info/RECORD +0 -23
- {pico_ioc-1.5.0.dist-info → pico_ioc-2.0.1.dist-info}/WHEEL +0 -0
- {pico_ioc-1.5.0.dist-info → pico_ioc-2.0.1.dist-info}/licenses/LICENSE +0 -0
- {pico_ioc-1.5.0.dist-info → pico_ioc-2.0.1.dist-info}/top_level.txt +0 -0
pico_ioc/config.py
DELETED
|
@@ -1,332 +0,0 @@
|
|
|
1
|
-
# src/pico_ioc/config.py
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
import os, json, configparser, pathlib
|
|
5
|
-
from dataclasses import is_dataclass, fields, MISSING
|
|
6
|
-
from typing import Any, Callable, Dict, Iterable, Optional, Sequence, Tuple, Protocol
|
|
7
|
-
|
|
8
|
-
# ---- Flags & metadata on classes / fields ----
|
|
9
|
-
_CONFIG_FLAG = "_pico_is_config_component"
|
|
10
|
-
_CONFIG_PREFIX = "_pico_config_prefix"
|
|
11
|
-
_FIELD_META = "_pico_config_field_meta" # dict: name -> FieldSpec
|
|
12
|
-
|
|
13
|
-
# ---- Source protocol & implementations ----
|
|
14
|
-
|
|
15
|
-
class ConfigSource(Protocol):
|
|
16
|
-
def get(self, key: str) -> Optional[str]: ...
|
|
17
|
-
def keys(self) -> Iterable[str]: ...
|
|
18
|
-
|
|
19
|
-
class EnvSource:
|
|
20
|
-
def __init__(self, prefix: str = ""):
|
|
21
|
-
self.prefix = prefix or ""
|
|
22
|
-
def get(self, key: str) -> Optional[str]:
|
|
23
|
-
# try PREFIX+KEY first, then KEY
|
|
24
|
-
v = os.getenv(self.prefix + key)
|
|
25
|
-
if v is not None:
|
|
26
|
-
return v
|
|
27
|
-
return os.getenv(key)
|
|
28
|
-
def keys(self) -> Iterable[str]:
|
|
29
|
-
# best-effort; env keys only (without prefix expansion)
|
|
30
|
-
return os.environ.keys()
|
|
31
|
-
|
|
32
|
-
class FileSource:
|
|
33
|
-
def __init__(self, path: os.PathLike[str] | str, optional: bool = False):
|
|
34
|
-
self.path = str(path)
|
|
35
|
-
self.optional = bool(optional)
|
|
36
|
-
self._cache: Dict[str, Any] = {}
|
|
37
|
-
self._load_once()
|
|
38
|
-
|
|
39
|
-
def _load_once(self):
|
|
40
|
-
p = pathlib.Path(self.path)
|
|
41
|
-
if not p.exists():
|
|
42
|
-
if self.optional:
|
|
43
|
-
self._cache = {}
|
|
44
|
-
return
|
|
45
|
-
raise FileNotFoundError(self.path)
|
|
46
|
-
text = p.read_text(encoding="utf-8")
|
|
47
|
-
|
|
48
|
-
# Try in order: JSON, INI, dotenv, YAML (if available)
|
|
49
|
-
# JSON
|
|
50
|
-
try:
|
|
51
|
-
data = json.loads(text)
|
|
52
|
-
self._cache = _flatten_obj(data)
|
|
53
|
-
return
|
|
54
|
-
except Exception:
|
|
55
|
-
pass
|
|
56
|
-
# INI
|
|
57
|
-
try:
|
|
58
|
-
cp = configparser.ConfigParser()
|
|
59
|
-
cp.read_string(text)
|
|
60
|
-
data = {s: dict(cp.items(s)) for s in cp.sections()}
|
|
61
|
-
# also root-level keys under DEFAULT
|
|
62
|
-
data.update(dict(cp.defaults()))
|
|
63
|
-
self._cache = _flatten_obj(data)
|
|
64
|
-
return
|
|
65
|
-
except Exception:
|
|
66
|
-
pass
|
|
67
|
-
# dotenv (simple KEY=VALUE per line)
|
|
68
|
-
try:
|
|
69
|
-
kv = {}
|
|
70
|
-
for line in text.splitlines():
|
|
71
|
-
line = line.strip()
|
|
72
|
-
if not line or line.startswith("#"):
|
|
73
|
-
continue
|
|
74
|
-
if "=" in line:
|
|
75
|
-
k, v = line.split("=", 1)
|
|
76
|
-
kv[k.strip()] = _strip_quotes(v.strip())
|
|
77
|
-
self._cache = _flatten_obj(kv)
|
|
78
|
-
if self._cache:
|
|
79
|
-
return
|
|
80
|
-
except Exception:
|
|
81
|
-
pass
|
|
82
|
-
# YAML if available
|
|
83
|
-
try:
|
|
84
|
-
import yaml # type: ignore
|
|
85
|
-
data = yaml.safe_load(text) or {}
|
|
86
|
-
self._cache = _flatten_obj(data)
|
|
87
|
-
return
|
|
88
|
-
except Exception:
|
|
89
|
-
# if everything fails, fallback to empty (optional) or raise
|
|
90
|
-
if self.optional:
|
|
91
|
-
self._cache = {}
|
|
92
|
-
return
|
|
93
|
-
raise ValueError(f"Unrecognized file format: {self.path}")
|
|
94
|
-
|
|
95
|
-
def get(self, key: str) -> Optional[str]:
|
|
96
|
-
v = self._cache.get(key)
|
|
97
|
-
return None if v is None else str(v)
|
|
98
|
-
|
|
99
|
-
def keys(self) -> Iterable[str]:
|
|
100
|
-
return self._cache.keys()
|
|
101
|
-
|
|
102
|
-
# ---- Field specs (overrides) ----
|
|
103
|
-
|
|
104
|
-
class FieldSpec:
|
|
105
|
-
__slots__ = ("sources", "keys", "default", "path_is_dot")
|
|
106
|
-
def __init__(self, *, sources: Tuple[str, ...], keys: Tuple[str, ...], default: Any, path_is_dot: bool):
|
|
107
|
-
self.sources = sources
|
|
108
|
-
self.keys = keys
|
|
109
|
-
self.default = default
|
|
110
|
-
self.path_is_dot = path_is_dot # true when keys are dotted-paths for structured files
|
|
111
|
-
|
|
112
|
-
class _ValueSentinel:
|
|
113
|
-
def __getitem__(self, key_default: str | Tuple[str, Any], /):
|
|
114
|
-
if isinstance(key_default, tuple):
|
|
115
|
-
key, default = key_default
|
|
116
|
-
else:
|
|
117
|
-
key, default = key_default, MISSING
|
|
118
|
-
# default sources order env>file unless overridden in Value(...)
|
|
119
|
-
return _ValueFactory(key, default)
|
|
120
|
-
Value = _ValueSentinel()
|
|
121
|
-
|
|
122
|
-
class _ValueFactory:
|
|
123
|
-
def __init__(self, key: str, default: Any):
|
|
124
|
-
self.key = key
|
|
125
|
-
self.default = default
|
|
126
|
-
def __call__(self, *, sources: Tuple[str, ...] = ("env","file")):
|
|
127
|
-
return FieldSpec(sources=tuple(sources), keys=(self.key,), default=self.default, path_is_dot=False)
|
|
128
|
-
|
|
129
|
-
class _EnvSentinel:
|
|
130
|
-
def __getitem__(self, key_default: str | Tuple[str, Any], /):
|
|
131
|
-
key, default = (key_default if isinstance(key_default, tuple) else (key_default, MISSING))
|
|
132
|
-
return FieldSpec(sources=("env",), keys=(key,), default=default, path_is_dot=False)
|
|
133
|
-
Env = _EnvSentinel()
|
|
134
|
-
|
|
135
|
-
class _FileSentinel:
|
|
136
|
-
def __getitem__(self, key_default: str | Tuple[str, Any], /):
|
|
137
|
-
key, default = (key_default if isinstance(key_default, tuple) else (key_default, MISSING))
|
|
138
|
-
return FieldSpec(sources=("file",), keys=(key,), default=default, path_is_dot=False)
|
|
139
|
-
File = _FileSentinel()
|
|
140
|
-
|
|
141
|
-
class _PathSentinel:
|
|
142
|
-
class _FilePath:
|
|
143
|
-
def __getitem__(self, key_default: str | Tuple[str, Any], /):
|
|
144
|
-
key, default = (key_default if isinstance(key_default, tuple) else (key_default, MISSING))
|
|
145
|
-
return FieldSpec(sources=("file",), keys=(key,), default=default, path_is_dot=True)
|
|
146
|
-
file = _FilePath()
|
|
147
|
-
Path = _PathSentinel()
|
|
148
|
-
|
|
149
|
-
# ---- Class decorator ----
|
|
150
|
-
|
|
151
|
-
def config_component(*, prefix: str = ""):
|
|
152
|
-
def dec(cls):
|
|
153
|
-
setattr(cls, _CONFIG_FLAG, True)
|
|
154
|
-
setattr(cls, _CONFIG_PREFIX, prefix or "")
|
|
155
|
-
if not hasattr(cls, _FIELD_META):
|
|
156
|
-
setattr(cls, _FIELD_META, {})
|
|
157
|
-
return cls
|
|
158
|
-
return dec
|
|
159
|
-
|
|
160
|
-
def is_config_component(cls: type) -> bool:
|
|
161
|
-
return bool(getattr(cls, _CONFIG_FLAG, False))
|
|
162
|
-
|
|
163
|
-
# ---- Registry / resolution ----
|
|
164
|
-
|
|
165
|
-
class ConfigRegistry:
|
|
166
|
-
"""Holds ordered sources and provides typed resolution for @config_component classes."""
|
|
167
|
-
def __init__(self, sources: Sequence[ConfigSource]):
|
|
168
|
-
self.sources = tuple(sources or ())
|
|
169
|
-
|
|
170
|
-
def resolve(self, keys: Iterable[str]) -> Optional[str]:
|
|
171
|
-
# try each key across sources in order
|
|
172
|
-
for key in keys:
|
|
173
|
-
for src in self.sources:
|
|
174
|
-
v = src.get(key)
|
|
175
|
-
if v is not None:
|
|
176
|
-
return v
|
|
177
|
-
return None
|
|
178
|
-
|
|
179
|
-
def register_field_spec(cls: type, name: str, spec: FieldSpec) -> None:
|
|
180
|
-
meta: Dict[str, FieldSpec] = getattr(cls, _FIELD_META, None) or {}
|
|
181
|
-
meta[name] = spec
|
|
182
|
-
setattr(cls, _FIELD_META, meta)
|
|
183
|
-
|
|
184
|
-
def build_component_instance(cls: type, registry: ConfigRegistry) -> Any:
|
|
185
|
-
prefix = getattr(cls, _CONFIG_PREFIX, "")
|
|
186
|
-
overrides: Dict[str, FieldSpec] = getattr(cls, _FIELD_META, {}) or {}
|
|
187
|
-
|
|
188
|
-
if is_dataclass(cls):
|
|
189
|
-
kwargs = {}
|
|
190
|
-
for f in fields(cls):
|
|
191
|
-
name = f.name
|
|
192
|
-
spec = overrides.get(name)
|
|
193
|
-
if spec:
|
|
194
|
-
val = _resolve_with_spec(spec, registry)
|
|
195
|
-
else:
|
|
196
|
-
# auto: PREFIX+NAME or NAME (env), NAME (file)
|
|
197
|
-
val = registry.resolve((prefix + name.upper(), name.upper()))
|
|
198
|
-
if val is None and f.default is not MISSING:
|
|
199
|
-
val = f.default
|
|
200
|
-
elif val is None and f.default_factory is not MISSING: # type: ignore
|
|
201
|
-
val = f.default_factory() # type: ignore
|
|
202
|
-
if val is None and f.default is MISSING and getattr(f, "default_factory", MISSING) is MISSING: # type: ignore
|
|
203
|
-
raise NameError(f"Missing config for field {cls.__name__}.{name}")
|
|
204
|
-
kwargs[name] = _coerce_type(val, f.type)
|
|
205
|
-
return cls(**kwargs)
|
|
206
|
-
|
|
207
|
-
# Non-dataclass: inspect __init__ signature
|
|
208
|
-
import inspect
|
|
209
|
-
sig = inspect.signature(cls.__init__)
|
|
210
|
-
hints = _get_type_hints_safe(cls.__init__, owner=cls)
|
|
211
|
-
kwargs = {}
|
|
212
|
-
for pname, par in sig.parameters.items():
|
|
213
|
-
if pname == "self" or par.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
|
|
214
|
-
continue
|
|
215
|
-
ann = hints.get(pname, par.annotation)
|
|
216
|
-
spec = overrides.get(pname)
|
|
217
|
-
if spec:
|
|
218
|
-
val = _resolve_with_spec(spec, registry)
|
|
219
|
-
else:
|
|
220
|
-
val = registry.resolve((prefix + pname.upper(), pname.upper()))
|
|
221
|
-
if val is None and par.default is not inspect._empty:
|
|
222
|
-
val = par.default
|
|
223
|
-
if val is None and par.default is inspect._empty:
|
|
224
|
-
raise NameError(f"Missing config for field {cls.__name__}.{pname}")
|
|
225
|
-
kwargs[pname] = _coerce_type(val, ann)
|
|
226
|
-
return cls(**kwargs)
|
|
227
|
-
|
|
228
|
-
# ---- helpers ----
|
|
229
|
-
|
|
230
|
-
def _resolve_with_spec(spec: FieldSpec, registry: ConfigRegistry) -> Any:
|
|
231
|
-
# respect spec.sources ordering, but try all keys for each source
|
|
232
|
-
for src_kind in spec.sources:
|
|
233
|
-
if src_kind == "env":
|
|
234
|
-
v = _resolve_from_sources(registry, spec.keys, predicate=lambda s: isinstance(s, EnvSource))
|
|
235
|
-
elif src_kind == "file":
|
|
236
|
-
if spec.path_is_dot:
|
|
237
|
-
v = _resolve_path_from_files(registry, spec.keys)
|
|
238
|
-
else:
|
|
239
|
-
v = _resolve_from_sources(registry, spec.keys, predicate=lambda s: isinstance(s, FileSource))
|
|
240
|
-
else:
|
|
241
|
-
v = None
|
|
242
|
-
if v is not None:
|
|
243
|
-
return v
|
|
244
|
-
return None if spec.default is MISSING else spec.default
|
|
245
|
-
|
|
246
|
-
def _resolve_from_sources(registry: ConfigRegistry, keys: Tuple[str, ...], predicate: Callable[[ConfigSource], bool]) -> Optional[str]:
|
|
247
|
-
for key in keys:
|
|
248
|
-
for src in registry.sources:
|
|
249
|
-
if predicate(src):
|
|
250
|
-
v = src.get(key)
|
|
251
|
-
if v is not None:
|
|
252
|
-
return v
|
|
253
|
-
return None
|
|
254
|
-
|
|
255
|
-
def _resolve_path_from_files(registry: ConfigRegistry, dotted_keys: Tuple[str, ...]) -> Optional[str]:
|
|
256
|
-
for key in dotted_keys:
|
|
257
|
-
path = key.split(".")
|
|
258
|
-
for src in registry.sources:
|
|
259
|
-
if isinstance(src, FileSource):
|
|
260
|
-
# FileSource caches flattened dict already
|
|
261
|
-
v = src.get(key)
|
|
262
|
-
if v is not None:
|
|
263
|
-
return v
|
|
264
|
-
return None
|
|
265
|
-
|
|
266
|
-
def _flatten_obj(obj: Any, prefix: str = "") -> Dict[str, Any]:
|
|
267
|
-
out: Dict[str, Any] = {}
|
|
268
|
-
if isinstance(obj, dict):
|
|
269
|
-
for k, v in obj.items():
|
|
270
|
-
k2 = (prefix + "." + str(k)) if prefix else str(k)
|
|
271
|
-
out.update(_flatten_obj(v, k2))
|
|
272
|
-
elif isinstance(obj, (list, tuple)):
|
|
273
|
-
for i, v in enumerate(obj):
|
|
274
|
-
k2 = (prefix + "." + str(i)) if prefix else str(i)
|
|
275
|
-
out.update(_flatten_obj(v, k2))
|
|
276
|
-
else:
|
|
277
|
-
out[prefix] = obj
|
|
278
|
-
if "." in prefix:
|
|
279
|
-
# also expose leaf as KEY without dots if single-segment? no; keep dotted only
|
|
280
|
-
pass
|
|
281
|
-
# also expose top-level KEY without dots when no prefix used:
|
|
282
|
-
if prefix and "." not in prefix:
|
|
283
|
-
out[prefix] = obj
|
|
284
|
-
# Additionally mirror top-level simple keys as UPPERCASE for convenience
|
|
285
|
-
if prefix and "." not in prefix:
|
|
286
|
-
out[prefix.upper()] = obj
|
|
287
|
-
return out
|
|
288
|
-
|
|
289
|
-
def _strip_quotes(s: str) -> str:
|
|
290
|
-
if (s.startswith('"') and s.endswith('"')) or (s.startswith("'") and s.endswith("'")):
|
|
291
|
-
return s[1:-1]
|
|
292
|
-
return s
|
|
293
|
-
|
|
294
|
-
def _coerce_type(val: Any, ann: Any) -> Any:
|
|
295
|
-
if val is None:
|
|
296
|
-
return None
|
|
297
|
-
# strings from sources come as str; coerce to basic types
|
|
298
|
-
try:
|
|
299
|
-
from typing import get_origin, get_args
|
|
300
|
-
origin = get_origin(ann) or ann
|
|
301
|
-
if origin in (int,):
|
|
302
|
-
return int(val)
|
|
303
|
-
if origin in (float,):
|
|
304
|
-
return float(val)
|
|
305
|
-
if origin in (bool,):
|
|
306
|
-
s = str(val).strip().lower()
|
|
307
|
-
if s in ("1","true","yes","y","on"): return True
|
|
308
|
-
if s in ("0","false","no","n","off"): return False
|
|
309
|
-
return bool(val)
|
|
310
|
-
except Exception:
|
|
311
|
-
pass
|
|
312
|
-
return val
|
|
313
|
-
|
|
314
|
-
def _get_type_hints_safe(fn, owner=None):
|
|
315
|
-
try:
|
|
316
|
-
import inspect
|
|
317
|
-
mod = inspect.getmodule(fn)
|
|
318
|
-
g = getattr(mod, "__dict__", {})
|
|
319
|
-
l = vars(owner) if owner is not None else None
|
|
320
|
-
from typing import get_type_hints
|
|
321
|
-
return get_type_hints(fn, globalns=g, localns=l, include_extras=True)
|
|
322
|
-
except Exception:
|
|
323
|
-
return {}
|
|
324
|
-
|
|
325
|
-
# ---- Public API helpers to be imported by users ----
|
|
326
|
-
|
|
327
|
-
__all__ = [
|
|
328
|
-
"config_component", "EnvSource", "FileSource",
|
|
329
|
-
"Env", "File", "Path", "Value",
|
|
330
|
-
"ConfigRegistry", "register_field_spec", "is_config_component",
|
|
331
|
-
]
|
|
332
|
-
|
pico_ioc/decorators.py
DELETED
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
import functools
|
|
3
|
-
from typing import Any, Iterable, Optional, Callable, Tuple
|
|
4
|
-
|
|
5
|
-
COMPONENT_FLAG = "_is_component"
|
|
6
|
-
COMPONENT_KEY = "_component_key"
|
|
7
|
-
COMPONENT_LAZY = "_component_lazy"
|
|
8
|
-
|
|
9
|
-
FACTORY_FLAG = "_is_factory_component"
|
|
10
|
-
PROVIDES_KEY = "_provides_name"
|
|
11
|
-
PROVIDES_LAZY = "_pico_lazy"
|
|
12
|
-
|
|
13
|
-
PLUGIN_FLAG = "_is_pico_plugin"
|
|
14
|
-
QUALIFIERS_KEY = "_pico_qualifiers"
|
|
15
|
-
|
|
16
|
-
COMPONENT_TAGS = "_pico_tags"
|
|
17
|
-
PROVIDES_TAGS = "_pico_tags"
|
|
18
|
-
|
|
19
|
-
ON_MISSING_META = "_pico_on_missing"
|
|
20
|
-
PRIMARY_FLAG = "_pico_primary"
|
|
21
|
-
CONDITIONAL_META = "_pico_conditional"
|
|
22
|
-
|
|
23
|
-
INFRA_META = "__pico_infrastructure__"
|
|
24
|
-
|
|
25
|
-
def factory_component(cls):
|
|
26
|
-
setattr(cls, FACTORY_FLAG, True)
|
|
27
|
-
return cls
|
|
28
|
-
|
|
29
|
-
def component(cls=None, *, name: Any = None, lazy: bool = False, tags: Iterable[str] = ()):
|
|
30
|
-
def dec(c):
|
|
31
|
-
setattr(c, COMPONENT_FLAG, True)
|
|
32
|
-
setattr(c, COMPONENT_KEY, name if name is not None else c)
|
|
33
|
-
setattr(c, COMPONENT_LAZY, bool(lazy))
|
|
34
|
-
setattr(c, COMPONENT_TAGS, tuple(tags) if tags else ())
|
|
35
|
-
return c
|
|
36
|
-
return dec(cls) if cls else dec
|
|
37
|
-
|
|
38
|
-
def provides(key: Any, *, lazy: bool = False, tags: Iterable[str] = ()):
|
|
39
|
-
def dec(fn):
|
|
40
|
-
@functools.wraps(fn)
|
|
41
|
-
def w(*a, **k):
|
|
42
|
-
return fn(*a, **k)
|
|
43
|
-
setattr(w, PROVIDES_KEY, key)
|
|
44
|
-
setattr(w, PROVIDES_LAZY, bool(lazy))
|
|
45
|
-
setattr(w, PROVIDES_TAGS, tuple(tags) if tags else ())
|
|
46
|
-
return w
|
|
47
|
-
return dec
|
|
48
|
-
|
|
49
|
-
def plugin(cls):
|
|
50
|
-
setattr(cls, PLUGIN_FLAG, True)
|
|
51
|
-
return cls
|
|
52
|
-
|
|
53
|
-
class Qualifier(str):
|
|
54
|
-
__slots__ = ()
|
|
55
|
-
|
|
56
|
-
def qualifier(*qs: Qualifier):
|
|
57
|
-
def dec(cls):
|
|
58
|
-
current: Iterable[Qualifier] = getattr(cls, QUALIFIERS_KEY, ())
|
|
59
|
-
seen = set(current)
|
|
60
|
-
merged = list(current)
|
|
61
|
-
for q in qs:
|
|
62
|
-
if q not in seen:
|
|
63
|
-
merged.append(q)
|
|
64
|
-
seen.add(q)
|
|
65
|
-
setattr(cls, QUALIFIERS_KEY, tuple(merged))
|
|
66
|
-
return cls
|
|
67
|
-
return dec
|
|
68
|
-
|
|
69
|
-
def on_missing(selector: object, *, priority: int = 0):
|
|
70
|
-
def dec(obj):
|
|
71
|
-
setattr(obj, ON_MISSING_META, {"selector": selector, "priority": int(priority)})
|
|
72
|
-
return obj
|
|
73
|
-
return dec
|
|
74
|
-
|
|
75
|
-
def primary(obj):
|
|
76
|
-
setattr(obj, PRIMARY_FLAG, True)
|
|
77
|
-
return obj
|
|
78
|
-
|
|
79
|
-
def conditional(
|
|
80
|
-
*,
|
|
81
|
-
profiles: Tuple[str, ...] = (),
|
|
82
|
-
require_env: Tuple[str, ...] = (),
|
|
83
|
-
predicate: Optional[Callable[[], bool]] = None,
|
|
84
|
-
):
|
|
85
|
-
def dec(obj):
|
|
86
|
-
setattr(obj, CONDITIONAL_META, {
|
|
87
|
-
"profiles": tuple(profiles),
|
|
88
|
-
"require_env": tuple(require_env),
|
|
89
|
-
"predicate": predicate,
|
|
90
|
-
})
|
|
91
|
-
return obj
|
|
92
|
-
return dec
|
|
93
|
-
|
|
94
|
-
def infrastructure(
|
|
95
|
-
_cls=None, *, order: int = 0,
|
|
96
|
-
profiles: Tuple[str, ...] = (),
|
|
97
|
-
require_env: Tuple[str, ...] = (),
|
|
98
|
-
predicate: Optional[Callable[[], bool]] = None,
|
|
99
|
-
):
|
|
100
|
-
def dec(cls):
|
|
101
|
-
setattr(cls, INFRA_META, {
|
|
102
|
-
"order": int(order),
|
|
103
|
-
"profiles": tuple(profiles),
|
|
104
|
-
"require_env": tuple(require_env),
|
|
105
|
-
"predicate": predicate,
|
|
106
|
-
})
|
|
107
|
-
return cls
|
|
108
|
-
return dec if _cls is None else dec(_cls)
|
|
109
|
-
|
|
110
|
-
__all__ = [
|
|
111
|
-
"component", "factory_component", "provides", "plugin",
|
|
112
|
-
"Qualifier", "qualifier",
|
|
113
|
-
"on_missing", "primary", "conditional", "infrastructure",
|
|
114
|
-
"COMPONENT_FLAG", "COMPONENT_KEY", "COMPONENT_LAZY",
|
|
115
|
-
"FACTORY_FLAG", "PROVIDES_KEY", "PROVIDES_LAZY",
|
|
116
|
-
"PLUGIN_FLAG", "QUALIFIERS_KEY", "COMPONENT_TAGS", "PROVIDES_TAGS",
|
|
117
|
-
"ON_MISSING_META", "PRIMARY_FLAG", "CONDITIONAL_META",
|
|
118
|
-
"INFRA_META",
|
|
119
|
-
]
|
|
120
|
-
|
pico_ioc/infra.py
DELETED
|
@@ -1,196 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
import re
|
|
3
|
-
from typing import Any, Callable, Iterable, Optional, Sequence, Tuple
|
|
4
|
-
|
|
5
|
-
class Select:
|
|
6
|
-
def __init__(self):
|
|
7
|
-
self._tags: set[str] = set()
|
|
8
|
-
self._profiles: set[str] = set()
|
|
9
|
-
self._class_name_regex: Optional[re.Pattern[str]] = None
|
|
10
|
-
self._method_name_regex: Optional[re.Pattern[str]] = None
|
|
11
|
-
|
|
12
|
-
def has_tag(self, *tags: str) -> "Select":
|
|
13
|
-
self._tags.update(t for t in tags if t)
|
|
14
|
-
return self
|
|
15
|
-
|
|
16
|
-
def profile_in(self, *profiles: str) -> "Select":
|
|
17
|
-
self._profiles.update(p for p in profiles if p)
|
|
18
|
-
return self
|
|
19
|
-
|
|
20
|
-
def class_name(self, regex: str) -> "Select":
|
|
21
|
-
self._class_name_regex = re.compile(regex)
|
|
22
|
-
return self
|
|
23
|
-
|
|
24
|
-
def method_name(self, regex: str) -> "Select":
|
|
25
|
-
self._method_name_regex = re.compile(regex)
|
|
26
|
-
return self
|
|
27
|
-
|
|
28
|
-
def is_effectively_empty(self) -> bool:
|
|
29
|
-
return not (self._tags or self._profiles or self._class_name_regex or self._method_name_regex)
|
|
30
|
-
|
|
31
|
-
def match_provider(self, key: Any, meta: dict, *, active_profiles: Sequence[str]) -> bool:
|
|
32
|
-
if self.is_effectively_empty():
|
|
33
|
-
return False
|
|
34
|
-
if self._tags:
|
|
35
|
-
tags = set(meta.get("tags", ()))
|
|
36
|
-
if not tags.intersection(self._tags):
|
|
37
|
-
return False
|
|
38
|
-
if self._profiles:
|
|
39
|
-
if not set(active_profiles).intersection(self._profiles):
|
|
40
|
-
return False
|
|
41
|
-
if self._class_name_regex and isinstance(key, type):
|
|
42
|
-
if not self._class_name_regex.search(getattr(key, "__name__", "")):
|
|
43
|
-
return False
|
|
44
|
-
return True
|
|
45
|
-
|
|
46
|
-
def match_method_name(self, method: str) -> bool:
|
|
47
|
-
if self._method_name_regex is None:
|
|
48
|
-
return True
|
|
49
|
-
return bool(self._method_name_regex.search(method))
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
class InfraQuery:
|
|
53
|
-
def __init__(self, container, profiles: Tuple[str, ...]):
|
|
54
|
-
self.c = container
|
|
55
|
-
self.profiles = profiles
|
|
56
|
-
|
|
57
|
-
def providers(self, where: Optional[Select] = None, *, limit: Optional[int] = None) -> list[tuple[Any, dict]]:
|
|
58
|
-
sel = where or Select()
|
|
59
|
-
items: list[tuple[Any, dict]] = []
|
|
60
|
-
for k, m in self.c._providers.items():
|
|
61
|
-
if sel.match_provider(k, m, active_profiles=self.profiles):
|
|
62
|
-
items.append((k, m))
|
|
63
|
-
if limit is not None and len(items) >= limit:
|
|
64
|
-
break
|
|
65
|
-
return items
|
|
66
|
-
|
|
67
|
-
def components(self, where: Optional[Select] = None, *, limit: Optional[int] = None) -> list[type]:
|
|
68
|
-
out: list[type] = []
|
|
69
|
-
for k, _m in self.providers(where=where, limit=limit):
|
|
70
|
-
if isinstance(k, type):
|
|
71
|
-
out.append(k)
|
|
72
|
-
return out
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
class InfraIntercept:
|
|
76
|
-
def __init__(self, container, profiles: Tuple[str, ...]):
|
|
77
|
-
self.c = container
|
|
78
|
-
self.profiles = profiles
|
|
79
|
-
self._per_method_cap: Optional[int] = None
|
|
80
|
-
|
|
81
|
-
def _collect_target_classes(self, where: Select) -> tuple[set[type], set[Any]]:
|
|
82
|
-
classes: set[type] = set()
|
|
83
|
-
keys: set[Any] = set()
|
|
84
|
-
for key, meta in self.c._providers.items():
|
|
85
|
-
if where.match_provider(key, meta, active_profiles=self.profiles):
|
|
86
|
-
keys.add(key)
|
|
87
|
-
if isinstance(key, type):
|
|
88
|
-
classes.add(key)
|
|
89
|
-
return classes, keys
|
|
90
|
-
|
|
91
|
-
def _guard_method_interceptor(self, interceptor, where: Select):
|
|
92
|
-
target_classes, _keys = self._collect_target_classes(where)
|
|
93
|
-
class_names = {cls.__name__ for cls in target_classes}
|
|
94
|
-
class Guarded:
|
|
95
|
-
def invoke(self, ctx, call_next):
|
|
96
|
-
tgt_cls = type(ctx.instance)
|
|
97
|
-
ok_class = any(isinstance(ctx.instance, cls) for cls in target_classes) or (getattr(tgt_cls, "__name__", "") in class_names)
|
|
98
|
-
ok_method = where.match_method_name(ctx.name)
|
|
99
|
-
if ok_class and ok_method:
|
|
100
|
-
return interceptor.invoke(ctx, call_next) if hasattr(interceptor, "invoke") else interceptor(ctx, call_next)
|
|
101
|
-
return call_next(ctx)
|
|
102
|
-
return Guarded()
|
|
103
|
-
|
|
104
|
-
def _guard_container_interceptor(self, interceptor, where: Select):
|
|
105
|
-
target_classes, keys = self._collect_target_classes(where)
|
|
106
|
-
class_names = {cls.__name__ for cls in target_classes}
|
|
107
|
-
def _ok(key: Any) -> bool:
|
|
108
|
-
if key in keys:
|
|
109
|
-
return True
|
|
110
|
-
if isinstance(key, type) and (key in target_classes or getattr(key, "__name__", "") in class_names):
|
|
111
|
-
return True
|
|
112
|
-
return False
|
|
113
|
-
class GuardedCI:
|
|
114
|
-
def around_resolve(self, ctx, call_next):
|
|
115
|
-
if _ok(ctx.key):
|
|
116
|
-
return interceptor.around_resolve(ctx, call_next)
|
|
117
|
-
return call_next(ctx)
|
|
118
|
-
def around_create(self, ctx, call_next):
|
|
119
|
-
if _ok(ctx.key):
|
|
120
|
-
return interceptor.around_create(ctx, call_next)
|
|
121
|
-
return call_next(ctx)
|
|
122
|
-
return GuardedCI()
|
|
123
|
-
|
|
124
|
-
def add(self, *, interceptor, where: Select) -> None:
|
|
125
|
-
sel = where or Select()
|
|
126
|
-
if sel.is_effectively_empty():
|
|
127
|
-
raise ValueError("empty selector for interceptor")
|
|
128
|
-
is_container = all(hasattr(interceptor, m) for m in ("around_resolve", "around_create"))
|
|
129
|
-
if is_container:
|
|
130
|
-
guarded = self._guard_container_interceptor(interceptor, sel)
|
|
131
|
-
self.c.add_container_interceptor(guarded)
|
|
132
|
-
return
|
|
133
|
-
guarded = self._guard_method_interceptor(interceptor, sel)
|
|
134
|
-
self.c.add_method_interceptor(guarded)
|
|
135
|
-
|
|
136
|
-
def limit_per_method(self, max_n: int) -> None:
|
|
137
|
-
self._per_method_cap = int(max_n)
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
class InfraMutate:
|
|
141
|
-
def __init__(self, container, profiles: Tuple[str, ...]):
|
|
142
|
-
self.c = container
|
|
143
|
-
self.profiles = profiles
|
|
144
|
-
|
|
145
|
-
def add_tags(self, component_or_key: Any, tags: Iterable[str]) -> None:
|
|
146
|
-
key = component_or_key
|
|
147
|
-
if key in self.c._providers:
|
|
148
|
-
meta = self.c._providers[key]
|
|
149
|
-
cur = tuple(meta.get("tags", ()))
|
|
150
|
-
new = tuple(dict.fromkeys(list(cur) + [t for t in tags if t]))
|
|
151
|
-
meta["tags"] = new
|
|
152
|
-
self.c._providers[key] = meta
|
|
153
|
-
|
|
154
|
-
def set_qualifiers(self, provider_key: Any, qualifiers: dict[str, Any]) -> None:
|
|
155
|
-
if provider_key in self.c._providers:
|
|
156
|
-
meta = self.c._providers[provider_key]
|
|
157
|
-
meta["qualifiers"] = tuple(qualifiers or ())
|
|
158
|
-
self.c._providers[provider_key] = meta
|
|
159
|
-
|
|
160
|
-
def replace_provider(self, *, key: Any, with_factory: Callable[[], object]) -> None:
|
|
161
|
-
if key in self.c._providers:
|
|
162
|
-
lazy = bool(self.c._providers[key].get("lazy", False))
|
|
163
|
-
self.c.bind(key, with_factory, lazy=lazy, tags=self.c._providers[key].get("tags", ()))
|
|
164
|
-
|
|
165
|
-
def wrap_provider(self, *, key: Any, around: Callable[[Callable[[], object]], Callable[[], object]]) -> None:
|
|
166
|
-
if key in self.c._providers:
|
|
167
|
-
meta = self.c._providers[key]
|
|
168
|
-
base_factory = meta.get("factory")
|
|
169
|
-
if callable(base_factory):
|
|
170
|
-
wrapped = around(base_factory)
|
|
171
|
-
self.c.bind(key, wrapped, lazy=bool(meta.get("lazy", False)), tags=meta.get("tags", ()))
|
|
172
|
-
|
|
173
|
-
def rename_key(self, *, old: Any, new: Any) -> None:
|
|
174
|
-
if old in self.c._providers and new not in self.c._providers:
|
|
175
|
-
self.c._providers[new] = self.c._providers.pop(old)
|
|
176
|
-
|
|
177
|
-
class Infra:
|
|
178
|
-
def __init__(self, *, container, profiles: Tuple[str, ...]):
|
|
179
|
-
self._c = container
|
|
180
|
-
self._profiles = profiles
|
|
181
|
-
self._query = InfraQuery(container, profiles)
|
|
182
|
-
self._intercept = InfraIntercept(container, profiles)
|
|
183
|
-
self._mutate = InfraMutate(container, profiles)
|
|
184
|
-
|
|
185
|
-
@property
|
|
186
|
-
def query(self) -> InfraQuery:
|
|
187
|
-
return self._query
|
|
188
|
-
|
|
189
|
-
@property
|
|
190
|
-
def intercept(self) -> InfraIntercept:
|
|
191
|
-
return self._intercept
|
|
192
|
-
|
|
193
|
-
@property
|
|
194
|
-
def mutate(self) -> InfraMutate:
|
|
195
|
-
return self._mutate
|
|
196
|
-
|