Source code for boss.configuration

import json

from heros import HERORef

from .factory import DatasourceHEROFactory, HEROFactory, PolledDatasourceHEROFactory
from .helper import file_from_url, get_class_by_name, get_remote_hero, log


[docs] def _heroref_arguments(classname: str) -> frozenset[str]: """ Return the argument names in which a HERO class receives HERORef values instead of RemoteHEROs. The names are read from the class attribute ``_boss_heroref_arguments`` of the class given by ``classname``. With ``wrap_target`` set, this is the unwrapped class. Names that match no argument are ignored. Args: classname: dotted name of the class to be built Returns: The argument names, empty if the class has no ``_boss_heroref_arguments``. Raises: TypeError: if ``_boss_heroref_arguments`` is a single string or contains a name that is not a string. """ names = getattr(get_class_by_name(classname), "_boss_heroref_arguments", ()) if isinstance(names, str): raise TypeError(f"_boss_heroref_arguments of {classname} must be an iterable of names, not a single string") names = frozenset(names) if bad := sorted(repr(name) for name in names if not isinstance(name, str)): raise TypeError(f"_boss_heroref_arguments of {classname} must contain only strings, got {', '.join(bad)}") return names
[docs] def _resolve_references(value: object, realm: str, *, as_ref: bool = False) -> object: """ Replace ``$name`` strings at any depth with remote HEROs or, with ``as_ref``, with HERORef values. A leading ``$$`` is an escape: one ``$`` is stripped and the string is passed on literally. Dict keys are not resolved. Containers are rebuilt, the input is not modified. Args: value: argument value, possibly a nested dict, list or tuple realm: realm in which the referenced HEROs are looked up or which the HERORef values carry as_ref: build ``HERORef(name, realm)`` instead of looking up a RemoteHERO Returns: The value with all references resolved. """ if isinstance(value, str): if value.startswith("$$"): return value[1:] if value.startswith("$"): if as_ref: return HERORef(value[1:], realm) return get_remote_hero(value[1:], realm=realm) return value if isinstance(value, dict): return {key: _resolve_references(val, realm, as_ref=as_ref) for key, val in value.items()} if isinstance(value, list): return [_resolve_references(item, realm, as_ref=as_ref) for item in value] if isinstance(value, tuple): return tuple(_resolve_references(item, realm, as_ref=as_ref) for item in value) return value
[docs] class Document(dict):
[docs] @classmethod def parse_string(cls, s: str): """ Parse a document in JSON format from a string. Args: s: string containing the JSON representation of the config """ try: obj = cls() obj.update(json.loads(s)) return obj except json.JSONDecodeError as e: log.error(f"Error while encoding json: {e}")
[docs] @classmethod def parse_url(cls, url: str): """ Parse a document in JSON format from a URL. Args: url: any URL supported by urllib (e.g. file://local.json or https://user:pass@couch.db/database/my_doc) """ f_handle = file_from_url(url) return cls.parse_string(f_handle.read())
[docs] class WorkerConfigurationDocument(Document):
[docs] def datasource_config(self): if "datasource" in self and isinstance(self["datasource"], dict): cfg = {"async": False, "interval": 5.0, "observables": {}} cfg.update(self["datasource"]) return cfg else: return None
[docs] def generate_tags(self, boss_name): """Add boss/configuration specific tags to the HERO.""" if "tags" not in self: self["tags"] = [] self["tags"].append(f"BOSS: {boss_name}")
[docs] def build_hero_for_worker(self, boss_name: str, worker_object, realm="heros"): # replace special string for asyncio loop and multiprocess pool self.generate_tags(boss_name) arguments = { key: worker_object._loop if val == "@_boss_loop" else val for key, val in self["arguments"].items() } heroref_arguments = _heroref_arguments(self["classname"]) self["arguments"] = { key: _resolve_references(val, realm, as_ref=key in heroref_arguments) for key, val in arguments.items() } base_config = { "classname": self["classname"], "arg_dict": self.get("arguments", {}), "extra_decorators": self.get("extra_decorators", {}), "wrap_target": self.get("wrap_target", None), "name": self["_id"], "realm": realm, "tags": self["tags"], } if (datasource_config := self.datasource_config()) is not None: if datasource_config["async"]: return DatasourceHEROFactory.build( **base_config, observables=datasource_config["observables"], ) else: return PolledDatasourceHEROFactory.build( **base_config, loop=worker_object._loop, interval=datasource_config["interval"], observables=datasource_config["observables"], ) else: return HEROFactory.build(**base_config)