"""The records config.json carries in lists and maps: an endpoint, a peer to
pull from, a coverage claim, a trust decision, a retention rule, and the two
small objects the node itself reads (face, policy).
These are read in many places - `peers` in five compartments, `coverage` in
four - and before this each reader implied its own shape. One dataclass per
record is the shape.
"""
from __future__ import annotations
import dataclasses
from typing import Any, Mapping, Optional
from .base import Block, Problems, all_str, is_hex64, is_int, non_negative_int, opt, positive_int
TIERS: tuple[str, ...] = ('probation', 'member', 'trusted', 'anchor')
CLASSES: tuple[str, ...] = ('leaf', 'edge', 'anchor')
COMPLETENESS: tuple[str, ...] = ('asserted', 'best-effort')
HANDOVER: tuple[str, ...] = ('offer', 'never')
[docs]@dataclasses.dataclass(frozen=True)
class Endpoint(Block):
"""One way to reach this node: `{transport, address[, priority]}`."""
transport: str
address: str
priority: int = 50
[docs] @classmethod
def check(cls, raw: Any, p: Problems) -> None:
# The list check names the whole list once; see NodeConfig.
pass
[docs] @classmethod
def from_dict(cls, raw: Any) -> 'Endpoint':
return cls(transport=raw['transport'], address=raw['address'], priority=int(raw.get('priority', 50)))
[docs]@dataclasses.dataclass(frozen=True)
class PeerPull(Block):
"""A peer this node pulls a shard from: `{pubkey, shard, filter[, pull_every, window]}`."""
pubkey: str
shard: str
filter: Mapping[str, Any]
pull_every: int = 900
window: Optional[int] = None # the peering manifest's budget.window, seconds
[docs] @staticmethod
def check_one(i: int, e: Any, p: Problems) -> None:
if not isinstance(e, Mapping) or not is_hex64(e.get('pubkey')) or not isinstance(e.get('shard'), str) \
or not isinstance(e.get('filter'), dict):
p.add('peers[%d] must be {pubkey (64 hex), shard, filter (object)[, pull_every]}' % i)
elif 'pull_every' in e and not positive_int(e['pull_every']):
p.add('peers[%d].pull_every must be a positive integer' % i)
[docs] @classmethod
def from_dict(cls, raw: Any) -> 'PeerPull':
return cls(pubkey=raw['pubkey'], shard=raw['shard'], filter=dict(raw['filter']),
pull_every=int(raw.get('pull_every', 900)), window=raw.get('window'))
[docs]@dataclasses.dataclass(frozen=True)
class CoverageClaim(Block):
"""A shard this node tells the mesh it holds, as a kind 30803 claim."""
shard: str
filter: Mapping[str, Any]
completeness: str = 'best-effort'
since: Optional[int] = None
until: Optional[int] = None
[docs] @staticmethod
def check_one(i: int, e: Any, p: Problems) -> None:
if not isinstance(e, Mapping) or not isinstance(e.get('shard'), str) or not isinstance(e.get('filter'), dict) \
or e.get('completeness', 'best-effort') not in COMPLETENESS:
p.add('coverage[%d] must be {shard, filter (object)[, completeness asserted|best-effort]}' % i)
[docs] @classmethod
def from_dict(cls, raw: Any) -> 'CoverageClaim':
return cls(shard=raw['shard'], filter=dict(raw['filter']), completeness=raw.get('completeness', 'best-effort'),
since=raw.get('since'), until=raw.get('until'))
[docs]@dataclasses.dataclass(frozen=True)
class TrustDecision(Block):
"""An operator's out-of-band decision about a peer: a tier, and when."""
tier: str
at: int = 0
[docs] @staticmethod
def check_one(pk: Any, e: Any, p: Problems) -> None:
tier = e.get('tier') if isinstance(e, Mapping) else e
if not is_hex64(pk) or tier not in TIERS or (isinstance(e, Mapping) and not is_int(e.get('at', 0))):
p.add('trust[%s] must be a tier name or {tier, at}' % str(pk)[:16])
[docs] @classmethod
def from_dict(cls, raw: Any) -> 'TrustDecision':
if isinstance(raw, Mapping):
return cls(tier=raw['tier'], at=int(raw.get('at', 0)))
return cls(tier=raw)
# How far in the future the relay face accepts an event. The face constant
# (fleetmesh_node/relayserver.py) is defined from this one: the config layer imports
# nothing that reaches a crypto dependency, so a tool that only reads config
# needs none.
FACE_FUTURE_MAX_SECONDS: int = 900
[docs]@dataclasses.dataclass(frozen=True)
class FaceConfig(Block):
"""The relay face: where it listens and how far in the future it accepts."""
key = 'face'
host: str = '127.0.0.1'
port: int = 0
future_seconds: int = FACE_FUTURE_MAX_SECONDS
# Plan D6: where the network compartment writes the merged roster
# ({network_id: [pubkeys]}, replaced atomically) for a roster-protected
# relay beside this node - the fleetmesh-strfry plugin reads it as
# `roster_file`. None: nothing is exported.
roster_export_path: Optional[str] = None
[docs] @classmethod
def check(cls, raw: Any, p: Problems) -> None:
if not isinstance(raw, Mapping) or not isinstance(raw.get('host', '127.0.0.1'), str) \
or not is_int(raw.get('port', 0)) or not 0 <= raw.get('port', 0) <= 65535:
p.add('face must be {host, port} with a port from 0 to 65535')
elif 'future_seconds' in raw and not non_negative_int(raw['future_seconds']):
p.add('face.future_seconds must be a non-negative integer')
elif raw.get('roster_export_path') is not None and not (
isinstance(raw['roster_export_path'], str) and raw['roster_export_path']):
p.add('face.roster_export_path must be a non-empty path')
[docs] @classmethod
def from_dict(cls, raw: Any) -> 'FaceConfig':
return cls(host=raw.get('host', '127.0.0.1'), port=int(raw.get('port', 0)),
future_seconds=int(raw.get('future_seconds', FACE_FUTURE_MAX_SECONDS)),
roster_export_path=raw.get('roster_export_path') or None)
[docs]@dataclasses.dataclass(frozen=True)
class VisibilityConfig(Block):
"""Whether this node is reachable in public, and per-unit overrides.
Mirrors the two kind 11801 tags one for one: `default` is the `visibility`
tag (absent means public), and each entry of `overrides` is one `expose`
tag. An override key is a fleetmesh protocol identifier, a plain
capability (relay, negentropy, blossom, ...) or an app URI - the same
"protocol or app URI" the `expose` tag takes. An empty block means the
default: public, nothing overridden.
"""
key = 'visibility'
label = 'visibility'
default: str = 'public'
overrides: Mapping[str, str] = dataclasses.field(default_factory=dict)
[docs] @staticmethod
def normalize(raw: Any) -> 'VisibilityConfig':
"""The typed block from a raw object; ValueError on anything wrong."""
if not isinstance(raw, Mapping):
raise ValueError('visibility must be an object {default, overrides}')
unknown = sorted(k for k in raw if k not in ('default', 'overrides'))
if unknown:
raise ValueError('visibility has no key %s (only default, overrides)' % ', '.join(unknown))
default = raw.get('default', 'public')
if default not in ('public', 'private'):
raise ValueError('visibility.default must be public or private')
ovr = raw.get('overrides') or {}
if not isinstance(ovr, Mapping):
raise ValueError('visibility.overrides must be an object of uri -> public|private')
out: dict[str, str] = {}
for unit, value in ovr.items():
if not isinstance(unit, str) or not unit:
raise ValueError('visibility.overrides keys must be non-empty strings')
if value not in ('public', 'private'):
raise ValueError('visibility.overrides[%s] must be public or private' % unit[:64])
out[unit] = value
return VisibilityConfig(default=default, overrides=out)
[docs] @classmethod
def check(cls, raw: Any, p: Problems) -> None:
try:
cls.normalize(raw)
except ValueError as e:
p.add(str(e))
[docs] @classmethod
def from_dict(cls, raw: Any) -> 'VisibilityConfig':
return cls.normalize(raw)
[docs] @classmethod
def merge(cls, raw: Any, default: Any = None, overrides: Any = None) -> 'VisibilityConfig':
"""The block after `default` and `overrides` are applied to `raw`.
`overrides` merges into what `raw` carried: a value of None removes one.
Raises ValueError on anything wrong, the caller's to turn into a refusal.
"""
base = cls.from_dict(raw) if isinstance(raw, Mapping) else cls()
out_overrides: Mapping[str, str] = dict(base.overrides)
if overrides is not None:
if not isinstance(overrides, Mapping):
raise ValueError('overrides must be an object of {protocol or app URI: public|private}; a null value clears one')
edited: dict[str, str] = dict(out_overrides)
for unit, value in overrides.items():
if not isinstance(unit, str) or not unit:
raise ValueError('an override key must be a non-empty protocol or app URI')
if value is None:
edited.pop(unit, None)
else:
edited[unit] = str(value)
out_overrides = edited
merged_default = str(default) if default is not None else base.default
return cls.normalize({'default': merged_default, 'overrides': dict(out_overrides)})
from .parameter import Parameter, ParamBlock
[docs]@dataclasses.dataclass(frozen=True)
class PolicyConfig(ParamBlock):
"""Whether strangers may enrol, and which protocols a peer must speak."""
key = 'policy'
open_enrolment: bool = True
protocols: tuple[str, ...] = ()
DERIVED: bool = False
PARAMS = (
Parameter(
key='open_enrolment', name='Open Enrolment',
description='Whether strangers may enrol without prior grant',
type=bool, default=True, tags=('peering', 'policy'),
),
Parameter(
key='protocols', name='Required Protocols',
description='Protocols a peer must speak to peer with this node',
type=list, item=str, default=(), tags=('peering', 'policy'),
),
)
[docs] @classmethod
def check(cls, raw: Any, p: Problems) -> None:
if not isinstance(raw, Mapping) or not isinstance(raw.get('open_enrolment', True), bool):
p.add('policy must be an object with a boolean open_enrolment')
else:
opt(raw, 'protocols', all_str, p, 'policy.protocols must be a list of identifiers')
[docs] @classmethod
def from_dict(cls, raw: Any) -> 'PolicyConfig':
return cls(open_enrolment=bool(raw.get('open_enrolment', True)), protocols=tuple(raw.get('protocols') or ()))
__all__ = ['Endpoint', 'PeerPull', 'CoverageClaim', 'TrustDecision', 'FaceConfig', 'PolicyConfig', 'VisibilityConfig',
'TIERS', 'CLASSES', 'COMPLETENESS', 'HANDOVER']