//! 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` 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)`. 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, /// 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, Sender)>, } 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, Sender)> { 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 { 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, out_rx: Receiver, mon_rx: Receiver, ) { 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, Sender)>, /// Monitors the peer holds on local actors: id → the local monitor. watched: HashMap, } 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) { 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 { 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, out_rx: &Receiver, mon_rx: &Receiver, 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, 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 = 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, 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) -> 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) { 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) -> 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 { 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::(); // Already registered. let (tx1, rx1) = channel::(); mons.outstanding.insert(MonitorId(1), (pid(1), tx1)); // In the inbox, never processed. let (tx2, rx2) = channel::(); 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::(); 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()); }); } }