"""Rhio cluster transport ladder rung for TransportRouter.
Integrates Rhio NATS JetStream and cluster blob replication into the transport ladder:
- Checks sidecar availability over local Unix domain socket (rhio.sock).
- Resolves peer Rhio endpoints from node descriptors (scheme 'rhio').
- Delivers messages to remote cluster peers via NATS JetStream pub/sub.
"""
from __future__ import annotations
import logging
import os
from typing import Any, Callable, Mapping, Optional
from fleetmesh_node.transport.const import TransportError
from fleetmesh_node.transport.ladder import FaultLog
from fleetmesh_node.transport.rung import Rung, Verdict, endpoints_of
from fleetmesh_node.sidecar.fleetmesh_rhio import RhioSidecarClient
log = logging.getLogger('rhio_rung')
__all__ = [
'RhioRung',
]
[docs]class RhioRung(Rung):
"""Transport rung delegating outbound deliveries to the Rhio cluster sidecar daemon."""
name: str = 'rhio'
rank: int = 12 # Cluster sync tier (below FIPS 5, above P2Panda 15)
[docs] def __init__(
self,
router: Optional[Any] = None,
sidecar_client: Optional[RhioSidecarClient] = None,
socket_path: Optional[str] = None,
enabled: bool = True,
clock: Optional[Callable[[], int]] = None,
):
self.router = router
self._client = sidecar_client
self._socket_path = socket_path
self.enabled = enabled
clk = clock or (getattr(router, 'clock', None) if router else None)
self._faults = FaultLog(self.name, clock=clk)
@property
def faults(self) -> FaultLog:
return self._faults
[docs] def fault_log(self) -> Optional[FaultLog]:
return self._faults
def _get_client(self) -> Optional[RhioSidecarClient]:
if self._client is not None:
return self._client
sock_path = self._socket_path
if sock_path is None and self.router is not None:
node_dir = getattr(self.router, 'dir', None) or getattr(self.router, 'node_dir', None)
if node_dir:
sock_path = os.path.join(node_dir, 'rhio.sock')
if sock_path and os.path.exists(sock_path):
self._client = RhioSidecarClient(sock_path)
return self._client
[docs] def available(self) -> bool:
"""Returns True if the Rhio sidecar socket is reachable and healthy."""
if not self.enabled:
return False
client = self._get_client()
if client is None:
return False
try:
st = client.status()
return bool(st.get('ok'))
except Exception:
return False
[docs] def target_of(self, desc: Optional[Mapping[str, Any]], theirs: Mapping[str, int]) -> Optional[str]:
"""Extract Rhio endpoint target from descriptor."""
if desc is None:
return None
_, where = endpoints_of(desc)
if 'rhio' in where:
return where['rhio']
# Check raw tags
for t in desc.get('tags', []):
if len(t) > 2 and t[0] in ('endpoint', 'address') and t[1] == 'rhio':
return str(t[2])
if len(t) > 1 and t[0] == 'c' and t[1] == 'rhio':
return ''
if 'rhio' in theirs:
return ''
return None
[docs] def deliver(
self,
message: Mapping[str, Any],
to_pubkey: str,
target: str,
anonymous: bool = False,
) -> Verdict:
"""Attempt delivery of message to target Rhio endpoint via JetStream."""
if not self.enabled:
raise TransportError("rhio rung is disabled")
client = self._get_client()
if client is None:
raise TransportError("rhio sidecar client unavailable")
subject = f"fleetmesh.{to_pubkey[:16]}" if to_pubkey else "fleetmesh.broadcast"
try:
res = client.publish(subject, dict(message))
if not res.get("ok"):
raise TransportError(f"rhio publish failed: {res.get('error', 'unknown error')}")
msg_id = res.get("id", "")
return {self.name: (True, f"published to {subject} id={msg_id[:16]} via JetStream")}
except Exception as e:
self._faults.record(f"deliver failed: {e}", ident=to_pubkey[:16] if to_pubkey else None)
raise TransportError(f"rhio delivery failed: {e}") from e
[docs] def health(self) -> Optional[Mapping[str, Any]]:
client = self._get_client()
st = {}
if client:
try:
st = dict(client.status())
except Exception:
pass
return {
'available': self.available(),
'sidecar_connected': bool(st.get('connected', False)),
'messages_count': st.get('messages_count', 0),
'blobs_count': st.get('blobs_count', 0),
}