Source code for fleetmesh_node.protocols

"""Pluggable protocol suites and package registry for Fleetmesh node.

Manages dynamic discovery, configuration, lifecycle, and multiplexing
across all supported open protocol families:
- Nostr & Blossom (`fleetmesh-protocol-nostr`)
- AT Protocol (`fleetmesh-protocol-atproto`)
- ActivityPub & ActivityStreams 2.0 (`fleetmesh-protocol-activitypub`)
- Secure Scuttlebutt (`fleetmesh-protocol-ssb`)
- p2panda (`fleetmesh-protocol-p2panda`)
- Rhio (`fleetmesh-protocol-rhio`)
"""
from __future__ import annotations

import importlib
import logging
from typing import Any, Callable, Mapping, Optional

from fleetmesh_core.wire.interfaces import (
    ProtocolHealth,
    ProtocolHostRouter,
    ProtocolPackage,
)

log = logging.getLogger(__name__)

# Registry of built-in protocol packages
BUILTIN_PACKAGE_LOADERS: dict[str, tuple[str, str]] = {
    'nostr': ('fleetmesh_node.protocols.nostr.package', 'NostrProtocolPackage'),
    'atproto': ('fleetmesh_node.protocols.atproto.package', 'AtprotoProtocolPackage'),
    'activitypub': ('fleetmesh_node.protocols.activitypub.package', 'ActivityPubProtocolPackage'),
    'ssb': ('fleetmesh_node.protocols.ssb.package', 'SSBProtocolPackage'),
    'p2panda': ('fleetmesh_node.protocols.p2panda.package', 'P2PandaProtocolPackage'),
    'rhio': ('fleetmesh_node.protocols.rhio.package', 'RhioProtocolPackage'),
}

_CUSTOM_PACKAGES: dict[str, type[ProtocolPackage]] = {}


