Merge branch 'rfc010-cluster': RFC 010 clustering (c1–c16 + Phase 6) onto the v0.7.0 + perf-audit tree

Both lines branched from ca1c983 (v0.6.1 + try_spawn). master carried
graceful shutdown, gen_server/gen_statem lifetime, v0.7.0 and the 16
perf-audit commits; rfc010-cluster carried clustering behind
`--features cluster`. Two resolutions beyond the automatic merge:

- tests/channel.rs: both sides deflaked the spawn-then-monitor race in
  channel_ops_interleaved_with_monitor_churn_multi_thread. Kept master's
  `spawn_monitor` (monitor registered before publish) over the cluster
  side's `go`-gated spawn; same intent, API-level fix.
- src/cluster/envelope.rs: master added `DownReason::Shutdown`, which
  made the `Frame::Down` reason codec non-exhaustive. New wire tag
  DR_SHUTDOWN = 6, encoded and decoded symmetrically. `Shutdown` never
  rides in a `Down` by contract (a target that honours the request
  exits normally); the tag exists so the codec stays total. Tags 1–5
  unchanged.

Gates on the merged tree (rustc 1.98.1): default 405/0, cluster 492/0
(0 ignored beyond the 11 pre-existing `ignore` doctests), clippy --lib
-D warnings on both configs, doctests. cluster_disconnect still ~1.8s
(SMARM_FAST_TIMING plumbing intact).
This commit is contained in:
claude-asm-audit
2026-09-12 05:25:50 +00:00
45 changed files with 10384 additions and 310 deletions
+630
View File
@@ -0,0 +1,630 @@
//! RFC 010 c6 — the per-peer connection actor.
//!
//! One actor per established control connection. It owns the whole
//! [`FramedConn`] and, in a single [`select`](crate::select), waits on two
//! things at once: its command inbox and the connection becoming readable (the
//! [`FdArm`](crate::scheduler::FdArm) the transport hands back). That is why it
//! is a plain select-loop actor rather than a `gen_server` or `gen_statem` —
//! neither of those can fold fd-readiness into its wait, and folding it in is
//! the whole job. The single owner sends and receives on the one `FramedConn`,
//! so no read/write split is needed.
//!
//! The handshake completes *before* this actor exists (on the accept/connect
//! path — c6b) and produces the [`Peer`]; the *path* then registers the
//! connection with the [`manager`](crate::cluster::manager), which takes
//! ownership of its [`ConnHandle`] and monitors the actor, so any exit
//! deregisters the connection. The actor itself holds no authority over its
//! own lifetime: it runs until the manager drops its handle (deregistration,
//! `Disconnect`, or manager shutdown), the connection ends, or liveness
//! expires. Heartbeat send and fixed-timeout liveness are the timeout arm of
//! the same `select` (c6c): [`HEARTBEAT_INTERVAL`] paces outbound
//! [`Frame::Heartbeat`](crate::cluster::envelope::Frame::Heartbeat)s, and a
//! [`LIVENESS_TIMEOUT`] window — reset by any inbound frame — tears the
//! connection down when it empties.
//!
//! c9 adds the third arm — the connection's dedicated **outbound inbox**
//! (`Sender<Frame>` bound in the manager-maintained outbound table, D13),
//! drained onto the wire in the same loop — and inbound *interpretation*:
//! `SendNamed` goes to the one resolution seam,
//! [`remote::deliver_named`](crate::cluster::remote::deliver_named).
//! `Send` goes to the pid seam (c10). The outbound
//! sender is a separate channel from `cmd_tx` on purpose: closing it is not
//! a stop signal — lifetime authority stays with the [`ConnHandle`] (D9).
//!
//! c12 adds the monitor plane, and it lives *here* on purpose. Two tables,
//! both owned by this actor and dying with the connection:
//!
//! - **outstanding** — monitors *this* node holds on actors at the peer:
//! `monitor_id → (target, Sender<RemoteDown>)`. Fed by
//! [`MonCmd`](crate::cluster::remote::MonCmd) from `monitor_remote`; the
//! actor records the id and *then* emits the `Monitor` frame, so a `Down`
//! frame can never race an entry that isn't there yet. An inbound `Down`
//! removes the entry and delivers.
//! - **watched** — monitors the *peer* holds on actors here: `monitor_id →
//! local Monitor`. An inbound `Monitor` is admitted only for a pid that
//! was exposed or crossed the wire (`is_watchable`, D12): a corpse answers
//! with its recorded terminal reason (RFC §6), an unwatchable or unknown
//! pid with `NoProc` — indistinguishable from dead, so nothing leaks. A
//! live watchable pid gets a local monitor whose `rx` is one more arm of
//! the select; its `Down` goes back as a frame.
//!
//! Because both tables are actor state, connection loss (c13) needs no
//! second bookkeeping owner: this actor's exit is the one place that knows
//! every monitor the link was carrying. `Monitors::teardown` runs on every
//! exit path and answers each outstanding monitor with `Disconnected` —
//! the roadmap's "partition vs. death" contrast: an actor that dies sends
//! its true reason over the link, a link that dies says only that.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use crate::channel::{channel, try_select_timeout, Receiver, Selectable, Sender};
use crate::cluster::envelope::{Frame, RemoteDownReason};
use crate::cluster::handshake::Peer;
use crate::cluster::manager::{Call, Registered, Reply, MANAGER};
use crate::cluster::remote::{
deliver_named, deliver_to_pid, InboundVerdict, MonCmd, RemoteDown, RemotePid,
};
use crate::cluster::transport::FramedConn;
use crate::cluster::Timing;
use crate::gen_server;
use crate::monitor::{
demonitor, is_watchable, monitor, terminal_reason, DownReason, Monitor, MonitorId,
};
use crate::pid::{Erased, Pid};
use crate::scheduler::spawn;
/// Commands to a running connection actor.
enum Cmd {
Shutdown,
}
/// The manager's authority over one connection actor: while this handle
/// lives the connection lives, and dropping it stops the actor and closes
/// the socket. Only the [`manager`](crate::cluster::manager) holds one —
/// callers of [`spawn_established`] get a [`Pid`] and no lifetime authority,
/// so a connection can never outlive, or die with, whichever actor happened
/// to establish it.
pub struct ConnHandle {
cmd_tx: Sender<Cmd>,
/// The connection's dedicated outbound inboxes — frames and monitor
/// commands. The manager moves them into the outbound table on
/// `Register` (see [`take_outbound`](ConnHandle::take_outbound)); a
/// `Duplicate` verdict drops them with the handle.
out_tx: Option<(Sender<Frame>, Sender<MonCmd>)>,
}
impl std::fmt::Debug for ConnHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ConnHandle")
}
}
impl ConnHandle {
/// Ask the connection to close and exit. Idempotent, and a no-op if the
/// actor has already gone. Dropping the handle does the same thing; this
/// exists for the manager's explicit `Disconnect` path.
pub fn shutdown(&self) {
let _ = self.cmd_tx.send(Cmd::Shutdown);
}
/// Manager-only: take the outbound senders to bind into the outbound
/// table. Once, at registration.
pub(crate) fn take_outbound(&mut self) -> Option<(Sender<Frame>, Sender<MonCmd>)> {
self.out_tx.take()
}
}
/// The name was already claimed by a live connection, so this one was
/// refused; its actor has been stopped and its socket closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RegisterRefused;
/// Spawn a connection actor for an **already-established** connection (the
/// handshake completed on the path and produced `peer`) and register it with
/// the manager, synchronously, before returning. The manager takes the
/// actor's [`ConnHandle`]; the caller gets only the [`Pid`], because
/// connection lifetime belongs to the table and not to the establishing
/// actor. A refusal has already stopped the actor and closed the socket.
pub fn spawn_established(
framed: FramedConn,
peer: Peer,
timing: Timing,
) -> Result<Pid, RegisterRefused> {
let (cmd_tx, cmd_rx) = channel();
let (out_tx, out_rx) = channel();
let (mon_tx, mon_rx) = channel();
let reg_peer = peer.clone();
let pid = spawn(move || run(framed, peer, timing, cmd_rx, out_rx, mon_rx)).pid();
match gen_server::call(
MANAGER,
Call::Register {
peer: reg_peer,
pid,
handle: ConnHandle {
cmd_tx,
out_tx: Some((out_tx, mon_tx)),
},
},
) {
Ok(Reply::Registered(Registered::Ok)) => Ok(pid),
// Duplicate name, or the manager is unreachable. Either way the
// handle went with the call and is dropped there (or never arrived
// and dropped with it), which stops the actor and closes the socket.
_ => Err(RegisterRefused),
}
}
/// Default for [`Timing::heartbeat_interval`]: how often this end emits
/// [`Frame::Heartbeat`] on an idle connection. The first one goes out
/// immediately at spawn, so the peer's liveness window starts fed.
pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);
/// Default for [`Timing::liveness_timeout`]: how long the connection may go
/// without a single inbound frame before it is declared dead and torn down. Any inbound frame resets the window —
/// heartbeats keep an idle connection alive, and real traffic (c8+) counts
/// for free. Fixed by design (RFC v2 §5): this is the control connection, a
/// heartbeat can never queue behind bulk traffic, so a fixed timeout is an
/// honest detector.
pub const LIVENESS_TIMEOUT: Duration = Duration::from_secs(4);
fn run(
mut framed: FramedConn,
_peer: Peer,
timing: Timing,
cmd_rx: Receiver<Cmd>,
out_rx: Receiver<Frame>,
mon_rx: Receiver<MonCmd>,
) {
let mut mons = Monitors::default();
match framed.readable_arm() {
Some(arm) => run_live(
&mut framed,
arm,
timing,
&cmd_rx,
&out_rx,
&mon_rx,
&mut mons,
),
None => run_inert(&cmd_rx),
}
framed.close();
mons.teardown(&mon_rx);
}
/// The monitor plane's two tables (module docs). Owned by the actor.
#[derive(Default)]
struct Monitors {
/// Monitors this node holds on peer actors: id → (target, delivery).
outstanding: HashMap<MonitorId, (RemotePid<Erased>, Sender<RemoteDown>)>,
/// Monitors the peer holds on local actors: id → the local monitor.
watched: HashMap<MonitorId, Monitor>,
}
impl Monitors {
/// The connection is gone, whatever the exit path (liveness expiry,
/// EOF, wire failure, commanded stop): release the peer's local
/// monitors, and answer every one of ours with `Disconnected` — nothing
/// more can be known about those actors. Commands still sitting in the
/// inbox are folded in first (a `Monitor` handed to us but never
/// processed gets its notice too; a `Demonitor` still cancels), so the
/// only registration that can miss this is one that lands after the
/// drain and before the inbox drops — the reader side backstops that
/// (`RemoteMonitor`). Entries leave the table as they are answered, and
/// this runs once per actor, so no monitor sees two notices.
fn teardown(&mut self, mon_rx: &Receiver<MonCmd>) {
for (_, m) in self.watched.drain() {
let _ = demonitor(&m);
}
while let Ok(Some(cmd)) = mon_rx.try_recv() {
match cmd {
MonCmd::Monitor { id, target, tx } => {
self.outstanding.insert(id, (target, tx));
}
MonCmd::Demonitor { id } => {
self.outstanding.remove(&id);
}
}
}
for (_, (pid, tx)) in self.outstanding.drain() {
let _ = tx.send(RemoteDown {
pid,
reason: RemoteDownReason::Disconnected,
});
}
}
/// Admit a peer's `Monitor` for local `(index, generation)`. Returns
/// the reason to answer with at once, or `None` if a live monitor was
/// installed. Corpse → recorded terminal reason (RFC §6, and only
/// watchable deaths are recorded); live watchable → monitor; anything
/// else → `NoProc`. The check-then-monitor race (dies in between) is
/// closed on the read side: a `NoProc` from a monitor we installed on a
/// live pid is upgraded through `terminal_reason` in `sweep_watched`.
fn admit(&mut self, id: MonitorId, index: u32, generation: u32) -> Option<DownReason> {
let pid = Pid::new(index, generation);
if let Some(reason) = terminal_reason(pid) {
return Some(reason);
}
if !is_watchable(pid) {
return Some(DownReason::NoProc);
}
let m = monitor(pid);
self.watched.insert(id, m);
None
}
fn cancel(&mut self, id: MonitorId) {
if let Some(m) = self.watched.remove(&id) {
let _ = demonitor(&m);
}
}
/// Collect every local `Down` that has arrived for a peer-held monitor.
fn sweep_watched(&mut self) -> Vec<(MonitorId, DownReason)> {
let mut fired = Vec::new();
for (id, m) in self.watched.iter() {
if let Ok(Some(down)) = m.rx.try_recv() {
let reason = match down.reason {
DownReason::NoProc => terminal_reason(m.target).unwrap_or(DownReason::NoProc),
r => r,
};
fired.push((*id, reason));
}
}
for (id, _) in &fired {
self.watched.remove(id);
}
fired
}
/// The peer reports a monitored actor down: deliver locally.
fn down(&mut self, id: MonitorId, reason: RemoteDownReason) {
if let Some((pid, tx)) = self.outstanding.remove(&id) {
let _ = tx.send(RemoteDown { pid, reason });
}
}
}
/// The steady-state loop over an fd-backed connection: one
/// `select_timeout` folds the command inbox, the outbound inbox, socket
/// readability, and the nearer of the two deadlines (`hb_send`,
/// `liveness`) into a single wait.
fn run_live(
framed: &mut FramedConn,
arm: crate::scheduler::FdArm,
timing: Timing,
cmd_rx: &Receiver<Cmd>,
out_rx: &Receiver<Frame>,
mon_rx: &Receiver<MonCmd>,
mons: &mut Monitors,
) {
let mut next_hb = Instant::now();
let mut live_until = Instant::now() + timing.liveness_timeout;
// The outbound senders live in the manager's table and are dropped on
// unbind; after that these arms would wake forever, so they drop out of
// the select (not a stop signal — see the module docs).
let mut out_open = true;
let mut mon_open = true;
// Which wait each select arm stands for. Built in lockstep with the
// `Selectable` vector each iteration, so a wake is decoded by name and
// never by position.
enum Arm {
Cmd,
Fd,
Out,
Mon,
/// A peer-held local monitor (any of them: firing sweeps them all).
Watched,
}
fn push<'s>(
arms: &mut Vec<&'s dyn Selectable>,
what: &mut Vec<Arm>,
s: &'s dyn Selectable,
a: Arm,
) {
arms.push(s);
what.push(a);
}
loop {
let now = Instant::now();
if now >= live_until {
break; // liveness expired: the peer is dead to us
}
if now >= next_hb {
if framed.send(&Frame::Heartbeat).is_err() {
break;
}
next_hb = now + timing.heartbeat_interval;
}
let wait = next_hb.min(live_until).saturating_duration_since(now);
let mut arms: Vec<&dyn Selectable> = Vec::new();
let mut what: Vec<Arm> = Vec::new();
push(&mut arms, &mut what, cmd_rx, Arm::Cmd);
push(&mut arms, &mut what, &arm, Arm::Fd);
if out_open {
push(&mut arms, &mut what, out_rx, Arm::Out);
}
if mon_open {
push(&mut arms, &mut what, mon_rx, Arm::Mon);
}
for m in mons.watched.values() {
push(&mut arms, &mut what, &m.rx, Arm::Watched);
}
match try_select_timeout(&arms, wait).map(|i| i.map(|i| &what[i])) {
Ok(Some(Arm::Cmd)) => {
if should_stop(cmd_rx) {
break;
}
}
Ok(Some(Arm::Fd)) => match pump_readable(framed, mons) {
Pump::Ended => break,
Pump::Frames(n) => {
if n > 0 {
live_until = Instant::now() + timing.liveness_timeout;
}
}
},
Ok(Some(Arm::Out)) => match pump_outbound(framed, out_rx) {
Outbound::Drained => {}
Outbound::Closed => out_open = false,
Outbound::WireFailed => break,
},
Ok(Some(Arm::Mon)) => match pump_moncmds(framed, mon_rx, mons) {
Outbound::Drained => {}
Outbound::Closed => mon_open = false,
Outbound::WireFailed => break,
},
Ok(Some(Arm::Watched)) => {
for (id, reason) in mons.sweep_watched() {
let frame = Frame::Down {
monitor_id: id.0,
reason: reason.into(),
};
if framed.send(&frame).is_err() {
return;
}
}
}
// A deadline passed; the top of the loop acts on whichever.
Ok(None) => {}
// The fd arm failed to register — the connection is gone.
Err(_) => break,
}
}
}
/// Drain the monitor-command inbox: record, then emit (module docs).
fn pump_moncmds(
framed: &mut FramedConn,
mon_rx: &Receiver<MonCmd>,
mons: &mut Monitors,
) -> Outbound {
loop {
match mon_rx.try_recv() {
Ok(Some(MonCmd::Monitor { id, target, tx })) => {
let frame = Frame::Monitor {
monitor_id: id.0,
index: target.index(),
generation: target.generation(),
};
mons.outstanding.insert(id, (target, tx));
if framed.send(&frame).is_err() {
return Outbound::WireFailed;
}
}
Ok(Some(MonCmd::Demonitor { id })) => {
if mons.outstanding.remove(&id).is_some()
&& framed.send(&Frame::Demonitor { monitor_id: id.0 }).is_err()
{
return Outbound::WireFailed;
}
}
Ok(None) => return Outbound::Drained,
Err(_) => return Outbound::Closed,
}
}
}
/// What one outbound-side wake (frames or monitor commands) yielded.
enum Outbound {
/// Everything queued went onto the wire; the inbox is open and empty.
Drained,
/// The manager unbound this connection's sender; nothing more will come.
Closed,
/// The socket refused a write: the connection is gone.
WireFailed,
}
/// Drain every queued outbound frame onto the wire.
fn pump_outbound(framed: &mut FramedConn, out_rx: &Receiver<Frame>) -> Outbound {
loop {
match out_rx.try_recv() {
Ok(Some(frame)) => {
if framed.send(&frame).is_err() {
return Outbound::WireFailed;
}
}
Ok(None) => return Outbound::Drained,
Err(_) => return Outbound::Closed,
}
}
}
/// No fd to select on (loopback): only a command can end the wait, and
/// neither heartbeats nor liveness run — a transport that can't report
/// readiness can't be timed either (same caveat as
/// [`FramedConn::recv_deadline`]). Loopback is a test transport; every real
/// connection is fd-backed.
fn run_inert(cmd_rx: &Receiver<Cmd>) {
loop {
let arms: [&dyn Selectable; 1] = [cmd_rx];
let _ = crate::channel::select(&arms);
if should_stop(cmd_rx) {
break;
}
}
}
/// Drain the command arm. Returns `true` when the actor should exit — a
/// shutdown was requested, or the last handle was dropped.
fn should_stop(cmd_rx: &Receiver<Cmd>) -> bool {
match cmd_rx.try_recv() {
Ok(Some(Cmd::Shutdown)) => true,
Ok(None) => false, // spurious wake
Err(_) => true, // all senders dropped
}
}
/// What one readable wake yielded.
enum Pump {
/// The connection has ended: EOF (clean or mid-frame) or an
/// unrecoverable stream error.
Ended,
/// Still up; this many complete frames were consumed (possibly zero, if
/// the wake delivered only part of a frame). Any nonzero count resets
/// the liveness window.
Frames(usize),
}
/// Surface an inbound verdict: one `smarm-trace` event, nothing else — it
/// is local knowledge (RFC §3). A no-op without the feature.
fn note_verdict(verdict: InboundVerdict) {
#[cfg(feature = "smarm-trace")]
crate::te!(crate::trace::Event::ClusterInbound(verdict.label()));
#[cfg(not(feature = "smarm-trace"))]
drop(verdict);
}
/// Consume one readable wake: exactly one socket read (which cannot block
/// after a level-triggered readable indication), then drain every complete
/// frame the buffer now holds. A blocking `recv` here would park the actor
/// past its heartbeat and liveness deadlines whenever a frame arrives split.
/// Every consumed frame counts for liveness; `SendNamed` goes to the one
/// name-resolution seam and `Send` to the pid seam. Verdicts are local
/// knowledge only — nothing goes back on the wire (RFC §3) — and surface
/// as one `smarm-trace` `ClusterInbound` event each (zero cost off).
/// `Monitor`/`Demonitor`/`Down` go to the [`Monitors`] tables; a `Monitor`
/// that can be answered at once is answered inline.
fn pump_readable(framed: &mut FramedConn, mons: &mut Monitors) -> Pump {
let eof = match framed.read_once() {
Ok(n) => n == 0,
Err(_) => return Pump::Ended,
};
let mut got = 0;
loop {
match framed.next_buffered() {
Ok(Some(frame)) => {
got += 1;
match frame {
Frame::SendNamed {
name,
type_hash,
payload,
} => {
note_verdict(deliver_named(&name, type_hash, &payload));
}
Frame::Send {
index,
generation,
type_hash,
payload,
} => {
note_verdict(deliver_to_pid(index, generation, type_hash, &payload));
}
Frame::Monitor {
monitor_id,
index,
generation,
} => {
let id = MonitorId(monitor_id);
if let Some(reason) = mons.admit(id, index, generation) {
let frame = Frame::Down {
monitor_id,
reason: reason.into(),
};
if framed.send(&frame).is_err() {
return Pump::Ended;
}
}
}
Frame::Demonitor { monitor_id } => mons.cancel(MonitorId(monitor_id)),
Frame::Down { monitor_id, reason } => mons.down(MonitorId(monitor_id), reason),
// Heartbeat: liveness only. Handshake frames after
// establishment: ignored.
_ => {}
}
}
Ok(None) => break,
Err(_) => return Pump::Ended, // corrupt stream
}
}
if eof {
Pump::Ended
} else {
Pump::Frames(got)
}
}
#[cfg(test)]
mod tests {
//! `Monitors::teardown` in isolation: the actor-side half of c13, pinned
//! separately because from the outside it is indistinguishable from the
//! read-side backstop in `RemoteMonitor` (both yield `Disconnected`).
use super::*;
use crate::pg::Incarnation;
fn pid(index: u32) -> RemotePid<Erased> {
RemotePid::from_parts("peer", Incarnation::new(1), index, 1)
}
#[test]
fn teardown_answers_every_outstanding_and_unread_monitor_once() {
crate::run(|| {
let mut mons = Monitors::default();
let (mon_tx, mon_rx) = channel::<MonCmd>();
// Already registered.
let (tx1, rx1) = channel::<RemoteDown>();
mons.outstanding.insert(MonitorId(1), (pid(1), tx1));
// In the inbox, never processed.
let (tx2, rx2) = channel::<RemoteDown>();
mon_tx
.send(MonCmd::Monitor {
id: MonitorId(2),
target: pid(2),
tx: tx2,
})
.ok()
.unwrap();
// Registered, then cancelled in the inbox: silence.
let (tx3, rx3) = channel::<RemoteDown>();
mons.outstanding.insert(MonitorId(3), (pid(3), tx3));
mon_tx
.send(MonCmd::Demonitor { id: MonitorId(3) })
.ok()
.unwrap();
mons.teardown(&mon_rx);
let d1 = rx1.recv().unwrap();
assert_eq!(
(d1.pid, d1.reason),
(pid(1), RemoteDownReason::Disconnected)
);
let d2 = rx2.recv().unwrap();
assert_eq!(
(d2.pid, d2.reason),
(pid(2), RemoteDownReason::Disconnected)
);
// Cancelled: no notice was sent (its sender is dropped, channel
// closed-empty), and nobody got a second one.
assert!(rx3.try_recv().is_err());
assert!(rx1.try_recv().is_err());
assert!(rx2.try_recv().is_err());
assert!(mons.outstanding.is_empty());
});
}
}
+365
View File
@@ -0,0 +1,365 @@
//! RFC 010 c6b — the handshake on the accept/connect path.
//!
//! Per D8 (re-amended): the c5 machines are driven by **straight-line code
//! on the path**, not by an actor. The dial side runs [`Initiator`]; the
//! acceptor loop runs [`Responder`]. A connection actor is spawned only
//! *after* a successful handshake ([`spawn_established`]); every reject,
//! protocol failure, timeout, and tie-break loss is resolved right here,
//! on the path, by closing — no actor ever exists for a connection that
//! didn't establish.
//!
//! Buffer trap (binding): the path reader and the steady-state actor share
//! ONE [`FramedConn`]. Its decode buffer may hold read-ahead past the
//! handshake frames, so the *whole* `FramedConn` travels into
//! [`spawn_established`] — never a fresh codec over the same socket.
//!
//! Layering: [`dial_handshake`] and [`accept_handshake`] are the bare path
//! steps — IO on a `FramedConn`, no manager, no actors — testable over the
//! loopback transport on plain threads. [`dial`] and [`spawn_acceptor`] are
//! the manager-integrated layer (actor context required): they keep the
//! [`manager`](crate::cluster::manager)'s dial-intent set honest and spawn
//! the connection actor on success.
use std::io;
use std::time::{Duration, Instant};
use crate::channel::{channel, Receiver, Selectable, Sender};
use crate::cluster::conn::spawn_established;
use crate::cluster::envelope::{Frame, RejectReason};
use crate::cluster::handshake::{
Initiator, InitiatorOutcome, Local, Peer, PeerStanding, Responder, ResponderOutcome,
};
use crate::cluster::manager::{Call, Reply, MANAGER};
use crate::cluster::transport::{FramedConn, Listener, RecvError, SendError, Transport};
use crate::cluster::Timing;
use crate::gen_server;
use crate::pid::Pid;
use crate::scheduler::{self, spawn};
/// Default for [`Timing::handshake_timeout`]: how long either side waits for
/// the peer's handshake frame before giving up and closing. Enforced on the path via [`FramedConn::recv_deadline`],
/// so a peer that connects and goes silent cannot wedge the acceptor.
pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
/// Why a handshake did not establish. In every case the connection has
/// already been closed on the path by the time this is returned.
#[derive(Debug)]
pub enum HandshakeError {
/// A `HelloReject` travelled — sent by us (accept side) or received by
/// us (dial side).
Rejected(RejectReason),
/// Accept side only: the inbound dial lost the simultaneous-connect
/// tie-break (D7) and was closed silently, no frame sent.
TieBreakLoss,
/// The peer spoke a valid frame that is wrong here (non-`Hello` first
/// frame; non-response to our `Hello`), or an undecodable byte stream.
Protocol,
/// EOF before the handshake resolved. On the dial side this is also
/// what losing the tie-break looks like: the peer closes silently.
Closed,
/// [`HANDSHAKE_TIMEOUT`] (or the caller's deadline) passed first.
TimedOut,
/// The transport failed mid-handshake.
Transport(io::Error),
}
fn from_send(e: SendError) -> HandshakeError {
match e {
// Handshake frames are small and self-made; an encode failure is a
// protocol-level impossibility, not a transport fault.
SendError::Encode(_) => HandshakeError::Protocol,
SendError::Io(e) => HandshakeError::Transport(e),
}
}
fn from_recv(e: RecvError) -> HandshakeError {
match e {
RecvError::Corrupt(_) => HandshakeError::Protocol,
RecvError::TruncatedByPeer => HandshakeError::Closed,
RecvError::Io(e) => HandshakeError::Transport(e),
RecvError::TimedOut => HandshakeError::TimedOut,
}
}
/// Dial-side path step: send our `Hello`, interpret the one response. On
/// `Ok` the connection is established and `framed` is live (with any
/// read-ahead intact in its buffer); on `Err` the connection is closed.
pub fn dial_handshake(
framed: &mut FramedConn,
local: &Local,
deadline: Instant,
) -> Result<Peer, HandshakeError> {
let (initiator, hello) = Initiator::new(local);
if let Err(e) = framed.send(&hello) {
framed.close();
return Err(from_send(e));
}
let outcome = match framed.recv_deadline(deadline) {
Ok(Some(frame)) => initiator.on_frame(frame),
Ok(None) => {
framed.close();
return Err(HandshakeError::Closed);
}
Err(e) => {
framed.close();
return Err(from_recv(e));
}
};
match outcome {
InitiatorOutcome::Established(peer) => Ok(peer),
InitiatorOutcome::Rejected(reason) => {
framed.close();
Err(HandshakeError::Rejected(reason))
}
InitiatorOutcome::Failed(_) => {
framed.close();
Err(HandshakeError::Protocol)
}
}
}
/// Accept-side path step: read the first frame, judge it, answer or close.
///
/// `standing_of` supplies the [`PeerStanding`] of the *offered* name — knowledge
/// only the frame reveals, which is why it is a callback and not a value
/// (the integrated acceptor asks the manager; loopback tests fabricate).
/// It is not called when the first frame is not a `Hello`.
///
/// On `Ok` the ack has been sent and `framed` is live (read-ahead intact);
/// on `Err` any owed reject has been sent and the connection is closed.
pub fn accept_handshake(
framed: &mut FramedConn,
local: Local,
standing_of: impl FnOnce(&str) -> PeerStanding,
deadline: Instant,
) -> Result<Peer, HandshakeError> {
let frame = match framed.recv_deadline(deadline) {
Ok(Some(frame)) => frame,
Ok(None) => {
framed.close();
return Err(HandshakeError::Closed);
}
Err(e) => {
framed.close();
return Err(from_recv(e));
}
};
let standing = match &frame {
Frame::Hello { node_name, .. } => standing_of(node_name),
_ => PeerStanding::Free,
};
match Responder::new(local).on_frame(frame, standing) {
ResponderOutcome::Accepted { reply, peer } => {
if let Err(e) = framed.send(&reply) {
framed.close();
return Err(from_send(e));
}
Ok(peer)
}
ResponderOutcome::Rejected { reply, reason } => {
// Best effort: the reject is the cross-version compatibility
// anchor, but if the write fails the peer sees a bare close,
// which it must survive anyway.
let _ = framed.send(&reply);
framed.close();
Err(HandshakeError::Rejected(reason))
}
ResponderOutcome::TieBreakLoss => {
// D7: close silently — the peer computes the same verdict.
framed.close();
Err(HandshakeError::TieBreakLoss)
}
ResponderOutcome::Failed(_) => {
framed.close();
Err(HandshakeError::Protocol)
}
}
}
// ---------------------------------------------------------------------------
// Manager-integrated layer
// ---------------------------------------------------------------------------
/// Why an integrated [`dial`] did not produce a connection.
#[derive(Debug)]
pub enum DialError {
/// Another dial to this peer name is already in flight.
AlreadyDialing,
/// The manager is not running (or answered nonsense).
ManagerUnavailable,
/// The transport could not connect.
Connect(io::Error),
/// Connected, but the handshake did not establish.
Handshake(HandshakeError),
/// The peer at `addr` established, but answered as a different name
/// than the one we dialed — the tie-break bookkeeping (keyed by the
/// dialed name) would be unsound, so the connection is closed.
PeerNameMismatch { expected: String, got: String },
/// The handshake established, but the manager refused the registration:
/// a connection to this peer already exists. The loser has been closed.
Duplicate,
}
impl DialError {
/// A short static label per kind, for the `smarm-trace` `ClusterDial`
/// event; the payload (io error, names) is not carried.
pub fn label(&self) -> &'static str {
match self {
DialError::AlreadyDialing => "already_dialing",
DialError::ManagerUnavailable => "manager_unavailable",
DialError::Connect(_) => "connect",
DialError::Handshake(_) => "handshake",
DialError::PeerNameMismatch { .. } => "peer_name_mismatch",
DialError::Duplicate => "duplicate",
}
}
}
/// Dial `peer_name` at `addr` and run the handshake, keeping the manager's
/// dial-intent set honest around it: the intent is registered *before*
/// connecting (so a crossing inbound `Hello` sees it) and cleared the
/// moment the handshake resolves, before the connection actor is spawned.
/// Must run inside an actor. Retrying is the caller's business (c7's dial
/// loop); a lost tie-break surfaces as `Handshake(Closed)` — the peer's
/// accepted connection is already on its way.
pub fn dial(
transport: &dyn Transport,
addr: &str,
peer_name: &str,
local: &Local,
timing: Timing,
) -> Result<Pid, DialError> {
let me = scheduler::self_pid();
match gen_server::call(
MANAGER,
Call::DialBegin {
name: peer_name.to_string(),
pid: me,
},
) {
Ok(Reply::DialBegan(true)) => {}
Ok(Reply::DialBegan(false)) => return Err(DialError::AlreadyDialing),
_ => return Err(DialError::ManagerUnavailable),
}
let result = connect_and_shake(transport, addr, local, timing);
// Cleared immediately on outcome — a stale intent during the established
// window would corrupt later tie-breaks. Synchronous (a call): the
// intent is provably gone before anything else happens.
let _ = gen_server::call(
MANAGER,
Call::DialEnd {
name: peer_name.to_string(),
},
);
let (mut framed, peer) = result?;
if peer.node_name != peer_name {
framed.close();
return Err(DialError::PeerNameMismatch {
expected: peer_name.to_string(),
got: peer.node_name,
});
}
spawn_established(framed, peer, timing).map_err(|_| DialError::Duplicate)
}
fn connect_and_shake(
transport: &dyn Transport,
addr: &str,
local: &Local,
timing: Timing,
) -> Result<(FramedConn, Peer), DialError> {
let conn = transport.dial(addr).map_err(DialError::Connect)?;
let mut framed = FramedConn::new(conn);
let deadline = Instant::now() + timing.handshake_timeout;
let peer = dial_handshake(&mut framed, local, deadline).map_err(DialError::Handshake)?;
Ok((framed, peer))
}
/// A running acceptor. [`shutdown`](AcceptorHandle::shutdown) (or dropping
/// the last handle) stops the accept loop only: connections it established
/// belong to the [`manager`](crate::cluster::manager) and keep running, to
/// be torn down through the table (`Disconnect`, a peer close, or manager
/// shutdown).
pub struct AcceptorHandle {
cmd_tx: Sender<()>,
addr: String,
}
impl AcceptorHandle {
/// Ask the acceptor to stop. Idempotent; a no-op if it already has.
pub fn shutdown(&self) {
let _ = self.cmd_tx.send(());
}
/// The concrete bound address, dialable as-is.
pub fn local_addr(&self) -> &str {
&self.addr
}
}
/// Spawn the acceptor actor over a bound listener. Each inbound connection
/// is handshaken **inline in the loop** (a deliberate serialization: the
/// per-frame deadline bounds how long any one peer can hold the line, and
/// nothing concurrent exists to be starved before c7). The listener must be
/// fd-backed ([`Listener::readable_arm`]); the loopback listener is not,
/// and its acceptor exits immediately — loopback handshakes are driven
/// synchronously through the path fns instead, per D8.
pub fn spawn_acceptor(listener: Box<dyn Listener>, local: Local, timing: Timing) -> AcceptorHandle {
let addr = listener.local_addr();
let (cmd_tx, cmd_rx) = channel();
spawn(move || accept_loop(listener, local, timing, cmd_rx));
AcceptorHandle { cmd_tx, addr }
}
fn accept_loop(
mut listener: Box<dyn Listener>,
local: Local,
timing: Timing,
cmd_rx: Receiver<()>,
) {
loop {
let Some(arm) = listener.readable_arm() else {
return;
};
let arms: [&dyn Selectable; 2] = [&cmd_rx, &arm];
match crate::channel::try_select(&arms) {
Ok(0) => match cmd_rx.try_recv() {
Ok(Some(())) => return,
Ok(None) => continue, // spurious wake
Err(_) => return, // all handles dropped
},
Ok(_) => {
// The listener is readable: accept completes without parking.
let conn = match listener.accept() {
Ok(conn) => conn,
Err(_) => return, // listener itself is broken
};
handle_inbound(FramedConn::new(conn), &local, timing);
}
Err(_) => return, // fd arm failed to register: listener is gone
}
}
}
/// Run the accept-side handshake for one inbound connection, asking the
/// manager for the [`PeerStanding`], and hand the established connection to the
/// manager. Every failure was already resolved on the path (reject sent /
/// closed, or the registration refused and the actor stopped), so there is
/// nothing for the acceptor to carry forward.
fn handle_inbound(mut framed: FramedConn, local: &Local, timing: Timing) {
let deadline = Instant::now() + timing.handshake_timeout;
let standing_of = |name: &str| match gen_server::call(
MANAGER,
Call::Standing {
peer_name: name.to_string(),
},
) {
Ok(Reply::Standing(s)) => s,
// Manager unreachable: nobody could register this connection anyway,
// so claim the name taken and reject rather than accept an orphan.
_ => PeerStanding::Claimed,
};
if let Ok(peer) = accept_handshake(&mut framed, local.clone(), standing_of, deadline) {
let _ = spawn_established(framed, peer, timing);
}
}
+316
View File
@@ -0,0 +1,316 @@
//! RFC 010 c7b — the connector: the dial loop that turns discovered
//! candidates into a full mesh.
//!
//! A plain select-loop actor (the c6 shape). It spawns its [`Strategy`] as a
//! child actor and receives [`Discovery`] events from it; it tracks which
//! peers are up by **subscribing to membership like any other consumer** —
//! no privileged channel into the manager, the same snapshot-then-stream
//! surface c8 will use. One `select` folds the command inbox, the discovery
//! stream, the membership stream, and the earliest retry deadline into a
//! single wait.
//!
//! Per-candidate state: dial on arrival; on failure retry with capped
//! exponential backoff ([`INITIAL_BACKOFF`] doubling to [`MAX_BACKOFF`]);
//! on the peer's `node_up` stop dialing and reset the backoff; on its
//! `node_down` resume immediately (a fresh sequence — the reconnect case is
//! the one backoff exists to pace, but the *first* retry after a death
//! should be prompt). A candidate bearing our own name is parked permanently
//! — that seed is us; so is one whose address answers as a different name
//! (`PeerNameMismatch`: a misconfigured or stale seed — each retry would
//! only blip the peer's membership). Every other failure retries: in
//! particular a `NameTaken` reject can be our own ghost at the peer, not
//! yet reaped by its liveness timer, so it must not park. Each attempt's
//! outcome is one `smarm-trace` `ClusterDial` event. A [`Discovery::Withdrawn`]
//! drops its `(name, addr)` from the dial set — only that: a live
//! connection is membership's, and a re-announce re-adds it fresh.
//!
//! Dials run **inline in the loop** — the same deliberate serialization as
//! the acceptor (c6b): each attempt is bounded by the connect + handshake
//! deadlines, and nothing concurrent exists to be starved. A wall of slow
//! unreachable seeds would stretch the loop's latency; revisit if a real
//! deployment ever hits that shape.
use std::collections::HashSet;
use std::time::{Duration, Instant};
use crate::channel::{channel, select, select_timeout, Receiver, Selectable, Sender};
use crate::cluster::connect::{dial, DialError};
use crate::cluster::discovery::{Discovery, Strategy};
use crate::cluster::handshake::Local;
use crate::cluster::membership::{subscribe, NodeEvent};
use crate::cluster::transport::Transport;
use crate::cluster::Timing;
use crate::scheduler::spawn;
/// Default for [`Timing::initial_backoff`]: first retry delay after a failed
/// dial attempt.
pub const INITIAL_BACKOFF: Duration = Duration::from_millis(250);
/// Default for [`Timing::max_backoff`]: an unreachable seed is retried this
/// often, forever.
pub const MAX_BACKOFF: Duration = Duration::from_secs(5);
enum Cmd {
Shutdown,
}
/// A running connector. `shutdown` (or dropping the last handle) stops the
/// dial loop and its strategy only — established connections belong to the
/// manager, exactly as with the acceptor.
pub struct ConnectorHandle {
cmd_tx: Sender<Cmd>,
}
impl ConnectorHandle {
/// Ask the connector to stop. Idempotent; a no-op if it already has.
pub fn shutdown(&self) {
let _ = self.cmd_tx.send(Cmd::Shutdown);
}
}
/// One discovered `(name, addr)` and our dial intent towards it.
struct Candidate {
name: String,
addr: String,
state: State,
}
/// The connector's *intent* for a candidate. Whether the peer is currently
/// up is a separate, name-keyed membership fact (`up` in [`run`]): a
/// candidate can arrive after its peer's `node_up` (the snapshot lands
/// before the strategy has said anything), so "up" cannot live on the
/// candidate alone — it is a filter over dialing, not a candidate state.
enum State {
/// Never dialed: this seed is the local node itself, or the address
/// answered as a *different* name than the one seeded
/// (`DialError::PeerNameMismatch` — a misconfigured or stale seed;
/// redialing would only blip the peer's membership forever). The way
/// back is the strategy's: `Withdrawn` then a fresh `Candidate`.
Parked,
/// Dial when due; on failure, back off.
Dialing {
/// Delay to apply after the *next* failure.
backoff: Duration,
next_attempt: Instant,
},
}
impl State {
fn fresh(timing: &Timing) -> Self {
State::Dialing {
backoff: timing.initial_backoff,
next_attempt: Instant::now(),
}
}
}
impl Candidate {
/// The retry deadline, if this candidate is dialing at all.
fn due(&self) -> Option<Instant> {
match self.state {
State::Parked => None,
State::Dialing { next_attempt, .. } => Some(next_attempt),
}
}
/// A dial attempt was made: schedule the retry, grow the backoff.
fn attempted(&mut self, timing: &Timing) {
if let State::Dialing {
backoff,
next_attempt,
} = &mut self.state
{
*next_attempt = Instant::now() + *backoff;
*backoff = (*backoff * 2).min(timing.max_backoff);
}
}
/// The peer came up: the next sequence (after a later `node_down`)
/// starts from the initial delay again.
fn peer_up(&mut self, timing: &Timing) {
if let State::Dialing { backoff, .. } = &mut self.state {
*backoff = timing.initial_backoff;
}
}
/// The peer went down: redial promptly, fresh sequence.
fn peer_down(&mut self, timing: &Timing) {
if matches!(self.state, State::Dialing { .. }) {
self.state = State::fresh(timing);
}
}
}
/// Spawn the connector actor. The strategy is spawned as its child; the
/// membership subscription is taken inside the actor. Must be called from
/// inside an actor (the same requirement as `dial`).
pub fn spawn_connector(
transport: Box<dyn Transport>,
local: Local,
strategy: Box<dyn Strategy>,
timing: Timing,
) -> ConnectorHandle {
let (cmd_tx, cmd_rx) = channel();
spawn(move || run(transport, local, strategy, timing, cmd_rx));
ConnectorHandle { cmd_tx }
}
fn run(
transport: Box<dyn Transport>,
local: Local,
strategy: Box<dyn Strategy>,
timing: Timing,
cmd_rx: Receiver<Cmd>,
) {
// Membership is the connector's source of truth for "who is up" — the
// snapshot seeds `up` before any candidate arrives.
let Some(events) = subscribe() else {
return; // no manager, no cluster to connect
};
let (disc_tx, disc_rx) = channel();
spawn(move || strategy.run(disc_tx));
let mut cands: Vec<Candidate> = Vec::new();
let mut up: HashSet<String> = HashSet::new();
let mut strategy_done = false;
loop {
// Drain every input, then act. Order does not matter: acting is
// idempotent against the resulting state.
match drain_cmd(&cmd_rx) {
Drained::Stop => return,
Drained::Open => {}
}
if !strategy_done {
strategy_done = drain_discoveries(&disc_rx, &local, &timing, &mut cands);
}
match drain_events(&events.rx, &timing, &mut up, &mut cands) {
Drained::Stop => return, // manager gone: the cluster is tearing down
Drained::Open => {}
}
// Dial everything due, inline (see the module docs on serialization).
let now = Instant::now();
for c in cands
.iter_mut()
.filter(|c| !up.contains(&c.name) && c.due().is_some_and(|d| d <= now))
{
// On success the manager's node_up is on its way and lands in
// `up` (backing off meanwhile keeps a racing re-attempt from
// spinning); every failure retries — see the module docs —
// except a peer-name mismatch, which parks the candidate.
let outcome = dial(&*transport, &c.addr, &c.name, &local, timing);
note_dial(&outcome);
match outcome {
Err(DialError::PeerNameMismatch { .. }) => c.state = State::Parked,
_ => c.attempted(&timing),
}
}
// Wait: until the earliest retry deadline among actionable
// candidates, or indefinitely if none is pending.
let deadline = cands
.iter()
.filter(|c| !up.contains(&c.name))
.filter_map(Candidate::due)
.min();
let mut arms: Vec<&dyn Selectable> = vec![&cmd_rx, &events.rx];
if !strategy_done {
arms.push(&disc_rx);
}
match deadline {
Some(d) => {
let wait = d.saturating_duration_since(Instant::now());
let _ = select_timeout(&arms, wait);
}
None => {
let _ = select(&arms);
}
}
}
}
enum Drained {
Open,
Stop,
}
fn drain_cmd(rx: &Receiver<Cmd>) -> Drained {
match rx.try_recv() {
Ok(Some(Cmd::Shutdown)) => Drained::Stop,
Ok(None) => Drained::Open,
Err(_) => Drained::Stop, // all handles dropped
}
}
/// Pull every pending discovery into the candidate set (deduplicated by
/// `(name, addr)`; a candidate bearing the local name is parked; a
/// `Withdrawn` removes its pair from the dial set and nothing else — see
/// [`Discovery::Withdrawn`]). Returns `true` once the strategy's channel
/// closes — it has said all it will.
fn drain_discoveries(
rx: &Receiver<Discovery>,
local: &Local,
timing: &Timing,
cands: &mut Vec<Candidate>,
) -> bool {
loop {
match rx.try_recv() {
Ok(Some(Discovery::Withdrawn { name, addr })) => {
cands.retain(|c| !(c.name == name && c.addr == addr));
}
Ok(Some(Discovery::Candidate { name, addr })) => {
if cands.iter().any(|c| c.name == name && c.addr == addr) {
continue;
}
let state = if name == local.node_name {
State::Parked
} else {
State::fresh(timing)
};
cands.push(Candidate { name, addr, state });
}
Ok(None) => return false,
Err(_) => return true, // strategy done; its candidates live on here
}
}
}
/// Fold pending membership events into `up`; each is also a transition on
/// that peer's candidates (see [`Candidate::peer_up`] / [`peer_down`]).
///
/// [`peer_down`]: Candidate::peer_down
fn drain_events(
rx: &Receiver<NodeEvent>,
timing: &Timing,
up: &mut HashSet<String>,
cands: &mut [Candidate],
) -> Drained {
loop {
match rx.try_recv() {
Ok(Some(NodeEvent::NodeUp(info))) => {
cands
.iter_mut()
.filter(|c| c.name == info.name)
.for_each(|c| c.peer_up(timing));
up.insert(info.name);
}
Ok(Some(NodeEvent::NodeDown(info))) => {
up.remove(&info.name);
cands
.iter_mut()
.filter(|c| c.name == info.name)
.for_each(|c| c.peer_down(timing));
}
Ok(None) => return Drained::Open,
Err(_) => return Drained::Stop,
}
}
}
/// Surface a dial outcome: one `smarm-trace` event, nothing else. The
/// connector's bookkeeping is decided by the caller.
fn note_dial(outcome: &Result<crate::pid::Pid, DialError>) {
#[cfg(feature = "smarm-trace")]
crate::te!(crate::trace::Event::ClusterDial(
outcome.as_ref().map_or_else(DialError::label, |_| "ok")
));
#[cfg(not(feature = "smarm-trace"))]
let _ = outcome;
}
+76
View File
@@ -0,0 +1,76 @@
//! RFC 010 c7b — peer discovery: the [`Strategy`] seam and the static-seeds
//! implementation.
//!
//! A strategy is **push-based and runs as its own actor**: the
//! [`connector`](crate::cluster::connector) spawns it with the sending end of
//! a channel, and the strategy emits [`Discovery`] events whenever it learns
//! something — once at startup for a static list, continuously for a future
//! mDNS/DNS strategy — for as long as it cares to run. Returning ends the
//! strategy actor; the candidates it pushed live on in the connector (the
//! connector owns all retry/backoff state, so a strategy never re-announces).
//!
//! A candidate is a **`(node_name, addr)` pair**, not a bare address: the
//! dial path and the D7 tie-break are keyed by peer *name* (the dial intent
//! must be registered before connecting so a crossing inbound `Hello` sees
//! it), so an anonymous dial would reintroduce exactly the
//! simultaneous-connect flap D7 exists to prevent. Discovery mechanisms know
//! names — that is what they discover.
use crate::channel::Sender;
/// A discovery event, as pushed by a [`Strategy`].
///
/// `Candidate` announces, `Withdrawn` retracts — the primitive pair. A
/// strategy that wants TTL semantics builds them on top (track its own
/// last-seen times, emit `Withdrawn` on expiry); the connector deliberately
/// has no clock of its own for candidates (D11: strategies never
/// re-announce, the connector owns retry). `#[non_exhaustive]` so more can
/// land without breaking strategies.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Discovery {
/// A peer worth dialing: its claimed node name and a dialable address.
Candidate { name: String, addr: String },
/// Stop dialing this `(name, addr)`. Dial-set only: a connection that
/// is already up is membership's business and is left alone; an
/// attempt in flight completes on its own; a later `Candidate` for the
/// same pair re-adds it with fresh backoff. Unknown pairs are ignored.
Withdrawn { name: String, addr: String },
}
/// A source of peers to dial. Implementations are spawned as actors by the
/// connector — see the module docs for the contract.
pub trait Strategy: Send + 'static {
/// Run the strategy: push [`Discovery`] events into `out` as they are
/// learned; return when done discovering (or when `out` reports closed —
/// the connector is gone). Runs inside an actor, so blocking
/// cooperatively is fine.
fn run(self: Box<Self>, out: Sender<Discovery>);
}
/// The static-seeds strategy: a fixed `(name, addr)` list, announced once.
#[derive(Debug, Clone, Default)]
pub struct StaticSeeds {
seeds: Vec<(String, String)>,
}
impl StaticSeeds {
pub fn new(seeds: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>) -> Self {
StaticSeeds {
seeds: seeds
.into_iter()
.map(|(n, a)| (n.into(), a.into()))
.collect(),
}
}
}
impl Strategy for StaticSeeds {
fn run(self: Box<Self>, out: Sender<Discovery>) {
for (name, addr) in self.seeds {
if out.send(Discovery::Candidate { name, addr }).is_err() {
return; // connector gone; nobody to discover for
}
}
}
}
+549
View File
@@ -0,0 +1,549 @@
//! RFC 010 c2 — the owned wire envelope.
//!
//! Every control-plane frame is `u32` little-endian length prefix (of tag +
//! body), `u8` tag, hand-encoded body. postcard appears in exactly one place:
//! the payload blob inside `Send`/`SendNamed`, via [`encode_payload`] /
//! [`decode_payload`] — the seam where a codec swap would land (RFC 010 §2).
//! Everything else is hand-rolled and wholly owned.
//!
//! Integers are little-endian. Strings are `u16` length + UTF-8 bytes.
//! Payload blobs are `u32` length + bytes. Enum-shaped fields
//! ([`RejectReason`], [`DownReason`]) are a single tag byte.
use crate::monitor::DownReason;
use crate::pg::Incarnation;
/// Wire protocol version, checked in the handshake (c5).
pub const PROTO_VERSION: u32 = 1;
/// Hard cap on the length prefix. The control plane never carries bulk data
/// (RFC 010 §5 — that is the jarred rkyv plane), so anything larger is
/// corruption or an attack, not a legitimate frame.
pub const MAX_FRAME_LEN: usize = 16 * 1024 * 1024;
/// Per-node metadata exchanged in the handshake (RFC 010 §1: not identity).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NodeMeta {
pub role: String,
pub region: String,
}
/// Why a `Hello` was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RejectReason {
/// Build hashes differ — not the same binary.
HashMismatch,
/// The offered node name is already claimed by a live peer.
NameTaken,
/// Wire protocol version mismatch.
ProtoVersion,
}
/// The control-plane frame inventory (RFC 010, *Implementation details*).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Frame {
Hello {
proto_version: u32,
build_hash: u64,
node_name: String,
incarnation: Incarnation,
meta: NodeMeta,
},
HelloAck {
node_name: String,
incarnation: Incarnation,
meta: NodeMeta,
},
HelloReject {
reason: RejectReason,
},
Heartbeat,
Send {
/// Target slot index (node is implicit in the connection, incarnation
/// is bound at handshake — RFC 010 §3).
index: u32,
generation: u32,
type_hash: u64,
payload: Vec<u8>,
},
SendNamed {
name: String,
type_hash: u64,
payload: Vec<u8>,
},
Monitor {
monitor_id: u64,
index: u32,
generation: u32,
},
Demonitor {
monitor_id: u64,
},
Down {
monitor_id: u64,
reason: RemoteDownReason,
},
}
/// Why a remotely-monitored actor is reported down: either the target's own
/// terminal [`DownReason`] as its node recorded it, or the *link* to that
/// node was lost (or absent) — which says nothing about the actor itself.
///
/// This is the cluster-side widening of `DownReason` (p5): `Disconnected`
/// is a fact about a connection, never about a local actor, so it lives
/// here rather than in the core enum — a local `Down` can never carry it,
/// and matches on `DownReason` stay exhaustive over actor outcomes only.
/// On the wire `Local(r)` uses `r`'s tag and `Disconnected` is tag 5,
/// bound since c11; no peer emits it today (a lost link is synthesized
/// locally), but the codec honours it both ways.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemoteDownReason {
/// The target itself terminated; the peer reported this reason.
Local(DownReason),
/// The link to the target's node was lost or was never up.
Disconnected,
}
impl RemoteDownReason {
/// The actor's own reason, if this was not a link loss.
pub fn local(self) -> Option<DownReason> {
match self {
RemoteDownReason::Local(r) => Some(r),
RemoteDownReason::Disconnected => None,
}
}
}
impl From<DownReason> for RemoteDownReason {
fn from(r: DownReason) -> Self {
RemoteDownReason::Local(r)
}
}
// Frame tags. 0 is deliberately unassigned so an all-zero buffer never parses.
const TAG_HELLO: u8 = 1;
const TAG_HELLO_ACK: u8 = 2;
const TAG_HELLO_REJECT: u8 = 3;
const TAG_HEARTBEAT: u8 = 4;
const TAG_SEND: u8 = 5;
const TAG_SEND_NAMED: u8 = 6;
const TAG_MONITOR: u8 = 7;
const TAG_DEMONITOR: u8 = 8;
const TAG_DOWN: u8 = 9;
// RejectReason tags.
const REJ_HASH_MISMATCH: u8 = 1;
const REJ_NAME_TAKEN: u8 = 2;
const REJ_PROTO_VERSION: u8 = 3;
// DownReason tags. Do not reuse tags.
const DR_EXIT: u8 = 1;
const DR_PANIC: u8 = 2;
const DR_STOPPED: u8 = 3;
const DR_NOPROC: u8 = 4;
const DR_DISCONNECTED: u8 = 5;
// `Shutdown` never rides in a `Down` by contract (a target that honours the
// request exits normally) — the tag exists so the codec stays total.
const DR_SHUTDOWN: u8 = 6;
/// Frame could not be encoded. The output buffer is left exactly as it was.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EncodeError {
/// tag + body exceed [`MAX_FRAME_LEN`].
FrameTooLarge { len: usize },
/// A string field exceeds `u16::MAX` bytes.
StringTooLong { len: usize },
}
impl core::fmt::Display for EncodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::FrameTooLarge { len } => {
write!(f, "frame body of {len} bytes exceeds MAX_FRAME_LEN")
}
Self::StringTooLong { len } => {
write!(f, "string field of {len} bytes exceeds u16::MAX")
}
}
}
}
impl std::error::Error for EncodeError {}
/// Frame could not be decoded. Everything here is *corruption* — "not enough
/// bytes yet" is the `Ok(None)` streaming case, never an error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecodeError {
/// The length prefix exceeds [`MAX_FRAME_LEN`].
FrameTooLarge { declared: usize },
/// The length prefix is zero — there is no tag byte.
EmptyFrame,
/// Unknown frame tag.
UnknownTag(u8),
/// Unknown tag for an enum-shaped field.
UnknownEnumTag { what: &'static str, tag: u8 },
/// A field ran past the declared frame end (the length prefix lied long,
/// or a length-carrying field inside the body lied).
Truncated,
/// Bytes were left over after the body (the length prefix lied short).
Trailing { extra: usize },
/// A string field was not valid UTF-8.
Utf8,
}
impl core::fmt::Display for DecodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::FrameTooLarge { declared } => {
write!(f, "declared frame length {declared} exceeds MAX_FRAME_LEN")
}
Self::EmptyFrame => write!(f, "zero-length frame (no tag byte)"),
Self::UnknownTag(t) => write!(f, "unknown frame tag {t}"),
Self::UnknownEnumTag { what, tag } => write!(f, "unknown {what} tag {tag}"),
Self::Truncated => write!(f, "frame body truncated mid-field"),
Self::Trailing { extra } => write!(f, "{extra} trailing bytes after frame body"),
Self::Utf8 => write!(f, "string field is not valid UTF-8"),
}
}
}
impl std::error::Error for DecodeError {}
impl Frame {
/// Append this frame, length-prefixed, to `out`.
///
/// On error `out` is left untouched.
pub fn encode(&self, out: &mut Vec<u8>) -> Result<(), EncodeError> {
let start = out.len();
out.extend_from_slice(&[0u8; 4]); // length placeholder, patched below
let result = self.encode_body(out);
match result {
Ok(()) => {
let frame_len = out.len() - start - 4;
if frame_len > MAX_FRAME_LEN {
out.truncate(start);
return Err(EncodeError::FrameTooLarge { len: frame_len });
}
// Cast is lossless: MAX_FRAME_LEN < u32::MAX, checked above.
let len32 = frame_len as u32;
out[start..start + 4].copy_from_slice(&len32.to_le_bytes());
Ok(())
}
Err(e) => {
out.truncate(start);
Err(e)
}
}
}
fn encode_body(&self, out: &mut Vec<u8>) -> Result<(), EncodeError> {
match self {
Frame::Hello {
proto_version,
build_hash,
node_name,
incarnation,
meta,
} => {
out.push(TAG_HELLO);
put_u32(out, *proto_version);
put_u64(out, *build_hash);
put_str(out, node_name)?;
put_u32(out, incarnation.get());
put_meta(out, meta)?;
}
Frame::HelloAck {
node_name,
incarnation,
meta,
} => {
out.push(TAG_HELLO_ACK);
put_str(out, node_name)?;
put_u32(out, incarnation.get());
put_meta(out, meta)?;
}
Frame::HelloReject { reason } => {
out.push(TAG_HELLO_REJECT);
out.push(match reason {
RejectReason::HashMismatch => REJ_HASH_MISMATCH,
RejectReason::NameTaken => REJ_NAME_TAKEN,
RejectReason::ProtoVersion => REJ_PROTO_VERSION,
});
}
Frame::Heartbeat => out.push(TAG_HEARTBEAT),
Frame::Send {
index,
generation,
type_hash,
payload,
} => {
out.push(TAG_SEND);
put_u32(out, *index);
put_u32(out, *generation);
put_u64(out, *type_hash);
put_blob(out, payload)?;
}
Frame::SendNamed {
name,
type_hash,
payload,
} => {
out.push(TAG_SEND_NAMED);
put_str(out, name)?;
put_u64(out, *type_hash);
put_blob(out, payload)?;
}
Frame::Monitor {
monitor_id,
index,
generation,
} => {
out.push(TAG_MONITOR);
put_u64(out, *monitor_id);
put_u32(out, *index);
put_u32(out, *generation);
}
Frame::Demonitor { monitor_id } => {
out.push(TAG_DEMONITOR);
put_u64(out, *monitor_id);
}
Frame::Down { monitor_id, reason } => {
out.push(TAG_DOWN);
put_u64(out, *monitor_id);
out.push(match reason {
RemoteDownReason::Local(DownReason::Exit) => DR_EXIT,
RemoteDownReason::Local(DownReason::Panic) => DR_PANIC,
RemoteDownReason::Local(DownReason::Stopped) => DR_STOPPED,
RemoteDownReason::Local(DownReason::NoProc) => DR_NOPROC,
RemoteDownReason::Local(DownReason::Shutdown) => DR_SHUTDOWN,
RemoteDownReason::Disconnected => DR_DISCONNECTED,
});
}
}
Ok(())
}
/// Try to decode one frame from the start of `buf`.
///
/// `Ok(Some((frame, consumed)))` — a full frame; the caller advances by
/// `consumed`. `Ok(None)` — not enough bytes yet (streaming); read more
/// and retry. `Err(_)` — the bytes are corrupt; the connection is dead.
pub fn decode(buf: &[u8]) -> Result<Option<(Frame, usize)>, DecodeError> {
let Some(prefix) = buf.get(0..4) else {
return Ok(None);
};
let mut len4 = [0u8; 4];
len4.copy_from_slice(prefix);
let declared = u32::from_le_bytes(len4) as usize;
if declared > MAX_FRAME_LEN {
return Err(DecodeError::FrameTooLarge { declared });
}
if declared == 0 {
return Err(DecodeError::EmptyFrame);
}
let Some(body) = buf.get(4..4 + declared) else {
return Ok(None);
};
let mut r = Reader { buf: body, pos: 0 };
let frame = Self::decode_body(&mut r)?;
if r.pos != body.len() {
return Err(DecodeError::Trailing {
extra: body.len() - r.pos,
});
}
Ok(Some((frame, 4 + declared)))
}
fn decode_body(r: &mut Reader<'_>) -> Result<Frame, DecodeError> {
let tag = r.u8()?;
let frame = match tag {
TAG_HELLO => Frame::Hello {
proto_version: r.u32()?,
build_hash: r.u64()?,
node_name: r.string()?,
incarnation: Incarnation::new(r.u32()?),
meta: r.meta()?,
},
TAG_HELLO_ACK => Frame::HelloAck {
node_name: r.string()?,
incarnation: Incarnation::new(r.u32()?),
meta: r.meta()?,
},
TAG_HELLO_REJECT => Frame::HelloReject {
reason: match r.u8()? {
REJ_HASH_MISMATCH => RejectReason::HashMismatch,
REJ_NAME_TAKEN => RejectReason::NameTaken,
REJ_PROTO_VERSION => RejectReason::ProtoVersion,
t => {
return Err(DecodeError::UnknownEnumTag {
what: "RejectReason",
tag: t,
})
}
},
},
TAG_HEARTBEAT => Frame::Heartbeat,
TAG_SEND => Frame::Send {
index: r.u32()?,
generation: r.u32()?,
type_hash: r.u64()?,
payload: r.blob()?,
},
TAG_SEND_NAMED => Frame::SendNamed {
name: r.string()?,
type_hash: r.u64()?,
payload: r.blob()?,
},
TAG_MONITOR => Frame::Monitor {
monitor_id: r.u64()?,
index: r.u32()?,
generation: r.u32()?,
},
TAG_DEMONITOR => Frame::Demonitor {
monitor_id: r.u64()?,
},
TAG_DOWN => Frame::Down {
monitor_id: r.u64()?,
reason: match r.u8()? {
DR_EXIT => RemoteDownReason::Local(DownReason::Exit),
DR_PANIC => RemoteDownReason::Local(DownReason::Panic),
DR_STOPPED => RemoteDownReason::Local(DownReason::Stopped),
DR_NOPROC => RemoteDownReason::Local(DownReason::NoProc),
DR_SHUTDOWN => RemoteDownReason::Local(DownReason::Shutdown),
DR_DISCONNECTED => RemoteDownReason::Disconnected,
t => {
return Err(DecodeError::UnknownEnumTag {
what: "RemoteDownReason",
tag: t,
})
}
},
},
t => return Err(DecodeError::UnknownTag(t)),
};
Ok(frame)
}
}
// ---------------------------------------------------------------------------
// Body writers
// ---------------------------------------------------------------------------
fn put_u32(out: &mut Vec<u8>, v: u32) {
out.extend_from_slice(&v.to_le_bytes());
}
fn put_u64(out: &mut Vec<u8>, v: u64) {
out.extend_from_slice(&v.to_le_bytes());
}
fn put_str(out: &mut Vec<u8>, s: &str) -> Result<(), EncodeError> {
let Ok(len) = u16::try_from(s.len()) else {
return Err(EncodeError::StringTooLong { len: s.len() });
};
out.extend_from_slice(&len.to_le_bytes());
out.extend_from_slice(s.as_bytes());
Ok(())
}
fn put_blob(out: &mut Vec<u8>, b: &[u8]) -> Result<(), EncodeError> {
let Ok(len) = u32::try_from(b.len()) else {
return Err(EncodeError::FrameTooLarge { len: b.len() });
};
out.extend_from_slice(&len.to_le_bytes());
out.extend_from_slice(b);
Ok(())
}
fn put_meta(out: &mut Vec<u8>, m: &NodeMeta) -> Result<(), EncodeError> {
put_str(out, &m.role)?;
put_str(out, &m.region)
}
// ---------------------------------------------------------------------------
// Body reader
// ---------------------------------------------------------------------------
struct Reader<'a> {
buf: &'a [u8],
pos: usize,
}
impl Reader<'_> {
fn take(&mut self, n: usize) -> Result<&[u8], DecodeError> {
let end = self.pos.checked_add(n).ok_or(DecodeError::Truncated)?;
let s = self.buf.get(self.pos..end).ok_or(DecodeError::Truncated)?;
self.pos = end;
Ok(s)
}
fn u8(&mut self) -> Result<u8, DecodeError> {
Ok(self.take(1)?[0])
}
fn u16(&mut self) -> Result<u16, DecodeError> {
let mut b = [0u8; 2];
b.copy_from_slice(self.take(2)?);
Ok(u16::from_le_bytes(b))
}
fn u32(&mut self) -> Result<u32, DecodeError> {
let mut b = [0u8; 4];
b.copy_from_slice(self.take(4)?);
Ok(u32::from_le_bytes(b))
}
fn u64(&mut self) -> Result<u64, DecodeError> {
let mut b = [0u8; 8];
b.copy_from_slice(self.take(8)?);
Ok(u64::from_le_bytes(b))
}
fn string(&mut self) -> Result<String, DecodeError> {
let len = self.u16()? as usize;
let bytes = self.take(len)?;
match core::str::from_utf8(bytes) {
Ok(s) => Ok(s.to_owned()),
Err(_) => Err(DecodeError::Utf8),
}
}
fn blob(&mut self) -> Result<Vec<u8>, DecodeError> {
let len = self.u32()? as usize;
Ok(self.take(len)?.to_vec())
}
fn meta(&mut self) -> Result<NodeMeta, DecodeError> {
Ok(NodeMeta {
role: self.string()?,
region: self.string()?,
})
}
}
// ---------------------------------------------------------------------------
// The postcard seam (RFC 010 §2) — the ONLY place payload bytes are produced
// or consumed. A codec swap lands here and nowhere else.
// ---------------------------------------------------------------------------
/// Payload (de)serialization failed at the codec seam.
#[derive(Debug)]
pub struct PayloadError(String);
impl core::fmt::Display for PayloadError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "payload codec: {}", self.0)
}
}
impl std::error::Error for PayloadError {}
/// Serialize a payload value to the wire blob.
pub fn encode_payload<T: serde::Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, PayloadError> {
postcard::to_allocvec(value).map_err(|e| PayloadError(e.to_string()))
}
/// Deserialize a payload value from the wire blob.
pub fn decode_payload<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T, PayloadError> {
postcard::from_bytes(bytes).map_err(|e| PayloadError(e.to_string()))
}
+238
View File
@@ -0,0 +1,238 @@
//! RFC 010 c8 — explicit exposure: the node's remote surface, and the
//! fixed-seed type hash.
//!
//! Nothing local is remotely reachable by default (RFC §4 — "a gun needs a
//! safety"). [`expose`] marks a registered name remotely addressable and
//! registers `M`'s decoder under [`type_hash::<M>()`](type_hash);
//! [`expose_type`] registers only the decoder (the reply-to path: a
//! `RemotePid<A>` received in a message is sendable only if `A::Msg`'s
//! decoder was explicitly registered). The exposed set is the node's
//! visible, auditable remote surface ([`exposed_names`]).
//!
//! ## Where the state lives
//!
//! On `RuntimeInner`, the [`pg`](crate::pg) pattern: a leaf-locked table,
//! cfg-gated behind the `cluster` feature (zero-cost-when-off, per c1).
//! Chosen over manager-held state because c9's inbound decode consults it
//! per frame — a hot path that must not serialize every remote delivery
//! through one gen_server. The state resets with the runtime, like every
//! registry.
//!
//! ## The watchable fold (D3), against the code as it stands
//!
//! RFC §4: the exposed set is not a new registry — it folds into the
//! existing `watchable` machinery, one set, two set-sites (a pid crossing
//! the membrane, and expose). Reading the code: `register` **already
//! stamps every named holder watchable** ("no successfully-registered actor
//! can die unflagged", registry.rs), so an exposed *name*'s holder needs no
//! extra mark here — the guarantee holds by registration, and re-registration
//! after a holder's death re-stamps the new holder for free (a per-tenancy
//! mark taken at expose time could not do that). The cluster's own
//! `mark_watchable` set-site is therefore the **pid crossing the wire** —
//! serialization of a pid into a frame, c10 — the exact analog of the
//! membrane crossing. What lives here is only the name/type-level state
//! neither the registry nor the slot bits can carry: which names are
//! exposed, and how to decode each type hash.
//!
//! ## The hash
//!
//! [`type_hash`] is FNV-1a 64 (fixed seed: the FNV offset basis) over
//! `TypeId`, so it is a constant of the binary: stable across runs of the
//! same build — exactly the scope the build-hash handshake reduces the mesh
//! to — and deliberately *not* stable across builds (scope guard: no
//! cross-version wire compatibility). A collision between two exposed types
//! degrades to a decode error or a refused channel, never a misroute — the
//! local `SendError::NoChannel` guarantee survives the network (RFC §3).
//!
//! ## The decoder contract
//!
//! A decoder is **decode-and-deliver-to-pid**: it captures `M` (the one
//! typed site), decodes the payload, and hands the value to the target's
//! published channel via the registry's own dynamic send. Wire-name →
//! local-pid resolution deliberately stays *outside* — that is c9's single
//! resolution seam, and it calls [`decode_deliver`].
use std::any::TypeId;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use crate::cluster::envelope::{decode_payload, PayloadError};
use crate::pid::{Name, Pid};
use crate::registry::{send_dyn, SendError};
use crate::scheduler::with_runtime;
/// The fixed-seed `TypeId` → `u64` hash: FNV-1a 64 over the `TypeId`'s hash
/// bytes, seeded with the FNV offset basis. A constant of the binary — see
/// the module docs for scope.
pub fn type_hash<M: 'static>() -> u64 {
let mut h = Fnv1a64::new();
TypeId::of::<M>().hash(&mut h);
h.finish()
}
/// FNV-1a 64 as a `Hasher`, so `TypeId` (opaque, `Hash`-only) can feed it.
/// Same constants as the const fns in [`crate::cluster`] (BUILD_HASH).
struct Fnv1a64(u64);
impl Fnv1a64 {
fn new() -> Self {
Fnv1a64(0xcbf2_9ce4_8422_2325)
}
}
impl Hasher for Fnv1a64 {
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.0 ^= b as u64;
self.0 = self.0.wrapping_mul(0x0000_0100_0000_01b3);
}
}
fn finish(&self) -> u64 {
self.0
}
}
/// Why a [`decode_deliver`] did not deliver. Payload-free mirror of the
/// registry's `SendError` where relevant — the caller (c9's inbound path)
/// has only bytes to give back, not a typed message.
#[derive(Debug)]
pub enum DeliverError {
/// No decoder is registered under this hash — the type was never
/// exposed here.
UnknownType,
/// The bytes did not decode as the registered type.
Decode(PayloadError),
/// The target actor is dead (or was never alive).
Dead,
/// The target is live but has no channel for this message type, or that
/// channel is closed — the `NoChannel` guarantee: a decoded value is
/// refused, never misrouted.
WrongChannel,
}
/// A registered decoder: decode `bytes` as the captured type and deliver to
/// `pid`'s published channel. `Arc`, so [`decode_deliver`] can clone it out
/// from under the exposure lock and call it lock-free — the decoder's
/// `send_dyn` takes the registry lock, and the two are mutual Leaves that
/// must never nest.
type Decoder = std::sync::Arc<dyn Fn(Pid, &[u8]) -> Result<(), DeliverError> + Send + Sync>;
/// The exposure state, one per runtime (a `RuntimeInner` field, pg-style).
pub(crate) struct ExposureState {
/// The exposed names: registry key → the type hash it expects.
exposed: HashMap<&'static str, u64>,
/// The decoders: type hash → decode-and-deliver.
decoders: HashMap<u64, Decoder>,
}
impl ExposureState {
pub(crate) fn new() -> Self {
ExposureState {
exposed: HashMap::new(),
decoders: HashMap::new(),
}
}
}
/// Mark `name` remotely addressable and register `M`'s decoder under its
/// type hash (so both name-sends and pid-sends of `M` work — RFC §4).
/// Returns the hash.
///
/// Exposure is a **name-level fact**, independent of who currently holds the
/// name (names late-bind: the registry re-resolves on every send, and c9's
/// seam resolves per delivery). Exposing an unregistered name is therefore
/// valid — deliveries fail with "unresolved" until someone registers it.
/// Idempotent. Must run inside [`run`](crate::run).
pub fn expose<M>(name: Name<M>) -> u64
where
M: serde::de::DeserializeOwned + Send + 'static,
{
let h = ensure_decoder::<M>();
with_runtime(|inner| {
inner.exposure.lock().exposed.insert(name.as_str(), h);
});
h
}
/// Register only `M`'s decoder (no name): the reply-to path. Returns the
/// hash. Idempotent. Must run inside [`run`](crate::run).
pub fn expose_type<M>() -> u64
where
M: serde::de::DeserializeOwned + Send + 'static,
{
ensure_decoder::<M>()
}
fn ensure_decoder<M>() -> u64
where
M: serde::de::DeserializeOwned + Send + 'static,
{
let h = type_hash::<M>();
with_runtime(|inner| {
inner
.exposure
.lock()
.decoders
.entry(h)
.or_insert_with(decoder::<M>);
});
h
}
/// The one typed site: decode as `M`, deliver via the registry's dynamic
/// send. See the module docs for the error mapping.
fn decoder<M>() -> Decoder
where
M: serde::de::DeserializeOwned + Send + 'static,
{
std::sync::Arc::new(|pid, bytes| {
let m: M = decode_payload(bytes).map_err(DeliverError::Decode)?;
send_dyn(pid, m).map_err(|e| match e {
SendError::Dead(_) | SendError::Unresolved(_) | SendError::NoMember(_) => {
DeliverError::Dead
}
SendError::NoChannel(_) | SendError::Closed(_) => DeliverError::WrongChannel,
})
})
}
/// The type hash `name` was exposed with, or `None` if it is not exposed.
/// Must run inside [`run`](crate::run).
pub fn exposed_hash(name: &str) -> Option<u64> {
with_runtime(|inner| inner.exposure.lock().exposed.get(name).copied())
}
/// Whether a decoder is registered under `hash`. Must run inside
/// [`run`](crate::run).
pub fn decoder_registered(hash: u64) -> bool {
with_runtime(|inner| inner.exposure.lock().decoders.contains_key(&hash))
}
/// Decode `bytes` under `hash`'s registered decoder and deliver to `pid`.
/// This is the delivery half c9's single resolution seam calls after it has
/// resolved a wire name to a local pid. Must run inside [`run`](crate::run).
pub fn decode_deliver(hash: u64, to: Pid, bytes: &[u8]) -> Result<(), DeliverError> {
// Clone the Arc under the lock, call outside it: the decoder's
// `send_dyn` takes the registry lock — a mutual Leaf with the exposure
// lock (the runtime asserts if Leaves nest). This also keeps unrelated
// deliveries uncoupled from a slow decode.
let d = with_runtime(|inner| inner.exposure.lock().decoders.get(&hash).cloned());
match d {
Some(d) => d(to, bytes),
None => Err(DeliverError::UnknownType),
}
}
/// The auditable remote surface: every exposed name and its type hash,
/// unordered. Must run inside [`run`](crate::run).
pub fn exposed_names() -> Vec<(&'static str, u64)> {
with_runtime(|inner| {
inner
.exposure
.lock()
.exposed
.iter()
.map(|(&n, &h)| (n, h))
.collect()
})
}
+178
View File
@@ -0,0 +1,178 @@
//! RFC 010 c5 — the handshake as a pure state machine.
//!
//! Frames in, actions out — no IO, no clocks, no actors. The c6 connection
//! actor drives these machines and executes their actions; everything
//! time-shaped (handshake deadline, heartbeats) lives there.
use crate::cluster::envelope::{Frame, NodeMeta, RejectReason, PROTO_VERSION};
use crate::pg::Incarnation;
/// This node's identity and metadata, as offered in (or checked against) a
/// `Hello`.
#[derive(Debug, Clone)]
pub struct Local {
pub node_name: String,
pub incarnation: Incarnation,
pub build_hash: u64,
pub meta: NodeMeta,
}
/// The peer identity a successful handshake yields (what c7 feeds `node_up`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Peer {
pub node_name: String,
pub incarnation: Incarnation,
pub meta: NodeMeta,
}
/// Driver-supplied standing of the *offered* name at this node — knowledge
/// the pure machine cannot have (c6 owns the connection table and dial
/// set). One answer, in the responder's own precedence: an established
/// peer under that name outranks an in-flight dial to it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PeerStanding {
/// Neither connected to nor dialing that name.
#[default]
Free,
/// An established peer already holds that name.
Claimed,
/// We have our own dial in flight to that name.
Dialing,
}
/// Simultaneous-connect tie-break: does the connection dialed by
/// `dialer_name` survive against the reverse dial?
/// The rule (ratified 2026-08-14, a wire-protocol fact): the connection
/// dialed by the lexicographically **smaller** name survives. Both ends know
/// both names, so both compute the same verdict — which is why the losing
/// side may close silently instead of sending a reject.
pub fn dial_wins(dialer_name: &str, acceptor_name: &str) -> bool {
dialer_name < acceptor_name
}
/// Dial side: emits `Hello` at construction, interprets the single response.
#[must_use]
#[derive(Debug)]
pub struct Initiator(());
/// What the dial side's response frame meant.
#[must_use]
#[derive(Debug, PartialEq, Eq)]
pub enum InitiatorOutcome {
Established(Peer),
Rejected(RejectReason),
/// Protocol violation before the ack — close. Carries the offending frame.
Failed(Frame),
}
impl Initiator {
/// Start a dial-side handshake: the returned frame is the `Hello` to
/// send; the returned machine is the right to interpret the response.
pub fn new(local: &Local) -> (Self, Frame) {
let hello = Frame::Hello {
proto_version: PROTO_VERSION,
build_hash: local.build_hash,
node_name: local.node_name.clone(),
incarnation: local.incarnation,
meta: local.meta.clone(),
};
(Initiator(()), hello)
}
/// Interpret the response. The `HelloAck` carries no hash or version —
/// the responder already checked ours against its own, and equality is
/// symmetric, so a one-sided check is sound.
pub fn on_frame(self, frame: Frame) -> InitiatorOutcome {
match frame {
Frame::HelloAck {
node_name,
incarnation,
meta,
} => InitiatorOutcome::Established(Peer {
node_name,
incarnation,
meta,
}),
Frame::HelloReject { reason } => InitiatorOutcome::Rejected(reason),
other => InitiatorOutcome::Failed(other),
}
}
}
/// Accept side: awaits exactly one `Hello`, answers or closes.
#[must_use]
#[derive(Debug)]
pub struct Responder {
local: Local,
}
/// What to do with an inbound connection's first frame.
#[must_use]
#[derive(Debug, PartialEq, Eq)]
pub enum ResponderOutcome {
/// Send the ack; the connection is established.
Accepted { reply: Frame, peer: Peer },
/// Send the reject, then close.
Rejected { reply: Frame, reason: RejectReason },
/// Lost the simultaneous-connect tie-break: close silently, no frame.
TieBreakLoss,
/// Protocol violation before Hello — close, no reply. Carries the frame.
Failed(Frame),
}
impl Responder {
pub fn new(local: Local) -> Self {
Responder { local }
}
/// Judge the connection's first frame. Check order is proto → hash →
/// name → tie-break: validity before identity. `HelloReject` is the
/// cross-version compatibility anchor, so a version-mismatched peer
/// still gets one.
pub fn on_frame(self, frame: Frame, standing: PeerStanding) -> ResponderOutcome {
let Frame::Hello {
proto_version,
build_hash,
node_name,
incarnation,
meta,
} = frame
else {
return ResponderOutcome::Failed(frame);
};
let reject = |reason| ResponderOutcome::Rejected {
reply: Frame::HelloReject { reason },
reason,
};
if proto_version != PROTO_VERSION {
return reject(RejectReason::ProtoVersion);
}
if build_hash != self.local.build_hash {
return reject(RejectReason::HashMismatch);
}
if node_name == self.local.node_name || standing == PeerStanding::Claimed {
return reject(RejectReason::NameTaken);
}
// Simultaneous connect: the inbound frame is the peer's dial. If our
// own in-flight dial wins instead, drop this one silently — the peer
// computes the same verdict (see `dial_wins`).
if standing == PeerStanding::Dialing && !dial_wins(&node_name, &self.local.node_name) {
return ResponderOutcome::TieBreakLoss;
}
ResponderOutcome::Accepted {
reply: Frame::HelloAck {
node_name: self.local.node_name,
incarnation: self.local.incarnation,
meta: self.local.meta,
},
peer: Peer {
node_name,
incarnation,
meta,
},
}
}
}
+295
View File
@@ -0,0 +1,295 @@
//! RFC 010 c6 — the cluster connection manager.
//!
//! One manager per runtime: the single registry of live peer connections and
//! the source of truth for whether a peer name is already claimed. The
//! accept/connect path registers each established connection here, handing
//! over its [`ConnHandle`] — **the manager owns connection lifetime**. A
//! connection lives as long as its table entry, so it neither outlives nor
//! dies with whichever actor happened to establish it. Registered actors are
//! also *monitored*, so the table self-heals on any exit path — a connection
//! that panics, is cancelled, or closes cleanly is removed without
//! cooperation from the dying actor.
//!
//! The manager also holds the **membership state** (c7a): `node_up` fires on
//! a successful registration and `node_down` on removal — they are derived
//! facts of the exact events this table already owns, so holding the view
//! here means no cross-actor race between "connection exists" and "node is
//! up". The consumer surface (event types, [`subscribe`], [`view`],
//! semantics) is [`membership`](crate::cluster::membership); no consumer
//! ever touches the table itself.
//!
//! The connector dial loop is c7b, built on top of both.
use std::collections::HashMap;
use crate::channel::Sender;
use crate::cluster::conn::ConnHandle;
use crate::cluster::handshake::{Peer, PeerStanding};
use crate::cluster::membership::{NodeEvent, NodeInfo};
use crate::cluster::remote::{bind_outbound, unbind_outbound};
use crate::gen_server::{GenServer, GenServerCtx, GenServerName, Watcher};
use crate::monitor::{monitor, Down};
use crate::pg::NodeId;
use crate::pid::Pid;
/// Well-known name of the singleton manager within a runtime. Connection
/// actors reach it by name rather than by a passed-around ref, so a restarted
/// manager is always found at the same key.
pub const MANAGER: GenServerName<Manager> = GenServerName::new("smarm.cluster.manager");
/// One live connection's entry: the actor running it, the handle whose
/// lifetime *is* the connection's (see the module docs), and the peer's
/// membership identity (what `node_up` announced and `node_down` will name).
struct ConnEntry {
pid: Pid,
info: NodeInfo,
_handle: ConnHandle,
}
/// The connection registry: peer name → the connection actor that owns that
/// peer's control connection. Plus the membership state layered on it (c7a):
/// subscribers, and the `(name, incarnation)` → [`NodeId`] memo.
pub struct Manager {
conns: HashMap<String, ConnEntry>,
/// In-flight dial intents: peer name -> the actor performing the dial.
/// Registered *before* connecting so a crossing inbound `Hello` sees it
/// ([`PeerStanding::Dialing`]); cleared the moment
/// the dial resolves, and — because the dialer is monitored — on the
/// dialer's death, so a panicking dial can never wedge the tie-break.
dials: HashMap<String, Pid>,
/// Membership subscribers; a closed channel is pruned on the next emit.
subscribers: Vec<Sender<NodeEvent>>,
/// The [`NodeId`] memo: a reconnect at the same incarnation keeps its id,
/// a restart (new incarnation) allocates a fresh one. Grows one entry per
/// distinct `(name, incarnation)` ever seen — unbounded in principle,
/// bounded in practice by restarts actually happening.
ids: HashMap<(String, u32), NodeId>,
/// Next id to allocate. Starts at 1: id 0 is
/// [`DEFAULT_NODE_ID`](crate::pg::DEFAULT_NODE_ID), the local node.
next_id: u32,
watcher: Option<Watcher<Manager>>,
}
impl Manager {
pub fn new() -> Self {
Manager {
conns: HashMap::new(),
dials: HashMap::new(),
subscribers: Vec::new(),
ids: HashMap::new(),
next_id: 1,
watcher: None,
}
}
/// The memoized id for `(name, incarnation)` — see the field docs.
fn node_id(&mut self, name: &str, incarnation: u32) -> NodeId {
*self
.ids
.entry((name.to_string(), incarnation))
.or_insert_with(|| {
let id = NodeId::new(self.next_id);
self.next_id += 1;
id
})
}
/// Deliver `event` to every live subscriber, pruning the dead: a closed
/// channel means the subscriber dropped its [`MembershipEvents`]
/// (crate::cluster::membership::MembershipEvents).
fn emit(&mut self, event: &NodeEvent) {
self.subscribers.retain(|tx| tx.send(event.clone()).is_ok());
}
}
impl Default for Manager {
fn default() -> Self {
Manager::new()
}
}
/// Outcome of a [`Call::Register`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Registered {
/// The name was free; this connection is now the peer of record.
Ok,
/// Another live connection already holds this name — the caller lost the
/// race (or is a duplicate) and must not run.
Duplicate,
}
/// Requests to the manager.
pub enum Call {
/// The path claims its peer's name for a freshly-established connection,
/// handing the manager the actor's [`ConnHandle`] and the handshake's
/// [`Peer`] (the membership identity `node_up` announces). The manager
/// monitors `pid` and holds the handle for as long as the entry lives; a
/// [`Registered::Duplicate`] verdict drops the handle here, which stops
/// the refused actor.
Register {
peer: Peer,
pid: Pid,
handle: ConnHandle,
},
/// Tear down the connection to `name`: the manager drops its handle, the
/// actor stops, and the monitor removes the entry. A no-op if no such
/// connection is live.
Disconnect { name: String },
/// The current peer names, sorted. For observation and tests.
Peers,
/// A dialer declares an in-flight dial to `name` before connecting. The
/// pid is the dialing actor, monitored so the intent dies with it.
DialBegin { name: String, pid: Pid },
/// The dial to `name` resolved (either way): drop the intent. A call,
/// not a cast, so the intent is provably gone before the dialer moves on.
DialEnd { name: String },
/// The [`PeerStanding`] of an inbound `Hello` offering `peer_name` — the
/// accept path asks this between reading the frame and judging it.
Standing { peer_name: String },
/// Subscribe `tx` to membership events, snapshot-then-stream: one
/// [`NodeEvent::NodeUp`] per live peer is queued into `tx` before this
/// call answers, so the stream is exact from its first event (handlers
/// are serialized — nothing interleaves with the snapshot). Use
/// [`subscribe`](crate::cluster::membership::subscribe).
Subscribe { tx: Sender<NodeEvent> },
/// The current view: every live peer's [`NodeInfo`], unordered. Use
/// [`view`](crate::cluster::membership::view).
View,
}
/// Replies from the manager.
#[derive(Debug)]
pub enum Reply {
Registered(Registered),
Disconnected,
Peers(Vec<String>),
/// `false`: another dial to this name is already in flight — do not dial.
DialBegan(bool),
DialEnded,
Standing(PeerStanding),
Subscribed,
View(Vec<NodeInfo>),
}
impl GenServer for Manager {
type Call = Call;
type Reply = Reply;
type Cast = ();
type Info = ();
type Timer = ();
fn init(&mut self, ctx: &GenServerCtx<Self>) {
self.watcher = Some(ctx.watcher());
}
/// Manager shutdown drops every entry (and with it every ConnHandle);
/// the outbound table must not outlive the connections it names.
fn terminate(&mut self) {
for name in self.conns.keys() {
unbind_outbound(name);
}
}
fn handle_call(&mut self, request: Call) -> Reply {
match request {
Call::Register {
peer,
pid,
mut handle,
} => {
if self.conns.contains_key(&peer.node_name) {
// `handle` drops here: the refused actor stops itself.
return Reply::Registered(Registered::Duplicate);
}
if let Some(w) = &self.watcher {
w.watch(monitor(pid));
}
// The outbound table (c9) is maintained here, inside the same
// serialized handlers that own the connection's lifetime.
if let Some((frames, monitors)) = handle.take_outbound() {
bind_outbound(&peer.node_name, peer.incarnation, frames, monitors);
}
let info = NodeInfo {
node: self.node_id(&peer.node_name, peer.incarnation.get()),
name: peer.node_name.clone(),
incarnation: peer.incarnation,
meta: peer.meta,
};
self.conns.insert(
peer.node_name,
ConnEntry {
pid,
info: info.clone(),
_handle: handle,
},
);
self.emit(&NodeEvent::NodeUp(info));
Reply::Registered(Registered::Ok)
}
Call::Disconnect { name } => {
// Dropping the entry drops the handle, which stops the actor.
if let Some(entry) = self.conns.remove(&name) {
unbind_outbound(&name);
self.emit(&NodeEvent::NodeDown(entry.info));
}
Reply::Disconnected
}
Call::Peers => {
let mut names: Vec<String> = self.conns.keys().cloned().collect();
names.sort();
Reply::Peers(names)
}
Call::DialBegin { name, pid } => {
if self.dials.contains_key(&name) {
return Reply::DialBegan(false);
}
if let Some(w) = &self.watcher {
w.watch(monitor(pid));
}
self.dials.insert(name, pid);
Reply::DialBegan(true)
}
Call::DialEnd { name } => {
self.dials.remove(&name);
Reply::DialEnded
}
Call::Standing { peer_name } => {
Reply::Standing(if self.conns.contains_key(&peer_name) {
PeerStanding::Claimed
} else if self.dials.contains_key(&peer_name) {
PeerStanding::Dialing
} else {
PeerStanding::Free
})
}
Call::Subscribe { tx } => {
// The snapshot: queued before `tx` joins the list, and — the
// handlers being serialized — before any later event.
for entry in self.conns.values() {
let _ = tx.send(NodeEvent::NodeUp(entry.info.clone()));
}
self.subscribers.push(tx);
Reply::Subscribed
}
Call::View => Reply::View(self.conns.values().map(|e| e.info.clone()).collect()),
}
}
fn handle_cast(&mut self, _request: ()) {}
fn handle_down(&mut self, down: Down) {
let mut downs = Vec::new();
self.conns.retain(|name, entry| {
let dead = entry.pid == down.pid;
if dead {
downs.push((name.clone(), entry.info.clone()));
}
!dead
});
for (name, info) in downs {
unbind_outbound(&name);
self.emit(&NodeEvent::NodeDown(info));
}
self.dials.retain(|_, pid| *pid != down.pid);
}
}
+97
View File
@@ -0,0 +1,97 @@
//! RFC 010 c7a — membership: `node_up`/`node_down` events and the view.
//!
//! The membership *state* lives inside the [`manager`](crate::cluster::manager)
//! — `node_up` and `node_down` are derived facts of the exact events the
//! manager already owns (a successful registration; a reap or `Disconnect`),
//! so holding the view anywhere else would only add a cross-actor ordering
//! seam. This module is the consumer surface: the event and view types, and
//! the [`subscribe`]/[`view`] entry points. No consumer ever touches the
//! connection table (roadmap-binding, enforced by module privacy: the table
//! is a private field, and nothing here exposes names→pids).
//!
//! ## Subscription semantics (ratified 2026-08-15)
//!
//! [`subscribe`] is **snapshot-then-stream**: the returned receiver first
//! yields one [`NodeEvent::NodeUp`] per currently-live peer, then live events
//! as they happen. Because the manager is a `gen_server` (handlers are
//! serialized), the snapshot is exact — no event can interleave with it, and
//! per-subscriber ordering matches the manager's processing order. There is
//! no join-race for late subscribers and no separate "get, then diff" dance;
//! [`view`] exists for observation, not for synchronization.
//!
//! A dropped subscriber is pruned on the next emission (its channel reports
//! closed) — no monitor needed, the sender itself tells us.
//!
//! ## NodeId identity
//!
//! A [`NodeId`] is a compact **local alias for the wire identity**
//! `(node_name, incarnation)`, memoized by the manager: a reconnect blip at
//! the same incarnation keeps its id (down, then up, same id), while a
//! restart — a new incarnation — gets a fresh one, so a node's ghost and its
//! successor are always distinguishable. Ids are allocated from 1;
//! [`DEFAULT_NODE_ID`](crate::pg::DEFAULT_NODE_ID) (0) remains the local
//! node, per [`pg`](crate::pg)'s framing.
use crate::channel::{channel, Receiver};
use crate::cluster::envelope::NodeMeta;
use crate::cluster::manager::{Call, Reply, MANAGER};
use crate::gen_server;
use crate::pg::{Incarnation, NodeId};
/// One live remote node, as the view and [`NodeEvent::NodeUp`] describe it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NodeInfo {
/// The local alias for `(name, incarnation)` — see the module docs.
pub node: NodeId,
/// The peer's claimed node name (handshake-verified).
pub name: String,
/// The peer's incarnation epoch, as offered in its `Hello`.
pub incarnation: Incarnation,
/// The peer's `Hello` metadata.
pub meta: NodeMeta,
}
/// A membership change, as delivered to subscribers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NodeEvent {
/// A peer's control connection established and registered.
NodeUp(NodeInfo),
/// That peer's connection ended — reaped, commanded down, or the manager
/// itself shut down. Carries the same [`NodeInfo`] the corresponding
/// `NodeUp` delivered, so consumers need no id→name reverse map.
NodeDown(NodeInfo),
}
/// A live membership subscription: the receiving end of the event stream
/// (the [`Monitor`](crate::monitor::Monitor) shape — read from [`rx`], drop
/// to unsubscribe).
///
/// [rx]: MembershipEvents::rx
pub struct MembershipEvents {
/// The event stream: the snapshot's `NodeUp`s first, then live events.
/// Fold it into a `select` from a plain actor, or pipe it into a
/// `gen_server` via `with_info`.
pub rx: Receiver<NodeEvent>,
}
/// Subscribe to membership events (snapshot-then-stream — see the module
/// docs). `None`: the manager is not running. Must be called from inside an
/// actor.
pub fn subscribe() -> Option<MembershipEvents> {
let (tx, rx) = channel();
match gen_server::call(MANAGER, Call::Subscribe { tx }) {
Ok(Reply::Subscribed) => Some(MembershipEvents { rx }),
_ => None,
}
}
/// The current view: every live peer's [`NodeInfo`], unordered. For
/// observation and tests; consumers that need to *track* the view should
/// [`subscribe`] instead (the snapshot makes the stream self-sufficient).
/// `None`: the manager is not running. Must be called from inside an actor.
pub fn view() -> Option<Vec<NodeInfo>> {
match gen_server::call(MANAGER, Call::View) {
Ok(Reply::View(v)) => Some(v),
_ => None,
}
}
+546
View File
@@ -0,0 +1,546 @@
//! RFC 010 c15 — distributed process groups (Phase 5).
//!
//! The Erlang `pg` shape (D18): every node's group store is the union of
//! its own local members and each peer's *announced* local members. There
//! is one **pg actor** per node — the c14 reaper grown up — and it is the
//! only writer of remote entries and the only sender of announcements:
//!
//! - **Origin owns its members.** Joins are local (`pg::join`), the eager
//! reaper is the liveness authority, and the origin announces every
//! change: `Join`/`Leave` incrementally to every up node, and a full
//! `Sync` of its local groups to a peer the moment that peer comes up
//! (`NodeUp`). Nobody monitors a remote member; a peer's `NodeDown` sweeps
//! every member it announced.
//! - **Transport is a pure consumer** of Phase 3/4: the exposed name
//! [`PG_NAME`] (`"pg"`) carrying [`PgMsg`] over postcard, sent with
//! [`remote::send`]. No new frame, no manager change.
//! - **No anti-entropy.** Per-origin ordering rides the single TCP link:
//! the actor sends `Sync` to a peer *before* it can send that peer any
//! `Join`/`Leave` (both from the same loop, over the same connection), and
//! a reconnect is a fresh `NodeUp` ⇒ fresh `Sync` replacing that peer's
//! set wholesale.
//! - **Local API unchanged.** `members`/`pick`/`dispatch` stay local-only
//! (`get_local_members`); a remote entry in the store carries the peer's
//! `NodeId` and never surfaces there. Cluster-wide reads are the new,
//! additive [`members_all`] over [`GroupMember`] (c16 adds `pick_any` /
//! `dispatch_any`).
//!
//! ## Ordering inside the node
//!
//! `pg::join`/`pg::leave` mutate the store on the caller's thread and then
//! *announce* to the actor's control inbox. Because the store op precedes the
//! announcement and the actor re-reads the store before broadcasting a
//! `Joined`, an announcement that has been overtaken (the member left or died
//! before the actor got to it) is dropped rather than advertised: the wire
//! never sees a `Join` for a member the origin no longer holds. `Leave`
//! broadcasts unconditionally — a spurious `Leave` is a no-op at the peer.
//!
//! Inbound: `NodeUp` is emitted by the manager on the accept/connect path,
//! *before* the peer's connection actor exists, so it is queued on the
//! membership stream before any frame from that peer can reach this inbox.
//! The actor still drains membership before it interprets a `PgMsg` whose
//! sender it does not know, and drops the message if the sender is still not
//! up (a ghost — its next `NodeUp` brings a `Sync`).
use std::collections::HashMap;
use crate::channel::{channel, select, Receiver, Selectable};
use crate::cluster::expose::expose;
use crate::cluster::membership::{subscribe, MembershipEvents, NodeEvent, NodeInfo};
use crate::cluster::remote::{
self, local_identity, send_to_remote, RemoteName, RemotePid, ToRemoteError,
};
use crate::monitor::Down;
use crate::pg::{
live, member_for, reaper_inboxes, sweep_local_death, Incarnation, Member, Membership, PgEvent,
};
use crate::pid::{assert_type, Addressable, Erased, Pid};
use crate::registry::{register, send_to, SendError};
use crate::scheduler::with_runtime;
use crate::Name;
/// The exposed name every node's pg actor answers under.
pub const PG_NAME: Name<PgMsg> = Name::new("pg");
/// The pg wire protocol. Every variant is origin-authored: `from` / the
/// pid's node is the node whose local members are being described.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PgMsg {
/// The origin's complete local membership, sent to a peer on `NodeUp`.
/// Replaces whatever the receiver held for that origin.
Sync {
from: String,
groups: Vec<(String, Vec<RemotePid<Erased>>)>,
},
/// The origin added `pid` (its own) to `group`.
Join {
group: String,
pid: RemotePid<Erased>,
},
/// The origin removed `pid` from `group` — voluntary leave or death.
Leave {
group: String,
pid: RemotePid<Erased>,
},
}
// Hand-rolled serde (the crate carries no serde-derive), as a 3-tuple with a
// leading tag: (0, from, groups) | (1, group, pid) | (2, group, pid).
impl serde::Serialize for PgMsg {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeTuple;
let mut t = s.serialize_tuple(3)?;
match self {
PgMsg::Sync { from, groups } => {
t.serialize_element(&0u8)?;
t.serialize_element(from)?;
t.serialize_element(groups)?;
}
PgMsg::Join { group, pid } => {
t.serialize_element(&1u8)?;
t.serialize_element(group)?;
t.serialize_element(pid)?;
}
PgMsg::Leave { group, pid } => {
t.serialize_element(&2u8)?;
t.serialize_element(group)?;
t.serialize_element(pid)?;
}
}
t.end()
}
}
impl<'de> serde::Deserialize<'de> for PgMsg {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = PgMsg;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a pg message tuple")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut seq: A,
) -> Result<PgMsg, A::Error> {
use serde::de::Error;
let tag: u8 = seq
.next_element()?
.ok_or_else(|| A::Error::custom("pg: missing tag"))?;
let text: String = seq
.next_element()?
.ok_or_else(|| A::Error::custom("pg: missing name"))?;
match tag {
0 => {
let groups = seq
.next_element()?
.ok_or_else(|| A::Error::custom("pg: missing groups"))?;
Ok(PgMsg::Sync { from: text, groups })
}
1 | 2 => {
let pid = seq
.next_element()?
.ok_or_else(|| A::Error::custom("pg: missing pid"))?;
Ok(if tag == 1 {
PgMsg::Join { group: text, pid }
} else {
PgMsg::Leave { group: text, pid }
})
}
t => Err(A::Error::custom(format!("pg: unknown tag {t}"))),
}
}
}
d.deserialize_tuple(3, V)
}
}
/// A member of a group as the cluster sees it: on this node (a plain
/// [`Pid`], sendable locally) or on a peer (a [`RemotePid`], sendable via
/// [`send_to_remote`](remote::send_to_remote)). `Pid` cannot hold a remote
/// (D14), hence the two-variant shape.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GroupMember {
Local(Pid),
Remote(RemotePid<Erased>),
}
/// Every member of `group` cluster-wide, in the store's order: local members
/// filtered by the same liveness backstop as [`members`](crate::pg::members),
/// remote members exactly as their origins last announced them. Must run
/// inside [`run`](crate::run).
pub fn members_all(group: &str) -> Vec<GroupMember> {
with_runtime(|inner| {
let me = inner.node_id;
let pg = inner.process_groups.lock();
pg.all_of(group)
.into_iter()
.filter_map(|m| {
if m.node == me {
live(inner, m.pid).then_some(GroupMember::Local(m.pid))
} else {
// A remote entry always has its node's name recorded
// (they land under the same lock); a missing one is a
// node already swept, so it hides rather than misnames.
pg.node_name(m.node).map(|name| {
GroupMember::Remote(RemotePid::from_parts(
name,
m.incarnation,
m.pid.index(),
m.pid.generation(),
))
})
}
})
.collect()
})
}
/// One member of `group` cluster-wide, or `None` if it has none: the first
/// entry in the store's order (this node's members in join order first when
/// they joined first — the same stateless first-live scan as
/// [`pick`](crate::pg::pick), extended over the peers' announced members).
/// Must run inside [`run`](crate::run).
pub fn pick_any(group: &str) -> Option<GroupMember> {
members_all(group).into_iter().next()
}
/// Why [`dispatch_any`] handed `msg` back.
#[derive(Debug)]
pub enum DispatchAnyError<M> {
/// The group has no member anywhere.
NoMember(M),
/// The pick was local and the local typed send failed.
Local(SendError<M>),
/// The pick was remote and the remote send failed at this node.
Remote(ToRemoteError<M>),
}
impl<M> DispatchAnyError<M> {
/// The undelivered message.
pub fn into_inner(self) -> M {
match self {
DispatchAnyError::NoMember(m) => m,
DispatchAnyError::Local(e) => e.into_inner(),
DispatchAnyError::Remote(e) => e.into_inner(),
}
}
}
/// [`pick_any`] and send in one step, returning the member reached: a local
/// pick goes through [`send_to`], a remote one through [`send_to_remote`]
/// (so `Ok` for a remote member means "handed to the connection", RFC 010
/// §3). Homogeneous pool assumed, as for [`dispatch`](crate::pg::dispatch);
/// a wrong `A` degrades to a clean error at the target, never a misroute.
/// Must run inside [`run`](crate::run).
pub fn dispatch_any<A>(group: &str, msg: A::Msg) -> Result<GroupMember, DispatchAnyError<A::Msg>>
where
A: Addressable,
A::Msg: serde::Serialize,
{
match pick_any(group) {
None => Err(DispatchAnyError::NoMember(msg)),
Some(GroupMember::Local(pid)) => send_to(assert_type::<A>(pid), msg)
.map(|()| GroupMember::Local(pid))
.map_err(DispatchAnyError::Local),
Some(GroupMember::Remote(rp)) => send_to_remote(rp.clone().assert_type::<A>(), msg)
.map(|()| GroupMember::Remote(rp))
.map_err(DispatchAnyError::Remote),
}
}
/// Attach the pg actor to the running cluster. Called once by
/// `cluster::start` after the manager is up and the local identity is set;
/// spawns the actor if this run has not joined anything yet.
pub(crate) fn attach_cluster() {
let _ = reaper_inboxes().ctl.send(PgEvent::Attach);
}
/// The attached half of the actor's state: who is up (by name) and the
/// membership stream.
struct Attached {
events: MembershipEvents,
peers: HashMap<String, NodeInfo>,
/// This node's wire identity: `Sync`'s `from`, and the stamp on every
/// pid we ship (attach requires it, so no `None` path exists here).
me: String,
incarnation: Incarnation,
}
/// The pg actor: the c14 reaper (`deaths`), the local API's announcements
/// (`ctl`), and — once attached — the membership stream and the exposed
/// `"pg"` inbox, all in one drain-then-select loop. `deaths`/`ctl` closing
/// is the run tearing down; the membership stream closing is the manager
/// gone (detach, keep reaping).
pub(crate) fn actor(deaths: Receiver<Down>, ctl: Receiver<PgEvent>) {
let (pg_tx, pg_rx) = channel::<PgMsg>();
let mut cl: Option<Attached> = None;
loop {
loop {
match deaths.try_recv() {
Ok(Some(down)) => on_death(cl.as_ref(), down.pid),
Ok(None) => break,
Err(_) => return,
}
}
loop {
match ctl.try_recv() {
Ok(Some(PgEvent::Attach)) => {
// Own the name BEFORE subscribing (which yields to the
// manager): a peer's first frame must find "pg" exposed
// and resolvable, or it is dropped. Idempotent for a
// re-attach: same actor, same channel (the registry
// refuses a *second* live one).
let _ = register(PG_NAME, pg_tx.clone());
expose(PG_NAME);
if let Some(a) = attach() {
cl = Some(a);
}
}
Ok(Some(PgEvent::Joined { group, pid })) => on_joined(cl.as_ref(), &group, pid),
Ok(Some(PgEvent::Left { group, pid })) => on_left(cl.as_ref(), &group, pid),
Ok(None) => break,
Err(_) => return,
}
}
if let Some(a) = cl.as_mut() {
if !drain_events(a) {
cl = None;
continue;
}
loop {
match pg_rx.try_recv() {
Ok(Some(msg)) => on_msg(a, msg),
Ok(None) => break,
Err(_) => return, // our own inbox: only on teardown
}
}
}
// Wait. Control first (attach/teardown must be prompt), then deaths,
// then the cluster arms.
let mut arms: Vec<&dyn Selectable> = vec![&ctl, &deaths];
if let Some(a) = cl.as_ref() {
arms.push(&a.events.rx);
arms.push(&pg_rx);
}
let _ = select(&arms);
}
}
fn attach() -> Option<Attached> {
let events = subscribe()?;
let (me, incarnation) = local_identity()?;
Some(Attached {
events,
peers: HashMap::new(),
me,
incarnation,
})
}
/// Fold pending membership events: `NodeUp` ⇒ record + `Sync` that peer;
/// `NodeDown` ⇒ sweep every member it announced. `false` when the stream
/// has closed.
fn drain_events(a: &mut Attached) -> bool {
loop {
match a.events.rx.try_recv() {
Ok(Some(NodeEvent::NodeUp(info))) => {
let name = info.name.clone();
a.peers.insert(name.clone(), info);
// Snapshot under the store lock, then stamp wire pids
// outside it (`from_local` marks watchable under the slot's
// cold lock — Leaf-on-Leaf nesting is asserted).
let local: Vec<(String, Vec<Pid>)> =
with_runtime(|inner| inner.process_groups.lock().groups_on(inner.node_id));
let groups = local
.into_iter()
.map(|(g, pids)| (g, pids.into_iter().map(|p| wire(a, p)).collect()))
.collect();
let msg = PgMsg::Sync {
from: a.me.clone(),
groups,
};
let _ = remote::send(RemoteName::new(name, PG_NAME), msg);
}
Ok(Some(NodeEvent::NodeDown(info))) => {
a.peers.remove(&info.name);
with_runtime(|inner| {
let mut pg = inner.process_groups.lock();
pg.remove_where(|m| m.node == info.node);
pg.forget_node_name(info.node);
});
}
Ok(None) => return true,
Err(_) => return false,
}
}
}
/// Send `msg` to every up peer. `NotConnected` is ignored: that peer's
/// `NodeDown` is on its way and its next `NodeUp` gets a `Sync`.
fn broadcast(a: &Attached, msg: PgMsg) {
for name in a.peers.keys() {
let _ = remote::send(RemoteName::new(name.clone(), PG_NAME), msg.clone());
}
}
fn on_death(a: Option<&Attached>, pid: Pid) {
let evicted = sweep_local_death(pid);
if let Some(a) = a {
for (group, ms) in evicted {
broadcast(
a,
PgMsg::Leave {
group,
pid: wire(a, ms.member.pid),
},
);
}
}
}
fn on_joined(a: Option<&Attached>, group: &str, pid: Pid) {
let Some(a) = a else { return };
// Re-check: a leave/death may have overtaken the announcement.
let still = with_runtime(|inner| {
let m = member_for(inner, pid);
inner.process_groups.lock().contains(group, &m)
});
if still {
broadcast(
a,
PgMsg::Join {
group: group.to_owned(),
pid: wire(a, pid),
},
);
}
}
fn on_left(a: Option<&Attached>, group: &str, pid: Pid) {
let Some(a) = a else { return };
broadcast(
a,
PgMsg::Leave {
group: group.to_owned(),
pid: wire(a, pid),
},
);
}
/// The wire form of a local member pid, stamped with the identity the
/// actor was attached with (marks watchable, like `from_local`).
fn wire(a: &Attached, pid: Pid) -> RemotePid<Erased> {
RemotePid::from_local_at(pid, a.me.clone(), a.incarnation)
}
/// The named origin's `NodeInfo`, if it is up. A second look at the
/// membership stream covers a `NodeUp` that landed after this loop
/// iteration's drain; anything still unknown is a ghost and is dropped.
fn origin(a: &mut Attached, name: &str) -> Option<NodeInfo> {
if let Some(i) = a.peers.get(name) {
return Some(i.clone());
}
drain_events(a);
a.peers.get(name).cloned()
}
/// `origin`, additionally requiring `pid` to be stamped with the origin's
/// current incarnation — a pid from a previous life of that node is a ghost.
fn origin_of(a: &mut Attached, pid: &RemotePid<Erased>) -> Option<NodeInfo> {
origin(a, pid.node()).filter(|i| i.incarnation == pid.incarnation())
}
fn remote_membership(origin: &NodeInfo, pid: &RemotePid<Erased>) -> Membership {
Membership {
member: Member {
node: origin.node,
incarnation: origin.incarnation,
pid: Pid::new(pid.index(), pid.generation()),
},
monitor: None,
}
}
fn on_msg(a: &mut Attached, msg: PgMsg) {
match msg {
PgMsg::Sync { from, groups } => {
let Some(info) = origin(a, &from) else { return };
with_runtime(|inner| {
let mut pg = inner.process_groups.lock();
pg.remove_where(|m| m.node == info.node);
pg.set_node_name(info.node, info.name.clone());
for (group, pids) in &groups {
// Origin-authored: only its own current-incarnation pids.
for p in pids
.iter()
.filter(|p| p.node() == from && p.incarnation() == info.incarnation)
{
pg.join(group, remote_membership(&info, p));
}
}
});
}
PgMsg::Join { group, pid } => {
let Some(info) = origin_of(a, &pid) else {
return;
};
with_runtime(|inner| {
let mut pg = inner.process_groups.lock();
pg.set_node_name(info.node, info.name.clone());
pg.join(&group, remote_membership(&info, &pid));
});
}
PgMsg::Leave { group, pid } => {
let Some(info) = origin_of(a, &pid) else {
return;
};
with_runtime(|inner| {
let ms = remote_membership(&info, &pid);
inner.process_groups.lock().leave(&group, ms.member);
});
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cluster::envelope::{decode_payload, encode_payload};
#[test]
fn pg_msg_roundtrips_every_variant() {
let p = RemotePid::<Erased>::from_parts("a", Incarnation::new(9), 3, 1);
for m in [
PgMsg::Sync {
from: "a".into(),
groups: vec![
("g".into(), vec![p.clone(), p.clone()]),
("h".into(), vec![]),
],
},
PgMsg::Sync {
from: "a".into(),
groups: vec![],
},
PgMsg::Join {
group: "g".into(),
pid: p.clone(),
},
PgMsg::Leave {
group: "g".into(),
pid: p.clone(),
},
] {
let bytes = encode_payload(&m).unwrap();
let back: PgMsg = decode_payload(&bytes).unwrap();
assert_eq!(back, m);
}
}
#[test]
fn pg_msg_rejects_unknown_tag() {
let bytes = encode_payload(&(7u8, "x", 0u32)).unwrap();
assert!(decode_payload::<PgMsg>(&bytes).is_err());
}
}
+835
View File
@@ -0,0 +1,835 @@
//! RFC 010 c9 — remote `Name` sends: the outbound path and the single
//! inbound name-resolution seam.
//!
//! ## Outbound (D13, ratified 2026-08-15)
//!
//! A module-private table `node name → Sender<Frame>` — one dedicated
//! outbound channel per live connection, populated and torn down by the
//! manager inside the same serialized handlers that own the connection's
//! lifetime (Register / Disconnect / reap), living on `RuntimeInner` beside
//! the exposure state. [`send`] is one leaf-lock lookup + one channel send:
//! no gen_server on the data plane, no published channel anyone holding a
//! pid could inject raw frames into. `Ok(())` means **handed to the
//! connection's inbox** — local knowledge only, exactly the BEAM contract
//! (RFC §3): a missing entry or a closed channel is
//! [`RemoteSendError::NotConnected`]; delivery confirmation is the monitor's
//! job (c11). The entry-present/actor-dying-mid-send window is *honest*
//! under that contract, not a bug.
//!
//! The outbound sender is deliberately **separate from the conn actor's
//! command channel**: if it were a clone of `cmd_tx`, the manager dropping
//! its `ConnHandle` would no longer close that channel and connection
//! lifetime would leak to whoever holds a sender — a D9 violation.
//!
//! Buffering is unbounded toward a slow peer (the BEAM `busy_dist_port`
//! shape); backpressure is out of c9's scope and noted here rather than
//! silently absent.
//!
//! ## Inbound — the ONE resolution seam (RFC v2)
//!
//! Every wire-name → local-pid resolution goes through [`deliver_named`],
//! and nothing else: the conn actor hands it the three fields of a
//! `SendNamed` and gets back a verdict. It checks the exposed set first (an
//! unexposed name is unreachable — the gun's safety), then the type hash
//! against what the name was exposed with, then resolves the name through
//! the registry and delivers via c8's [`decode_deliver`]. When an owned-name
//! table lands beside the `&'static str` registry, it slots in here without
//! touching call sites. Module privacy enforces the funnel: the exposed and
//! outbound tables are `pub(crate)`, and no other module resolves names for
//! the wire.
//!
//! Refusals are silent to the sender by design (§3: send failure reflects
//! local knowledge only); they are observable locally as the returned
//! [`InboundVerdict`], which the conn actor may log or count.
//!
//! ## Pids (c10, D14)
//!
//! [`RemotePid<A>`] = `(node_name, incarnation, index, generation)` +
//! phantom — identity-bound, dead when that incarnation dies, never
//! redirects. The node travels as its **name** (a global identifier, so a pid
//! forwarded through a third node needs no re-mapping); NodeId is a local
//! alias and never crosses. A local `Pid<A>` serializes *as* a `RemotePid`
//! stamped from the ambient [local identity](set_local_identity); a
//! `RemotePid` deserializes into `Pid<A>` only when it names this node (the
//! collapse), else it is a decode error — fields that may hold a pid from
//! anywhere are typed `RemotePid<A>`.
//!
//! [`send_to_remote`] is the pid-targeted send. A self-node pid short-
//! circuits to the local typed send with the message object itself — no
//! encode, no frame (zero-copy-equivalent). Otherwise the outbound table
//! (widened to carry each node's **current incarnation**) does the RFC v2 §3
//! check at the send site: a pid of a dead incarnation is
//! [`ToRemoteError::DeadIncarnation`] and no frame is emitted. Inbound
//! `Send` frames are delivered by index/generation through c8's
//! [`decode_deliver`]: the target actor's published channel for the exposed
//! type is the only route (the reply-to path requires
//! [`expose_type`](crate::cluster::expose::expose_type) at the receiver).
use std::cell::Cell;
use std::collections::HashMap;
use std::marker::PhantomData;
use crate::channel::{channel, Receiver, RecvError, Selectable, Sender};
use crate::cluster::envelope::{encode_payload, Frame, PayloadError, RemoteDownReason};
use crate::cluster::expose::{decode_deliver, exposed_hash, type_hash, DeliverError};
use crate::monitor::{demonitor, monitor, Monitor, MonitorId};
use crate::pg::Incarnation;
use crate::pid::{Addressable, Erased, Name, Pid};
use crate::registry::{send_to, whereis, SendError};
use crate::scheduler::with_runtime;
/// A name on a specific remote node: `(node_name, Name<M>)`. Sendable via
/// [`send`]; typed, so the payload is `M` and the wire hash is
/// [`type_hash::<M>()`](type_hash).
pub struct RemoteName<M> {
node: String,
name: Name<M>,
_marker: PhantomData<fn() -> M>,
}
impl<M> RemoteName<M> {
pub fn new(node: impl Into<String>, name: Name<M>) -> Self {
RemoteName {
node: node.into(),
name,
_marker: PhantomData,
}
}
pub fn node(&self) -> &str {
&self.node
}
pub fn name(&self) -> Name<M> {
self.name
}
}
impl<M> Clone for RemoteName<M> {
fn clone(&self) -> Self {
RemoteName {
node: self.node.clone(),
name: self.name,
_marker: PhantomData,
}
}
}
impl<M> std::fmt::Debug for RemoteName<M> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}@{}", self.name.as_str(), self.node)
}
}
/// Why a remote send did not leave this node. Local knowledge only.
#[derive(Debug)]
pub enum RemoteSendError<M> {
/// No live connection to that node right now (never connected, or gone
/// and not yet re-dialed). The message is handed back.
NotConnected(M),
/// The payload did not serialize.
Encode(M, PayloadError),
}
impl<M> RemoteSendError<M> {
pub fn into_inner(self) -> M {
match self {
RemoteSendError::NotConnected(m) | RemoteSendError::Encode(m, _) => m,
}
}
}
/// The outbound table, one per runtime (a `RuntimeInner` field): per live
/// node, its current incarnation (the RFC v2 §3 send-site check) and the
/// connection's dedicated outbound sender. Plus this node's own wire
/// identity, which pid serialization stamps.
pub(crate) struct Outbound {
by_node: HashMap<String, Route>,
local: Option<(String, Incarnation)>,
}
/// One live connection as the outbound path sees it: the peer's current
/// incarnation and the two inboxes of its connection actor — frames (c9)
/// and monitor bookkeeping (c12, [`MonCmd`]).
pub(crate) struct Route {
incarnation: Incarnation,
frames: Sender<Frame>,
monitors: Sender<MonCmd>,
}
impl Outbound {
pub(crate) fn new() -> Self {
Outbound {
by_node: HashMap::new(),
local: None,
}
}
}
/// Set this node's wire identity — what serialized pids are stamped with
/// and what a `RemotePid` must name to collapse. `cluster::start` sets it;
/// exposed for local tests. Must run inside [`run`](crate::run).
pub fn set_local_identity(node: &str, incarnation: Incarnation) {
with_runtime(|inner| {
inner.outbound.lock().local = Some((node.to_string(), incarnation));
});
}
/// This node's wire identity, if set. Must run inside [`run`](crate::run).
pub fn local_identity() -> Option<(String, Incarnation)> {
with_runtime(|inner| inner.outbound.lock().local.clone())
}
/// Manager-only: bind `node`'s outbound channels at `incarnation`. Called
/// inside `Register`.
pub(crate) fn bind_outbound(
node: &str,
incarnation: Incarnation,
frames: Sender<Frame>,
monitors: Sender<MonCmd>,
) {
with_runtime(|inner| {
inner.outbound.lock().by_node.insert(
node.to_string(),
Route {
incarnation,
frames,
monitors,
},
);
});
}
/// Test probe: bind an arbitrary sender as `node`'s outbound so a test can
/// assert what frames leave — or don't. Same table, same lookup as the real
/// path (this is how "no frame emitted" is asserted at the frame level).
/// Frames only: there is no connection actor behind a probe, so a
/// [`monitor_remote`] against a probed node reports `Disconnected`.
pub fn bind_outbound_probe(node: &str, incarnation: Incarnation, tx: Sender<Frame>) {
drop(bind_outbound_probe_with_monitors(node, incarnation, tx));
}
/// The monitor half of a probed node's inbox: opaque, held only to be
/// dropped. See [`bind_outbound_probe_with_monitors`].
pub struct MonitorInbox {
_rx: Receiver<MonCmd>,
}
/// Test probe: like [`bind_outbound_probe`], but the monitor-command
/// receiver is handed back instead of dropped, so a test can stage the
/// c13 drain gap — a `Monitor` command that reached the connection's inbox
/// and dies unread when the inbox is dropped. While the inbox lives,
/// [`monitor_remote`] against the probed node is simply in flight.
pub fn bind_outbound_probe_with_monitors(
node: &str,
incarnation: Incarnation,
tx: Sender<Frame>,
) -> MonitorInbox {
let (mon_tx, mon_rx) = channel();
bind_outbound(node, incarnation, tx, mon_tx);
MonitorInbox { _rx: mon_rx }
}
/// Manager-only: unbind `node`'s outbound channel. Called on `Disconnect`,
/// reap, and manager shutdown. Dropping the sender is what closes the conn
/// actor's outbound arm — but that arm's closure is NOT a stop signal (the
/// cmd channel is, per D9); the actor simply stops selecting on it.
pub(crate) fn unbind_outbound(node: &str) {
with_runtime(|inner| {
inner.outbound.lock().by_node.remove(node);
});
}
/// Send `msg` to `target`. `Ok(())` = handed to the connection's inbox, and
/// nothing more — see the module docs. Must run inside
/// [`run`](crate::run).
pub fn send<M>(target: RemoteName<M>, msg: M) -> Result<(), RemoteSendError<M>>
where
M: serde::Serialize + Send + 'static,
{
let payload = match encode_payload(&msg) {
Ok(p) => p,
Err(e) => return Err(RemoteSendError::Encode(msg, e)),
};
let frame = Frame::SendNamed {
name: target.name.as_str().to_string(),
type_hash: type_hash::<M>(),
payload,
};
match hand_to_connection(&target.node, frame) {
Ok(()) => Ok(()),
Err(NotConnected) => Err(RemoteSendError::NotConnected(msg)),
}
}
/// No live connection to the named node — the payload-free form of
/// [`RemoteSendError::NotConnected`], for the raw path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NotConnected;
/// The untyped escape hatch: send pre-encoded `payload` under an explicit
/// `type_hash`. Exists so tests (and future codecs) can put deliberately
/// wrong frames on the wire; the typed [`send`] cannot express a hash/type
/// mismatch, by design. Same `Ok` semantics as [`send`].
pub fn send_remote_raw(
node: &str,
name: &str,
type_hash: u64,
payload: &[u8],
) -> Result<(), NotConnected> {
hand_to_connection(
node,
Frame::SendNamed {
name: name.to_string(),
type_hash,
payload: payload.to_vec(),
},
)
}
/// One lookup, one send. Clone the sender out under the lock and send
/// outside it (a channel send can unpark the conn actor).
fn hand_to_connection(node: &str, frame: Frame) -> Result<(), NotConnected> {
let tx = with_runtime(|inner| {
inner
.outbound
.lock()
.by_node
.get(node)
.map(|r| r.frames.clone())
});
match tx {
Some(tx) => tx.send(frame).map_err(|_| NotConnected),
None => Err(NotConnected),
}
}
// ---- pids ---------------------------------------------------------------
/// A pid on some node: `(node_name, incarnation, index, generation)` plus
/// the actor type. See the module docs. Serializes as a 4-tuple.
pub struct RemotePid<A> {
node: String,
incarnation: Incarnation,
index: u32,
generation: u32,
_marker: PhantomData<fn() -> A>,
}
impl<A> RemotePid<A> {
/// Build from raw parts (tests, and codecs re-hydrating a pid).
pub fn from_parts(
node: impl Into<String>,
incarnation: Incarnation,
index: u32,
generation: u32,
) -> Self {
RemotePid {
node: node.into(),
incarnation,
index,
generation,
_marker: PhantomData,
}
}
/// The wire form of a local pid, stamped with this node's identity, and
/// **marked watchable** — asking for the wire form *is* the intent to
/// ship the pid, so this is the same D12 set-site as `Pid::serialize`
/// (c12 made it explicit: a peer may monitor exactly the pids that
/// crossed, and a pid handed out via `from_local` in a hand-built reply
/// has crossed). Must run inside [`run`](crate::run).
///
/// `None` when this runtime has no wire identity (no `cluster::start`,
/// no [`set_local_identity`]): such a pid cannot name a node, and a
/// stamped `("", 0)` would be dropped by every peer with no signal.
/// The pid is not marked watchable in that case either.
pub fn from_local(pid: Pid<A>) -> Option<Self> {
let (node, incarnation) = local_identity()?;
Some(Self::from_local_at(pid, node, incarnation))
}
/// `from_local` with the identity supplied by the caller — for a holder
/// that already carries the node's identity (the pg actor) and must not
/// have a `None` path. Marks watchable like `from_local`.
pub(crate) fn from_local_at(pid: Pid<A>, node: String, incarnation: Incarnation) -> Self {
crate::monitor::mark_watchable(pid);
RemotePid::from_parts(node, incarnation, pid.index(), pid.generation())
}
/// The collapse: `Some(local pid)` iff this pid names this very node
/// (name and incarnation). Must run inside [`run`](crate::run).
pub fn local(&self) -> Option<Pid<A>> {
let (n, i) = local_identity()?;
(n == self.node && i == self.incarnation)
.then(|| crate::pid::assert_type::<A>(Pid::new(self.index, self.generation)))
}
/// Drop the actor type: the untyped `RemotePid<Erased>`, the form
/// [`RemoteDown`] and [`RemoteMonitor`] carry (mirrors [`Pid::erase`]).
pub fn erase(self) -> RemotePid<Erased> {
RemotePid::from_parts(self.node, self.incarnation, self.index, self.generation)
}
/// Re-type an erased pid as `RemotePid<B>` — the unchecked mirror of
/// `pid::assert_type`, with the same degradation: a wrong `B` means the
/// target refuses the payload's hash (never a misroute).
pub(crate) fn assert_type<B>(self) -> RemotePid<B> {
RemotePid::from_parts(self.node, self.incarnation, self.index, self.generation)
}
pub fn node(&self) -> &str {
&self.node
}
pub fn incarnation(&self) -> Incarnation {
self.incarnation
}
pub fn index(&self) -> u32 {
self.index
}
pub fn generation(&self) -> u32 {
self.generation
}
}
impl<A> Clone for RemotePid<A> {
fn clone(&self) -> Self {
RemotePid::from_parts(
self.node.clone(),
self.incarnation,
self.index,
self.generation,
)
}
}
impl<A> PartialEq for RemotePid<A> {
fn eq(&self, o: &Self) -> bool {
self.node == o.node
&& self.incarnation == o.incarnation
&& self.index == o.index
&& self.generation == o.generation
}
}
impl<A> Eq for RemotePid<A> {}
impl<A> std::fmt::Debug for RemotePid<A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"<{}.{}@{}#{}>",
self.index,
self.generation,
self.node,
self.incarnation.get()
)
}
}
impl<A> serde::Serialize for RemotePid<A> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
(
self.node.as_str(),
self.incarnation.get(),
self.index,
self.generation,
)
.serialize(s)
}
}
impl<'de, A> serde::Deserialize<'de> for RemotePid<A> {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let (node, inc, index, generation) = <(String, u32, u32, u32)>::deserialize(d)?;
Ok(RemotePid::from_parts(
node,
Incarnation::new(inc),
index,
generation,
))
}
}
/// Why a pid-targeted send did not leave this node. Local knowledge only.
#[derive(Debug)]
pub enum ToRemoteError<M> {
/// No live connection to the pid's node.
NotConnected(M),
/// The pid's incarnation is not that node's current one (RFC v2 §3): the
/// actor died with its incarnation. Detected at the send site; no frame.
DeadIncarnation(M),
/// The payload did not serialize.
Encode(M, PayloadError),
/// The pid collapsed to a local one and the local typed send failed.
Local(SendError<M>),
}
impl<M> ToRemoteError<M> {
/// The undelivered message.
pub fn into_inner(self) -> M {
match self {
ToRemoteError::NotConnected(m)
| ToRemoteError::DeadIncarnation(m)
| ToRemoteError::Encode(m, _) => m,
ToRemoteError::Local(e) => e.into_inner(),
}
}
}
/// Send `msg` to a pid, wherever it lives. Self-node pids short-circuit to
/// the local typed send with `msg` itself (no encode, no frame); others go
/// out as a `Send` frame after the incarnation check. `Ok(())` for a remote
/// target = handed to the connection's inbox. Must run inside
/// [`run`](crate::run).
pub fn send_to_remote<A>(target: RemotePid<A>, msg: A::Msg) -> Result<(), ToRemoteError<A::Msg>>
where
A: Addressable,
A::Msg: serde::Serialize,
{
if let Some(local) = target.local() {
return send_to(local, msg).map_err(ToRemoteError::Local);
}
let route = with_runtime(|inner| {
inner
.outbound
.lock()
.by_node
.get(&target.node)
.map(|r| (r.incarnation, r.frames.clone()))
});
let (current, tx) = match route {
Some(r) => r,
None => return Err(ToRemoteError::NotConnected(msg)),
};
if current != target.incarnation {
return Err(ToRemoteError::DeadIncarnation(msg));
}
let payload = match encode_payload(&msg) {
Ok(p) => p,
Err(e) => return Err(ToRemoteError::Encode(msg, e)),
};
let frame = Frame::Send {
index: target.index,
generation: target.generation,
type_hash: type_hash::<A::Msg>(),
payload,
};
tx.send(frame).map_err(|_| ToRemoteError::NotConnected(msg))
}
/// The inbound `Send` seam: deliver `payload` under `type_hash` to the local
/// actor `(index, generation)`. Node and incarnation are implicit in the
/// connection (bound at handshake) — the frame carries only the slot
/// identity. Delivery goes through c8's decoder table, so only types the
/// receiver has [`expose_type`](crate::cluster::expose::expose_type)d (or
/// exposed by name) can land; anything else is refused, never misrouted.
pub fn deliver_to_pid(
index: u32,
generation: u32,
type_hash: u64,
payload: &[u8],
) -> InboundVerdict {
let pid = Pid::new(index, generation);
match decode_deliver(type_hash, pid, payload) {
Ok(()) => InboundVerdict::Delivered,
Err(e) => InboundVerdict::Refused(e),
}
}
/// What the inbound seam did with a `SendNamed`. Local observability only;
/// nothing goes back on the wire (RFC §3).
#[derive(Debug)]
pub enum InboundVerdict {
/// Decoded and handed to the name's holder.
Delivered,
/// The name is not in this node's exposed set.
NotExposed,
/// The frame's hash is not the hash the name was exposed with.
HashMismatch { expected: u64, got: u64 },
/// Exposed, but no live holder right now (unbound, or its holder died
/// and the binding is being pruned).
Unresolved,
/// Resolved, but the delivery half refused it (decode failure, or the
/// holder's channel does not accept the exposed type — a local
/// re-registration under a different type; never a misroute).
Refused(DeliverError),
}
impl InboundVerdict {
/// A short static label for tracing/counting (`smarm-trace` records one
/// `ClusterInbound` event per frame with it).
pub fn label(&self) -> &'static str {
match self {
InboundVerdict::Delivered => "delivered",
InboundVerdict::NotExposed => "not_exposed",
InboundVerdict::HashMismatch { .. } => "hash_mismatch",
InboundVerdict::Unresolved => "unresolved",
InboundVerdict::Refused(_) => "refused",
}
}
}
/// THE inbound resolution seam: exposed-set check → hash check → registry
/// resolution → c8 delivery. See the module docs. Must run inside
/// [`run`](crate::run) — the conn actor's context.
pub fn deliver_named(name: &str, type_hash: u64, payload: &[u8]) -> InboundVerdict {
let Some(expected) = exposed_hash(name) else {
return InboundVerdict::NotExposed;
};
if expected != type_hash {
return InboundVerdict::HashMismatch {
expected,
got: type_hash,
};
}
let Some(pid) = whereis(name) else {
return InboundVerdict::Unresolved;
};
match decode_deliver(type_hash, pid, payload) {
Ok(()) => InboundVerdict::Delivered,
Err(e) => InboundVerdict::Refused(e),
}
}
// ---- monitors (c12) -----------------------------------------------------
/// Bookkeeping commands from [`monitor_remote`]/[`demonitor_remote`] to the
/// connection actor that owns the link to the target's node. The actor
/// records the registration and *then* emits the `Monitor` frame itself, so
/// a `Down` can never arrive at a table that does not yet know the id. It
/// lives in the actor (not on `RuntimeInner`) so the bookkeeping dies with
/// the connection — exactly what c13 needs to synthesize `Disconnected`.
pub(crate) enum MonCmd {
Monitor {
id: MonitorId,
target: RemotePid<Erased>,
tx: Sender<RemoteDown>,
},
Demonitor {
id: MonitorId,
},
}
/// A remotely-monitored actor's termination notice — the cluster analog of
/// [`Down`](crate::monitor::Down), with the pid in its wire form because it
/// may name any node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteDown {
/// The pid that was being monitored.
pub pid: RemotePid<Erased>,
/// How it went down. `Disconnected` means the *link* to its node was
/// lost (or absent) — nothing is known about the actor itself.
pub reason: RemoteDownReason,
}
enum Watch {
/// The target collapsed to this node: an ordinary local monitor,
/// translated on read.
Local(Monitor),
/// The target is elsewhere: the connection actor for its node holds the
/// registration and forwards the peer's `Down` frame here. The
/// `RemoteState` is the read-side backstop (c13): a channel that closes
/// while `Live` — the connection died with our command unread — reads
/// as `Disconnected` once; afterwards, and after a cancel, closed is
/// just closed.
Remote(Receiver<RemoteDown>, Cell<RemoteState>),
}
/// Where a remote-watch stands from the reader's side.
#[derive(Clone, Copy, PartialEq, Eq)]
enum RemoteState {
/// No notice yet, not cancelled: a closed channel means `Disconnected`.
Live,
/// The one notice has been read (or synthesized): nothing more is due.
Done,
/// `demonitor_remote` ran: never synthesize.
Cancelled,
}
/// A live remote monitor: read its one [`RemoteDown`] with
/// [`recv`](RemoteMonitor::recv)/[`try_recv`](RemoteMonitor::try_recv), or
/// fold it into a `select` via [`arm`](RemoteMonitor::arm). Distinct from
/// [`Monitor`] on purpose: its target is a [`RemotePid`], its notice a
/// [`RemoteDown`], and it can report `Disconnected` — none of which a local
/// monitor can express. Dropping it discards an unread notice, like the
/// local one; after [`demonitor_remote`] the channel is closed and empty, so
/// `recv` errs rather than parking — also like the local one.
///
/// Exactly one notice is guaranteed even if the connection actor dies with
/// the registration unread (the c13 drain gap): a channel that closes
/// before any notice — and before any cancel — reads as `Disconnected`,
/// once. The next read is the ordinary closed-channel `Err`.
pub struct RemoteMonitor {
/// This registration's process-unique id — minted here, echoed by the
/// peer in its `Down` frame.
pub id: MonitorId,
/// The pid being monitored.
pub target: RemotePid<Erased>,
watch: Watch,
}
impl RemoteMonitor {
/// Block (cooperatively) for the notice.
pub fn recv(&self) -> Result<RemoteDown, RecvError> {
match &self.watch {
Watch::Local(m) => m.rx.recv().map(|d| RemoteDown {
pid: self.target.clone(),
reason: d.reason.into(),
}),
Watch::Remote(rx, st) => match rx.recv() {
Ok(d) => {
st.set(RemoteState::Done);
Ok(d)
}
Err(e) => self.closed(st).ok_or(e),
},
}
}
/// The notice if it has arrived; `Ok(None)` if not yet.
pub fn try_recv(&self) -> Result<Option<RemoteDown>, RecvError> {
match &self.watch {
Watch::Local(m) => m.rx.try_recv().map(|o| {
o.map(|d| RemoteDown {
pid: self.target.clone(),
reason: d.reason.into(),
})
}),
Watch::Remote(rx, st) => match rx.try_recv() {
Ok(Some(d)) => {
st.set(RemoteState::Done);
Ok(Some(d))
}
Ok(None) => Ok(None),
Err(e) => self.closed(st).map(Some).ok_or(e),
},
}
}
/// The channel closed. While `Live` — no notice yet, no cancel — that
/// is the connection having died with our registration unread, so
/// synthesize the one `Disconnected` and mark `Done`; otherwise closed
/// is just closed.
fn closed(&self, st: &Cell<RemoteState>) -> Option<RemoteDown> {
if st.get() != RemoteState::Live {
return None;
}
st.set(RemoteState::Done);
Some(RemoteDown {
pid: self.target.clone(),
reason: RemoteDownReason::Disconnected,
})
}
/// The selectable arm: readiness means [`try_recv`](Self::try_recv)
/// will yield the notice.
pub fn arm(&self) -> &dyn Selectable {
match &self.watch {
Watch::Local(m) => &m.rx,
Watch::Remote(rx, _) => rx,
}
}
}
impl std::fmt::Debug for RemoteMonitor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RemoteMonitor")
.field("id", &self.id)
.field("target", &self.target)
.finish_non_exhaustive()
}
}
/// Monitor `target`, wherever it lives. Exactly one [`RemoteDown`] arrives:
///
/// - self-node pid ⇒ an ordinary local monitor underneath (same NoProc rule);
/// - no live connection to the pid's node ⇒ `Disconnected`, queued at once
/// (the remote analog of NoProc: nothing can be known);
/// - the pid's incarnation is not the node's current one ⇒ `NoProc`, queued
/// at once — the node is *known* to have restarted, so its actor is a
/// corpse, not a partition (RFC v2 §3);
/// - otherwise the connection actor registers the id and sends `Monitor`;
/// the peer answers with the true terminal reason on exit, or immediately
/// with the recorded reason for a corpse (`terminal_reason`, RFC §6) or
/// `NoProc` for a pid it never exposed and never shipped.
///
/// The connection dropping while the monitor is outstanding delivers
/// `Disconnected` (c13): the connection actor synthesizes it on teardown,
/// and the monitor's own read path backstops the case where the actor died
/// with the registration still unread. Must run inside [`run`](crate::run).
pub fn monitor_remote<A>(target: RemotePid<A>) -> RemoteMonitor {
if let Some(local) = target.local() {
let m = monitor(local);
return RemoteMonitor {
id: m.id,
target: target.erase(),
watch: Watch::Local(m),
};
}
let target = target.erase();
let (id, route) = with_runtime(|inner| {
let id = inner.alloc_monitor_id();
let route = inner
.outbound
.lock()
.by_node
.get(&target.node)
.map(|r| (r.incarnation, r.monitors.clone()));
(id, route)
});
let (tx, rx) = channel::<RemoteDown>();
let immediate = match route {
None => Some(RemoteDownReason::Disconnected),
Some((current, _)) if current != target.incarnation => {
Some(RemoteDownReason::Local(crate::monitor::DownReason::NoProc))
}
Some((_, mon_tx)) => {
let cmd = MonCmd::Monitor {
id,
target: target.clone(),
tx: tx.clone(),
};
match mon_tx.send(cmd) {
Ok(()) => None,
Err(_) => Some(RemoteDownReason::Disconnected), // actor already gone
}
}
};
if let Some(reason) = immediate {
let _ = tx.send(RemoteDown {
pid: target.clone(),
reason,
});
}
RemoteMonitor {
id,
target,
watch: Watch::Remote(rx, Cell::new(RemoteState::Live)),
}
}
/// Cancel `m`. No future notice will be *sent* for it; a notice already in
/// flight from the peer is dropped on arrival, and one already sitting in
/// `m` is discarded when `m` is dropped (same contract as
/// [`demonitor`]). Unlike the local form this returns nothing: the
/// registration is owned by the connection actor, so whether the `Down`
/// beat the cancel is not local knowledge. Must run inside
/// [`run`](crate::run).
pub fn demonitor_remote(m: &RemoteMonitor) {
match &m.watch {
Watch::Local(local) => {
let _ = demonitor(local);
}
Watch::Remote(_, st) => {
// Cancel first: a channel closing after this is closed, not a
// Disconnected notice — the caller asked for silence.
st.set(RemoteState::Cancelled);
let mon_tx = with_runtime(|inner| {
inner
.outbound
.lock()
.by_node
.get(&m.target.node)
.map(|r| r.monitors.clone())
});
if let Some(mon_tx) = mon_tx {
let _ = mon_tx.send(MonCmd::Demonitor { id: m.id });
}
}
}
}
+298
View File
@@ -0,0 +1,298 @@
//! RFC 010 c3 — transport abstraction for the **control** connection.
//!
//! Scope, per RFC 010 v2 §5 and D2:
//!
//! - A "connection" here is the *control* connection: the one carrying this
//! RFC's frame inventory ([`crate::cluster::envelope::Frame`]), whose
//! heartbeats feed failure detection. The trait deliberately says nothing
//! about how many connections a peer pair may hold — the jarred rkyv bulk
//! plane opens **additional per-peer connections** outside this trait, and
//! nothing here may foreclose that.
//! - Homogeneous smarm⇄smarm only. The BEAM membrane is *not* a transport
//! impl and the trait does not accommodate it (D2).
//! - Addresses are opaque, **pre-resolved** strings. Name resolution is a
//! single separate seam (roadmap c9); impls reject unresolved names rather
//! than resolving them.
//!
//! Blocking model: [`Conn`] calls block the caller. The TCP impl parks the
//! calling *actor* (fd readiness via the scheduler); the loopback impl blocks
//! the calling *OS thread* and is a test transport — do not drive it from a
//! scheduler thread.
//!
//! Framing is not part of the trait: [`FramedConn`] is the single shared
//! codec that turns any byte-stream [`Conn`] into a frame pipe, feeding
//! [`Frame::decode`]'s incremental contract. Impls never re-implement
//! framing, and the conformance suite exercises the same codec over every
//! impl.
use std::io;
use crate::cluster::envelope::{DecodeError, EncodeError, Frame};
pub mod loopback;
pub mod tcp;
/// An established control connection: a bidirectional byte stream.
pub trait Conn: Send {
/// Read at least one byte, blocking the caller until data is available,
/// EOF, or error. `Ok(0)` means EOF: the peer closed and all bytes it
/// wrote before closing have been consumed.
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
/// Write the whole buffer, blocking the caller as needed.
fn write_all(&mut self, buf: &[u8]) -> io::Result<()>;
/// Close both directions. Idempotent. Bytes already written remain
/// readable at the peer, which then observes EOF; peer writes after this
/// fail.
fn close(&mut self);
/// Diagnostic label for logs only. Mesh identity comes from the
/// handshake (`Hello`/`HelloAck`), never from the transport.
fn peer_addr(&self) -> String;
/// Readiness as a [`select`](crate::select) arm, for transports backed by
/// a file descriptor. `Some` lets a driver wait on "this connection is
/// readable" alongside an ordinary command inbox in a single `select`, so
/// one actor can interleave reading with control messages without a
/// second thread. The default is `None`: a transport with no fd (the
/// in-memory loopback) cannot be selected on and must be driven another
/// way.
fn readable_arm(&self) -> Option<crate::scheduler::FdArm> {
None
}
}
/// A bound listen point producing inbound [`Conn`]s.
pub trait Listener: Send {
/// Accept the next inbound connection, blocking the caller.
fn accept(&mut self) -> io::Result<Box<dyn Conn>>;
/// The concrete bound address, dialable as-is (e.g. the real port when
/// bound with port 0).
fn local_addr(&self) -> String;
/// Readiness as a [`select`](crate::select) arm, mirroring
/// [`Conn::readable_arm`]: `Some` lets an acceptor wait on "an inbound
/// connection is pending" alongside a command inbox in one `select`, so
/// it can be told to stop without a poll loop. Default `None` (the
/// loopback listener has no fd and must be driven synchronously).
fn readable_arm(&self) -> Option<crate::scheduler::FdArm> {
None
}
}
/// A way of establishing control connections. Object-safe on purpose: the
/// connector and membership layers hold `&dyn Transport` / boxed conns
/// rather than growing a generic parameter.
pub trait Transport: Send + Sync {
/// Connect to a peer's listen address. Blocks the caller until
/// established or failed.
fn dial(&self, addr: &str) -> io::Result<Box<dyn Conn>>;
/// Bind a listen point.
fn listen(&self, addr: &str) -> io::Result<Box<dyn Listener>>;
}
impl std::fmt::Debug for dyn Conn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Conn({})", self.peer_addr())
}
}
impl std::fmt::Debug for dyn Listener {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Listener({})", self.local_addr())
}
}
/// Error surface of [`FramedConn::send`].
#[derive(Debug)]
pub enum SendError {
/// The frame could not be encoded (e.g. a field over its wire limit).
Encode(EncodeError),
/// The transport failed mid-write.
Io(io::Error),
}
impl std::fmt::Display for SendError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SendError::Encode(e) => write!(f, "frame encode failed: {e:?}"),
SendError::Io(e) => write!(f, "transport write failed: {e}"),
}
}
}
impl std::error::Error for SendError {}
/// Error surface of [`FramedConn::recv`].
#[derive(Debug)]
pub enum RecvError {
/// The byte stream is not a valid frame stream (bad tag, lying length,
/// oversized frame, …). The connection is unusable.
Corrupt(DecodeError),
/// The peer closed mid-frame: EOF arrived with a partial frame buffered.
/// Distinct from a clean close, which is `Ok(None)`.
TruncatedByPeer,
/// The transport failed mid-read.
Io(io::Error),
/// The deadline passed before a full frame arrived
/// ([`FramedConn::recv_deadline`] only; plain [`recv`](FramedConn::recv)
/// never returns this).
TimedOut,
}
impl std::fmt::Display for RecvError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RecvError::Corrupt(e) => write!(f, "frame stream corrupt: {e:?}"),
RecvError::TruncatedByPeer => write!(f, "peer closed mid-frame"),
RecvError::Io(e) => write!(f, "transport read failed: {e}"),
RecvError::TimedOut => write!(f, "deadline passed mid-receive"),
}
}
}
impl std::error::Error for RecvError {}
/// How many bytes each blocking read asks the transport for.
const READ_CHUNK: usize = 8 * 1024;
/// The shared framed codec: one of these per control connection, owning the
/// [`Conn`] and the reassembly buffer. Frames may arrive split or coalesced
/// arbitrarily; [`recv`](FramedConn::recv) reassembles either way.
pub struct FramedConn {
conn: Box<dyn Conn>,
rbuf: Vec<u8>,
}
impl FramedConn {
pub fn new(conn: Box<dyn Conn>) -> Self {
FramedConn {
conn,
rbuf: Vec::new(),
}
}
/// Encode and write one frame.
pub fn send(&mut self, frame: &Frame) -> Result<(), SendError> {
let mut out = Vec::new();
frame.encode(&mut out).map_err(SendError::Encode)?;
self.conn.write_all(&out).map_err(SendError::Io)
}
/// Receive the next frame. `Ok(None)` is a clean close: EOF at a frame
/// boundary. EOF mid-frame is [`RecvError::TruncatedByPeer`].
pub fn recv(&mut self) -> Result<Option<Frame>, RecvError> {
loop {
match Frame::decode(&self.rbuf) {
Ok(Some((frame, consumed))) => {
self.rbuf.drain(..consumed);
return Ok(Some(frame));
}
Ok(None) => {}
Err(e) => return Err(RecvError::Corrupt(e)),
}
let mut chunk = [0u8; READ_CHUNK];
let n = self.conn.read(&mut chunk).map_err(RecvError::Io)?;
if n == 0 {
return if self.rbuf.is_empty() {
Ok(None)
} else {
Err(RecvError::TruncatedByPeer)
};
}
self.rbuf.extend_from_slice(&chunk[..n]);
}
}
/// Like [`recv`](FramedConn::recv), but gives up with
/// [`RecvError::TimedOut`] once `deadline` passes without a full frame.
/// The deadline is enforced between reads via the connection's fd arm
/// (so the caller must be an actor); a transport with no fd (loopback)
/// cannot be timed out and this degrades to a plain blocking `recv` —
/// the same caveat as liveness.
pub fn recv_deadline(
&mut self,
deadline: std::time::Instant,
) -> Result<Option<Frame>, RecvError> {
loop {
match Frame::decode(&self.rbuf) {
Ok(Some((frame, consumed))) => {
self.rbuf.drain(..consumed);
return Ok(Some(frame));
}
Ok(None) => {}
Err(e) => return Err(RecvError::Corrupt(e)),
}
if let Some(arm) = self.conn.readable_arm() {
let left = deadline.saturating_duration_since(std::time::Instant::now());
if left.is_zero() {
return Err(RecvError::TimedOut);
}
match crate::channel::try_select_timeout(&[&arm], left) {
Ok(Some(_)) => {}
Ok(None) => return Err(RecvError::TimedOut),
Err(e) => return Err(RecvError::Io(e)),
}
}
let mut chunk = [0u8; READ_CHUNK];
let n = self.conn.read(&mut chunk).map_err(RecvError::Io)?;
if n == 0 {
return if self.rbuf.is_empty() {
Ok(None)
} else {
Err(RecvError::TruncatedByPeer)
};
}
self.rbuf.extend_from_slice(&chunk[..n]);
}
}
/// One socket read, appended to the reassembly buffer. Returns the byte
/// count (`0` = EOF). For select-loop callers that were just told the fd
/// is readable: under the level-triggered IO thread exactly one read per
/// readable wake never blocks and never loses data — leftover socket
/// bytes re-signal on the next select, and complete frames already
/// reassembled are drained with [`next_buffered`](FramedConn::next_buffered).
/// (A plain [`recv`](FramedConn::recv) can block into the socket while
/// the buffer holds a partial frame, which a loop with deadlines to keep
/// cannot afford.)
pub fn read_once(&mut self) -> std::io::Result<usize> {
let mut chunk = [0u8; READ_CHUNK];
let n = self.conn.read(&mut chunk)?;
self.rbuf.extend_from_slice(&chunk[..n]);
Ok(n)
}
/// Decode the next complete frame already sitting in the reassembly
/// buffer, without touching the socket. `Ok(None)` means the buffer
/// holds no complete frame (empty, or a partial awaiting more bytes).
pub fn next_buffered(&mut self) -> Result<Option<Frame>, DecodeError> {
match Frame::decode(&self.rbuf) {
Ok(Some((frame, consumed))) => {
self.rbuf.drain(..consumed);
Ok(Some(frame))
}
Ok(None) => Ok(None),
Err(e) => Err(e),
}
}
/// Close the underlying connection (idempotent, see [`Conn::close`]).
pub fn close(&mut self) {
self.conn.close();
}
/// Diagnostic label of the underlying connection.
pub fn peer_addr(&self) -> String {
self.conn.peer_addr()
}
/// The underlying connection's readiness arm, if it is fd-backed (see
/// [`Conn::readable_arm`]).
pub fn readable_arm(&self) -> Option<crate::scheduler::FdArm> {
self.conn.readable_arm()
}
}
+274
View File
@@ -0,0 +1,274 @@
//! In-memory loopback transport — a shipped **test** transport.
//!
//! Lets Phases 2–4 exercise protocol logic (connector, membership,
//! monitors) through the real transport trait and the real framed codec
//! without sockets or timing flake.
//!
//! Blocking model: calls block the **OS thread** on a condvar. That is the
//! right shape for plain `#[test]`s driving protocol state machines; it is
//! the wrong shape for scheduler threads. Do not drive a loopback conn from
//! inside an actor — use the TCP impl there.
//!
//! Semantics mirror TCP shutdown where it matters for the codec: bytes
//! written before `close` remain readable at the peer, which then sees EOF;
//! writes toward a closed peer fail with `BrokenPipe`. Write buffers are
//! unbounded, so writes never block — backpressure is not simulated.
use std::collections::{HashMap, VecDeque};
use std::io;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use super::{Conn, Listener, Transport};
/// Poison-tolerant lock: a panicked holder in a *test* transport must not
/// cascade; the byte-queue state stays consistent under every early return.
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
match m.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
}
}
// ---------------------------------------------------------------------------
// One direction of a duplex: a byte queue with close flags for both ends
// ---------------------------------------------------------------------------
#[derive(Default)]
struct PipeState {
bytes: VecDeque<u8>,
/// The writing end closed: readers drain remaining bytes, then EOF.
write_closed: bool,
/// The reading end closed: writers fail with `BrokenPipe`.
read_closed: bool,
}
#[derive(Default)]
struct Pipe {
state: Mutex<PipeState>,
cv: Condvar,
}
impl Pipe {
fn write_all(&self, buf: &[u8]) -> io::Result<()> {
let mut st = lock(&self.state);
if st.write_closed {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"loopback conn closed locally",
));
}
if st.read_closed {
return Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"loopback peer closed",
));
}
st.bytes.extend(buf);
self.cv.notify_all();
Ok(())
}
fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
let mut st = lock(&self.state);
loop {
if !st.bytes.is_empty() {
let n = st.bytes.len().min(buf.len());
for (slot, byte) in buf.iter_mut().zip(st.bytes.drain(..n)) {
*slot = byte;
}
return Ok(n);
}
if st.write_closed || st.read_closed {
return Ok(0); // EOF: peer closed, or our own end closed.
}
st = match self.cv.wait(st) {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
}
}
/// Close from the writer side: remaining bytes stay readable, then EOF.
fn close_write(&self) {
lock(&self.state).write_closed = true;
self.cv.notify_all();
}
/// Close from the reader side: peer writes fail from now on.
fn close_read(&self) {
lock(&self.state).read_closed = true;
self.cv.notify_all();
}
}
// ---------------------------------------------------------------------------
// Conn: two pipes, one per direction
// ---------------------------------------------------------------------------
/// One end of an established loopback connection.
pub struct LoopbackConn {
tx: Arc<Pipe>,
rx: Arc<Pipe>,
peer: String,
}
impl Conn for LoopbackConn {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.rx.read(buf)
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.tx.write_all(buf)
}
fn close(&mut self) {
self.tx.close_write();
self.rx.close_read();
}
fn peer_addr(&self) -> String {
self.peer.clone()
}
}
impl Drop for LoopbackConn {
fn drop(&mut self) {
self.close();
}
}
fn conn_pair(listen_addr: &str, conn_no: u64) -> (LoopbackConn, LoopbackConn) {
let a_to_b = Arc::new(Pipe::default());
let b_to_a = Arc::new(Pipe::default());
let dialer = LoopbackConn {
tx: a_to_b.clone(),
rx: b_to_a.clone(),
peer: listen_addr.to_string(),
};
let accepted = LoopbackConn {
tx: b_to_a,
rx: a_to_b,
peer: format!("{listen_addr}#dialer-{conn_no}"),
};
(dialer, accepted)
}
// ---------------------------------------------------------------------------
// Listener + registry
// ---------------------------------------------------------------------------
#[derive(Default)]
struct AcceptState {
pending: VecDeque<LoopbackConn>,
closed: bool,
}
#[derive(Default)]
struct AcceptQueue {
state: Mutex<AcceptState>,
cv: Condvar,
}
/// A bound loopback listen point.
pub struct LoopbackListener {
addr: String,
queue: Arc<AcceptQueue>,
registry: Arc<Mutex<Registry>>,
}
impl Listener for LoopbackListener {
fn accept(&mut self) -> io::Result<Box<dyn Conn>> {
let mut st = lock(&self.queue.state);
loop {
if let Some(conn) = st.pending.pop_front() {
return Ok(Box::new(conn));
}
if st.closed {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"loopback listener closed",
));
}
st = match self.queue.cv.wait(st) {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
}
}
fn local_addr(&self) -> String {
self.addr.clone()
}
}
impl Drop for LoopbackListener {
fn drop(&mut self) {
lock(&self.registry).listeners.remove(&self.addr);
let mut st = lock(&self.queue.state);
st.closed = true;
self.queue.cv.notify_all();
}
}
#[derive(Default)]
struct Registry {
listeners: HashMap<String, Arc<AcceptQueue>>,
dial_count: u64,
}
/// The loopback transport. Addresses are arbitrary strings scoped to one
/// transport instance; distinct instances never see each other's listeners.
#[derive(Default)]
pub struct LoopbackTransport {
registry: Arc<Mutex<Registry>>,
}
impl Transport for LoopbackTransport {
fn dial(&self, addr: &str) -> io::Result<Box<dyn Conn>> {
let (queue, conn_no) = {
let mut reg = lock(&self.registry);
reg.dial_count += 1;
let no = reg.dial_count;
match reg.listeners.get(addr) {
Some(q) => (q.clone(), no),
None => {
return Err(io::Error::new(
io::ErrorKind::ConnectionRefused,
format!("no loopback listener at {addr:?}"),
));
}
}
};
let (dialer, accepted) = conn_pair(addr, conn_no);
let mut st = lock(&queue.state);
if st.closed {
return Err(io::Error::new(
io::ErrorKind::ConnectionRefused,
format!("loopback listener at {addr:?} closed"),
));
}
st.pending.push_back(accepted);
queue.cv.notify_all();
Ok(Box::new(dialer))
}
fn listen(&self, addr: &str) -> io::Result<Box<dyn Listener>> {
let queue = Arc::new(AcceptQueue::default());
let mut reg = lock(&self.registry);
if reg.listeners.contains_key(addr) {
return Err(io::Error::new(
io::ErrorKind::AddrInUse,
format!("loopback listener already bound at {addr:?}"),
));
}
reg.listeners.insert(addr.to_string(), queue.clone());
Ok(Box::new(LoopbackListener {
addr: addr.to_string(),
queue,
registry: self.registry.clone(),
}))
}
}
+285
View File
@@ -0,0 +1,285 @@
//! TCP transport — the production control-plane transport.
//!
//! Blocking model: every blocking point parks the **calling actor** on fd
//! readiness ([`crate::scheduler::wait_readable`] / `wait_writable`); the
//! scheduler thread is never blocked. All conn/listener methods must
//! therefore run inside an actor. `listen` itself only binds (no waiting)
//! and is callable anywhere.
//!
//! Addresses are pre-resolved `ip:port` strings (`SocketAddr` syntax, IPv4
//! or IPv6). Hostnames are rejected with `InvalidInput`: name resolution is
//! the single c9 seam, not something each transport does on the side.
//!
//! Writes use `send(2)` with `MSG_NOSIGNAL` — a peer reset must surface as
//! `BrokenPipe`/`ConnectionReset`, not `SIGPIPE`.
use std::io;
use std::net::{SocketAddr, TcpListener as StdListener, TcpStream};
use std::os::fd::{AsRawFd, RawFd};
use crate::scheduler::{wait_readable, wait_writable};
use super::{Conn, Listener, Transport};
// ---------------------------------------------------------------------------
// sockaddr plumbing
// ---------------------------------------------------------------------------
/// A `sockaddr_in`/`sockaddr_in6` built from a parsed `SocketAddr`, plus its
/// length, ready for `connect(2)`.
union SockAddrUnion {
v4: libc::sockaddr_in,
v6: libc::sockaddr_in6,
}
fn to_sockaddr(sa: &SocketAddr) -> (SockAddrUnion, libc::socklen_t) {
match sa {
SocketAddr::V4(v4) => {
let raw = libc::sockaddr_in {
sin_family: libc::AF_INET as libc::sa_family_t,
sin_port: v4.port().to_be(),
sin_addr: libc::in_addr {
s_addr: u32::from_be_bytes(v4.ip().octets()).to_be(),
},
sin_zero: [0; 8],
};
(
SockAddrUnion { v4: raw },
std::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t,
)
}
SocketAddr::V6(v6) => {
let raw = libc::sockaddr_in6 {
sin6_family: libc::AF_INET6 as libc::sa_family_t,
sin6_port: v6.port().to_be(),
sin6_flowinfo: v6.flowinfo(),
sin6_addr: libc::in6_addr {
s6_addr: v6.ip().octets(),
},
sin6_scope_id: v6.scope_id(),
};
(
SockAddrUnion { v6: raw },
std::mem::size_of::<libc::sockaddr_in6>() as libc::socklen_t,
)
}
}
}
fn parse_addr(addr: &str) -> io::Result<SocketAddr> {
addr.parse().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("{addr:?} is not a resolved ip:port — resolution is the c9 seam"),
)
})
}
fn so_error(fd: RawFd) -> io::Result<()> {
let mut err: libc::c_int = 0;
let mut len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;
let rc = unsafe {
libc::getsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_ERROR,
(&mut err) as *mut _ as *mut libc::c_void,
&mut len,
)
};
if rc != 0 {
return Err(io::Error::last_os_error());
}
if err != 0 {
return Err(io::Error::from_raw_os_error(err));
}
Ok(())
}
// ---------------------------------------------------------------------------
// Conn
// ---------------------------------------------------------------------------
/// One established TCP control connection. Owns the socket; drop closes it.
pub struct TcpConn {
stream: TcpStream,
closed: bool,
}
impl TcpConn {
fn fd(&self) -> RawFd {
self.stream.as_raw_fd()
}
}
impl Conn for TcpConn {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.closed {
return Ok(0);
}
if buf.is_empty() {
return Ok(0);
}
loop {
wait_readable(self.fd())?;
let n = unsafe { libc::read(self.fd(), buf.as_mut_ptr() as *mut _, buf.len()) };
if n >= 0 {
return Ok(n as usize);
}
let e = io::Error::last_os_error();
match e.kind() {
// Spurious readiness or signal: park again.
io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => continue,
_ => return Err(e),
}
}
}
fn write_all(&mut self, mut buf: &[u8]) -> io::Result<()> {
if self.closed {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"tcp conn closed locally",
));
}
while !buf.is_empty() {
wait_writable(self.fd())?;
let n = unsafe {
libc::send(
self.fd(),
buf.as_ptr() as *const _,
buf.len(),
libc::MSG_NOSIGNAL,
)
};
if n >= 0 {
buf = &buf[n as usize..];
continue;
}
let e = io::Error::last_os_error();
match e.kind() {
io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => continue,
_ => return Err(e),
}
}
Ok(())
}
fn close(&mut self) {
if !self.closed {
self.closed = true;
// Best-effort: the peer sees EOF after draining. The fd itself
// is released when the owning stream drops.
let _ = self.stream.shutdown(std::net::Shutdown::Both);
}
}
fn peer_addr(&self) -> String {
match self.stream.peer_addr() {
Ok(sa) => sa.to_string(),
Err(_) => "<disconnected>".to_string(),
}
}
fn readable_arm(&self) -> Option<crate::scheduler::FdArm> {
Some(crate::scheduler::FdArm::readable(self.fd()))
}
}
// ---------------------------------------------------------------------------
// Listener
// ---------------------------------------------------------------------------
/// A bound TCP listen point (non-blocking socket; accept parks the actor).
pub struct TcpListener {
inner: StdListener,
local: SocketAddr,
}
impl Listener for TcpListener {
fn readable_arm(&self) -> Option<crate::scheduler::FdArm> {
Some(crate::scheduler::FdArm::readable(self.inner.as_raw_fd()))
}
fn accept(&mut self) -> io::Result<Box<dyn Conn>> {
loop {
wait_readable(self.inner.as_raw_fd())?;
match self.inner.accept() {
Ok((stream, _peer)) => {
stream.set_nonblocking(true)?;
return Ok(Box::new(TcpConn {
stream,
closed: false,
}));
}
Err(e)
if e.kind() == io::ErrorKind::WouldBlock
|| e.kind() == io::ErrorKind::Interrupted =>
{
continue;
}
Err(e) => return Err(e),
}
}
}
fn local_addr(&self) -> String {
self.local.to_string()
}
}
// ---------------------------------------------------------------------------
// Transport
// ---------------------------------------------------------------------------
/// The TCP transport. Stateless; every call stands alone.
pub struct TcpTransport;
impl Transport for TcpTransport {
fn dial(&self, addr: &str) -> io::Result<Box<dyn Conn>> {
let sa = parse_addr(addr)?;
let family = match sa {
SocketAddr::V4(_) => libc::AF_INET,
SocketAddr::V6(_) => libc::AF_INET6,
};
let fd = unsafe {
libc::socket(
family,
libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC,
0,
)
};
if fd < 0 {
return Err(io::Error::last_os_error());
}
// From here the fd is owned by `stream`; any early return drops it.
let stream = unsafe {
use std::os::fd::FromRawFd;
TcpStream::from_raw_fd(fd)
};
let (raw, len) = to_sockaddr(&sa);
let rc = unsafe { libc::connect(fd, (&raw) as *const _ as *const libc::sockaddr, len) };
if rc != 0 {
let e = io::Error::last_os_error();
if e.raw_os_error() != Some(libc::EINPROGRESS) {
return Err(e);
}
// Connect in flight: park until the socket is writable, then the
// verdict is in SO_ERROR.
wait_writable(fd)?;
so_error(fd)?;
}
Ok(Box::new(TcpConn {
stream,
closed: false,
}))
}
fn listen(&self, addr: &str) -> io::Result<Box<dyn Listener>> {
let sa = parse_addr(addr)?;
let inner = StdListener::bind(sa)?;
inner.set_nonblocking(true)?;
let local = inner.local_addr()?;
Ok(Box::new(TcpListener { inner, local }))
}
}