rn-forge-commons 0.8.0__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.
Potentially problematic release.
This version of rn-forge-commons might be problematic. Click here for more details.
- rn_forge/commons/__init__.py +130 -0
- rn_forge/commons/config.py +442 -0
- rn_forge/commons/exceptions.py +84 -0
- rn_forge/commons/findings.py +71 -0
- rn_forge/commons/fs/__init__.py +1 -0
- rn_forge/commons/fs/blocks.py +228 -0
- rn_forge/commons/fs/documents.py +814 -0
- rn_forge/commons/fs/hashing.py +26 -0
- rn_forge/commons/fs/locks.py +110 -0
- rn_forge/commons/fs/paths.py +326 -0
- rn_forge/commons/fs/state.py +207 -0
- rn_forge/commons/generation/__init__.py +34 -0
- rn_forge/commons/generation/apply.py +238 -0
- rn_forge/commons/generation/artifacts.py +296 -0
- rn_forge/commons/generation/plan.py +166 -0
- rn_forge/commons/generation/templated.py +59 -0
- rn_forge/commons/integration/__init__.py +5 -0
- rn_forge/commons/integration/messaging.py +84 -0
- rn_forge/commons/integration/objects.py +118 -0
- rn_forge/commons/integration/resilience.py +315 -0
- rn_forge/commons/integration/secrets.py +78 -0
- rn_forge/commons/lang/__init__.py +7 -0
- rn_forge/commons/lang/collections.py +827 -0
- rn_forge/commons/lang/dataclasses.py +495 -0
- rn_forge/commons/lang/models.py +145 -0
- rn_forge/commons/lang/reflection.py +229 -0
- rn_forge/commons/lang/types.py +52 -0
- rn_forge/commons/lang/utils.py +300 -0
- rn_forge/commons/logging/__init__.py +26 -0
- rn_forge/commons/logging/logger.py +1057 -0
- rn_forge/commons/logging/structlog.py +196 -0
- rn_forge/commons/py.typed +0 -0
- rn_forge/commons/runtime/__init__.py +5 -0
- rn_forge/commons/runtime/console.py +260 -0
- rn_forge/commons/runtime/environment.py +119 -0
- rn_forge/commons/runtime/plugins.py +77 -0
- rn_forge/commons/runtime/subprocess.py +403 -0
- rn_forge/commons/runtime/tasks.py +356 -0
- rn_forge/commons/testing.py +143 -0
- rn_forge/commons/text/__init__.py +7 -0
- rn_forge/commons/text/markdown.py +182 -0
- rn_forge/commons/text/templates.py +186 -0
- rn_forge_commons-0.8.0.dist-info/METADATA +250 -0
- rn_forge_commons-0.8.0.dist-info/RECORD +46 -0
- rn_forge_commons-0.8.0.dist-info/WHEEL +4 -0
- rn_forge_commons-0.8.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Public API for ``rn_forge.commons``.
|
|
2
|
+
|
|
3
|
+
Import from this package when you want the common helpers without reaching
|
|
4
|
+
into individual modules::
|
|
5
|
+
|
|
6
|
+
from rn_forge.commons import AppLogger, Config, DictUtils, JsonUtils
|
|
7
|
+
|
|
8
|
+
logger = AppLogger.initialize(root_logger_name="my-service")
|
|
9
|
+
cfg = Config("config")
|
|
10
|
+
logger.info("database.host={}", cfg.get("database.host"))
|
|
11
|
+
|
|
12
|
+
The re-export surface covers configuration, collections, dataclasses,
|
|
13
|
+
logging, subprocesses, task execution, and general utility helpers.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
# Modules are grouped by kind of mechanism (lang, fs, logging, runtime,
|
|
17
|
+
# integration); public class names are unaffected and stay re-exported here.
|
|
18
|
+
# The developer-tooling surface lives in two packages that depend on this one:
|
|
19
|
+
# `rn-forge-cli` (Typer wiring, standard options, exit codes) and
|
|
20
|
+
# `rn-forge-tooling` holds the lifecycle verbs and install mechanics.
|
|
21
|
+
# `generation` and `text` are imported directly, never through this facade: it
|
|
22
|
+
# imports eagerly, so a re-export here would load them for every commons user.
|
|
23
|
+
# There are deliberately no compatibility re-exports in either direction.
|
|
24
|
+
|
|
25
|
+
from rn_forge.commons.config import Config
|
|
26
|
+
from rn_forge.commons.exceptions import AppException
|
|
27
|
+
from rn_forge.commons.findings import Finding, Severity
|
|
28
|
+
from rn_forge.commons.fs.blocks import ManagedBlock
|
|
29
|
+
from rn_forge.commons.fs.documents import (
|
|
30
|
+
ConfigFormat,
|
|
31
|
+
DocumentError,
|
|
32
|
+
DocumentUtils,
|
|
33
|
+
JsonUtils,
|
|
34
|
+
YamlUtils,
|
|
35
|
+
)
|
|
36
|
+
from rn_forge.commons.fs.hashing import ContentHash
|
|
37
|
+
from rn_forge.commons.fs.locks import DirectoryLock, atomic_symlink
|
|
38
|
+
from rn_forge.commons.fs.paths import PathUtils
|
|
39
|
+
from rn_forge.commons.fs.state import StateStore
|
|
40
|
+
from rn_forge.commons.integration.messaging import (
|
|
41
|
+
AsyncMessageBus,
|
|
42
|
+
HandlerRegistry,
|
|
43
|
+
InMemoryMessageBus,
|
|
44
|
+
MessageBus,
|
|
45
|
+
)
|
|
46
|
+
from rn_forge.commons.integration.objects import (
|
|
47
|
+
AsyncObjectStore,
|
|
48
|
+
InMemoryObjectStore,
|
|
49
|
+
ObjectNotFound,
|
|
50
|
+
ObjectStore,
|
|
51
|
+
)
|
|
52
|
+
from rn_forge.commons.integration.secrets import (
|
|
53
|
+
AsyncSecretStore,
|
|
54
|
+
EnvSecretStore,
|
|
55
|
+
SecretNotFound,
|
|
56
|
+
SecretStore,
|
|
57
|
+
)
|
|
58
|
+
from rn_forge.commons.lang.collections import (
|
|
59
|
+
DictUtils,
|
|
60
|
+
ListUtils,
|
|
61
|
+
MergeResult,
|
|
62
|
+
)
|
|
63
|
+
from rn_forge.commons.lang.dataclasses import (
|
|
64
|
+
DataclassMixin,
|
|
65
|
+
LenientDataclassMixin,
|
|
66
|
+
StrictDataclassMixin,
|
|
67
|
+
)
|
|
68
|
+
from rn_forge.commons.lang.reflection import ReflectUtils
|
|
69
|
+
from rn_forge.commons.lang.types import JsonValue
|
|
70
|
+
from rn_forge.commons.lang.utils import AppUtils, Base64
|
|
71
|
+
from rn_forge.commons.logging import (
|
|
72
|
+
AppLogger,
|
|
73
|
+
LoggingConfig,
|
|
74
|
+
)
|
|
75
|
+
from rn_forge.commons.runtime.console import AppConsole, OutputMode, console
|
|
76
|
+
from rn_forge.commons.runtime.environment import Environment
|
|
77
|
+
from rn_forge.commons.runtime.plugins import EntryPointLoader, PluginError
|
|
78
|
+
from rn_forge.commons.runtime.subprocess import Process
|
|
79
|
+
from rn_forge.commons.runtime.tasks import Task, TaskPool
|
|
80
|
+
|
|
81
|
+
__all__ = [
|
|
82
|
+
"AppConsole",
|
|
83
|
+
"AppException",
|
|
84
|
+
"AppLogger",
|
|
85
|
+
"AppUtils",
|
|
86
|
+
"AsyncMessageBus",
|
|
87
|
+
"AsyncObjectStore",
|
|
88
|
+
"AsyncSecretStore",
|
|
89
|
+
"Base64",
|
|
90
|
+
"Config",
|
|
91
|
+
"ConfigFormat",
|
|
92
|
+
"ContentHash",
|
|
93
|
+
"DataclassMixin",
|
|
94
|
+
"DictUtils",
|
|
95
|
+
"DirectoryLock",
|
|
96
|
+
"DocumentError",
|
|
97
|
+
"DocumentUtils",
|
|
98
|
+
"EntryPointLoader",
|
|
99
|
+
"EnvSecretStore",
|
|
100
|
+
"Environment",
|
|
101
|
+
"Finding",
|
|
102
|
+
"HandlerRegistry",
|
|
103
|
+
"InMemoryMessageBus",
|
|
104
|
+
"InMemoryObjectStore",
|
|
105
|
+
"JsonUtils",
|
|
106
|
+
"JsonValue",
|
|
107
|
+
"LenientDataclassMixin",
|
|
108
|
+
"ListUtils",
|
|
109
|
+
"LoggingConfig",
|
|
110
|
+
"ManagedBlock",
|
|
111
|
+
"MergeResult",
|
|
112
|
+
"MessageBus",
|
|
113
|
+
"ObjectNotFound",
|
|
114
|
+
"ObjectStore",
|
|
115
|
+
"OutputMode",
|
|
116
|
+
"PathUtils",
|
|
117
|
+
"PluginError",
|
|
118
|
+
"Process",
|
|
119
|
+
"ReflectUtils",
|
|
120
|
+
"SecretNotFound",
|
|
121
|
+
"SecretStore",
|
|
122
|
+
"Severity",
|
|
123
|
+
"StateStore",
|
|
124
|
+
"StrictDataclassMixin",
|
|
125
|
+
"Task",
|
|
126
|
+
"TaskPool",
|
|
127
|
+
"YamlUtils",
|
|
128
|
+
"atomic_symlink",
|
|
129
|
+
"console",
|
|
130
|
+
]
|
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
"""Configuration loader with reference resolution.
|
|
2
|
+
|
|
3
|
+
Loads configuration from JSON or YAML files (single file or directory),
|
|
4
|
+
deep-merges multiple files, and resolves internal references:
|
|
5
|
+
|
|
6
|
+
- ``${path}`` — value interpolation (replaces with the resolved value)
|
|
7
|
+
- ``@{path}`` — dict reference (resolves to the dict at *path*)
|
|
8
|
+
- ``#{path}`` — list reference (resolves to the list at *path*)
|
|
9
|
+
- ``__extends__`` key — inherits and merges from another dict path
|
|
10
|
+
|
|
11
|
+
Reference paths use the same dot-delimited notation as
|
|
12
|
+
:meth:`~rn_forge.commons.lang.collections.DictUtils.get`.
|
|
13
|
+
|
|
14
|
+
Provides:
|
|
15
|
+
Config: Immutable-ish configuration object loaded from one or more
|
|
16
|
+
JSON/YAML files with automatic reference resolution.
|
|
17
|
+
|
|
18
|
+
Typical usage::
|
|
19
|
+
|
|
20
|
+
from rn_forge.commons.config import Config
|
|
21
|
+
|
|
22
|
+
cfg = Config("settings", "base.yaml")
|
|
23
|
+
db_host = cfg.get("database.host", default="localhost")
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import copy
|
|
29
|
+
import re
|
|
30
|
+
from collections.abc import Iterator
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import Any, Literal, cast
|
|
33
|
+
|
|
34
|
+
from rn_forge.commons.fs.documents import JsonUtils, YamlUtils
|
|
35
|
+
from rn_forge.commons.lang.collections import DictUtils
|
|
36
|
+
from rn_forge.commons.logging import AppLogger
|
|
37
|
+
|
|
38
|
+
_SENTINEL = object()
|
|
39
|
+
|
|
40
|
+
_REF_DICT_PATTERN = re.compile(r"^@\{(.+)}$")
|
|
41
|
+
_REF_LIST_PATTERN = re.compile(r"^#\{(.+)}$")
|
|
42
|
+
_REF_VALUE_PATTERN = re.compile(r"\$\{([^{}]+)}")
|
|
43
|
+
|
|
44
|
+
_MAX_RESOLVE_DEPTH = 64
|
|
45
|
+
|
|
46
|
+
_LOGGER = AppLogger.get_logger(__name__)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------------------
|
|
50
|
+
# Config
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Config:
|
|
55
|
+
"""Immutable-ish configuration object with reference resolution.
|
|
56
|
+
|
|
57
|
+
Loads one or more JSON/YAML files, deep-merges them in sorted order, and
|
|
58
|
+
optionally resolves internal ``${}``, ``@{}``, ``#{}`` references and
|
|
59
|
+
``__extends__`` inheritance.
|
|
60
|
+
|
|
61
|
+
Supports dict-like read access via ``cfg["key"]``, ``"key" in cfg``,
|
|
62
|
+
``iter(cfg)``, and ``len(cfg)``.
|
|
63
|
+
|
|
64
|
+
Example::
|
|
65
|
+
|
|
66
|
+
from rn_forge.commons.config import Config
|
|
67
|
+
|
|
68
|
+
cfg = Config("config/")
|
|
69
|
+
host = cfg.get("database.host", default="localhost")
|
|
70
|
+
cfg.set("database.port", 5432)
|
|
71
|
+
raw = cfg.as_dict()
|
|
72
|
+
|
|
73
|
+
Reference forms::
|
|
74
|
+
|
|
75
|
+
service_url: "https://${service.host}:${service.port}"
|
|
76
|
+
database: "@{services.primary_db}"
|
|
77
|
+
all_hosts:
|
|
78
|
+
- "#{services.hosts}"
|
|
79
|
+
- "localhost"
|
|
80
|
+
production:
|
|
81
|
+
__extends__: "@{profiles.base}"
|
|
82
|
+
debug: false
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
*paths: str | Path,
|
|
88
|
+
config_type: Literal["json", "yaml"] = "yaml",
|
|
89
|
+
resolve: bool = True,
|
|
90
|
+
) -> None:
|
|
91
|
+
"""Load and optionally resolve a configuration from file(s).
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
*paths: Path segments joined via :class:`~pathlib.Path`. If the
|
|
95
|
+
result is a file it is loaded directly; if a directory, all
|
|
96
|
+
files matching ``*.{config_type}`` (recursively, sorted) are
|
|
97
|
+
loaded and deep-merged.
|
|
98
|
+
config_type: ``"yaml"`` (default) or ``"json"`` — determines
|
|
99
|
+
the file extension filter and parser.
|
|
100
|
+
resolve: When ``True`` (default), call
|
|
101
|
+
:meth:`resolve_references` immediately after loading.
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
FileNotFoundError: If the resolved path does not exist.
|
|
105
|
+
"""
|
|
106
|
+
config_path = Path(*paths)
|
|
107
|
+
if not config_path.exists():
|
|
108
|
+
_LOGGER.warning("Config.__init__ | path={} | missing=true", config_path) # noqa: PLE1205 # brace-style log format
|
|
109
|
+
raise FileNotFoundError(f"Config path not found: {config_path}")
|
|
110
|
+
|
|
111
|
+
config_files = (
|
|
112
|
+
[config_path]
|
|
113
|
+
if config_path.is_file()
|
|
114
|
+
else sorted(config_path.rglob(f"*.{config_type}"))
|
|
115
|
+
)
|
|
116
|
+
_LOGGER.verbose("config_files: {}", config_files)
|
|
117
|
+
|
|
118
|
+
reader = JsonUtils.read_file if config_type == "json" else YamlUtils.read_file
|
|
119
|
+
configs = [reader(f) for f in config_files]
|
|
120
|
+
_LOGGER.trace("config_list: {}", configs)
|
|
121
|
+
|
|
122
|
+
self._data: dict[str, Any] = {}
|
|
123
|
+
DictUtils.merge(self._data, *configs)
|
|
124
|
+
|
|
125
|
+
if resolve:
|
|
126
|
+
self.resolve_references()
|
|
127
|
+
_LOGGER.success("Config Loaded: {}", config_path)
|
|
128
|
+
|
|
129
|
+
# -- public API --------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
def get(self, key_path: str, *, default: Any = None) -> Any:
|
|
132
|
+
"""Retrieve a value using a dot-delimited key path.
|
|
133
|
+
|
|
134
|
+
Delegates to :meth:`~rn_forge.commons.lang.collections.DictUtils.get`.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
key_path: Dot-delimited path, e.g. ``"database.host"``.
|
|
138
|
+
default: Value returned when the path cannot be resolved.
|
|
139
|
+
Defaults to ``None``.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
The resolved value, or *default* if the path is absent.
|
|
143
|
+
"""
|
|
144
|
+
return DictUtils.get(self._data, key_path, default=default)
|
|
145
|
+
|
|
146
|
+
def set(self, key_path: str, value: Any) -> None:
|
|
147
|
+
"""Set a value using a dot-delimited key path.
|
|
148
|
+
|
|
149
|
+
Delegates to :meth:`~rn_forge.commons.lang.collections.DictUtils.set`.
|
|
150
|
+
Intermediate dicts are created automatically.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
key_path: Dot-delimited path to the target key.
|
|
154
|
+
value: The value to assign.
|
|
155
|
+
|
|
156
|
+
Raises:
|
|
157
|
+
KeyError: If a non-numeric index is used on a list segment.
|
|
158
|
+
IndexError: If a list index is out of bounds.
|
|
159
|
+
TypeError: If traversal encounters a non-container at an
|
|
160
|
+
intermediate path segment.
|
|
161
|
+
"""
|
|
162
|
+
DictUtils.set(self._data, key_path, value)
|
|
163
|
+
|
|
164
|
+
def as_dict(self) -> dict[str, Any]:
|
|
165
|
+
"""Return a deep copy of the configuration data as a plain dict.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
A deep copy of the internal ``dict[str, Any]``. Mutating the
|
|
169
|
+
returned value does not affect this :class:`Config` instance.
|
|
170
|
+
"""
|
|
171
|
+
return copy.deepcopy(self._data)
|
|
172
|
+
|
|
173
|
+
def resolve_references(self) -> None:
|
|
174
|
+
"""Resolve all ``${}``, ``@{}``, ``#{}`` references and ``__extends__``
|
|
175
|
+
inheritance in the loaded configuration.
|
|
176
|
+
|
|
177
|
+
Called automatically when ``resolve=True`` (the default). Safe to call
|
|
178
|
+
again after programmatic mutations.
|
|
179
|
+
|
|
180
|
+
Example::
|
|
181
|
+
|
|
182
|
+
cfg = Config("settings.yaml", resolve=False)
|
|
183
|
+
cfg.set("service.host", "localhost")
|
|
184
|
+
cfg.resolve_references()
|
|
185
|
+
"""
|
|
186
|
+
_LOGGER.verbose("Config.resolve_references: keys={}", list(self._data.keys()))
|
|
187
|
+
_LOGGER.trace("pre-resolve: {}", self._data)
|
|
188
|
+
self._resolve_dict(self._data, depth=0)
|
|
189
|
+
_LOGGER.verbose(
|
|
190
|
+
"Config.resolve_references complete | keys={}",
|
|
191
|
+
list(self._data.keys()),
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
# -- reference resolution (private) ------------------------------------
|
|
195
|
+
|
|
196
|
+
def _resolve_dict(self, data: dict[str, Any], *, depth: int) -> None:
|
|
197
|
+
if depth > _MAX_RESOLVE_DEPTH:
|
|
198
|
+
_LOGGER.warning( # noqa: PLE1205 # brace-style log format
|
|
199
|
+
"Config._resolve_dict | depth={} | max_depth_exceeded=true",
|
|
200
|
+
depth,
|
|
201
|
+
)
|
|
202
|
+
raise RecursionError(
|
|
203
|
+
f"Reference resolution exceeded max depth ({_MAX_RESOLVE_DEPTH}). "
|
|
204
|
+
"Check for circular references."
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
# handle __extends__ first — inherit from the referenced dict
|
|
208
|
+
if "__extends__" in data:
|
|
209
|
+
parent_ref = data.pop("__extends__")
|
|
210
|
+
_LOGGER.trace("__extends__: {}", parent_ref)
|
|
211
|
+
parent = self._resolve_value(parent_ref, depth=depth)
|
|
212
|
+
if not isinstance(parent, dict):
|
|
213
|
+
_LOGGER.warning( # noqa: PLE1205 # brace-style log format
|
|
214
|
+
"Config._resolve_dict | extends_ref={} | invalid_parent_type={}",
|
|
215
|
+
parent_ref,
|
|
216
|
+
type(parent).__name__,
|
|
217
|
+
)
|
|
218
|
+
raise TypeError(
|
|
219
|
+
f"__extends__ must resolve to a dict, got {type(parent).__name__}"
|
|
220
|
+
)
|
|
221
|
+
merged = DictUtils.merge({}, cast(dict[str, Any], parent), data)
|
|
222
|
+
data.clear()
|
|
223
|
+
data.update(merged)
|
|
224
|
+
|
|
225
|
+
for key, value in data.items():
|
|
226
|
+
if isinstance(value, dict):
|
|
227
|
+
self._resolve_dict(cast(dict[str, Any], value), depth=depth + 1)
|
|
228
|
+
elif isinstance(value, list):
|
|
229
|
+
data[key] = self._resolve_list(cast(list[Any], value), depth=depth + 1)
|
|
230
|
+
elif isinstance(value, str) and _is_reference(value):
|
|
231
|
+
data[key] = self._resolve_value(value, depth=depth + 1)
|
|
232
|
+
|
|
233
|
+
def _resolve_list(self, items: list[Any], *, depth: int) -> list[Any]:
|
|
234
|
+
if depth > _MAX_RESOLVE_DEPTH:
|
|
235
|
+
_LOGGER.warning( # noqa: PLE1205 # brace-style log format
|
|
236
|
+
"Config._resolve_list | depth={} | max_depth_exceeded=true",
|
|
237
|
+
depth,
|
|
238
|
+
)
|
|
239
|
+
raise RecursionError(
|
|
240
|
+
f"Reference resolution exceeded max depth ({_MAX_RESOLVE_DEPTH}). "
|
|
241
|
+
"Check for circular references."
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
result: list[Any] = []
|
|
245
|
+
for item in items:
|
|
246
|
+
if isinstance(item, dict):
|
|
247
|
+
self._resolve_dict(cast(dict[str, Any], item), depth=depth + 1)
|
|
248
|
+
result.append(item)
|
|
249
|
+
elif isinstance(item, list):
|
|
250
|
+
result.append(
|
|
251
|
+
self._resolve_list(cast(list[Any], item), depth=depth + 1)
|
|
252
|
+
)
|
|
253
|
+
elif isinstance(item, str) and _is_reference(item):
|
|
254
|
+
resolved = self._resolve_value(item, depth=depth + 1)
|
|
255
|
+
# #{} list references are flattened into the parent list
|
|
256
|
+
if _REF_LIST_PATTERN.match(item) and isinstance(resolved, list):
|
|
257
|
+
result.extend(cast(list[Any], resolved))
|
|
258
|
+
else:
|
|
259
|
+
result.append(resolved)
|
|
260
|
+
else:
|
|
261
|
+
result.append(item)
|
|
262
|
+
return result
|
|
263
|
+
|
|
264
|
+
def _resolve_value(self, value: str, *, depth: int) -> Any:
|
|
265
|
+
"""Resolve a single string that may contain one or more references."""
|
|
266
|
+
if depth > _MAX_RESOLVE_DEPTH:
|
|
267
|
+
_LOGGER.warning( # noqa: PLE1205 # brace-style log format
|
|
268
|
+
"Config._resolve_value | value={} | depth={} | max_depth_exceeded=true",
|
|
269
|
+
value,
|
|
270
|
+
depth,
|
|
271
|
+
)
|
|
272
|
+
raise RecursionError(
|
|
273
|
+
f"Reference resolution exceeded max depth ({_MAX_RESOLVE_DEPTH}). "
|
|
274
|
+
"Check for circular references."
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
resolved = self._expand_value_placeholders(value)
|
|
278
|
+
|
|
279
|
+
if not isinstance(resolved, str):
|
|
280
|
+
return resolved
|
|
281
|
+
|
|
282
|
+
for pattern, kind in (
|
|
283
|
+
(_REF_DICT_PATTERN, "dict"),
|
|
284
|
+
(_REF_LIST_PATTERN, "list"),
|
|
285
|
+
):
|
|
286
|
+
whole_ref = self._resolve_whole_string_ref(resolved, pattern, kind)
|
|
287
|
+
if whole_ref is not _SENTINEL:
|
|
288
|
+
return whole_ref
|
|
289
|
+
|
|
290
|
+
return resolved
|
|
291
|
+
|
|
292
|
+
def _expand_value_placeholders(self, value: str) -> Any:
|
|
293
|
+
"""Iteratively expand all ``${}`` placeholders in *value*.
|
|
294
|
+
|
|
295
|
+
Returns the fully substituted string, or the referenced value itself
|
|
296
|
+
(with its original type preserved) when *value* is a single
|
|
297
|
+
placeholder.
|
|
298
|
+
"""
|
|
299
|
+
resolved: Any = value
|
|
300
|
+
|
|
301
|
+
for _ in range(_MAX_RESOLVE_DEPTH):
|
|
302
|
+
if not isinstance(resolved, str) or not _REF_VALUE_PATTERN.search(resolved):
|
|
303
|
+
return resolved
|
|
304
|
+
|
|
305
|
+
made_progress = False
|
|
306
|
+
ref_paths = _REF_VALUE_PATTERN.findall(resolved)
|
|
307
|
+
_LOGGER.trace("Value References: {} | {}", resolved, ref_paths)
|
|
308
|
+
for ref_path in ref_paths:
|
|
309
|
+
resolved, made_progress = self._substitute_value_ref(
|
|
310
|
+
resolved, ref_path, made_progress
|
|
311
|
+
)
|
|
312
|
+
if not isinstance(resolved, str):
|
|
313
|
+
return resolved
|
|
314
|
+
|
|
315
|
+
if not made_progress:
|
|
316
|
+
return resolved # no placeholder was resolvable — stop
|
|
317
|
+
|
|
318
|
+
raise RecursionError(
|
|
319
|
+
f"Reference resolution exceeded max depth ({_MAX_RESOLVE_DEPTH}). "
|
|
320
|
+
"Check for circular references."
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
def _substitute_value_ref(
|
|
324
|
+
self, resolved: str, ref_path: str, made_progress: bool
|
|
325
|
+
) -> tuple[Any, bool]:
|
|
326
|
+
"""Substitute a single ``${ref_path}`` placeholder into *resolved*."""
|
|
327
|
+
placeholder = f"${{{ref_path}}}"
|
|
328
|
+
ref_value = DictUtils.get(self._data, ref_path, default=_SENTINEL)
|
|
329
|
+
_LOGGER.trace("Referenced Value: {} | {}", ref_path, ref_value)
|
|
330
|
+
if ref_value is _SENTINEL:
|
|
331
|
+
_LOGGER.warning( # noqa: PLE1205 # brace-style log format
|
|
332
|
+
"Config._resolve_value | unresolved_placeholder={}",
|
|
333
|
+
placeholder,
|
|
334
|
+
)
|
|
335
|
+
return resolved, made_progress # unresolvable placeholder — skip it
|
|
336
|
+
|
|
337
|
+
if placeholder == resolved:
|
|
338
|
+
# entire string is one reference — preserve the resolved type
|
|
339
|
+
return ref_value, True
|
|
340
|
+
|
|
341
|
+
# partial substitution — coerce to string
|
|
342
|
+
replaced = resolved.replace(placeholder, str(ref_value))
|
|
343
|
+
_LOGGER.trace("Post Substitution: {} | {}", resolved, replaced)
|
|
344
|
+
return replaced, True
|
|
345
|
+
|
|
346
|
+
def _resolve_whole_string_ref(
|
|
347
|
+
self, resolved: str, pattern: re.Pattern[str], kind: str
|
|
348
|
+
) -> Any:
|
|
349
|
+
"""Resolve a whole-string ``@{}``/``#{}`` reference.
|
|
350
|
+
|
|
351
|
+
Returns ``_SENTINEL`` when *resolved* does not match *pattern* at all
|
|
352
|
+
(caller should try the next reference kind); otherwise returns the
|
|
353
|
+
referenced value, or *resolved* unchanged if the reference path is
|
|
354
|
+
absent from the configuration.
|
|
355
|
+
"""
|
|
356
|
+
m = pattern.match(resolved)
|
|
357
|
+
if not m:
|
|
358
|
+
return _SENTINEL
|
|
359
|
+
ref = DictUtils.get(self._data, m.group(1), default=_SENTINEL)
|
|
360
|
+
if ref is _SENTINEL:
|
|
361
|
+
_LOGGER.warning( # noqa: PLE1205 # brace-style log format
|
|
362
|
+
"Config._resolve_value | unresolved_{}_ref={}", kind, m.group(1)
|
|
363
|
+
)
|
|
364
|
+
return resolved
|
|
365
|
+
_LOGGER.trace("Config._resolve_value | resolved_{}_ref={}", kind, m.group(1))
|
|
366
|
+
return ref
|
|
367
|
+
|
|
368
|
+
# -- dunder protocols --------------------------------------------------
|
|
369
|
+
|
|
370
|
+
def __getitem__(self, key: str) -> Any:
|
|
371
|
+
"""Return the top-level value for *key* (no dot-path support).
|
|
372
|
+
|
|
373
|
+
Args:
|
|
374
|
+
key: A top-level key in the configuration dict.
|
|
375
|
+
|
|
376
|
+
Returns:
|
|
377
|
+
The value at *key*.
|
|
378
|
+
|
|
379
|
+
Raises:
|
|
380
|
+
KeyError: If *key* is not present.
|
|
381
|
+
"""
|
|
382
|
+
return self._data[key]
|
|
383
|
+
|
|
384
|
+
def __contains__(self, key: object) -> bool:
|
|
385
|
+
"""Return ``True`` if *key* is a top-level key in the configuration.
|
|
386
|
+
|
|
387
|
+
Args:
|
|
388
|
+
key: The key to test.
|
|
389
|
+
|
|
390
|
+
Returns:
|
|
391
|
+
``True`` if *key* exists at the top level, ``False`` otherwise.
|
|
392
|
+
"""
|
|
393
|
+
return key in self._data
|
|
394
|
+
|
|
395
|
+
def __iter__(self) -> Iterator[str]:
|
|
396
|
+
"""Iterate over top-level keys in the configuration.
|
|
397
|
+
|
|
398
|
+
Returns:
|
|
399
|
+
An iterator over top-level key strings.
|
|
400
|
+
"""
|
|
401
|
+
return iter(self._data)
|
|
402
|
+
|
|
403
|
+
def __len__(self) -> int:
|
|
404
|
+
"""Return the number of top-level keys in the configuration.
|
|
405
|
+
|
|
406
|
+
Returns:
|
|
407
|
+
An integer count of top-level keys.
|
|
408
|
+
"""
|
|
409
|
+
return len(self._data)
|
|
410
|
+
|
|
411
|
+
def __repr__(self) -> str:
|
|
412
|
+
"""Return an unambiguous string representation of this :class:`Config`.
|
|
413
|
+
|
|
414
|
+
Returns:
|
|
415
|
+
A string of the form ``Config({...})``.
|
|
416
|
+
"""
|
|
417
|
+
return f"Config({self._data!r})"
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
# ---------------------------------------------------------------------------
|
|
421
|
+
# Module-level helpers
|
|
422
|
+
# ---------------------------------------------------------------------------
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _is_reference(value: str) -> bool:
|
|
426
|
+
"""Return True if *value* contains any reference syntax."""
|
|
427
|
+
if (
|
|
428
|
+
_REF_DICT_PATTERN.match(value) or _REF_LIST_PATTERN.match(value)
|
|
429
|
+
) and _REF_VALUE_PATTERN.search(value):
|
|
430
|
+
_LOGGER.warning( # noqa: PLE1205 # brace-style log format
|
|
431
|
+
"Nested references are discouraged due to complexity: {} | {}",
|
|
432
|
+
value,
|
|
433
|
+
_REF_VALUE_PATTERN.findall(value),
|
|
434
|
+
)
|
|
435
|
+
return bool(
|
|
436
|
+
_REF_DICT_PATTERN.match(value)
|
|
437
|
+
or _REF_LIST_PATTERN.match(value)
|
|
438
|
+
or _REF_VALUE_PATTERN.search(value)
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
__all__ = ["Config"]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Structured exception base classes for ``rn-forge-*`` packages.
|
|
2
|
+
|
|
3
|
+
Typical usage::
|
|
4
|
+
|
|
5
|
+
from rn_forge.commons import AppException
|
|
6
|
+
|
|
7
|
+
AppException.check(user_id, "User id is required", error_code=400)
|
|
8
|
+
|
|
9
|
+
raise AppException(
|
|
10
|
+
"Unable to process order {}",
|
|
11
|
+
order_id,
|
|
12
|
+
error_code=409,
|
|
13
|
+
customer_id=customer_id,
|
|
14
|
+
)
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
__all__ = ["AppException"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AppException(Exception):
|
|
23
|
+
"""Base exception with structured error code and contextual data.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
message: Human-readable description; supports ``str.format`` positional args.
|
|
27
|
+
*message_args: Positional arguments forwarded to ``message.format()``.
|
|
28
|
+
error_code: Application-specific integer error code (default ``-1``).
|
|
29
|
+
**error_data: Arbitrary key/value context attached to the exception.
|
|
30
|
+
|
|
31
|
+
Example::
|
|
32
|
+
|
|
33
|
+
raise AppException(
|
|
34
|
+
"Invalid state transition: {} -> {}",
|
|
35
|
+
old_state,
|
|
36
|
+
new_state,
|
|
37
|
+
error_code=1001,
|
|
38
|
+
order_id=order_id,
|
|
39
|
+
)
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
message: str
|
|
43
|
+
error_code: int
|
|
44
|
+
error_data: dict[str, Any]
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
message: str,
|
|
49
|
+
*message_args: Any,
|
|
50
|
+
error_code: int = -1,
|
|
51
|
+
**error_data: Any,
|
|
52
|
+
) -> None:
|
|
53
|
+
self.message = message.format(*message_args)
|
|
54
|
+
self.error_code = error_code
|
|
55
|
+
self.error_data = error_data
|
|
56
|
+
super().__init__(self.message)
|
|
57
|
+
|
|
58
|
+
def __str__(self) -> str:
|
|
59
|
+
return f"{self.error_code} | {self.message} | {self.error_data}"
|
|
60
|
+
|
|
61
|
+
def __repr__(self) -> str:
|
|
62
|
+
return (
|
|
63
|
+
f"{type(self).__name__}("
|
|
64
|
+
f"message={self.message!r}, "
|
|
65
|
+
f"error_code={self.error_code!r}, "
|
|
66
|
+
f"error_data={self.error_data!r})"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def check(cls, value: Any, message: str, *message_args: Any, **kwargs: Any) -> None:
|
|
71
|
+
"""Raise this exception if *value* is falsy.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
value: The value to test.
|
|
75
|
+
message: Exception message (supports positional format args).
|
|
76
|
+
*message_args: Forwarded to ``message.format()``.
|
|
77
|
+
**kwargs: Forwarded as ``error_code`` / ``error_data`` to the constructor.
|
|
78
|
+
|
|
79
|
+
Example::
|
|
80
|
+
|
|
81
|
+
AppException.check(path.exists(), "Missing file: {}", path, error_code=404)
|
|
82
|
+
"""
|
|
83
|
+
if not value:
|
|
84
|
+
raise cls(message, *message_args, **kwargs)
|