Source code for fleetmesh_node.compartment.base

"""BASE: the abstract compartment every mechanism in this node extends.

A compartment is one mechanism of the node - link, budget, announce - and it
is written as a set of declarations rather than wired into the node by hand.
Six of them, each a tuple of frozen records on the class, each with a census
behind it and a package that defines it:

    PARAMS     what it can be told          its config block (node/config)
    CHANNELS   what it says                 fleetmesh_node/channels
    METRICS    what it measures             fleetmesh_node/metrics
    COMMANDS   what it can be asked to do   fleetmesh_node/compartment/command.py
    LIFECYCLE  how it fails, and restarts   fleetmesh_node/lifecycle
    STORES     what it keeps in memory      fleetmesh_node/stores

The base class is abstract in two senses, both enforced:

  * It cannot be built. `Compartment(node)` raises, and so does any class
    that says `class X(Compartment, abstract=True)` - a KIND of compartment,
    like sidecar_bridge.Bridge, which is extended rather than run.
  * Its declarations are linted when a subclass is DEFINED, not when a node
    happens to build it. A concrete compartment must have a name; a store,
    command, channel or metric must be unique within it; a snapshot must have
    something to carry; a command's `reads`/`writes` must name a store this
    compartment declares, or one of a compartment it `requires` or `uses`.
    A class that breaks one of those fails at import, with every problem
    listed - which is what makes the declarations a lint rather than prose.

And it is a working default for everything a compartment need not say: no
tick, no state, no trouble, and a snapshot derived from its SNAPSHOT stores.
"""
from __future__ import annotations

import threading
import time
from typing import (
    TYPE_CHECKING,
    Any,
    Callable,
    ClassVar,
    Mapping,
    Optional,
    Protocol,
    Sequence,
    TypedDict,
    TypeVar,
    Union,
    runtime_checkable,
)

from ..channels import journal
from . import lifecycle as lifecycle_mod
from . import stores as stores_mod
from ..interfaces import CommandSpec
from .command import Command
from .every import Every
from .problem import (
    Note,
    NoteList,
    Trouble,
    TroubleList,
)
from .refusals import Refusals
from .worker import Worker

T = TypeVar('T', bound='Compartment')


