"""The pieces every config block is built from.
A block is a frozen dataclass with a `from_dict` that reads the operator's
JSON and a `check` that names every problem in it. Problems are collected,
not raised one at a time: an operator fixes a file once, not one line per
restart. The messages are the interface the tests and the operator read, so
they say which field and what it must be.
"""
from __future__ import annotations
import dataclasses
import json
from typing import Any, Callable, ClassVar, Mapping, Optional, TypeVar
from fleetmesh_core.wire import spelling
T = TypeVar('T', bound='Block')
[docs]class ConfigError(ValueError):
"""config.json says something the node cannot run on. The message lists
every problem, because an operator fixes a file once, not one line per
restart."""
[docs]class Problems:
"""Sentences about what is wrong, in file order."""
[docs] def __init__(self) -> None:
self.items: list[str] = []
[docs] def add(self, sentence: str) -> None:
self.items.append(sentence)
def __bool__(self) -> bool:
return bool(self.items)
def __iter__(self):
return iter(self.items)
[docs]def is_hex64(v: Any) -> bool:
return spelling.is_hex(v, 64)
[docs]def is_int(v: Any) -> bool:
return spelling.is_int(v)
[docs]def is_relay_url(v: Any) -> bool:
return isinstance(v, str) and v.startswith(('ws://', 'wss://'))
[docs]def is_http_url(v: Any) -> bool:
return isinstance(v, str) and v.startswith(('http://', 'https://'))
[docs]def all_str(v: Any) -> bool:
return isinstance(v, list) and all(isinstance(x, str) for x in v)
[docs]def all_int(v: Any) -> bool:
return isinstance(v, list) and all(is_int(x) for x in v)
[docs]def opt(raw: Mapping[str, Any], key: str, pred: Callable[[Any], bool], p: Problems, must: str) -> None:
"""When `key` is present, it has to satisfy `pred`; otherwise say `must`."""
if key in raw and not pred(raw[key]):
p.add(must)
[docs]def positive_int(v: Any) -> bool:
return is_int(v) and v > 0
[docs]def non_negative_int(v: Any) -> bool:
return is_int(v) and v >= 0
[docs]@dataclasses.dataclass(frozen=True)
class Block:
"""A typed section of config.json.
`check(raw, p)` names what is wrong with the raw object; `from_dict(raw)`
builds the block from a raw object that `check` passed. Subclasses write
both: the first is the sentence an operator reads, the second the shape
the compartment reads. `key` is the top-level name the block lives under,
`label` the prefix its sentences use (defaults to the key).
"""
key: ClassVar[str] = ''
label: ClassVar[str] = ''
[docs] @classmethod
def check(cls, raw: Any, p: Problems) -> None:
if not isinstance(raw, Mapping):
p.add('%s must be an object' % (cls.label or cls.key))
[docs] @classmethod
def from_dict(cls: type[T], raw: Any) -> T:
raise NotImplementedError
[docs] @classmethod
def parse(cls: type[T], raw: Any) -> T:
"""check then from_dict, raising ConfigError with every sentence."""
p = Problems()
cls.check(raw, p)
if p:
raise ConfigError('; '.join(p))
return cls.from_dict(raw)
[docs] def to_dict(self) -> Mapping[str, Any]:
"""The JSON shape, tuples made lists, as the file would carry it."""
return json.loads(json.dumps(dataclasses.asdict(self)))
__all__ = ['Block', 'ConfigError', 'Problems', 'is_hex64', 'is_int', 'is_relay_url', 'is_http_url', 'all_str',
'all_int', 'opt', 'positive_int', 'non_negative_int', 'Optional']