Skip to main content

MeshRuntime

Struct MeshRuntime 

Source
pub struct MeshRuntime { /* private fields */ }
Expand description

The mesh runtime orchestrates transport, connections, and message bridging.

It maintains a set of active peer connections (keyed by node ID) and provides the plumbing to:

  1. Send a MeshIpcEnvelope to a connected peer.
  2. Receive an envelope from a peer and inject it into the local A2ARouter.

Implementations§

Source§

impl MeshRuntime

Source

pub fn set_leaf_ingress( &self, ingress: Arc<LeafIngress>, ) -> Result<(), Arc<LeafIngress>>

Install the service-owned leaf gate before the listener starts.

Source

pub fn leaf_ingress(&self) -> Option<&Arc<LeafIngress>>

Source

pub fn set_authentication(&self, auth: MeshAuthentication) -> bool

Source

pub fn authentication(&self) -> Option<&MeshAuthentication>

Source

pub fn start_liveness(self: &Arc<Self>, cfg: LivenessConfig)

Start the liveness ping/pong between verified peers (idempotent).

Source

pub fn liveness(&self) -> Option<&Arc<Liveness>>

The liveness service, when started.

Source

pub fn set_enforcing(&self, enforcing: bool)

Say whether admission is enforce (see the field). Takes effect for the peer events emitted after the call.

Source

pub fn enforcing(&self) -> bool

Whether admission is enforce.

Source

pub fn new(node_id: String) -> Self

Create a new mesh runtime for the given local node.

Source

pub fn with_discovery(node_id: String, kademlia_id: [u8; 32]) -> Self

Create a mesh runtime with discovery state initialized.

The kademlia_id is used as the local key in the Kademlia routing table. Heartbeat tracking starts with default configuration.

Source

pub fn set_control_sink(&self, topic: &str, sink: Arc<dyn PeerControlSink>)

Install the sink for the control topic topic (first call wins). Only the topics in CONTROL_TOPICS are control topics.

Source

pub fn subscribe_peer_events(&self) -> Receiver<MeshPeerEvent>

Subscribe to live mesh peer membership / health events (WEFT-120).

Source

pub fn peer_event_bus(&self) -> &MeshPeerEventBus

Shared peer-event bus (for boot wiring and tests).

Source

pub fn emit_peer_event(&self, event: MeshPeerEvent)

Publish a peer event (used by external discovery / tests).

Source

pub fn set_assessment_transport(&self, transport: Arc<AssessmentTransport>)

Attach the assessment transport used for AssessmentSync demux (WEFT-117).

Idempotent (first call wins). Safe after the runtime is wrapped in Arc so boot can wire the transport after mesh listener spawn.

Source

pub fn assessment_transport(&self) -> Option<Arc<AssessmentTransport>>

Shared assessment transport, if registered.

Source

pub async fn broadcast_raw(&self, data: &[u8]) -> usize

Broadcast raw encoded frame bytes to every connected peer.

Used by the assessment gossip/diff push loop. Failures on individual peers are logged and skipped (best-effort fan-out).

Source

pub async fn push_pending_assessment(&self) -> usize

Drain pending assessment broadcast (diff/gossip) and push to all peers.

Returns the number of peers that received the frame, or 0 if nothing was pending / transport not wired.

Source

pub async fn assessment_gossip_tick(&self) -> usize

Drive one assessment gossip tick using the published local report.

Source

pub fn node_id(&self) -> &str

Return this node’s identifier.

Source

pub fn set_local_router(&mut self, router: Arc<A2ARouter>)

Attach the local A2A router for incoming message injection.

Source

pub fn set_local_delivery(&mut self, delivery: Arc<dyn LocalDelivery>)

Attach any LocalDelivery sink for inbound messages (a mesh service delivers to tenants instead of an in-kernel router).

Source

pub fn register_peer_topic(&self, topic: &str, peer_node_id: &str)

Register a remote peer as a subscriber for the given topic.

Called from [handle_incoming] when a mesh.subscribe control envelope is received. De-duplicates: if the peer is already registered for this topic, the call is a no-op.

Source

pub fn unregister_peer_topic(&self, topic: &str, peer_node_id: &str)

Remove a peer’s subscription for the given topic.

Called when a peer disconnects or sends an explicit unsubscribe.

Source

pub fn unregister_all_peer_topics(&self, peer_node_id: &str)

Remove all topic subscriptions for the given peer.

Called when disconnect_peer is invoked so stale entries are cleaned up and future publishes don’t attempt dead channels.

Source

pub fn peers_for_topic(&self, topic: &str) -> Vec<String>

Return the list of peer node IDs subscribed to the given topic.

Used by the A2A router’s Topic handler to forward published messages to remote nodes.

Source

pub fn set_chain_manager(&self, cm: Arc<ChainManager>)

Attach the ExoChain manager for auditable peer-envelope logging.

Idempotent (first call wins; subsequent calls are no-ops). Uses interior mutability so this can be called after the runtime has been wrapped in Arc, which matches the boot-sequence ordering where the chain manager is constructed after the mesh listener.