[docs]def register_protocol(name: str, package_cls: type[ProtocolPackage]) -> None: """Register a custom or third-party protocol package class.""" clean_name = name.lower().strip() _CUSTOM_PACKAGES[clean_name] = package_cls
[docs]def get_available_protocols() -> tuple[str, ...]: """Return all currently registered protocol names.""" return tuple(sorted(set(BUILTIN_PACKAGE_LOADERS.keys()) | set(_CUSTOM_PACKAGES.keys())))
[docs]def load_protocol_package_class(name: str) -> type[ProtocolPackage]: """Dynamically load and return the ProtocolPackage class for a given name.""" clean_name = name.lower().strip() if clean_name in _CUSTOM_PACKAGES: return _CUSTOM_PACKAGES[clean_name] if clean_name in BUILTIN_PACKAGE_LOADERS: mod_name, cls_name = BUILTIN_PACKAGE_LOADERS[clean_name] try: mod = importlib.import_module(mod_name) cls = getattr(mod, cls_name) return cls except Exception as e: raise ImportError(f"Failed to load protocol package '{clean_name}' from {mod_name}.{cls_name}: {e}") from e raise KeyError(f"Unknown protocol package '{name}'. Available: {get_available_protocols()}")
[docs]def create_protocol_package(name: str, **kwargs) -> ProtocolPackage: """Instantiate a protocol package by name with provided arguments.""" cls = load_protocol_package_class(name) return cls(**kwargs)
[docs]class ProtocolManager: """Orchestrates configuration, lifecycle, and routing across all protocol packages."""
[docs] def __init__( self, node_dir: Optional[str] = None, keystore: Optional[Any] = None, clock: Optional[Callable[[], int]] = None, name: str = 'meshnode', ): self.node_dir = node_dir self.keystore = keystore self.clock = clock self.node_name = name self._packages: dict[str, ProtocolPackage] = {} self._mounted_host: Optional[ProtocolHostRouter] = None
@property def packages(self) -> Mapping[str, ProtocolPackage]: return dict(self._packages)
[docs] def get_package(self, name: str) -> Optional[ProtocolPackage]: return self._packages.get(name.lower().strip())
[docs] def load_suites_config( self, suites_config: Any, backend_store: Optional[Any] = None, blob_store: Optional[Any] = None, grants: Optional[Any] = None, node_instance: Optional[Any] = None, private_key: Optional[Any] = None, strain_ledger: Optional[Any] = None, ) -> dict[str, ProtocolPackage]: """Initialize protocol packages based on ProtocolSuitesConfig or mapping.""" suites_dict: Mapping[str, Any] = {} if hasattr(suites_config, 'to_dict'): suites_dict = suites_config.to_dict() elif hasattr(suites_config, 'as_dict'): suites_dict = suites_config.as_dict() elif hasattr(suites_config, '__dict__'): suites_dict = { k: getattr(suites_config, k).to_dict() if hasattr(getattr(suites_config, k), 'to_dict') else (getattr(suites_config, k).as_dict() if hasattr(getattr(suites_config, k), 'as_dict') else getattr(suites_config, k)) for k in ('nostr', 'atproto', 'activitypub', 'ssb', 'p2panda', 'rhio') if getattr(suites_config, k, None) is not None } elif isinstance(suites_config, Mapping): suites_dict = dict(suites_config) if self._packages: self.stop_all() self._packages.clear() # 1. Nostr cfg_nostr = suites_dict.get('nostr') if cfg_nostr is not None and (isinstance(cfg_nostr, Mapping) and cfg_nostr.get('enabled', True)): from fleetmesh_node.protocols.nostr.package import NostrProtocolPackage pkg_nostr = NostrProtocolPackage( backend=backend_store, blob_store=blob_store, grants=grants, node=node_instance, clock=self.clock, name=self.node_name, pubkey=getattr(self.keystore, 'node_pk', None) if self.keystore else None, ) pkg_nostr.configure(cfg_nostr if isinstance(cfg_nostr, Mapping) else {}) self._packages['nostr'] = pkg_nostr # 2. ATProto cfg_atp = suites_dict.get('atproto') if cfg_atp is not None and (isinstance(cfg_atp, Mapping) and cfg_atp.get('enabled', True)): from fleetmesh_node.protocols.atproto.package import AtprotoProtocolPackage pkg_atp = AtprotoProtocolPackage( blob_store=blob_store, keystore=self.keystore, ) pkg_atp.configure(cfg_atp if isinstance(cfg_atp, Mapping) else {}) self._packages['atproto'] = pkg_atp # 3. ActivityPub cfg_ap = suites_dict.get('activitypub') if cfg_ap is not None and (isinstance(cfg_ap, Mapping) and cfg_ap.get('enabled', True)): from fleetmesh_node.protocols.activitypub.package import ActivityPubProtocolPackage domain = cfg_ap.get('domain', 'node.fleetmesh.local') if isinstance(cfg_ap, Mapping) else 'node.fleetmesh.local' pkg_ap = ActivityPubProtocolPackage( domain=domain, username="node", private_key=private_key or getattr(self.keystore, 'ed25519_sk', None), blob_store=blob_store, strain_ledger=strain_ledger, keystore=self.keystore, ) pkg_ap.configure(cfg_ap if isinstance(cfg_ap, Mapping) else {}) self._packages['activitypub'] = pkg_ap # 4. SSB cfg_ssb = suites_dict.get('ssb') if cfg_ssb is not None and (isinstance(cfg_ssb, Mapping) and cfg_ssb.get('enabled', True)): from fleetmesh_node.protocols.ssb.package import SSBProtocolPackage pkg_ssb = SSBProtocolPackage( node_dir=self.node_dir or "/tmp/fleetmesh-ssb", private_key=private_key or getattr(self.keystore, 'ed25519_sk', None), ) pkg_ssb.configure(cfg_ssb if isinstance(cfg_ssb, Mapping) else {}) self._packages['ssb'] = pkg_ssb # 5. P2Panda cfg_p2p = suites_dict.get('p2panda') if cfg_p2p is not None and (isinstance(cfg_p2p, Mapping) and cfg_p2p.get('enabled', False)): if 'p2panda' in _CUSTOM_PACKAGES or 'p2panda' in BUILTIN_PACKAGE_LOADERS: try: pkg_p2p = create_protocol_package( 'p2panda', node_dir=self.node_dir, keystore=self.keystore, blob_store=blob_store, ) pkg_p2p.configure(cfg_p2p if isinstance(cfg_p2p, Mapping) else {}) self._packages['p2panda'] = pkg_p2p except Exception as e: log.warning("Could not instantiate p2panda protocol package: %s", e) # 6. Rhio cfg_rhio = suites_dict.get('rhio') if cfg_rhio is not None and (isinstance(cfg_rhio, Mapping) and cfg_rhio.get('enabled', False)): if 'rhio' in _CUSTOM_PACKAGES or 'rhio' in BUILTIN_PACKAGE_LOADERS: try: pkg_rhio = create_protocol_package( 'rhio', node_dir=self.node_dir, keystore=self.keystore, blob_store=blob_store, ) pkg_rhio.configure(cfg_rhio if isinstance(cfg_rhio, Mapping) else {}) self._packages['rhio'] = pkg_rhio except Exception as e: log.warning("Could not instantiate rhio protocol package: %s", e) return dict(self._packages)
[docs] def mount_ingress(self, host: ProtocolHostRouter) -> None: """Mount all active protocol packages onto the shared host multiplexer.""" self._mounted_host = host for name, pkg in self._packages.items(): try: pkg.mount_ingress(host) log.info("Mounted ingress for protocol '%s'", name) except Exception as e: log.exception("Failed to mount ingress for protocol '%s': %s", name, e)
[docs] def mount_transport_rungs(self, router: Any) -> list[Any]: """Mount outbound rungs into TransportRouter ladder.""" mounted = [] for name, pkg in self._packages.items(): try: rung = pkg.transport_rung(router) if rung is not None: if hasattr(router, 'register_rung'): router.register_rung(rung) elif hasattr(router, 'add_rung'): router.add_rung(rung) mounted.append(rung) except Exception as e: log.exception("Failed to build transport rung for protocol '%s': %s", name, e) return mounted
[docs] def start_all(self) -> None: """Start all configured protocol packages.""" for name, pkg in self._packages.items(): try: pkg.start() except Exception as e: log.exception("Error starting protocol package '%s': %s", name, e)
[docs] def stop_all(self) -> None: """Stop all configured protocol packages and unmount ingress.""" for name, pkg in self._packages.items(): try: pkg.stop() except Exception as e: log.exception("Error stopping protocol package '%s': %s", name, e) if self._mounted_host is not None: for name in self._packages: try: self._mounted_host.unmount_all(name) except Exception: pass self._mounted_host = None
[docs] def health(self) -> dict[str, ProtocolHealth]: """Collect health telemetry across all loaded protocol packages.""" return {name: pkg.health() for name, pkg in self._packages.items()}
[docs] def descriptor_capabilities(self) -> tuple[tuple[str, str], ...]: """Aggregate descriptor capabilities from all active packages.""" caps: list[tuple[str, str]] = [] for pkg in self._packages.values(): try: caps.extend(pkg.descriptor_capabilities()) except Exception: pass return tuple(caps)