Source code for fleetmesh_node.app.views

"""Views the CLI and the control socket share: a peer's grants and windows.

Separate because `meshnode peer` reads them straight from the files when no
daemon is running, and must not import the node to do so.
"""
from __future__ import annotations

import json
from typing import Any, Mapping, Optional, TypedDict

from fleetmesh_core.accounting import accounting
from fleetmesh_core.wire.wire_types import GrantRow, HistoryRow, PendingRow
from ..storage import grants as grants_mod


[docs]class GrantView(TypedDict, total=False): peer: str issued: Optional[GrantRow] received: Optional[GrantRow] issued_history: list[HistoryRow] received_history: list[HistoryRow] pending: Optional[PendingRow] seed_applied: Optional[tuple[str, int]]
[docs]class WindowView(TypedDict, total=False): epoch: int closed: int severity: Optional[str] measured: dict[str, int] claimed: Optional[dict[str, int]] receipts_in: int my_usage: dict[str, int] my_receipts_sent: int
def _live_peers(grants: grants_mod.GrantStore) -> list[str]: """GrantStore.peers() as a plain list of pubkeys. The store's own annotation is unreadable to the checker because GrantStore.list shadows the builtin in its class body (fleetmesh_node/grants.py, not owned by this change).""" raw: Any = grants.peers() return [str(p) for p in raw]
[docs]def grant_view(grants: grants_mod.GrantStore, pk: str) -> GrantView: """Both grants with a peer, their history, the pending tier and the seed. The same structure whether read from the files or asked of the daemon.""" return { 'peer': pk, 'issued': grants.get(pk, grants_mod.ISSUED), 'issued_history': grants.history(pk, grants_mod.ISSUED), 'received': grants.get(pk, grants_mod.RECEIVED), 'received_history': grants.history(pk, grants_mod.RECEIVED), 'pending': grants.pending(pk), 'seed_applied': grants.seed_applied(pk), }
[docs]def windows_view(source: Any, pk: str, last: int = 0) -> list[WindowView]: """The windows this node priced for a peer, from an accounts database: measured against claimed in the issuer frame, receipts in and sent. `source` is an AccountStore (its `_all` takes the store lock and closes the cursor before letting go - the daemon path) or a bare read-only sqlite3 connection (the CLI reading the file beside a stopped or running node). Either way every statement is finished and its cursor closed before the next; `.fetchone()` on its own leaves the statement live to be finalised by whichever thread the collector happens to run in. """ def rows(q: str, args: tuple[Any, ...]) -> list[Any]: if hasattr(source, '_all'): return list(source._all(q, args)) cur = source.execute(q, args) try: return cur.fetchall() finally: cur.close() def one(q: str, args: tuple[Any, ...]) -> Any: got = rows(q, args) return got[0] if got else None def col(q: str, args: tuple[Any, ...]) -> list[Any]: return [r[0] for r in rows(q, args)] epochs = sorted(set(col('SELECT epoch FROM meters WHERE peer=?', (pk,))) | set(col('SELECT epoch FROM evaluated WHERE peer=?', (pk,)))) epochs = epochs[-last:] if last else epochs out: list[WindowView] = [] for e in epochs: sev = one('SELECT severity FROM evaluated WHERE peer=? AND epoch=?', (pk, e)) by = one("SELECT counters FROM meters WHERE peer=? AND epoch=? AND side='by'", (pk, e)) me = one("SELECT counters FROM meters WHERE peer=? AND epoch=? AND side='of_me'", (pk, e)) n_in = one('SELECT count(*) FROM receipts WHERE peer=? AND epoch=?', (pk, e))[0] latest = one('SELECT body FROM receipts WHERE peer=? AND epoch=? ORDER BY seq DESC LIMIT 1', (pk, e)) chain = one('SELECT state FROM chain WHERE peer=? AND epoch=?', (pk, e)) out.append({'epoch': e, 'closed': accounting.window_bounds(e, 3600)[1], 'severity': (sev[0] or None) if sev else 'open', 'measured': json.loads(by[0]) if by else {}, 'claimed': json.loads(latest[0])['counters'] if latest else None, 'receipts_in': n_in, 'my_usage': json.loads(me[0]) if me else {}, 'my_receipts_sent': json.loads(chain[0])['seq'] if chain else 0}) return out
PLANES: tuple[tuple[str, str, tuple[str, ...]], ...] = ( ('relays', 'link', ('relays',)), ('dropped', 'link', ('dropped',)), ('recent_faults', 'link', ('recent_faults',)), ('publish_refused_in_window', 'link', ('publish_refused_in_window',)), ('cooling', 'link', ('cooling',)), ('inbox', 'link', ('inbox',)), ('wraps_in', 'link', ('wraps_in',)), ('wraps_seen_again', 'link', ('wraps_seen_again',)), ('unfinished_envelopes', 'link', ('unfinished_envelopes',)), ('awaiting_ack', 'link', ('awaiting_ack',)), ('unacknowledged', 'link', ('unacknowledged',)), ('sessions_open', 'sync', ('open',)), ('sessions_refused', 'sync', ('refused',)), ('sync_unsent', 'sync', ('unsent',)), ('malformed_sync', 'sync', ('malformed',)), ('budget_rejected', 'budget', ('rejected',)), ('receipts_refused', 'budget', ('receipts_refused',)), ('malformed_complaints', 'reporter', ('malformed',)), ('peering_refused', 'peering', ('refusals', 'recent')), ('throttled', 'scheduler', ('throttled',)), ('capacity', 'capacity', ()), ('strain', 'strain', ()), )
[docs]def node_health(app: Any) -> Mapping[str, Any]: """Assemble the operator health report across all compartments and node planes.""" report = app.subsystems.report() if app._built else {} def plane(name: str, path: tuple[str, ...]) -> Any: d: Any = report.get(name) if d is None: return None if not path: return {k: v for k, v in d.items() if k != 'refusals'} for key in path: d = d.get(key) if isinstance(d, dict) else None return d h = {key: plane(name, path) for key, name, path in app.PLANES} h.update({ 'rejected': dict(app.rejected), 'handler_failures': app.counts['handler failed'], 'tick_failures': app.counts['tick failed'], 'close_failures': app.counts['close failed'], 'last_tick_error': app._last_tick_error, 'config_error': app._config_error, 'subsystems': report, 'control': app.control.state() if getattr(app, 'control', None) is not None else None, 'subsystem_trouble': app.subsystems.trouble() if app._built else [], 'subsystem_notes': app.subsystems.notes() if app._built else [], }) return h
[docs]def node_status(app: Any) -> Mapping[str, Any]: """Assemble the complete status.json view for a running or stopped NodeApp.""" from .. import release as release_mod from ..interfaces import EvaluationRow, GrantStatusRow, PendingGrantRow, RepricedRow h = app.health() subs = h['subsystems'] def has(name: str, key: str, default: int = 0) -> Any: return (subs.get(name) or {}).get(key, default) face_url = app.face.url if app.face is not None else (app.host.url if getattr(app, 'host', None) is not None else '') st = { 'did': app.ks.did, 'class': app.cfg['class'], 'face': face_url, 'release': release_mod.running().as_dict(), 'relays': app.relays, 'descriptor': app.descriptor['id'] if app.descriptor else None, 'visibility': app.visibility_state(), 'peers': _live_peers(app.grants), 'grants': [GrantStatusRow(peer=g['peer'][:16], direction=g['direction'], tier=g['payload'].get('tier'), status=g['status']) for g in app.grants.list()], 'evaluations': [EvaluationRow(peer=r.peer[:16], epoch=r.epoch, severity=r.severity, state=r.state) for r in app.budget.evaluations[-10:]] if app._built else [], 'repriced': [RepricedRow(peer=r.peer[:16], epoch=r.epoch, was=r.was, severity=r.severity, remedy_cancelled=r.remedy_cancelled) for r in app.budget.repriced[-5:]] if app._built else [], 'pending_grants': [PendingGrantRow(peer=p[:16], tier=pend['payload'].get('tier'), from_epoch=pend['decided_epoch'] + 1) for p in _live_peers(app.grants) if (pend := app.grants.pending(p)) is not None], 'refused_sessions': has('sync', 'refused'), 'reports_published': has('reporter', 'published'), 'pending_findings': has('reporter', 'pending'), 'events_stored': app.store.count(), 'at': app.clock(), 'health': h, } if app._last_tick: st['last_tick'] = [list(map(str, d)) for d in app._last_tick] return st