Source

pub fn add_peer(&self, node_id: String, sender: Sender<Vec<u8>>)

Register a peer connection using an already-established channel.

This is the low-level entry point used after a TCP (or other transport) connection has been set up and the node-ID exchange has completed. Higher-level helpers like connect_peer build on top of this.

Source

pub fn route_is_foreign(&self, node_id: &str, tx: &Sender<Vec<u8>>) -> bool

True when node_id is routed through some channel other than tx.

Source

pub fn add_peer_tallied( &self, node_id: String, sender: Sender<Vec<u8>>, tally: &RouteTally, )

add_peer that counts the route in tally, so the owning connection can tell in O(1) when it is removed or replaced.

Source

pub fn register_authenticated_as( &self, node_id: String, sender: Sender<Vec<u8>>, verified: bool, class: PeerClass, tally: &RouteTally, ) -> bool

register_authenticated with the admitted class of the connection, so outbound decisions that need a full node (peer_licensed) can tell a leaf.

Source

pub fn routes_via(&self, tx: &Sender<Vec<u8>>) -> bool

Remove every route that still points at tx (a closed connection’s outbound channel). Routes since replaced by a newer connection are left alone; Left is emitted only for routes actually removed. Returns the number removed. True when some route currently sends through tx’s channel. O(peers): diagnostics and tests only; connections use RouteTally.

Source

pub fn disconnect_channel(&self, tx: &Sender<Vec<u8>>) -> usize

Source

pub async fn send_to_peer( &self, node_id: &str, envelope: MeshIpcEnvelope, ) -> KernelResult<()>

Send a MeshIpcEnvelope to a connected peer.

Serializes the envelope to JSON bytes and pushes them into the peer’s outbound channel. Returns an error if the peer is not connected or the channel is closed/full.

Source

pub async fn route_to_remote( &self, node_id: &str, message: KernelMessage, ) -> KernelResult<()>

Build and send a message to a remote node.

Wraps a KernelMessage in a MeshIpcEnvelope with the correct source/dest and sends it to the named peer.

Source

pub async fn handle_incoming(&self, data: &[u8]) -> KernelResult<()>

Handle incoming raw bytes from a peer.

First attempts AssessmentSync demux via the registered AssessmentTransport (WEFT-117). Non-assessment traffic is deserialized as a MeshIpcEnvelope and injected into the local A2A router. The message target is unwrapped from RemoteNode if present so that the local router delivers to the correct local process.

Source

pub async fn handle_incoming_from( &self, data: &[u8], outbound: Sender<Vec<u8>>, ) -> KernelResult<()>

Handle incoming bytes while auto-registering the sending peer.

Used by the mesh accept loop: the kernel doesn’t know the peer’s node ID until the first envelope arrives, so we opportunistically register envelope.source_node → outbound before dispatching. Always (re)registers the channel: on reconnect the node_id is unchanged but the TCP connection — and thus the outbound channel — is new, and a stale entry would route every push to the dead channel of the previous connection. This is what wires A2ARouter topic forwarding to inbound leaf subscribers (they send mesh.subscribe, then the kernel can call send_to_peer back over this connection).

Source

pub async fn handle_incoming_peer( &self, data: &[u8], outbound: Sender<Vec<u8>>, peer: Option<&PeerCtx>, ) -> KernelResult<()>

handle_incoming_from with the connection’s authenticated identity.

With peer = Some(ctx) and ctx.node_verified, the route is registered under ctx.peer_id (never under the envelope’s claim), an envelope whose source_node differs is rejected, and the route cannot later be taken over by an unverified connection. With None (or an unverified ctx) behaviour is the pre-admission one: the peer is registered under its claimed source_node, with a warning the first time that id is seen.

Source

pub async fn handle_incoming_tallied( &self, data: &[u8], outbound: Sender<Vec<u8>>, peer: Option<&PeerCtx>, tally: Option<&RouteTally>, ) -> KernelResult<()>

handle_incoming_peer that also counts the routes it registers in tally (the serving connection’s O(1) “is my route still there” signal).

Source

pub fn peer_route(&self, node_id: &str) -> Option<(u64, bool)>

The connection id and verified flag of the current route to node_id (None when not connected). Lets a cache of per-connection facts check it still describes the connection in use.

Source

pub fn peer_count(&self) -> usize

Number of currently connected peers.

Source

pub fn peer_verified(&self, node_id: &str) -> bool

True when node_id is routed through a connection whose node id admission verified.

Source

pub fn peer_licensed(&self, node_id: &str) -> bool

True when node_id is routed through a verified connection whose admitted class is node: the outbound twin of mesh_artifact_tunnel::licensed_peer. A verified leaf is not.

Source

pub fn peer_ids(&self) -> Vec<String>

List the node IDs of all connected peers.

Source

pub fn peer_details(&self) -> Vec<PeerDetail>

Per-peer connection detail, sorted by node id (observability only).

Round-trip time is deliberately absent: nothing in the runtime measures it (PeerMetrics is never fed), and a made-up zero would read as a perfect link.

