Source code for fleetmesh_node.protocols.p2panda.package

"""fleetmesh-protocol-p2panda: p2panda protocol package for Fleetmesh.

Conforms to ProtocolPackage (fleetmesh_core.wire.interfaces.ProtocolPackage).
Mounts p2panda operation log ingress onto ProtocolHostRouter, provides
P2PandaRung for TransportRouter ladder, and manages append-only SQLite persistence.
"""
from __future__ import annotations

import json
import logging
import urllib.parse
from typing import Any, Mapping, Optional

from fleetmesh_core.wire.interfaces import (
    ProtocolHealth,
    ProtocolHostRouter,
    ProtocolIdentityAdapter,
)
from fleetmesh_core.wire.p2panda import P2PandaOperation, P2PandaOperationDict
from fleetmesh_node.protocols.base import BaseProtocolPackage
from .identity import P2PandaIdentityAdapter
from .rung import P2PandaRung
from .store import P2PandaLogStore, P2PandaStoreError

__all__ = [
    'P2PandaProtocolPackage',
]

log = logging.getLogger(__name__)


[docs]class P2PandaProtocolPackage(BaseProtocolPackage): """The p2panda protocol suite for Fleetmesh.""" name: str = 'p2panda' version: str = '0.4.0' standards: tuple[str, ...] = ( 'p2panda-v0.4.0', 'cbor-rfc8949', 'ed25519-chain', )
[docs] def __init__( self, node_dir: Optional[str] = None, keystore: Optional[Any] = None, blob_store: Optional[Any] = None, store: Optional[P2PandaLogStore] = None, **kwargs: Any, ) -> None: self.node_dir = node_dir self.keystore = keystore self.blob_store = blob_store self.config: Mapping[str, Any] = {} self._enabled: bool = True self._running: bool = False self._messages_in: int = 0 self._messages_out: int = 0 # Identity Adapter if keystore is not None: self.identity: Optional[P2PandaIdentityAdapter] = P2PandaIdentityAdapter.from_keystore(keystore) else: self.identity = None # Persistent Log Store if store is not None: self.store: P2PandaLogStore = store elif node_dir: import os db_path = os.path.join(node_dir, "p2panda.db") self.store = P2PandaLogStore(db_path) else: self.store = P2PandaLogStore(":memory:") # Outbound Transport Rung self.rung: P2PandaRung = P2PandaRung( store=self.store, identity=self.identity, enabled=self._enabled, ) self._host: Optional[ProtocolHostRouter] = None
[docs] def configure(self, config: Mapping[str, Any]) -> None: self.config = dict(config) self._enabled = bool(self.config.get('enabled', True)) self.rung.enabled = self._enabled # Dev/LAN only; off unless the operator wrote it on. self.rung.allow_local_peers = bool(self.config.get('allow_local_peers', False))
[docs] def identity_adapter(self, keystore: Any) -> Optional[ProtocolIdentityAdapter]: if keystore is not None: return P2PandaIdentityAdapter.from_keystore(keystore) return self.identity
[docs] def mount_ingress(self, host: ProtocolHostRouter) -> None: if not self._enabled: return self._host = host from fleetmesh_node.transport import ws # 1. GET /p2panda/status def _handle_status(conn: Any, req: Any) -> bool: body_dict = { 'status': 'online' if self._running else 'configured', 'name': self.name, 'version': self.version, 'author': self.identity.author_id if self.identity else '', 'operations_count': self.store.count_operations(), 'authors_count': len(self.store.list_authors()), } body = json.dumps(body_dict, indent=2).encode('utf-8') ws.http_response(conn, "200 OK", body, "application/json") return True # 2. GET & POST /p2panda/operations def _op_to_json_dict(op: P2PandaOperation) -> P2PandaOperationDict: return op.to_dict(json_safe=True) def _handle_operations(conn: Any, req: Any) -> bool: method = getattr(req, 'method', 'GET').upper() uri = getattr(req, 'path', '') parsed = urllib.parse.urlparse(uri) if method == 'GET': qparams = urllib.parse.parse_qs(parsed.query) author = qparams.get('author', [None])[0] target_route = parsed.path if not author and target_route.startswith('/p2panda/operations/'): tail = target_route[len('/p2panda/operations/'):].strip('/') if tail: single_op = self.store.get_operation(tail) if single_op is not None: ws.http_response( conn, "200 OK", json.dumps(_op_to_json_dict(single_op)).encode('utf-8'), "application/json", ) return True author = tail if author: from_seq = int(qparams.get('from_seq', [0])[0]) limit = int(qparams.get('limit', [100])[0]) ops = self.store.get_log(author, from_seq=from_seq, limit=limit) ops_data = [_op_to_json_dict(op) for op in ops] body = json.dumps({'author': author, 'operations': ops_data}).encode('utf-8') ws.http_response(conn, "200 OK", body, "application/json") return True else: authors = self.store.list_authors() body = json.dumps({'authors': authors, 'total_operations': self.store.count_operations()}).encode('utf-8') ws.http_response(conn, "200 OK", body, "application/json") return True elif method == 'POST': try: payload = ws.read_body(conn, req) except Exception as e: ws.http_response(conn, "400 Bad Request", json.dumps({'error': str(e)}).encode('utf-8')) return True headers = getattr(req, 'headers', {}) content_type = headers.get(b'content-type', b'').decode('utf-8', errors='ignore').lower() try: if 'cbor' in content_type: op = P2PandaOperation.from_cbor(payload) else: op_dict = json.loads(payload.decode('utf-8')) op = P2PandaOperation.from_dict(op_dict) inserted = self.store.append_operation(op, verify_chain=True) self._messages_in += 1 status = "201 Created" if inserted else "200 OK" ws.http_response( conn, status, json.dumps({'op_id': op.id, 'inserted': inserted, 'seq_num': op.seq_num}).encode('utf-8'), "application/json", ) return True except P2PandaStoreError as e: ws.http_response(conn, "422 Unprocessable Entity", json.dumps({'error': str(e)}).encode('utf-8')) return True except Exception as e: ws.http_response(conn, "400 Bad Request", json.dumps({'error': str(e)}).encode('utf-8')) return True return False host.mount_route('/p2panda/status', _handle_status, methods=('GET',), owner=self.name) host.mount_route('/p2panda/operations', _handle_operations, methods=('GET', 'POST'), owner=self.name)
[docs] def transport_rung(self, context: Any) -> Optional[Any]: if not self._enabled: return None return self.rung
[docs] def compartments(self) -> tuple[type[Any], ...]: return ()
[docs] def start(self) -> None: if not self._enabled: return self._running = True
[docs] def stop(self) -> None: self._running = False if self.store is not None: self.store.close()
[docs] def health(self) -> ProtocolHealth: if not self._enabled: return ProtocolHealth( healthy=True, status="disabled", connections_active=0, messages_in=0, messages_out=0, errors=(), ) return ProtocolHealth( healthy=True, status="serving" if self._running else "configured", connections_active=0, messages_in=self._messages_in, messages_out=self._messages_out, errors=(), )
[docs] def descriptor_capabilities(self) -> tuple[tuple[str, str], ...]: if not self._enabled: return () return (('c', 'p2panda'), ('c', 'cbor'))