[docs]class EveryJobReport(TypedDict): """One EVERY job as `report()` gives it. `seconds` and `next_run` are None for a job that is off (`Every.is_off`).""" seconds: Optional[Union[int, float]] last_run: Optional[int] next_run: Optional[int]
[docs]def wall() -> int: """The wall clock in whole seconds: every compartment's default clock.""" return int(time.time())
if TYPE_CHECKING: from .registry import Registry
[docs]@runtime_checkable class CompartmentProtocol(Protocol): """The contract the Registry relies on, stated structurally. `Compartment` below is the convenient base class and every compartment in fleetmesh_node/ extends it, but the registry's verbs need only this surface. Naming it lets a test double or a foreign compartment be typed against the contract without inheriting the base. """ # Read-only in the contract: a compartment declares `name: str = 'strain'` # and a plain mutable attribute would make that an invariance mismatch. @property def name(self) -> Optional[str]: ... @property def attr(self) -> Optional[str]: ... @property def requires(self) -> tuple[str, ...]: ... @property def uses(self) -> tuple[str, ...]: ... @property def optional(self) -> bool: ... @property def enabled_by(self) -> Optional[str]: ... @property def reads(self) -> tuple[str, ...]: ... @property def live(self) -> tuple[str, ...]: ... @property def config_cls(self) -> Optional[type[Any]]: ... @property def api(self) -> str: ... @property def protocol(self) -> str: ... @property def piuris(self) -> tuple[str, ...]: ... @property def exact_types(self) -> tuple[str, ...]: ... @property def commands(self) -> Mapping[str, CommandSpec]: ... @property def CHANNELS(self) -> tuple[Any, ...]: ... @property def METRICS(self) -> tuple[Any, ...]: ... @property def COMMANDS(self) -> tuple[Any, ...]: ... @property def EVERY(self) -> tuple[Any, ...]: ... @property def WORKERS(self) -> tuple[Any, ...]: ... @property def LIFECYCLE(self) -> lifecycle_mod.Lifecycle: ... @property def STORES(self) -> tuple[Any, ...]: ... @property def NEEDS(self) -> tuple[Any, ...]: ... @property def SCHEMA(self) -> tuple[Any, ...]: ... @property def MIGRATIONS(self) -> tuple[Any, ...]: ... @property def HANDLERS(self) -> tuple[Any, ...]: ... @property def holdings(self) -> Optional[stores_mod.Holdings]: ... @property def db(self) -> Any: ... @property def refusals(self) -> Refusals: ... @property def cli(self) -> tuple[tuple[str, Callable[..., Any]], ...]: ... @property def sidecars(self) -> tuple[Any, ...]: ...
[docs] def wire(self, registry: 'Registry', ctx: Any) -> None: ...
[docs] def start(self) -> None: ...
[docs] def start_workers(self) -> None: ...
[docs] def stop_workers(self) -> None: ...
[docs] def tick(self, now: int) -> list[tuple[Any, ...]]: ...
[docs] def run_tick(self, now: int) -> list[tuple[Any, ...]]: ...
[docs] def stop(self) -> Any: ...
[docs] def state(self) -> Mapping[str, Any]: ...
[docs] def trouble(self) -> list[str]: ...
[docs] def notes(self) -> list[str]: ...
[docs] def report(self) -> Mapping[str, Any]: ...
[docs] def sections(self) -> Mapping[str, Any]: ...
[docs] def snapshot(self) -> Mapping[str, Any]: ...
[docs] def restore(self, state: Mapping[str, Any]) -> None: ...
[docs] def command(self, name: str, args: Mapping[str, Any]) -> Any: ...
[docs] def handle(self, inbound: Any) -> Any: ...
[docs] def capability_protocols(self) -> Sequence[str]: ...
[docs] def descriptor_tags(self) -> Sequence[Sequence[str]]: ...
[docs]class Compartment: """One compartment of the node. Assembled, ticked and read uniformly. The `subsystem/1` declaration. Every compartment states, as class attributes, what it is and what it needs, and `Registry.assemble()` reads those to build the node in dependency order: name the one word the CLI, status.json and the docs use requires names of compartments this one must be built after (it receives them already constructed through ctx) uses names of OPTIONAL compartments this one reaches when they are present; it must still work without them. The assembler holds them to the same manifest order as `requires` (listed earlier) but does not demand they be built. Resolve each once in `from_context` with `ctx.optional(name)`; never probe the node per call. optional True if the node runs without it; it is then built only when `enabled_by` names a config section that is present enabled_by the config key whose presence turns an optional one on reads / live config keys read; of those, the ones re-read each tick api the declaration version this class was written against protocol the schema digest it was built against, or '' if it reads no schema (checked at assembly when set) piuris the wire protocols (PIURI prefixes) this one handles; the registry routes each to its `handle(inbound)` exact_types whole message types it handles, routed exactly `from_context(ctx)` is the one constructor the assembler calls. The default forwards to `cls(node=ctx.node)` so a compartment that has not been migrated still builds; a migrated one overrides it and names its dependencies there and nowhere else. """ API: str = 'subsystem/1' # How far back `trouble` looks. Long enough to catch a fault that recurs on # a slow cadence - receipts go every ten minutes - and short enough that a # fault which has stopped stops being reported. TROUBLE_WINDOW: int = 1800 name: Optional[str] = None attr: Optional[str] = None # attribute the node keeps it under, when not `name` requires: tuple[str, ...] = () # compartments built before this one uses: tuple[str, ...] = () # optional compartments reached when present optional: bool = False # off unless `enabled_by` is configured enabled_by: Optional[str] = None # config key that turns an optional one on reads: tuple[str, ...] = () # config keys this compartment reads live: tuple[str, ...] = () # of those, the ones a running node re-reads each tick config_cls: Optional[type[Any]] = None # the node/config Block that types this one's own key api: str = API protocol: str = '' # schema digest built against, or '' piuris: tuple[str, ...] = () # PIURI prefixes routed to handle() exact_types: tuple[str, ...] = () # exact message types routed to handle() commands: Mapping[str, CommandSpec] = {} # name -> {'args': {...}, 'does': str, 'reply': str} # What this compartment can say, declared here rather than as a topic name # in a central list. A Channel carries both renderings - the structured # payload a reader gets and the line a person reads - so an event cannot # reach the control socket and miss the journal, which is what 45 # journal.line call sites against 6 bus emits had already produced. See # fleetmesh_node/channels.py. CHANNELS: tuple[Any, ...] = () # What this compartment measures. fleetmesh_node/metrics reads it through # getattr(obj, 'METRICS', ()), so the census never needed the default - # which is exactly why its absence went unnoticed until something asked a # compartment for `c.METRICS` directly and got AttributeError on 27 of # 29. Four surfaces, four defaults: a declaration surface that is only # present when used is not a surface. METRICS: tuple[Any, ...] = () COMMANDS: tuple[Any, ...] = () EVERY: tuple[Any, ...] = () WORKERS: tuple[Any, ...] = () # How this compartment behaves when it fails: the breaker that turns # repeated tick failures into a quarantine with backoff. The default # suits nearly every compartment; one that must be ticked whatever # happens declares Lifecycle(breaker=Breaker(failures=0)). See # fleetmesh_node/lifecycle. LIFECYCLE: lifecycle_mod.Lifecycle = lifecycle_mod.DEFAULT # What this compartment keeps: every collection that grows with the # outside world, with its bound and what happens at it. The base builds # one container per store and binds it as `self.<key>`, so the # declaration is also the allocation and the two cannot drift. See # fleetmesh_node/stores. STORES: tuple[stores_mod.Store, ...] = () # What this compartment takes from the node: its dependencies, declared # where the compartment is. The base `from_context` resolves each against # the NodeContext at assembly. See fleetmesh_node/compartment/need.py. NEEDS: tuple[Any, ...] = () # What this compartment persists: relational database schema, declared # as Table and Index entries. The base instantiates a database adapter # (sqlite, psql, etc.) bound to the compartment. SCHEMA: tuple[Any, ...] = () # Schema evolution: versioned migrations applied in order by the database # adapter after SCHEMA. MIGRATIONS: tuple[Any, ...] = () # Inbound wire protocol message handlers, dispatched by base handle(inbound). HANDLERS: tuple[Any, ...] = () # CLI extension verbs declared by a plugin or compartment: (('verb', register_fn),) cli: tuple[tuple[str, Callable[..., Any]], ...] = () # Sidecar manifests declared by a plugin or compartment: ({...}, '@/path/to/manifest.json') sidecars: tuple[Any, ...] = () # Runtime collections, database adapter, and refusals buffer bound to this instance holdings: Optional[stores_mod.Holdings] = None db: Any = None # The store class a compartment's `db` must be, when it is not the generic # adapter. from_context fills a `db` parameter, and without this it filled # it with a SqliteAdapter whatever the class used it as - so Updates, which # reads `db` as an UpdateStore, could not be built by a running node at # all (audit 2026-10-15, B13). Named here, the store is opened as that # class, through the node's locator like every other store. # # Naming it also says the compartment owns its store: the base opens one # only to hand to a `db` parameter, never on its own account. A class that # declares SCHEMA and builds its own store used to get one or two generic # adapters as well, which nothing read - an orphan `<name>.sqlite` on disk # and a handle left to the collector (B5). STORE_CLS: Optional[type] = None refusals: Refusals = None # type: ignore[assignment] # Set from the class keyword: `class Bridge(Compartment, abstract=True)`. # Read from the class's own __dict__, so a concrete subclass of an # abstract kind is concrete without saying so. abstract: ClassVar[bool] = True def __init_subclass__(cls, abstract: bool = False, **kw: Any) -> None: """Derive what is derived, then lint what is declared. Derived: `commands` from `COMMANDS`, so the control socket and the CLI never need a hand-written dict beside the declarations; and `live` for this compartment's own config key from its parameters (see `_derive_live`). Linted: everything in `declaration_problems`. A problem is a TypeError naming the class and every problem at once, raised here - at import - so a malformed compartment never reaches a node. """ super().__init_subclass__(**kw) cls.abstract = abstract # Read before `commands` is derived, which writes it into __dict__. hand_written = 'commands' in cls.__dict__ if cls.COMMANDS: cls.commands = {c.key: c.to_spec(subsystem=cls.name or '') for c in cls.COMMANDS if isinstance(c, Command)} if cls.HANDLERS and 'exact_types' not in cls.__dict__: exact_from_handlers = tuple( h.kind for h in cls.HANDLERS if getattr(h, 'exact', False) or getattr(h, 'kind', '').startswith(('http://', 'https://')) ) if exact_from_handlers: cls.exact_types = tuple(sorted(set(cls.exact_types + exact_from_handlers))) cls._derive_live() problems = cls.declaration_problems() if cls.COMMANDS and hand_written: problems.append('a compartment that declares COMMANDS does not also write `commands`: ' 'it is derived from them') if problems: raise TypeError('%s declares what it cannot be:\n %s' % (cls.__qualname__, '\n '.join(problems))) @classmethod def _derive_live(cls) -> None: """`live` for this compartment's own config key, from its parameters. `live` named the config keys a running node re-reads each tick, and `Parameter.live` says the same thing per setting - two expressions of one fact, kept in step by hand. The parameters win: whether a reload reaches a value is a property of the value, and the compartment's tuple was the copy. Only the compartment's OWN key is derived, and only when its block states parameters. Other keys in `live` belong to blocks this compartment merely reads (`scheduler` re-reads `peers`, which is a NodeConfig field and not its own block) and stay declared. """ blk = cls.config_cls params = getattr(blk, 'PARAMS', None) own = getattr(blk, 'key', '') if blk is not None else '' if params is None or not own: return rest = tuple(k for k in (cls.live or ()) if k != own) cls.live = rest + ((own,) if any(p.live for p in params) else ())
[docs] @classmethod def declaration_problems(cls) -> list[str]: """Everything wrong with this class's declarations, as sentences. Collected rather than raised one at a time, like `Metric.problems` and `config.Problems`: whoever fixes one wants to see them all. Returns Problems (a list subclass) holding typed Problem instances. """ from . import lint as lint_mod return lint_mod.declaration_problems(cls, Compartment)
[docs] @classmethod def store_refs(cls) -> tuple[tuple[str, str, str], ...]: """(command, compartment, store) for every store of ANOTHER compartment this one's commands read.""" out: list[tuple[str, str, str]] = [] for c in cls.COMMANDS: if isinstance(c, Command): for ref in c.reads: other, dot, key = ref.partition('.') if dot: out.append((c.key, other, key)) return tuple(out)
[docs] def __new__(cls, *args: Any, **kw: Any) -> 'Compartment': if cls.__dict__.get('abstract', False): raise TypeError('%s is abstract: extend it, with a name, rather than build it' % cls.__name__) return super().__new__(cls)
[docs] def __init__( self, node: Any = None, clock: Optional[Callable[[], int]] = None, cfg: Optional[Mapping[str, Any] | Callable[[], Mapping[str, Any]]] = None, says: Optional[Any] = None, db: Optional[Any] = None, ) -> None: self.node: Any = node # The clock every compartment reads: the node's (`ctx.clock`), or the # wall in whole seconds. 28 of 29 compartments took one and 25 wrote # the same default by hand, after this ran - which is why the ledger # below used to reach for `getattr(self, 'clock', time.time)`. It is # still read late, through `self.clock`, so a suite that swaps the # clock on a built compartment moves the refusals with it. self.clock: Callable[[], int] = clock or wall self._injected_cfg: Optional[Mapping[str, Any] | Callable[[], Mapping[str, Any]]] = cfg self._injected_says: Optional[Any] = says self.refusals: Refusals = Refusals(self.name, clock=lambda: int(self.clock())) # One container per declared store, each bound under its key. A # subclass that assigns `self.<key>` afterwards has replaced the # container with something unbounded; Registry.add refuses that. self.holdings: stores_mod.Holdings = stores_mod.Holdings(self.STORES) for key, container in self.holdings.items(): setattr(self, key, container) self._every_last: dict[str, int] = {} self._stop_event: threading.Event = threading.Event() self._worker_threads: dict[str, threading.Thread] = {} if db is not None: self.db: Any = db elif getattr(self, 'db', None) is not None: pass # Already initialized by subclass elif self.SCHEMA and self.STORE_CLS is None: self.db = type(self).open_store(getattr(node, 'locator', None), getattr(node, 'dir', None), self.clock) else: self.db = None
[docs] @classmethod def open_store(cls, locator: Any, directory: Optional[str], clock: Callable[[], int]) -> Any: """This compartment's store, where the node keeps it. The one place a compartment's database is opened: `__init__` and `from_context` each had a copy of this, and both ran for one build (audit D5). STORE_CLS when named, else the generic adapter over SCHEMA. Through the node's locator when it has one, its directory when not, and in memory for a compartment built with neither, as a suite builds it. """ from ..storage.adapter import SqliteAdapter, adapter_from_locator from ..storage.locator import Locator if locator is None and directory: locator = Locator.from_config(directory) name = cls.name or 'store' if cls.STORE_CLS is not None: return locator.open(cls.STORE_CLS, name) if locator is not None else cls.STORE_CLS(':memory:') if locator is not None: return adapter_from_locator(locator, name, schema=cls.SCHEMA, migrations=cls.MIGRATIONS, clock=clock) return SqliteAdapter(':memory:', schema=cls.SCHEMA, migrations=cls.MIGRATIONS, clock=clock)
@property def stop_event(self) -> threading.Event: return self._stop_event @property def stopping(self) -> bool: return self._stop_event.is_set()
[docs] def relay_destination(self, default: Optional[Sequence[str]] = None) -> list[str]: """Where this node's own signed events go (plan D2): the node decides - its public relays, or its network relays while it is fully private and publishes no public descriptor. A compartment built without a node (a suite) or against a node that does not answer gets `default` (its own configured relays), so nothing changes outside a running node. A node that answers with an empty list means nowhere: a fully private node with no network publishes its peer-directed events to nobody.""" fn = getattr(self.node, 'destination_relays', None) if callable(fn): try: out = fn() except Exception: # noqa: BLE001 - a node in trouble publishes to its own relays out = None if isinstance(out, (list, tuple)): return list(out) return list(default if default is not None else (getattr(self, 'relays', None) or ()))
[docs] @classmethod def from_context(cls: type[T], ctx: Any) -> T: """Build from a NodeContext. When NEEDS is declared, constructs from declarations.""" declared: tuple[Any, ...] = tuple(getattr(cls, 'NEEDS', ()) or ()) if not declared and not cls.SCHEMA: return cls(node=ctx.node) kwargs = {} for need in declared: if not getattr(need, 'late', False): kwargs[need.key] = need.resolve(ctx, cls) import inspect sig = inspect.signature(cls.__init__) params = sig.parameters has_varkw = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) if ('node' in params or has_varkw) and 'node' not in kwargs: kwargs['node'] = getattr(ctx, 'node', None) if ('clock' in params or has_varkw) and 'clock' not in kwargs: kwargs['clock'] = getattr(ctx, 'clock', None) if ('cfg' in params or has_varkw) and 'cfg' not in kwargs: kwargs['cfg'] = getattr(ctx, 'cfg_getter', lambda: getattr(ctx, 'cfg', None))() if ('says' in params or has_varkw) and 'says' not in kwargs: kwargs['says'] = getattr(ctx, 'says', None) or getattr(getattr(ctx, 'node', None), 'says', None) # Opened only for a constructor that takes it. One that does not builds # its own, and a store opened here for it was a handle nobody closed. if cls.SCHEMA and 'db' not in kwargs and ('db' in params or has_varkw): node = getattr(ctx, 'node', None) kwargs['db'] = cls.open_store(getattr(ctx, 'locator', None) or getattr(node, 'locator', None), getattr(ctx, 'dir', None) or getattr(node, 'dir', None), ctx.clock) return cls(**kwargs)
[docs] def settings(self) -> Any: """This compartment's own config block, typed, as the file says now. `config_cls` names the Block; its `key` is read through `config()` so the read is counted against `reads` like any other. Parsed on each call, so a compartment that lists its key in `live` sees an edit without a restart; the others call it once at construction. """ if self.config_cls is None: raise TypeError('%s declares no config_cls' % type(self).__name__) # `or {}` turned `key: false` into `{}`, which a SWITCHABLE block reads # as present - so on (audit 2026-10-15, B6). from_dict already handles # a bare bool, and anything else that is not a mapping, itself; only # an absent key becomes {} here, as it always did. raw = self.config(self.config_cls.key) return self.config_cls.from_dict({} if raw is None else raw)
# ---- lifecycle ----------------------------------------------------------
[docs] def wire(self, registry: 'Registry', ctx: Any) -> None: """Reach the compartments built after this one, once all exist. The assembler builds in tick order and some edges run against it: link records into strain, which ticks later; peering refuses through capacity, built after budget. Each compartment names those edges here, with `registry.get(name)`, and nowhere else - the node used to hold every one of them in one block that nothing checked. Called once, after the whole manifest is built and before `start()`. """
[docs] def start_workers(self) -> None: """Start all declared WORKERS that are not already running.""" if not hasattr(self, '_stop_event'): self._stop_event = threading.Event() self._stop_event.clear() if not hasattr(self, '_worker_threads'): self._worker_threads = {} import inspect for w in getattr(self, 'WORKERS', ()): if not isinstance(w, Worker): continue if not w.should_run(self): continue existing = self._worker_threads.get(w.name) if existing is not None and existing.is_alive(): continue fn = getattr(self, w.run, None) if not callable(fn): continue sig = inspect.signature(fn) target = (lambda f=fn: f(self._stop_event)) if len(sig.parameters) > 0 else fn t = threading.Thread(target=target, name=w.name or f"{self.name or 'compartment'}-{w.run}", daemon=w.daemon) self._worker_threads[w.name] = t t.start()
[docs] def stop_workers(self) -> None: """Signal and join all running worker threads.""" if hasattr(self, '_stop_event'): self._stop_event.set() stop_attr = getattr(self, '_stop', None) if stop_attr is not None and isinstance(stop_attr, threading.Event): stop_attr.set() threads = getattr(self, '_worker_threads', {}) for w in getattr(self, 'WORKERS', ()): if not isinstance(w, Worker): continue t = threads.get(w.name) if t is not None and t.is_alive(): t.join(timeout=w.timeout) # A thread still running after its timeout keeps its handle. Its # handle used to be dropped regardless, so the next start_workers # - a restart after quarantine - found no thread and started a # second copy beside the one still running (audit 2026-10-15, B7). # Kept, start_workers sees it alive and leaves it be; report() # keeps saying it is alive. if t is None or not t.is_alive(): threads.pop(w.name, None)
[docs] def start(self) -> None: """Everything that needs the rest of the node to exist already.""" self.start_workers()
[docs] def run_every(self, now: int) -> list[tuple[Any, ...]]: """Run each declared EVERY job that is due at `now`, recording last run time.""" did: list[tuple[Any, ...]] = [] if not hasattr(self, '_every_last'): self._every_last = {} # Each job on its own: one that raised used to end the tick for every # job after it (audit 2026-10-15, B10). The first raise is kept and # raised once the rest have run, so the registry still counts a failed # tick and its breaker still trips. A job that raised is stamped like # one that ran, so it waits its interval rather than retrying hot. failed: Optional[BaseException] = None for job in getattr(self, 'EVERY', ()): if not isinstance(job, Every): continue if not job.due(self, now): continue self._every_last[job.name] = now try: res = job.execute(self, now) except Exception as e: if failed is None: failed = e continue if res is None: continue if isinstance(res, (list, tuple)): if res and isinstance(res[0], tuple): did.extend(res) elif res and not isinstance(res[0], tuple): did.append(tuple(res)) elif isinstance(res, dict): rep = None if job.report is not None: if callable(job.report): rep = job.report(self, res) else: rep = getattr(self, job.report)(res) else: reporter = getattr(self, f'_report_{job.run}', None) if reporter is not None: rep = reporter(res) if rep: if isinstance(rep, (list, tuple)): did.extend(rep) else: did.append(rep) if failed is not None: raise failed return did
_tick_runs_every: bool = False
[docs] def tick(self, now: int) -> list[tuple[Any, ...]]: """Periodic work. Runs due EVERY jobs when not overridden.""" return self.run_every(now)
[docs] def run_tick(self, now: int) -> list[tuple[Any, ...]]: """Run periodic work (EVERY) and any custom tick logic.""" if self.__class__.tick is Compartment.tick: return self.run_every(now) if self._tick_runs_every: return list(self.tick(now) or []) return self.run_every(now) + list(self.tick(now) or [])
[docs] def stop(self) -> Any: """Anything that must be said before the node goes. Must not raise.""" self.stop_workers() db = getattr(self, 'db', None) if db is not None: self.db = None if hasattr(db, 'close'): try: db.close() except Exception: pass return None
def __del__(self) -> None: """Close the database handle of a compartment nobody stopped. Only that. This called stop(), and a subclass's stop() is where a compartment says goodbye - the budget's is the farewell receipt to every peer. So an instance the collector found, one `assemble()` had thrown away, could speak for a node that never ran it (audit 2026-10-15, B8). The handle is what the collector must not leak; the rest is stop()'s, and stop() is the registry's to call. Not wrapped: a raise here cannot propagate, and Python reports it through sys.unraisablehook - which is the one way a finalizer can say a close failed (check-swallowed counts `close` as a call that matters). """ db = self.__dict__.get('db') if db is not None and hasattr(db, 'close'): db.close() # ---- being watched ------------------------------------------------------
[docs] def state(self) -> Mapping[str, Any]: """What this compartment is, as plain data. Never raises. A compartment with a shape worth naming returns its TypedDict.""" return {}
[docs] def trouble_with( self, message: str, *, code: str = 'fault', severity: str = 'trouble', since: Optional[int] = None, hint: Optional[str] = None, **metadata: Any, ) -> Trouble: """Create a typed Trouble instance associated with this compartment.""" return Trouble( message, code=code, compartment=self.name or '', severity=severity, since=since or self.clock(), hint=hint, **metadata, )
[docs] def trouble(self) -> list[str]: """What an operator should be told without having to ask for it. Everything here is WRONG: a watcher reds on it and a deploy fails on it. Something worth reading that is not a fault goes in `notes()`. May return a list of strings or typed Trouble instances. """ return TroubleList()
[docs] def note_with( self, message: str, *, topic: str = 'general', level: str = 'info', since: Optional[int] = None, **metadata: Any, ) -> Note: """Create a typed Note instance associated with this compartment.""" return Note( message, topic=topic, compartment=self.name or '', level=level, since=since or self.clock(), **metadata, )
[docs] def notes(self) -> list[str]: """What an operator would want to read, that is not a fault. A relay cooling after a rate-limit, a peer that announced it is leaving: the node behaving, and the reason a quiet mesh is quiet. Kept apart from `trouble()` so no reader has to classify prose. May return a list of strings or typed Note instances. """ return NoteList()
[docs] def report(self) -> Mapping[str, Any]: """state plus refusals, which is what health and the CLI both render. Plus, for a compartment that declares stores, what each one holds now (sizes and counts only - a report never carries the entries).""" s = dict(self.state()) s['refusals'] = self.refusals.state() holdings = getattr(self, 'holdings', None) if holdings is not None and len(holdings): s['stores'] = holdings.live() s.update(self.sections()) if getattr(self, 'EVERY', ()): if not hasattr(self, '_every_last'): self._every_last = {} every_rep: dict[str, EveryJobReport] = {} for job in self.EVERY: if not isinstance(job, Every): continue last = self._every_last.get(job.name) if job.is_off(self): # Off is null, not a number: there is no next run. every_rep[job.name] = {'seconds': None, 'last_run': last, 'next_run': None} continue sec = job.get_seconds(self) sec_val = int(sec) if sec == int(sec) else sec next_run = (last + int(sec)) if last is not None else None every_rep[job.name] = { 'seconds': sec_val, 'last_run': last, 'next_run': next_run, } s['every'] = every_rep if getattr(self, 'WORKERS', ()): threads = getattr(self, '_worker_threads', {}) s['workers'] = { w.name: { 'alive': bool(threads.get(w.name) is not None and threads[w.name].is_alive()) } for w in self.WORKERS if isinstance(w, Worker) } return s
[docs] def sections(self) -> Mapping[str, Any]: """What a KIND of compartment adds to every report of its kind - a bridge, its link - so that a subclass's own state() stays its own.""" return {}
# ---- across a process restart ----------------------------------------------
[docs] def snapshot(self) -> Mapping[str, Any]: """What this compartment hands the next process: every SNAPSHOT store, by key. Override only for state that is not in a store, and then override restore() with it.""" return self.holdings.snapshot() if self.holdings is not None else {}
[docs] def restore(self, state: Mapping[str, Any]) -> None: """Take back what snapshot() handed on. All or nothing: every store checks its part before any is loaded, so a raise leaves it fresh.""" if self.holdings is not None: self.holdings.restore(state)
[docs] def get_command(self, name: str) -> Optional[Any]: """Look up a declared command by key, bound to this compartment.""" cmd = next((c for c in getattr(self, 'COMMANDS', ()) if getattr(c, 'key', None) == name), None) if cmd is not None and hasattr(cmd, 'bind'): return cmd.bind(self) return None
@property def bound_commands(self) -> tuple[Any, ...]: """All declared commands bound to this compartment instance.""" return tuple(c.bind(self) for c in getattr(self, 'COMMANDS', ()) if hasattr(c, 'bind')) # ---- being operated -----------------------------------------------------
[docs] def command(self, name: str, args: Mapping[str, Any]) -> Any: """Answer a declared command: its arguments checked against the declaration, then what its `run` names. A KeyError for a name this compartment does not declare; a CommandError for arguments it does not take. The KeyError is the declared contract and a dozen suites assert it, so it stays. `Registry.dispatch` is what turns this one shape into a ControlError on the way to the control socket - see the note there (audit I14).""" cmd = next((c for c in self.COMMANDS if isinstance(c, Command) and c.key == name), None) if cmd is None: raise KeyError(name) return cmd.execute(self, args)
[docs] def handle(self, inbound: Any, *args: Any, **kw: Any) -> Any: """Answer an inbound wire protocol message according to HANDLERS declarations.""" if not self.HANDLERS: return None msg = getattr(inbound, 'message', inbound) if not isinstance(msg, dict): return None t = msg.get('type', '') if not isinstance(t, str): return None for h in self.HANDLERS: if hasattr(h, 'matches') and h.matches(t, self.piuris): return h.execute(self, inbound, *args, **kw) return None
[docs] def config(self, key: str, default: Any = None) -> Any: """A config key, or `default`. Safe on a compartment with no node.""" cfg = self._injected_cfg if callable(cfg): cfg = cfg() if cfg is None and self.node is not None: cfg = getattr(self.node, 'cfg', None) return (cfg or {}).get(key, default)
[docs] def say(self, name: str, *args: Any, **kw: Any) -> Any: """Raise a declared channel to the node log, if a log is reachable. In a running node, delegates to the injected `says` logger or `self.node.says.say()`. In tests or standalone runs without a full node log, formats the channel's declared line and prints to `journal.line`, preserving the existing format and avoiding regressions. """ log = self._injected_says if log is None and self.node is not None: log = getattr(self.node, 'says', None) if log is not None and hasattr(log, 'say'): return log.say(name, *args, **kw) ch = next((c for c in getattr(self, 'CHANNELS', ()) if c.name == name), None) if ch is not None: journal.line(' %s' % (self.name or ''), ch.said(*args, **kw)) return None
# ---- capability advertisement -------------------------------------------
[docs] def capability_protocols(self) -> Sequence[str]: """Protocols (PIURIs or dialects) this compartment advertises in kind 11801 descriptor.""" return ()
[docs] def descriptor_tags(self) -> Sequence[Sequence[str]]: """Extra Nostr tags this compartment adds to the kind 11801 descriptor.""" return ()