feat(cluster): RFC 010 c10–c16, follow-ups and Phase 6 (squash of 16ef583..d9c62a8)

Tree snapshot of d9c62a8 (2026-08-18). The 20 source commits between
16ef583 (c9) and d9c62a8 were never pushed and the clone that held them
was lost; this commit carries their combined tree verbatim so the build
history stays auditable from the c1–c9 commits below it. Original
hashes as recorded in the session handoff:

  c10  f03e94d  pid targeting + auto-serialization (RemotePid, D14 name
                on the wire); Phase 3 gate
  c11  7ef4bad  DownReason::Disconnected, wire tag 5
  c12  d124162  remote monitors (Monitor/Demonitor/Down frames)
  c13  9de967b  connection-loss synthesis (A+B: Monitors::teardown +
                unread-command Disconnected); Phase 4 gate
  c14  7e822b7  eager pg eviction (reaper actor, ReaperInboxes)
       dbe1a22  InboundVerdict::label(), trace::Event::ClusterInbound
       31a9877  tests/channel.rs monitor-churn target gated on `go`
       653559e  Discovery::Withdrawn{name, addr}
  c15  b41d76e  distributed pg: Sync on NodeUp, Join/Leave broadcast,
                NodeDown sweep, members_all; PgMsg wire type
  c16  fafa881  pick_any / dispatch_any; Phase 5 complete
  Phase 6 Tier A:
       195c73e  p4  NodeEvent::NodeDown(NodeInfo)
       48fd766  p1  connector Candidate{name, addr, state}
       ce8cf99  p2+p7 conn.rs select arms as Vec<Arm>; Outbound::Drained
       bf24988  p6  RemotePid::from_local -> Option
       9ae0380  p3  PeerStanding{Free, Claimed, Dialing}
       c7d62a1  p11 cluster::Timing knobs, threaded by value
       46f171d  p11 cluster_disconnect un-ignored on SMARM_FAST_TIMING
  Phase 6 Tier B:
       391a9ae  p5  cluster::RemoteDownReason{Local, Disconnected};
                    DownReason::Disconnected removed from core
       7ddd908  p9  pg ctl channel unconditional, one cfg seam at spawn
       d9c62a8      PeerNameMismatch parks the candidate; ClusterDial trace

