Source code for fleetmesh_strfry.bridge

"""Live Streaming Bridge (StrfryRelayBridge).

Real-time bidirectional streaming between a local/remote strfry relay (via WebSocket)
and the Fleetmesh node store and P2P gossip planes.

Moved verbatim from meshnode's fleetmesh_node/strfry_bridge.py; only the import paths changed.
"""
from __future__ import annotations

import collections
import threading
import time
from typing import Any, Callable, Deque, Optional, Sequence

from fleetmesh_node.protocols.nostr import client as relay
from fleetmesh_node.interfaces import NostrEvent

from .policy import DEFAULT_STRFRY_URL, StrfryPolicyEngine


[docs]class StrfryRelayBridge: """Live bidirectional WebSocket streaming bridge connecting strfry and Fleetmesh."""
[docs] def __init__( self, store_backend: Any, strfry_url: str = DEFAULT_STRFRY_URL, policy_engine: Optional[StrfryPolicyEngine] = None, kinds: Optional[Sequence[int]] = None, clock: Optional[Callable[[], int]] = None, ) -> None: self.store: Any = store_backend self.strfry_url: str = strfry_url self.policy: StrfryPolicyEngine = policy_engine or StrfryPolicyEngine(store_backend=store_backend) self.kinds: list[int] = list(kinds or [0, 1, 3, 6, 7, 1059, 11801, 11802, 11803, 30801, 30802, 30803]) self.clock: Callable[[], int] = clock or (lambda: int(time.time())) self.connected: bool = False self.last_connected_at: Optional[int] = None self.ingress_count: int = 0 self.egress_count: int = 0 self.errors_count: int = 0 self.last_error: Optional[str] = None self._relay: Optional[relay.Relay] = None self._thread: Optional[threading.Thread] = None self._stop_event: threading.Event = threading.Event() self._egress_queue: Deque[NostrEvent] = collections.deque(maxlen=1000) self._lock: threading.Lock = threading.Lock()
[docs] def enqueue(self, event: NostrEvent) -> None: """Queue `event` for strfry; it goes out on the next flush_egress. The queue holds the newest 1000: when full, the oldest is dropped.""" if isinstance(event, dict): with self._lock: self._egress_queue.append(event)
[docs] def start(self) -> None: """Launch background streaming bridge worker.""" with self._lock: if self._thread is not None and self._thread.is_alive(): return self._stop_event.clear() self._thread = threading.Thread(target=self._run_loop, name=f'strfry-bridge-{self.strfry_url}', daemon=True) self._thread.start()
[docs] def stop(self) -> None: """Stop background worker and close WebSocket.""" self._stop_event.set() with self._lock: if self._relay is not None: try: self._relay.close() except Exception: pass self._relay = None self.connected = False if self._thread is not None and self._thread.is_alive(): self._thread.join(timeout=1.0) self._thread = None
[docs] def publish_to_strfry(self, event: NostrEvent) -> tuple[bool, str]: """Publish an outbound event to the strfry relay after egress policy check.""" # 1. Egress Policy Evaluation verdict = self.policy.evaluate_egress(event) act = verdict.get('action', 'allow') if act == 'drop': return False, f"egress dropped: {verdict.get('msg', 'policy')}" elif act == 'shadowDrop': return True, "shadow dropped" elif act == 'redact': # A redacted event is the same event with fewer tags; its id and sig # are deliberately left as they were - the relay is expected to # refuse it, and the audit trail shows what was attempted. event = {**event, 'tags': verdict.get('redacted_tags', [])} # 2. WebSocket publication via dedicated relay client to prevent socket contention pub_client = relay.Relay(self.strfry_url, timeout=5.0) try: pub_client.connect() ok_pub, reason = pub_client.publish(event) if ok_pub: self.egress_count += 1 return ok_pub, reason except Exception as e: self.errors_count += 1 self.last_error = str(e) self.enqueue(event) return False, str(e) finally: pub_client.close()
def _run_loop(self) -> None: consecutive_errors = 0 while not self._stop_event.is_set(): try: r = relay.Relay(self.strfry_url, timeout=10.0) r.connect() with self._lock: self._relay = r self.connected = True self.last_connected_at = int(time.time()) self.last_error = None consecutive_errors = 0 # Subscribe to strfry sid = r.subscribe([{'kinds': self.kinds}], ready=False) # Anything queued while strfry was away goes out now, not # the next time strfry happens to send us something. self.flush_egress() # Process incoming stream for ev in r.events(sid): if self._stop_event.is_set(): break # Pass through writePolicy engine verdict = self.policy.evaluate_ingress({'type': 'new', 'event': ev}) if verdict.get('action') == 'accept': self.ingress_count += 1 if self.policy.store is not self.store and hasattr(self.store, 'insert_event'): self.store.insert_event(ev, self.clock()) if hasattr(self.store, 'note_origin'): try: self.store.note_origin(ev.get('id', ''), getattr(self.store, 'LOCAL', 'local')) except Exception: pass # Flush pending egress self.flush_egress() except Exception as e: consecutive_errors += 1 self.errors_count += 1 self.last_error = f'{type(e).__name__}: {e}' with self._lock: self.connected = False if self._relay is not None: try: self._relay.close() except Exception: pass self._relay = None if not self._stop_event.is_set(): backoff = min(10.0, 0.5 * (2 ** min(consecutive_errors, 4))) self._stop_event.wait(backoff)
[docs] def flush_egress(self) -> int: """Send queued egress to strfry; returns how many went out. Driven from three places: after every (re)connect of the read loop, after every inbound event, and from the plugin's tick() - so a quiet strfry that sends nothing still gets what was queued for it. What cannot be sent because strfry is unreachable is put back at the front of the queue for the next attempt, in order. """ raw_items: list[NostrEvent] = [] with self._lock: while self._egress_queue and len(raw_items) < 20: raw_items.append(self._egress_queue.popleft()) if not raw_items: return 0 items: list[NostrEvent] = [] for ev in raw_items: verdict = self.policy.evaluate_egress(ev) act = verdict.get('action', 'allow') # A redacted event is a different event: its id and signature # cover the tags, so strfry would refuse it. Withhold it instead. if act in ('drop', 'shadowDrop', 'redact'): continue items.append(ev) if not items: return 0 sent = 0 pub_client = relay.Relay(self.strfry_url, timeout=5.0) try: pub_client.connect() while items: ev = items[0] try: ok_p, _ = pub_client.publish(ev) except Exception: break # connection gone; keep this and the rest items.pop(0) if ok_p: self.egress_count += 1 sent += 1 # a relay that says "false" has judged the event; retrying it is pointless except Exception as e: self.last_error = f'{type(e).__name__}: {e}' finally: pub_client.close() if items: with self._lock: self._egress_queue.extendleft(reversed(items)) return sent
[docs] def pending_egress(self) -> int: with self._lock: return len(self._egress_queue)
[docs] def stats(self) -> dict[str, Any]: return { 'strfry_url': self.strfry_url, 'connected': self.connected, 'last_connected_at': self.last_connected_at, 'ingress_count': self.ingress_count, 'egress_count': self.egress_count, 'errors_count': self.errors_count, 'last_error': self.last_error, 'pending_egress': self.pending_egress(), 'policy': self.policy.stats(), }