"""The shared surface a compartment is built from.
Every compartment used to be constructed by hand in fleetmesh_node/app/core.py from
whichever of the node's stores and services it happened to need, in one of
six different signature styles, with `node=self` passed alongside so the
compartment could reach anything the signature forgot. `NodeContext` is the
one typed object that replaces that: the stores, the transport, the face, the
clock, the config, and the handful of node-level callables a compartment
still has to reach. A compartment's `from_context(ctx)` says, in one place,
what it takes from the node, and a third party writing a compartment against
`subsystem/1` has a stable thing to write against.
`node` stays on the context as a labelled escape hatch, not a hidden one:
`scheduler` calls `node.propose`/`node.pull` and `trust` calls
`node.regrant`, which are NodeApp methods and not stores. Anything reaching
for `ctx.node` beyond those is a dependency that should be named here instead.
Standard library only.
"""
from __future__ import annotations
import os
import threading
from dataclasses import dataclass, field
from typing import Any, Callable, Mapping, NamedTuple, Optional, Sequence, TypeVar
from ..channels import NodeEventBus
from ..interfaces import NostrEvent
from ..config.base import Block
from ..config.node import NodeConfigDict
[docs]class NodeStores(NamedTuple):
"""The four durable stores a node keeps, as one argument."""
events: Any # eventstore.NodeStore
grants: Any # grants.GrantStore
accounts: Any # accounts.AccountStore
blobs: Any # blobstore.BlobStore
def _no_descriptor() -> Optional[NostrEvent]:
return None
B = TypeVar('B', bound=Block)
[docs]@dataclass
class NodeContext:
"""Explicit, typed context handed to every compartment at assembly.
`cfg` is the live config dict the node mutates on reload; a compartment
that must see changes reads through `cfg_of(key)` on each tick rather than
copying a section at construction. `descriptor` is a getter because the
descriptor is mined or loaded in start() and does not exist at the time
the context is made.
"""
dir: str
ks: Any # keystore.Keystore
cfg: NodeConfigDict
clock: Callable[[], int]
events: NodeEventBus
stores: NodeStores
relays: list[str]
transport: Optional[Any] = None # transport.TransportRouter
router: Optional[Any] = None # router.ProtocolRouter
face: Optional[Any] = None # relayserver.RelayServer
host: Optional[Any] = None # transport.host.ProtocolHostRouter
peers: Optional[Any] = None # peers.Peers
policy: Optional[Any] = None # fleetmesh_core.peering.Policy
ledger: Optional[Any] = None # fleetmesh_core.accounting.standing.Ledger
timeout: float = 15.0
stop: threading.Event = field(default_factory=threading.Event)
descriptor: Callable[[], Optional[NostrEvent]] = _no_descriptor
# The public copy of the descriptor, or None when this node publishes no
# public descriptor at all (plan D2: a fully private node). Every
# publication that reaches the public relays goes through this.
public_descriptor: Callable[[], Optional[NostrEvent]] = _no_descriptor
digest: Optional[str] = None # schema digest this node speaks
node: Optional[Any] = None # the NodeApp; see module docstring
says: Optional[Any] = None # node log / channels router
# Write `cfg` back to the node directory. A compartment that changes
# what this node claims (coverage, a price) calls this rather than
# importing the app's config writer - the node owns its directory and
# the file is what the next tick reads. No-op outside a running node.
persist_cfg: Callable[[], None] = lambda: None
# Rebuild and republish the descriptor from what the compartments say
# now. For a compartment whose declaration can change after start (a
# sidecar whose self-tests begin or stop passing). No-op outside a
# running node, where there is no descriptor to correct.
redescribe: Callable[[], Any] = lambda: None
# Node-internal methods reached by compartments:
regrant: Callable[..., Any] = lambda *a, **kw: None
propose: Callable[..., Any] = lambda *a, **kw: ('declined', None)
pull: Callable[..., Any] = lambda *a, **kw: {}
amend: Callable[..., Any] = lambda *a, **kw: (None, None)
# the one wire door for control commands (app/control.py; remote's control/1.0)
wire_request: Callable[..., Any] = lambda *a, **kw: None
build_descriptor: Callable[[], Any] = lambda: None
@property
def _amend(self) -> Callable[..., Any]:
return self.amend
# ---- derived -------------------------------------------------------------
@property
def pubkey(self) -> str:
return getattr(self.ks, 'node_pk', '')
@property
def did(self) -> str:
return getattr(self.ks, 'did', '')
@property
def node_class(self) -> str:
return str(self.cfg.get('class', 'edge'))
[docs] def cfg_of(self, key: str, default: Any = None) -> Any:
"""A top-level config key as it is *now*, for compartments that read
live. The same contract `Compartment.config()` keeps."""
return self.cfg.get(key, default)
[docs] def cfg_getter(self) -> Callable[[], Mapping[str, Any]]:
"""The `lambda: self.cfg` several compartments take, named."""
return lambda: self.cfg
[docs] def block(self, block_cls: type[B]) -> B:
"""A compartment's config section as its typed block, *now*.
`block_cls.key` names the section; an absent section is the default
block. The file was checked at the door (load_config) and on every
reload, so from_dict here cannot meet a shape it refuses - a block
that reads live calls this each tick and gets the current values.
"""
raw = self.cfg.get(block_cls.key)
return block_cls.from_dict({} if raw is None else raw)
[docs] def block_getter(self, block_cls: type[B]) -> Callable[[], B]:
"""`lambda: ctx.block(cls)`, for a compartment that reads live."""
return lambda: self.block(block_cls)
[docs] def path(self, *parts: str) -> str:
return os.path.join(self.dir, *parts)
[docs] def optional(self, name: str) -> Optional[Any]:
"""A compartment named in the caller's `uses`, if the node built it;
None when it is off. Resolved once at construction: the manifest
orders `uses` before the user, so a present one is already built.
Tests that assemble without a node fall back to the attribute set on
`node` by assemble(), which is the same object either way."""
reg = getattr(self, '_registry', None)
if reg is not None:
res = reg.get(name)
if res is not None:
return res
registry = getattr(self.node, 'subsystems', None) if self.node is not None else None
if registry is not None:
res = registry.get(name)
if res is not None:
return res
return getattr(self.node, name, None) if self.node is not None else None
# ---- the previous keyword-style constructor, kept for callers ------------
[docs] @classmethod
def build(cls, directory: str, ks: Any, cfg: NodeConfigDict, clock: Callable[[], int],
events: NodeEventBus, stores: NodeStores, relays: Sequence[str],
transport: Optional[Any] = None, router: Optional[Any] = None, **more: Any) -> NodeContext:
return cls(dir=directory, ks=ks, cfg=cfg, clock=clock, events=events, stores=stores,
relays=list(relays), transport=transport, router=router, **more)