Verified at d9c62a8: default 361/0, cluster 448/0, clippy --lib on
default / cluster / cluster+smarm-trace, fmt, 10x flake on
cluster_dial_mismatch, 5x on cluster_pg.
This commit is contained in:
claude-asm-audit
2026-08-18 16:00:00 +02:00
parent 16ef583455
commit 4c0e42152f
32 changed files with 4202 additions and 578 deletions
+380 -51
View File
@@ -27,21 +27,52 @@
//! 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).
//! Frames the connection actor has no business with yet (`Send`, `Monitor`,
//! …: c10/c11) are consumed for liveness and otherwise ignored. The outbound
//! `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;
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;
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::pid::Pid;
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.
@@ -57,11 +88,11 @@ enum Cmd {
/// to establish it.
pub struct ConnHandle {
cmd_tx: Sender<Cmd>,
/// The connection's dedicated outbound inbox. The manager moves this
/// into the outbound table on `Register` (see
/// [`take_outbound`](ConnHandle::take_outbound)); a `Duplicate` verdict
/// drops it with the handle.
out_tx: Option<Sender<Frame>>,
/// 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 {
@@ -78,9 +109,9 @@ impl ConnHandle {
let _ = self.cmd_tx.send(Cmd::Shutdown);
}
/// Manager-only: take the outbound sender to bind into the outbound
/// 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>> {
pub(crate) fn take_outbound(&mut self) -> Option<(Sender<Frame>, Sender<MonCmd>)> {
self.out_tx.take()
}
}
@@ -96,11 +127,16 @@ pub struct RegisterRefused;
/// 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) -> Result<Pid, RegisterRefused> {
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, cmd_rx, out_rx)).pid();
let pid = spawn(move || run(framed, peer, timing, cmd_rx, out_rx, mon_rx)).pid();
match gen_server::call(
MANAGER,
Call::Register {
@@ -108,7 +144,7 @@ pub fn spawn_established(framed: FramedConn, peer: Peer) -> Result<Pid, Register
pid,
handle: ConnHandle {
cmd_tx,
out_tx: Some(out_tx),
out_tx: Some((out_tx, mon_tx)),
},
},
) {
@@ -120,25 +156,136 @@ pub fn spawn_established(framed: FramedConn, peer: Peer) -> Result<Pid, Register
}
}
/// 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.
/// 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);
/// 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 —
/// 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, cmd_rx: Receiver<Cmd>, out_rx: Receiver<Frame>) {
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, &cmd_rx, &out_rx),
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
@@ -148,15 +295,39 @@ fn run(mut framed: FramedConn, _peer: Peer, cmd_rx: Receiver<Cmd>, out_rx: Recei
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() + LIVENESS_TIMEOUT;
// The outbound sender lives in the manager's table and is dropped on
// unbind; after that this arm would wake forever, so it drops out of
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 {
@@ -166,33 +337,57 @@ fn run_live(
if framed.send(&Frame::Heartbeat).is_err() {
break;
}
next_hb = now + HEARTBEAT_INTERVAL;
next_hb = now + timing.heartbeat_interval;
}
let wait = next_hb.min(live_until).saturating_duration_since(now);
// Arm indices: 0 cmd, 1 fd, 2 outbound (when open).
let mut arms: Vec<&dyn Selectable> = vec![cmd_rx, &arm];
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 {
arms.push(out_rx);
push(&mut arms, &mut what, out_rx, Arm::Out);
}
match try_select_timeout(&arms, wait) {
Ok(Some(0)) => {
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(1)) => match pump_readable(framed) {
Ok(Some(Arm::Fd)) => match pump_readable(framed, mons) {
Pump::Ended => break,
Pump::Frames(n) => {
if n > 0 {
live_until = Instant::now() + LIVENESS_TIMEOUT;
live_until = Instant::now() + timing.liveness_timeout;
}
}
},
Ok(Some(_)) => match pump_outbound(framed, out_rx) {
Outbound::Sent => {}
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.
@@ -201,9 +396,42 @@ fn run_live(
}
}
/// What one outbound wake yielded.
/// 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 {
Sent,
/// 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.
@@ -219,7 +447,7 @@ fn pump_outbound(framed: &mut FramedConn, out_rx: &Receiver<Frame>) -> Outbound
return Outbound::WireFailed;
}
}
Ok(None) => return Outbound::Sent,
Ok(None) => return Outbound::Drained,
Err(_) => return Outbound::Closed,
}
}
@@ -261,16 +489,26 @@ enum Pump {
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` additionally goes
/// to the one inbound resolution seam. Its verdict is local knowledge only
/// — nothing goes back on the wire (RFC §3) — and is currently discarded
/// (a future trace hook is the place to surface it). Frames for later
/// chunks (`Send` c10, `Monitor`/`Down` c11) are consumed and ignored.
fn pump_readable(framed: &mut FramedConn) -> Pump {
/// 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,
@@ -280,13 +518,43 @@ fn pump_readable(framed: &mut FramedConn) -> Pump {
match framed.next_buffered() {
Ok(Some(frame)) => {
got += 1;
if let Frame::SendNamed {
name,
type_hash,
payload,
} = frame
{
let _verdict = deliver_named(&name, type_hash, &payload);
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,
@@ -299,3 +567,64 @@ fn pump_readable(framed: &mut FramedConn) -> Pump {
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());
});
}
}
+48 -28
View File
@@ -27,16 +27,17 @@ use crate::channel::{channel, Receiver, Selectable, Sender};
use crate::cluster::conn::spawn_established;
use crate::cluster::envelope::{Frame, RejectReason};
use crate::cluster::handshake::{
HelloCtx, Initiator, InitiatorOutcome, Local, Peer, Responder, ResponderOutcome,
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};
/// How long either side waits for the peer's handshake frame before giving
/// up and closing. Enforced on the path via [`FramedConn::recv_deadline`],
/// 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);
@@ -119,7 +120,7 @@ pub fn dial_handshake(
/// Accept-side path step: read the first frame, judge it, answer or close.
///
/// `ctx_for` supplies the [`HelloCtx`] for the *offered* name — knowledge
/// `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`.
@@ -129,7 +130,7 @@ pub fn dial_handshake(
pub fn accept_handshake(
framed: &mut FramedConn,
local: Local,
ctx_for: impl FnOnce(&str) -> HelloCtx,
standing_of: impl FnOnce(&str) -> PeerStanding,
deadline: Instant,
) -> Result<Peer, HandshakeError> {
let frame = match framed.recv_deadline(deadline) {
@@ -143,11 +144,11 @@ pub fn accept_handshake(
return Err(from_recv(e));
}
};
let ctx = match &frame {
Frame::Hello { node_name, .. } => ctx_for(node_name),
_ => HelloCtx::default(),
let standing = match &frame {
Frame::Hello { node_name, .. } => standing_of(node_name),
_ => PeerStanding::Free,
};
match Responder::new(local).on_frame(frame, ctx) {
match Responder::new(local).on_frame(frame, standing) {
ResponderOutcome::Accepted { reply, peer } => {
if let Err(e) = framed.send(&reply) {
framed.close();
@@ -199,6 +200,21 @@ pub enum DialError {
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
@@ -211,6 +227,7 @@ pub fn dial(
addr: &str,
peer_name: &str,
local: &Local,
timing: Timing,
) -> Result<Pid, DialError> {
let me = scheduler::self_pid();
match gen_server::call(
@@ -224,7 +241,7 @@ pub fn dial(
Ok(Reply::DialBegan(false)) => return Err(DialError::AlreadyDialing),
_ => return Err(DialError::ManagerUnavailable),
}
let result = connect_and_shake(transport, addr, local);
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.
@@ -242,17 +259,18 @@ pub fn dial(
got: peer.node_name,
});
}
spawn_established(framed, peer).map_err(|_| DialError::Duplicate)
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() + HANDSHAKE_TIMEOUT;
let deadline = Instant::now() + timing.handshake_timeout;
let peer = dial_handshake(&mut framed, local, deadline).map_err(DialError::Handshake)?;
Ok((framed, peer))
}
@@ -286,14 +304,19 @@ impl AcceptorHandle {
/// 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) -> AcceptorHandle {
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, cmd_rx));
spawn(move || accept_loop(listener, local, timing, cmd_rx));
AcceptorHandle { cmd_tx, addr }
}
fn accept_loop(mut listener: Box<dyn Listener>, local: Local, cmd_rx: Receiver<()>) {
fn accept_loop(
mut listener: Box<dyn Listener>,
local: Local,
timing: Timing,
cmd_rx: Receiver<()>,
) {
loop {
let Some(arm) = listener.readable_arm() else {
return;
@@ -311,7 +334,7 @@ fn accept_loop(mut listener: Box<dyn Listener>, local: Local, cmd_rx: Receiver<(
Ok(conn) => conn,
Err(_) => return, // listener itself is broken
};
handle_inbound(FramedConn::new(conn), &local);
handle_inbound(FramedConn::new(conn), &local, timing);
}
Err(_) => return, // fd arm failed to register: listener is gone
}
@@ -319,27 +342,24 @@ fn accept_loop(mut listener: Box<dyn Listener>, local: Local, cmd_rx: Receiver<(
}
/// Run the accept-side handshake for one inbound connection, asking the
/// manager for the [`HelloCtx`], and hand the established connection to 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) {
let deadline = Instant::now() + HANDSHAKE_TIMEOUT;
let ctx_for = |name: &str| match gen_server::call(
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::HelloCtx {
Call::Standing {
peer_name: name.to_string(),
},
) {
Ok(Reply::HelloCtx(ctx)) => ctx,
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.
_ => HelloCtx {
name_claimed: true,
dialing_this_peer: false,
},
_ => PeerStanding::Claimed,
};
if let Ok(peer) = accept_handshake(&mut framed, local.clone(), ctx_for, deadline) {
let _ = spawn_established(framed, peer);
if let Ok(peer) = accept_handshake(&mut framed, local.clone(), standing_of, deadline) {
let _ = spawn_established(framed, peer, timing);
}
}
+147 -60
View File
@@ -15,9 +15,14 @@
//! `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. 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.
//! — 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
@@ -25,21 +30,23 @@
//! unreachable seeds would stretch the loop's latency; revisit if a real
//! deployment ever hits that shape.
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::time::{Duration, Instant};
use crate::channel::{channel, select, select_timeout, Receiver, Selectable, Sender};
use crate::cluster::connect::dial;
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::pg::NodeId;
use crate::cluster::Timing;
use crate::scheduler::spawn;
/// First retry delay after a failed dial attempt.
/// Default for [`Timing::initial_backoff`]: first retry delay after a failed
/// dial attempt.
pub const INITIAL_BACKOFF: Duration = Duration::from_millis(250);
/// Backoff ceiling: an unreachable seed is retried this often, forever.
/// Default for [`Timing::max_backoff`]: an unreachable seed is retried this
/// often, forever.
pub const MAX_BACKOFF: Duration = Duration::from_secs(5);
enum Cmd {
@@ -60,15 +67,74 @@ impl ConnectorHandle {
}
}
/// One discovered `(name, addr)` and its dial state.
/// One discovered `(name, addr)` and our dial intent towards it.
struct Candidate {
name: String,
addr: String,
/// This seed is the local node itself: never dialed.
parked: bool,
/// Delay to apply after the *next* failure.
backoff: Duration,
next_attempt: Instant,
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
@@ -78,9 +144,10 @@ 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, cmd_rx));
spawn(move || run(transport, local, strategy, timing, cmd_rx));
ConnectorHandle { cmd_tx }
}
@@ -88,10 +155,11 @@ 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 `connected` before any candidate arrives.
// snapshot seeds `up` before any candidate arrives.
let Some(events) = subscribe() else {
return; // no manager, no cluster to connect
};
@@ -99,8 +167,7 @@ fn run(
spawn(move || strategy.run(disc_tx));
let mut cands: Vec<Candidate> = Vec::new();
let mut connected: HashSet<String> = HashSet::new();
let mut names: HashMap<NodeId, String> = HashMap::new(); // NodeDown carries only the id
let mut up: HashSet<String> = HashSet::new();
let mut strategy_done = false;
loop {
@@ -111,9 +178,9 @@ fn run(
Drained::Open => {}
}
if !strategy_done {
strategy_done = drain_discoveries(&disc_rx, &local, &mut cands);
strategy_done = drain_discoveries(&disc_rx, &local, &timing, &mut cands);
}
match drain_events(&events.rx, &mut connected, &mut names, &mut cands) {
match drain_events(&events.rx, &timing, &mut up, &mut cands) {
Drained::Stop => return, // manager gone: the cluster is tearing down
Drained::Open => {}
}
@@ -122,23 +189,26 @@ fn run(
let now = Instant::now();
for c in cands
.iter_mut()
.filter(|c| !c.parked && !connected.contains(&c.name) && c.next_attempt <= now)
.filter(|c| !up.contains(&c.name) && c.due().is_some_and(|d| d <= now))
{
// The outcome does not branch the bookkeeping: on success the
// manager's node_up is on its way and flips `connected` (backing
// off meanwhile keeps a racing re-attempt from spinning); every
// failure retries — see the module docs.
let _ = dial(&*transport, &c.addr, &c.name, &local);
c.next_attempt = Instant::now() + c.backoff;
c.backoff = (c.backoff * 2).min(MAX_BACKOFF);
// 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| !c.parked && !connected.contains(&c.name))
.map(|c| c.next_attempt)
.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 {
@@ -170,23 +240,31 @@ fn drain_cmd(rx: &Receiver<Cmd>) -> Drained {
}
/// Pull every pending discovery into the candidate set (deduplicated by
/// `(name, addr)`; a candidate bearing the local name is parked). Returns
/// `true` once the strategy's channel closes — it has said all it will.
fn drain_discoveries(rx: &Receiver<Discovery>, local: &Local, cands: &mut Vec<Candidate>) -> bool {
/// `(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 parked = name == local.node_name;
cands.push(Candidate {
name,
addr,
parked,
backoff: INITIAL_BACKOFF,
next_attempt: Instant::now(),
});
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
@@ -194,36 +272,45 @@ fn drain_discoveries(rx: &Receiver<Discovery>, local: &Local, cands: &mut Vec<Ca
}
}
/// Fold pending membership events into `connected` (and the id→name map).
/// `node_up` resets its candidates' backoff; `node_down` schedules a prompt
/// redial with a fresh sequence.
/// 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>,
connected: &mut HashSet<String>,
names: &mut HashMap<NodeId, String>,
timing: &Timing,
up: &mut HashSet<String>,
cands: &mut [Candidate],
) -> Drained {
loop {
match rx.try_recv() {
Ok(Some(NodeEvent::NodeUp(info))) => {
names.insert(info.node, info.name.clone());
for c in cands.iter_mut().filter(|c| c.name == info.name) {
c.backoff = INITIAL_BACKOFF;
}
connected.insert(info.name);
cands
.iter_mut()
.filter(|c| c.name == info.name)
.for_each(|c| c.peer_up(timing));
up.insert(info.name);
}
Ok(Some(NodeEvent::NodeDown { node })) => {
if let Some(name) = names.remove(&node) {
connected.remove(&name);
let now = Instant::now();
for c in cands.iter_mut().filter(|c| c.name == name) {
c.backoff = INITIAL_BACKOFF;
c.next_attempt = now;
}
}
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;
}
+11 -2
View File
@@ -20,13 +20,22 @@ use crate::channel::Sender;
/// A discovery event, as pushed by a [`Strategy`].
///
/// Additive-only for now (candidates are announced, never withdrawn);
/// `#[non_exhaustive]` so expiry can land later without breaking strategies.
/// `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
+49 -11
View File
@@ -81,10 +81,45 @@ pub enum Frame {
},
Down {
monitor_id: u64,
reason: DownReason,
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;
@@ -101,11 +136,12 @@ const REJ_HASH_MISMATCH: u8 = 1;
const REJ_NAME_TAKEN: u8 = 2;
const REJ_PROTO_VERSION: u8 = 3;
// DownReason tags. c11 adds `Disconnected = 5`; do not reuse tags.
// 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;
/// Frame could not be encoded. The output buffer is left exactly as it was.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -272,10 +308,11 @@ impl Frame {
out.push(TAG_DOWN);
put_u64(out, *monitor_id);
out.push(match reason {
DownReason::Exit => DR_EXIT,
DownReason::Panic => DR_PANIC,
DownReason::Stopped => DR_STOPPED,
DownReason::NoProc => DR_NOPROC,
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::Disconnected => DR_DISCONNECTED,
});
}
}
@@ -364,13 +401,14 @@ impl Frame {
TAG_DOWN => Frame::Down {
monitor_id: r.u64()?,
reason: match r.u8()? {
DR_EXIT => DownReason::Exit,
DR_PANIC => DownReason::Panic,
DR_STOPPED => DownReason::Stopped,
DR_NOPROC => DownReason::NoProc,
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_DISCONNECTED => RemoteDownReason::Disconnected,
t => {
return Err(DecodeError::UnknownEnumTag {
what: "DownReason",
what: "RemoteDownReason",
tag: t,
})
}
+16 -11
View File
@@ -25,14 +25,19 @@ pub struct Peer {
pub meta: NodeMeta,
}
/// Driver-supplied context for an inbound `Hello` — knowledge the pure
/// machine cannot have (c6 owns the connection table and dial set).
#[derive(Debug, Clone, Copy, Default)]
pub struct HelloCtx {
/// The offered name is already claimed by an established peer.
pub name_claimed: bool,
/// We have our own dial in flight to this peer name.
pub dialing_this_peer: bool,
/// 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
@@ -124,7 +129,7 @@ impl Responder {
/// 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, ctx: HelloCtx) -> ResponderOutcome {
pub fn on_frame(self, frame: Frame, standing: PeerStanding) -> ResponderOutcome {
let Frame::Hello {
proto_version,
build_hash,
@@ -147,13 +152,13 @@ impl Responder {
if build_hash != self.local.build_hash {
return reject(RejectReason::HashMismatch);
}
if node_name == self.local.node_name || ctx.name_claimed {
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 ctx.dialing_this_peer && !dial_wins(&node_name, &self.local.node_name) {
if standing == PeerStanding::Dialing && !dial_wins(&node_name, &self.local.node_name) {
return ResponderOutcome::TieBreakLoss;
}
+20 -17
View File
@@ -24,7 +24,7 @@ use std::collections::HashMap;
use crate::channel::Sender;
use crate::cluster::conn::ConnHandle;
use crate::cluster::handshake::{HelloCtx, Peer};
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};
@@ -53,7 +53,7 @@ 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
/// (the `dialing_this_peer` half of [`HelloCtx`]); cleared the moment
/// ([`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>,
@@ -143,9 +143,9 @@ pub enum Call {
/// 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 [`HelloCtx`] for an inbound `Hello` offering `peer_name` — the
/// The [`PeerStanding`] of an inbound `Hello` offering `peer_name` — the
/// accept path asks this between reading the frame and judging it.
HelloCtx { peer_name: String },
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
@@ -166,7 +166,7 @@ pub enum Reply {
/// `false`: another dial to this name is already in flight — do not dial.
DialBegan(bool),
DialEnded,
HelloCtx(HelloCtx),
Standing(PeerStanding),
Subscribed,
View(Vec<NodeInfo>),
}
@@ -206,8 +206,8 @@ impl GenServer for Manager {
}
// The outbound table (c9) is maintained here, inside the same
// serialized handlers that own the connection's lifetime.
if let Some(out) = handle.take_outbound() {
bind_outbound(&peer.node_name, out);
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()),
@@ -230,9 +230,7 @@ impl GenServer for Manager {
// 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 {
node: entry.info.node,
});
self.emit(&NodeEvent::NodeDown(entry.info));
}
Reply::Disconnected
}
@@ -255,10 +253,15 @@ impl GenServer for Manager {
self.dials.remove(&name);
Reply::DialEnded
}
Call::HelloCtx { peer_name } => Reply::HelloCtx(HelloCtx {
name_claimed: self.conns.contains_key(&peer_name),
dialing_this_peer: self.dials.contains_key(&peer_name),
}),
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.
@@ -279,13 +282,13 @@ impl GenServer for Manager {
self.conns.retain(|name, entry| {
let dead = entry.pid == down.pid;
if dead {
downs.push((name.clone(), entry.info.node));
downs.push((name.clone(), entry.info.clone()));
}
!dead
});
for (name, node) in downs {
for (name, info) in downs {
unbind_outbound(&name);
self.emit(&NodeEvent::NodeDown { node });
self.emit(&NodeEvent::NodeDown(info));
}
self.dials.retain(|_, pid| *pid != down.pid);
}
+3 -3
View File
@@ -57,9 +57,9 @@ 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. Which [`NodeInfo`] this id named was delivered in
/// the corresponding `NodeUp`.
NodeDown { node: NodeId },
/// 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
+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());
}
}
+605 -10
View File
@@ -41,15 +41,41 @@
//! 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::Sender;
use crate::cluster::envelope::{encode_payload, Frame, PayloadError};
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::pid::Name;
use crate::registry::whereis;
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
@@ -111,26 +137,97 @@ impl<M> RemoteSendError<M> {
}
}
/// The outbound table, one per runtime (a `RuntimeInner` field).
/// 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, Sender<Frame>>,
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,
}
}
}
/// Manager-only: bind `node`'s outbound channel. Called inside `Register`.
pub(crate) fn bind_outbound(node: &str, tx: Sender<Frame>) {
/// 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().by_node.insert(node.to_string(), tx);
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
@@ -191,13 +288,249 @@ pub fn send_remote_raw(
/// 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).cloned());
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)]
@@ -217,6 +550,20 @@ pub enum InboundVerdict {
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.
@@ -238,3 +585,251 @@ pub fn deliver_named(name: &str, type_hash: u64, payload: &[u8]) -> InboundVerdi
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 });
}
}
}
}