obj.ConfiguredNode: Add class

Add methods for retrieving configuration values to TreeNode. The main
benefit being that config values are looked up recursively from leaf to
root.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-08-22 08:33:56 +02:00
commit c810655556
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61

View file

@ -0,0 +1,335 @@
from __future__ import annotations
import abc
from collections.abc import Iterable, Iterator, Mapping
from copy import deepcopy
from typing import TYPE_CHECKING, Any, TypeVar, cast, override
from ..log import INFO, log
from .TreeNode import TreeError
from .TreeNode import TreeNode as Base
if TYPE_CHECKING:
from jw.util.App import App
T = TypeVar('T')
class _Missing:
@override
def __repr__(self) -> str:
return 'MISSING'
_MISSING = _Missing()
_RAISE = object()
class AliasCycleError(TreeError):
"""Raised when alias resolution finds a cycle."""
class ConfigLookupError(TreeError, LookupError):
"""Raised when a configuration value cannot be found."""
class ConfigTypeError(TreeError, TypeError):
"""Raised when a configuration value has the wrong type."""
def _is_set(value: Any) -> bool:
"""Return whether a config value is meaningful.
Policy:
- None means "not set"; keep looking / keep the inherited value.
- False, 0, "", [], and {} are meaningful values.
"""
return value is not None
def _key_parts(key: str | Iterable[str]) -> tuple[str, ...]:
if isinstance(key, str):
if not key:
raise ValueError('Configuration key must not be empty')
return tuple(key.split('.'))
ret = tuple(key)
if not ret:
raise ValueError('Configuration key must not be empty')
if not all(isinstance(part, str) and part for part in ret):
raise ValueError(f'Invalid configuration key: {ret!r}')
return ret
def _get_nested(
mapping: Mapping[str, Any],
key: str | Iterable[str],
default: Any = _RAISE,
) -> Any:
parts = _key_parts(key)
ret: Any = mapping
for part in parts:
if not isinstance(ret, Mapping) or part not in ret:
if default is not _RAISE:
return default
raise ConfigLookupError(f'No configuration value for {".".join(parts)!r}')
ret = ret[part]
return ret
def _deep_merge(
base: Mapping[str, Any],
overlay: Mapping[str, Any],
) -> Mapping[str, Any]:
"""Deep-merge overlay into base.
Rules:
- dict + dict: recursive merge
- None in overlay: ignored, meaning "not set"
- any other value in overlay: replaces base value
"""
ret = deepcopy(dict(base))
for key, value in overlay.items():
if not _is_set(value):
continue
previous = ret.get(key, _MISSING)
if isinstance(previous, Mapping) and isinstance(value, Mapping):
ret[key] = _deep_merge(previous, value)
else:
ret[key] = deepcopy(value)
return ret
class ConfiguredNode(Base):
@override
def _log_data(self, buf: ConfiguredNode.LogData) -> None:
super()._log_data(buf)
buf[self._class_path(super())] = {
'app': self.app.__class__.__name__,
'conf': self.conf,
}
def get_conf_value(
self,
key: str | Iterable[str],
default: Any = _MISSING,
) -> Any:
"""Return the nearest meaningful config value for key.
Lookup order is self -> parent -> ... -> root.
None is treated as "not set" and skipped.
"""
for obj in self.iter_lineage():
if not isinstance(obj, ConfiguredNode):
continue
value = _get_nested(obj.conf, key, _MISSING)
if value is not _MISSING and _is_set(value):
return value
if default is not _MISSING:
return default
raise ConfigLookupError(
f'No configuration value for {".".join(_key_parts(key))!r} at '
f'{self.obj_path!r}'
)
def get_merged_conf_value(
self,
key: str | Iterable[str],
default: Any = _MISSING,
) -> Any:
"""Return the effective merged config value for key.
Merge order is root -> ... -> parent -> self.
Dicts are deep-merged. Scalars and lists replace previous values.
None is treated as "not set" and skipped.
"""
ret: Any = _MISSING
for obj in self.iter_lineage():
log(INFO, f'Looking for "{key}" in {obj}')
if not isinstance(obj, ConfiguredNode):
continue
value = _get_nested(obj.conf, key, _MISSING)
if value is _MISSING or not _is_set(value):
continue
if isinstance(value, Mapping):
if isinstance(ret, Mapping):
ret = _deep_merge(ret, value)
else:
ret = deepcopy(dict(value))
else:
ret = deepcopy(value)
if ret is not _MISSING:
return ret
if default is not _MISSING:
return default
raise ConfigLookupError(
f'No merged configuration value for '
f'"{".".join(_key_parts(key))}" at "{self.obj_path}"'
)
@classmethod
def str_or_none_from_conf(
cls, conf: Mapping[str, Any], keys: Iterable[str]
) -> str | None:
for key in keys:
ret = conf.get(key, None)
if ret is not None:
return cast('str', ret)
return None
@classmethod
def str_from_conf(cls, conf: Mapping[str, Any], keys: Iterable[str]) -> str:
ret = cls.str_or_none_from_conf(conf, keys)
if ret is None:
import json
from jw.util.log import ERR, log_m
log_m(
ERR,
json.dumps(
conf, sort_keys = True, indent = 4, separators = (',', ': ')
)
)
missing = ', '.join([f'"{key}"' for key in keys])
raise ValueError(
f'None of the keys {missing} found in config, specify at least one'
)
return ret
def conf_str_or_none(self, keys: Iterable[str]) -> str | None:
return self.str_or_none_from_conf(self.conf, keys)
def conf_str(self, keys: Iterable[str]) -> str:
return self.str_from_conf(self.conf, keys)
@classmethod
def pretty_str_from_conf(cls, conf: Mapping[str, Any]) -> str:
import json
return json.dumps(conf, sort_keys = True, indent = 4, separators = (',', ': '))
@property
def pretty_conf_str(self) -> str:
return self.pretty_str_from_conf(self.conf)
def resolve_alias(self, section: str, name: str) -> str:
"""Resolve name through aliases.<section>.
Aliases are read from the effective merged config, so aliases can be
inherited and overridden throughout the object tree.
A non-aliased name resolves to itself.
"""
aliases = self.get_merged_conf_value(('aliases', section), default = {})
if not isinstance(aliases, Mapping):
raise ConfigTypeError(
f'Expected aliases.{section} at {self.obj_path!r} to be a mapping, '
f'got {type(aliases).__name__}'
)
chain: list[str] = []
while name in aliases:
if name in chain:
cycle_start = chain.index(name)
cycle = ' -> '.join([*chain[cycle_start:], name])
raise AliasCycleError(f'Alias cycle in {section!r}: {cycle}')
chain.append(name)
target = aliases[name]
if not _is_set(target):
# A None alias target means "no alias here"; keep the current name.
break
if not isinstance(target, str):
raise ConfigTypeError(
f'Alias target for aliases.{section}.{name} at {self.obj_path!r} '
f'must be str, got {type(target).__name__}'
)
name = target
return name
def get_conf_section(
self,
section: str,
default: Any = _MISSING,
) -> Mapping[str, Any]:
"""Return an effective merged top-level config section."""
ret = self.get_merged_conf_value(section, default = default)
if ret is default and default is not _MISSING:
return cast('Mapping[str, Any]', ret)
if not isinstance(ret, Mapping):
raise ConfigTypeError(
f'Expected section {section!r} at {self.obj_path!r} to be a mapping, '
f'got {type(ret).__name__}'
)
return cast('Mapping[str, Any]', ret)
def get_conf_section_item(
self,
section: str,
name: str,
expected_type: type[T] | tuple[type[Any], ...] | None = None,
default: Any = _MISSING,
) -> Any:
"""Resolve name via aliases.<section>, then return section[resolved_name]."""
resolved_name = self.resolve_alias(section, name)
section_conf = self.get_conf_section(section, default = {})
ret = section_conf.get(resolved_name, _MISSING)
if ret is _MISSING or not _is_set(ret):
if default is not _MISSING:
return default
raise ConfigLookupError(
f'No item {resolved_name!r} in section {section!r} at '
f'{self.obj_path!r} (resolved from {name!r})'
)
if expected_type is not None and not isinstance(ret, expected_type):
if isinstance(expected_type, tuple):
expected = ' | '.join(t.__name__ for t in expected_type)
else:
expected = expected_type.__name__
raise ConfigTypeError(
f'Expected {section}.{resolved_name} at {self.obj_path!r} '
f'to be {expected}, got {type(ret).__name__}'
)
return ret
def iter_conf_section_names(self, section: str) -> Iterator[str]:
"""Iterate names defined in an effective merged section."""
yield from self.get_conf_section(section, default = {}).keys()
@abc.abstractmethod
def _app(self) -> App:
...
@property
def app(self) -> App:
return self._app()
@abc.abstractmethod
def _conf(self) -> Mapping[str, Any]:
...
@property
def conf(self) -> Mapping[str, Any]:
return self._conf()