Source

pub fn disconnect_peer(&self, node_id: &str)

Disconnect a peer, dropping its send channel.

Also cleans up any topic subscriptions the peer registered so future publishes don’t attempt to send to a closed channel.

Source

pub fn disconnect_all_peers(&self) -> usize

Disconnect every connected peer (used by mesh service stop / shutdown).

Returns the number of peers that were disconnected.

Source

pub fn register_peer_address(&self, node_id: &str, addr: &str)

Register a peer’s network address for future connection.

Stored in the discovery state’s address map. If discovery is not initialized this is a no-op.

Source

pub fn discover_peers(&self) -> Vec<(String, String)>

Return known peers from the discovery address map.

Each entry is (node_id, address). Returns an empty vec if discovery is not initialized.

Source

pub fn record_heartbeat(&self, node_id: &str)

Record a heartbeat from the given peer (marks it alive).

If the peer is not yet tracked by the heartbeat system it will be added automatically.

Source

pub fn mesh_time_us(&self) -> u64

Get the current mesh-synchronized time in microseconds since epoch.

If time sync is active (synced from authority), returns the authority-aligned time. Otherwise returns local system time.

Source

pub fn clock_uncertainty_us(&self) -> u64

Get the clock uncertainty estimate in microseconds.

Source

pub fn clock_source(&self) -> ClockSource

Get the current clock source quality.

Source

pub fn set_clock_source(&self, source: ClockSource)

Set the local clock source (e.g., after NTP sync is confirmed).

Source

pub fn sync_clock_from_peer( &self, peer_id: &str, peer_time_us: u64, peer_source: ClockSource, )

Process a time sync sample from a peer’s heartbeat.

Source

pub fn is_time_authority(&self) -> bool

Check if this node is the time authority.

Source

pub fn check_peer_health(&self) -> Vec<String>

Return node IDs of peers that heartbeat considers suspect or dead.

Source

pub fn remove_dead_peers(&self)

Disconnect peers that the heartbeat tracker considers dead.

Emits MeshPeerEvent::Unreachable before the connection is dropped so cluster membership can mark partition/failure separately from a graceful MeshPeerEvent::Left.

Source

pub fn discovery_mut(&mut self) -> Option<&mut DiscoveryState>

Mutable access to discovery state (for tests and setup code).

Source

pub fn discovery(&self) -> Option<&DiscoveryState>

Shared access to discovery state.

Source

pub fn build_chain_sync_request(&self, from_seq: u64) -> Vec<u8> ⓘ

Build a serialized ChainSyncRequest for sending to a peer.

The request asks for chain events starting after from_seq. When a chain manager is attached, after_hash is filled from the local tip at from_seq (or the head hash when from_seq is the tip).

Source

pub fn build_chain_sync_response( &self, after_sequence: u64, max_events: u32, ) -> Option<ChainSyncResponse>

Build a chain sync response from the local chain (server side).

Returns None when no chain manager is attached.

Source

pub fn handle_chain_sync_response(&self, data: &[u8]) -> KernelResult<usize>

Handle an incoming chain sync response by replaying remote events into the local [ChainManager] via [ChainManager::append_signed].

Returns the number of events newly applied (idempotent skips are not counted). When no chain manager is attached, returns the number of events in the payload without applying them (legacy / transport-only callers). See Self::handle_chain_sync_outcome for the typed form, which also reports a stop at an authority event.

Merge policy (ADR-089): linear catch-up only. A hash mismatch at the same sequence surfaces as a mesh error (fork) rather than silent overwrite — multi-parent merge commits are a later layer.

Source

pub fn handle_chain_sync_outcome( &self, data: &[u8], ) -> KernelResult<ChainSyncOutcome>

Self::handle_chain_sync_response with a typed, non-fatal stop: replication halts cleanly at the first authority-bearing event (a reserved source or kind, see chain::RESERVED_SOURCES) and says where, instead of failing the batch. Verified replication of authority events is future work; skipping one would leave a sequence gap.

Trait Implementations§

Source§

fn set_control_sink(&self, topic: &str, sink: Arc<dyn PeerControlSink>)

Receive topic with sink (first registration wins).
Source§

fn peer_ids(&self) -> Vec<String>

Peers to ask for a catch-up sync (the answering side checks admission).
Source§

fn peer_licensed(&self, peer: &str) -> bool

True when peer may be sent bindings and grants: verified by admission and of class node.
Source§

fn route_to_remote<'life0, 'life1, 'async_trait>( &'life0 self, peer: &'life1 str, msg: KernelMessage, ) -> Pin<Box<dyn Future<Output = KernelResult<()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Send msg to peer.
Source§

fn subscribe_peer_events(&self) -> Option<Receiver<MeshPeerEvent>>

Peer-join events, for the sync on connect (None: this mesh has none and only the periodic sync runs).

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Pointee for T

Source§

type Pointer = u32

Source§

fn debug( pointer: <T as Pointee>::Pointer, f: &mut Formatter<'_>, ) -> Result<(), Error>

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more