//! Distribution's runtime side (ADR 0072, *Pids* and *Transport*): remote //! pids, the node table, and the hooks through which `proc` operations on //! a remote pid reach the transport. No network here: `tl_dist_start` //! (`node.rs`) runs the transport and installs its [`Hooks`]; the //! transport comes back in through [`inbound`]. //! //! - **Pids.** A local pid is the scheduler's counter: 0 or more. A remote //! pid is negative, `-1 - (node << 46 | serial)`: an index into the node //! table (16 bits) and the pid on that node (its serial, 46 bits). Both //! fit in a tagged `Int`'s 63 bits, so equality stays word equality, and //! every operation on a pid tells the two apart with one sign test. //! - **No hooks, no distribution.** Until hooks are installed, an operation //! on a remote pid does what it does on a dead pid: a send is dropped, a //! link is not made, a monitor gets `Down(pid, Crashed("noproc"))` at //! once, `demonitor`, `unlink`, `kill` and `stop` are ignored. A program //! that never starts distribution links nothing of the transport, nor //! the remote halves of links and monitors: the hooks make those //! ([`outbound`]). //! - **Ties across nodes.** A local actor keeps its links to remote pids //! with its other links (whichever side made them), the remote pids it //! monitors in `Ties::watching` (a local monitor is kept by the watched //! actor, which a remote one cannot be), and the remote actors that //! monitor it with its other monitors. The started node's [`Dist`] //! (`node.rs`) lists, per node, the local actors tied to it, so a lost //! node reaches only those //! ([`inbound::node_down`]). A tie is made, and a remote exit or `Down` //! counts, only under the local actor's lock while it is alive: an exit //! then always finds the tie, or the tie is never made. A `Down` goes //! into the watcher's inbox under the same lock that ends its monitor, //! so a `demonitor` (which ends it under that lock too) either ends it //! first, or finds its `Down` delivered: none comes after it. //! - **Unlink across nodes** is Erlang's (`erl_dist_protocol`, *Link //! Protocol*, OTP 23). The unlinker's half goes at once to *unlinking* //! (`Ties::unlinking`), with an id, and the unlink goes to the other //! node, which removes its half (unless it is unlinking too) and //! acknowledges the id, under its actor's lock, so ahead of anything the //! actor sends after. The unlinker forgets the unlink at the //! acknowledgement of the same id. Meanwhile an exit through the link is //! ignored, and a link from the other side too (it left before the //! unlink arrived, so the other side ends unlinked); a link from the //! unlinker's side is a new link. So crossing links and unlinks leave //! both sides agreeing. //! - **A `Remote` subject's owner is always a remote pid**: a subject whose //! owner is local is a `Subject` (constructor 0), however it was made. //! `receive` relies on it to refuse a `Remote` subject (its owner is never //! the receiver), and `send` to route it by its owner's sign. //! - **Back-pressure.** A send to a peer whose outbound queue is full //! parks the sending actor ([`send_parking`]) until the transport's //! thread finds the queue drained ([`wake_sender`]): the actor waits, //! never its scheduler thread. It cannot send anything else meanwhile, //! so its messages keep their order. use std::collections::{HashMap, HashSet}; use std::ffi::CString; use std::hash::BuildHasherDefault; use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering}; use std::sync::{Mutex, MutexGuard, RwLock}; use crate::abi::{Ctx, Value, YIELD_NONE}; use crate::otp::Wait; use crate::sched::{Actor, Exit, IdHasher, Proc, Shared, park, this}; /// Bits of a remote pid's node-table index. pub(crate) const NODE_BITS: u32 = 16; /// Bits of a remote pid's serial: the pid on its own node. A node's pids /// at or past `1 << 46` (70 trillion spawns) cannot be named on another /// node: [`remote`] refuses them, and the codec with it. pub(crate) const SERIAL_BITS: u32 = 46; /// The most nodes a node ever knows: the table only grows, one entry per /// incarnation of a peer. pub(crate) const MAX_NODES: usize = 1 << NODE_BITS; const SERIAL_MASK: u64 = (1 << SERIAL_BITS) - 1; /// Whether `pid` is on another node. #[inline] pub(crate) fn is_remote(pid: i64) -> bool { pid < 0 } /// The remote pid of `serial` on node-table entry `node`, if `serial` fits /// in [`SERIAL_BITS`] (a local pid of that node is never negative). #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) fn remote(node: u16, serial: i64) -> Option { let serial = u64::try_from(serial).ok().filter(|s| *s <= SERIAL_MASK)?; // At most 2^62 - 1: the result is at least -2^62, a tagged Int's least. let bits = (u64::from(node) << SERIAL_BITS) | serial; Some(-1 - bits as i64) } /// A remote pid's node-table entry and serial. pub(crate) fn parts(pid: i64) -> (u16, i64) { debug_assert!(is_remote(pid)); let bits = (-1 - pid) as u64; ((bits >> SERIAL_BITS) as u16, (bits & SERIAL_MASK) as i64) } /// A node as the table knows it: its name and its incarnation (Erlang's /// *creation*), random at each start, so a restarted node is a new entry. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Node { pub(crate) name: String, pub(crate) incarnation: u64, } /// The node table: append-only, so a remote pid names the same incarnation /// for as long as the program runs, and an index is never reused. Its /// limit is a run's: once full, no new node or restarted peer can be /// reached until the program restarts. Logged when 3/4 full and when full; /// each peer name may add a share of it only (`node.rs`). #[derive(Default)] pub(crate) struct Nodes { entries: Vec, index: HashMap<(String, u64), u16>, /// A node was refused for want of room: logged once. full: bool, } #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] impl Nodes { /// The index of `name`'s `incarnation`, added if new; `None` once the /// table holds [`MAX_NODES`]. pub(crate) fn index(&mut self, name: &str, incarnation: u64) -> Option { let key = (name.to_owned(), incarnation); if let Some(i) = self.index.get(&key) { return Some(*i); } if self.entries.len() >= MAX_NODES { if !std::mem::replace(&mut self.full, true) { eprintln!( "louise: dist: the node table is full ({MAX_NODES} nodes and incarnations): \ no new node or restarted peer can be reached until this program restarts" ); } return None; } let i = self.entries.len() as u16; self.entries.push(Node { name: key.0.clone(), incarnation, }); self.index.insert(key, i); if self.entries.len() == MAX_NODES / 4 * 3 { eprintln!( "louise: dist: the node table is 3/4 full: it holds every incarnation of every \ node this program has known, and only grows" ); } Some(i) } /// The index of `name`'s `incarnation`, if the table has it. pub(crate) fn find(&self, name: &str, incarnation: u64) -> Option { self.index.get(&(name.to_owned(), incarnation)).copied() } pub(crate) fn get(&self, index: u16) -> Option<&Node> { self.entries.get(usize::from(index)) } } /// What distribution keeps beside the scheduler: the node table, and the /// local actors tied to each node. The started node owns it (`node.rs`): /// only the hooks and the transport reach it, so a program that does not /// start distribution has none. Each lock is held for one operation, never /// while taking another; the codec takes the node table's under the /// registry's (`wire`). The ties' lock is a leaf: a link takes it under /// the linking actor's lock ([`outbound::link`]), a monitored spawn under /// the new actor's or the asker's ([`outbound::monitor_spawned`], /// [`inbound::watch_spawned`]), and nothing takes an actor's lock under /// it. So does a link's frame, or a monitored spawn's answer, queued /// under the same lock, with the node table's read lock and the /// transport's queue. #[derive(Default)] #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) struct Dist { pub(crate) nodes: RwLock, /// By node-table index: the local actors that linked or monitored one /// of its pids, or that one of its pids linked or monitored (each also /// notes the node, in `Ties::nodes`). An actor stays listed until it /// exits or the node is lost, even if a remote exit or `Down` already /// took its ties: the fan-out then finds nothing to do for it, and its /// exit still unlists it. tied: Mutex>>, /// The last unlink's id ([`Dist::unlink_id`]). unlinks: AtomicU64, } type Pids = HashSet>; #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] impl Dist { fn tied(&self) -> MutexGuard<'_, HashMap>> { self.tied .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } /// `local` linked or monitored a pid of `node`. fn tie(&self, node: u16, local: i64) { self.tied().entry(node).or_default().insert(local); } /// A new unlink's id: unique among this node's, so among the unlinks /// one actor has waiting for the same pid's node, as Erlang requires. pub(crate) fn unlink_id(&self) -> u64 { self.unlinks.fetch_add(1, Ordering::Relaxed) + 1 } /// `local` exited, listed under `nodes` (`Ties::nodes`): unlist it /// (`Hooks::exit`). pub(crate) fn untie(&self, local: i64, nodes: &[u16]) { let mut tied = self.tied(); for node in nodes { if let Some(set) = tied.get_mut(node) { set.remove(&local); } } } /// The local actors tied to `node`, in pid order, unlisted. fn take(&self, node: u16) -> Vec { let mut pids: Vec = self .tied() .remove(&node) .unwrap_or_default() .into_iter() .collect(); pids.sort_unstable(); pids } /// The local actors listed as tied to `node`, in pid order. #[cfg(test)] pub(crate) fn tied_to(&self, node: u16) -> Vec { let mut pids: Vec = self .tied() .get(&node) .into_iter() .flatten() .copied() .collect(); pids.sort_unstable(); pids } } /// An exit signal across nodes. #[derive(Clone, Debug, PartialEq)] pub(crate) enum Signal { /// `kill`: the target stops with `Killed`, trapping or not. Kill, /// `stop` (ADR 0060): an `ExitSignal(from, Shutdown)` if the target /// traps exits, else it stops with `Shutdown`. Stop, /// `from`, linked to the target, exited with this reason. Linked(Exit), } /// The transport, as `proc` operations reach it. Each hook runs on the /// thread of the actor performing the operation (or exiting), which it /// must not unwind, nor park but through [`send_parking`]. The hooks do the /// whole remote job, the local halves of ties and the node's [`Dist`] /// included: the scheduler only tests a pid's sign and calls them. A hook /// answers asynchronously, through [`inbound`]: a link to a pid that is /// gone, or on a node that is not connected, with an exit signal /// (`noproc`, `noconnection`); a monitor with a `Down`. pub(crate) struct Hooks { /// Send `message` to `(owner, tag)`, whose message type is `wire` in /// the type registry, from the running actor of `ctx`. The message is /// borrowed: the hook encodes it, and the caller drops it once it /// returns. While the peer's queue is full, the hook parks the actor /// ([`send_parking`]); on return, `yielding` may be set (it exited /// meanwhile). An error is a message the sender cannot encode, a bug /// in the program: the caller panics with it (ADR 0072, *Settled*), a /// panic message the hook made ([`unsendable`]). pub(crate) send: fn(ctx: *mut Ctx, owner: i64, tag: i64, wire: i64, message: Value) -> Result<(), CString>, /// The running actor `me` links to the remote `other`: its own half /// and the link frame, under its lock ([`outbound::link`]). pub(crate) link: fn(sched: &Shared, me: &Actor, other: i64), /// The running actor `me` monitors the remote `watched`, its `Down` /// due on `tag`: its own half ([`outbound::monitor`]), then the /// monitor. False if it makes none: the caller answers `noproc`, as /// for a dead pid. pub(crate) monitor: fn(sched: &Shared, me: &Actor, watched: i64, tag: i64) -> bool, /// The running actor `me` stops monitoring the remote `watched` on /// `tag`: its own half first ([`outbound::demonitor`]), after which /// no `Down` of it is delivered, then the watched node's. pub(crate) demonitor: fn(me: &Actor, watched: i64, tag: i64), /// The running actor `me` unlinks the remote `other`: its own half /// goes to unlinking and the unlink frame is queued, under its lock /// ([`outbound::unlink`]); from then on no exit through the link /// counts. pub(crate) unlink: fn(me: &Actor, other: i64), /// An exit signal from `from` (local) to `to` (remote). pub(crate) signal: fn(from: i64, to: i64, signal: &Signal), /// `watched` (local), monitored by `watcher` (remote) on `tag`, exited. pub(crate) down: fn(watched: i64, watcher: i64, tag: i64, reason: &Exit), /// The local `pid` exited, listed under `nodes` (`Ties::nodes`, never /// empty): unlist it from the node's [`Dist`]. pub(crate) exit: fn(pid: i64, nodes: &[u16]), } /// The installed hooks: null until the transport starts. static HOOKS: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); fn hooks() -> Option<&'static Hooks> { // SAFETY: only `install` stores a non-null pointer, from a `'static`. unsafe { HOOKS.load(Ordering::Acquire).as_ref() } } /// Whether distribution runs: a peer may still wake an actor, so every /// actor waiting is no deadlock. pub(crate) fn running() -> bool { hooks().is_some() || TRANSPORT.load(Ordering::Acquire) } /// A transport runs (`transport::start_program`). static TRANSPORT: AtomicBool = AtomicBool::new(false); /// How to stop the running transport and join its thread: set only by /// `transport::start_program`, so a program that never starts /// distribution reaches no transport code through [`shutdown`]. static STOP: Mutex> = Mutex::new(None); /// The transport started; `stop` stops it. // Only the transport calls it, tests included: none without TLS. #[cfg_attr( not(feature = "tls"), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) fn transport_started(stop: fn()) { // Opaque to the optimizer, as in `install`: `shutdown` must not call // the one function it could be. *STOP .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::hint::black_box(stop)); TRANSPORT.store(true, Ordering::Release); } /// The transport stopped, its thread joined. // Only the transport calls it, tests included: none without TLS. #[cfg_attr( not(feature = "tls"), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) fn transport_stopped() { TRANSPORT.store(false, Ordering::Release); } /// Stop the transport, if one runs, and join its thread: the scheduler /// calls it once its threads are done, before its shared state (which the /// transport's inbound handler delivers to) is dropped. pub(crate) fn shutdown() { let stop = STOP .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .take(); if let Some(stop) = stop { stop(); } } /// Route remote operations to `hooks` from now on. #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) fn install(hooks: &'static Hooks) { // Opaque to the optimizer: with one caller, whole-program LTO would // otherwise know the only table `HOOKS` can hold, and call its hooks // directly from `op_send` and `op_monitor`, linking the transport into // every program (the size test of ADR 0042 checks it does not). let hooks = std::hint::black_box(std::ptr::from_ref(hooks).cast_mut()); HOOKS.store(hooks, Ordering::Release); } /// Back to no distribution (the transport stopped). #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) fn uninstall() { HOOKS.store(std::ptr::null_mut(), Ordering::Release); } // ---- outbound: `proc` operations on a remote pid ------------------------------- /// `send` to a remote subject: `message` is borrowed. Dropped without /// hooks, as a send to a dead actor; an error is the sender's panic. May /// park the running actor (back-pressure). pub(crate) fn send( ctx: *mut Ctx, owner: i64, tag: i64, wire: i64, message: Value, ) -> Result<(), CString> { match hooks() { Some(h) => (h.send)(ctx, owner, tag, wire, message), None => Ok(()), } } /// The sender's panic message for a message it cannot send, `why` /// ([`Hooks::send`]). Made by the hooks, so a program that never starts /// distribution links none of it. #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) fn unsendable(why: &str) -> CString { CString::new(format!("send to another node: {why}")).unwrap_or_default() } /// An actor parked on a peer's full queue: its pid and its wait's number, /// so that a late wake reaches no later wait ([`wake_sender`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Waiter { pub(crate) pid: i64, pub(crate) wait: u64, } /// One try of [`send_parking`]'s. pub(crate) enum Try { /// Sent, or refused for good: what the send returns. Done(Result<(), String>), /// The queue is full: the frame, given back. Full(F), } /// Send `frame` from the running actor of `ctx`, parking it while the /// peer's queue is full (ADR 0072, *Back-pressure*). `attempt` queues the /// frame or gives it back; given a [`Waiter`], it registers it under the /// queue's lock when full, and the transport wakes it ([`wake_sender`]) /// once the queue drains or its node is down; `unwait` forgets a waiter /// that something else woke. The actor waits as on a socket (`Wait::Io`), /// set before the registered try, so a drain between that try and the /// parking is not lost; a woken actor tries again, unregistered first. /// `None` if the actor exited while parked: the frame is dropped (at most /// once), `yielding` is set, and the caller unwinds. /// /// # Safety /// `ctx` must be the running actor's context. #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) unsafe fn send_parking( ctx: *mut Ctx, mut frame: F, mut attempt: impl FnMut(F, Option) -> Try, unwait: impl Fn(Waiter), ) -> Option> { // SAFETY: forwarded caller guarantee. let (a, _) = unsafe { this(ctx) }; let mut waiter = None; loop { match attempt(frame, waiter) { Try::Done(done) => { if waiter.is_some() { a.with_proc(|p| p.wait = Wait::Ready); } return Some(done); } Try::Full(back) => { frame = back; let Some(w) = waiter else { let wait = a.with_proc(|p| p.park_as(Wait::Io)); waiter = Some(Waiter { pid: a.pid, wait }); continue; }; // SAFETY: forwarded caller guarantee; its wait is set. let exited = unsafe { let woke = park(ctx); crate::heap::drop_value(ctx, woke); (*ctx).yielding != YIELD_NONE }; unwait(w); if exited { return None; } waiter = None; } } } } /// Resume `waiter`, parked by [`send_parking`], if it still waits there: /// its peer's queue drained, or its node is down. From any thread. #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) fn wake_sender(sched: &Shared, waiter: Waiter) { if sched.with_proc(waiter.pid, |p| p.resume(waiter.wait)) == Some(true) { sched.schedule(waiter.pid); } } /// `link` from the running actor `me` to the remote `other`: no link /// without hooks, as with a dead pid. pub(crate) fn link(sched: &Shared, me: &Actor, other: i64) { if let Some(h) = hooks() { (h.link)(sched, me, other); } } /// `monitor` from the running actor `me` of the remote `watched`, its /// `Down` due on `tag`. Without hooks, false: the caller answers /// `noproc`, as for a dead pid. pub(crate) fn monitor(sched: &Shared, me: &Actor, watched: i64, tag: i64) -> bool { hooks().is_some_and(|h| (h.monitor)(sched, me, watched, tag)) } /// `demonitor` from the running actor `me` of the remote `watched` on /// `tag`. Without hooks, nothing: no `Down` can come from a transport. pub(crate) fn demonitor(me: &Actor, watched: i64, tag: i64) { if let Some(h) = hooks() { (h.demonitor)(me, watched, tag); } } /// `unlink` from the running actor `me` of the remote `other`. Without /// hooks, nothing: only hooks link to a remote pid. pub(crate) fn unlink(me: &Actor, other: i64) { if let Some(h) = hooks() { (h.unlink)(me, other); } } /// The local `pid`, listed under `nodes` (`Ties::nodes`), exited. Only a /// hook or the transport ties an actor to a node: without distribution, /// `nodes` is empty and the caller never calls this. pub(crate) fn exit(pid: i64, nodes: &[u16]) { if let Some(h) = hooks() { (h.exit)(pid, nodes); } } /// The local half of a link to the remote `other`, of node `node`, made by /// the local actor (a new link, whatever unlink of `other` it still has /// waiting): whether `dist` must list the actor under the node. #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] fn link_half(p: &mut Proc, other: i64, node: u16) -> bool { let ties = p.ties(); ties.link_remote(other); ties.tie(node) } /// List the local `pid` under `node` in `dist`, its ties having named the /// node for the first time. Outside the actor's lock ([`Dist`]'s lock /// order), so an exit may have taken its ties meanwhile and unlisted it /// before this: then unlist it again. An exit after the check below /// unlists it itself ([`Hooks::exit`]). #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] fn list(sched: &Shared, dist: &Dist, pid: i64, node: u16) { dist.tie(node, pid); if sched.with_proc(pid, |p| p.dead) != Some(false) { dist.untie(pid, &[node]); } } /// An exit signal from `from` (local) to the remote `to`: ignored without /// hooks, as for a dead pid. pub(crate) fn signal(from: i64, to: i64, signal: Signal) { if let Some(h) = hooks() { (h.signal)(from, to, &signal); } } /// The local `watched`, monitored by the remote `watcher` on `tag`, exited /// with `reason`: its `Down` goes to the watcher's node. Out of line: an /// exit with only local watchers never calls it. #[cold] #[inline(never)] pub(crate) fn down(watched: i64, watcher: i64, tag: i64, reason: &Exit) { if let Some(h) = hooks() { (h.down)(watched, watcher, tag, reason); } } /// The local halves of the ties a running actor makes to a remote pid, for /// the hooks to make before they send the link or monitor: the actor's /// own half, listed in the node's [`Dist`]. Only the hooks reach it, so a /// program that never starts distribution links none of it. #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) mod outbound { use super::{Dist, Proc, link_half, list, parts}; use crate::sched::{Actor, Shared}; /// `me` links to the remote `other`: its own half, listed under the /// node if it names the node first, then `send`, which queues the link /// frame, all under its lock. `None` if it has already exited (killed /// while running): as from a dead pid, no link is due, and nothing is /// sent. Else whether `send` queued the frame. /// /// Under the lock, because an exit takes it to take the links, and /// sends their exits after: the link frame is then always ahead of /// `me`'s exit on the node's ordered stream. Queued after the lock, an /// exit in between (a `kill` from another thread) could pass it, be /// ignored for want of a link, and leave `other` linked to a pid that /// is gone. /// /// Listed before the frame is queued, under the same lock: a node lost /// once the frame is queued then finds `me` in its fan-out /// ([`super::inbound::node_down`]), which waits for the lock and ends /// the link with `noconnection`. Listed after the lock, a loss in /// between would find nothing, and the link would outlive its node. /// A loss before the frame is queued makes `send` fail. pub(crate) fn link( dist: &Dist, me: &Actor, other: i64, send: impl FnOnce() -> bool, ) -> Option { let node = parts(other).0; me.with_proc(|p| (!p.dead).then(|| half(dist, p, me.pid, other, node, send))) } /// The new actor `child`, not yet scheduled, links to the remote /// `asker` of its spawn (`spawn_link_on`): as [`link`], so its link /// frame leaves before anything it does, and a loss of the asker's /// node finds it. `None` if it has already exited (a peer killed it by /// its serial). #[cfg_attr( not(feature = "tls"), allow(dead_code, reason = "only a started node spawns for a peer") )] pub(crate) fn link_spawned( sched: &Shared, dist: &Dist, child: i64, asker: i64, send: impl FnOnce() -> bool, ) -> Option { let node = parts(asker).0; sched.with_alive(child, |p| half(dist, p, child, asker, node, send)) } /// The new actor `child`, not yet scheduled, is monitored by the remote /// `asker` of its spawn, its `Down` due on `tag` (`spawn_monitor_on`): /// the monitor is made and listed under the asker's node, then `send` /// queues the spawn's answer, under its lock. Its `Down` then always /// follows the answer on the node's ordered stream, so the asker's node /// has the monitor when the `Down` arrives; and a loss of that node once /// the answer is queued finds `child` and forgets the monitor. If /// `send` fails (the node is not up), the monitor is forgotten at once. /// `None` if `child` has already exited (a peer killed it by its /// serial): nothing was sent. Else whether `send` queued the answer. #[cfg_attr( not(feature = "tls"), allow(dead_code, reason = "only a started node spawns for a peer") )] pub(crate) fn monitor_spawned( sched: &Shared, dist: &Dist, child: i64, asker: i64, tag: i64, send: impl FnOnce() -> bool, ) -> Option { let node = parts(asker).0; sched.with_alive(child, |p| { let ties = p.ties(); ties.monitors.push((asker, tag)); if ties.tie(node) { dist.tie(node, child); } let sent = send(); if !sent { p.demonitor(asker, tag); } sent }) } /// `pid`'s half of its link to `other`, of node `node`, listed under /// the node if new to it, then the frame: whether it was queued. Under /// the actor's lock, which may take the ties' ([`Dist`]). fn half( dist: &Dist, p: &mut Proc, pid: i64, other: i64, node: u16, send: impl FnOnce() -> bool, ) -> bool { if link_half(p, other, node) { dist.tie(node, pid); } send() } /// `me` monitors the remote `watched`, its `Down` due on `tag`: its /// own half. False if it has already exited (killed while running): /// no `Down` is due to it. pub(crate) fn monitor(sched: &Shared, dist: &Dist, me: &Actor, watched: i64, tag: i64) -> bool { let node = parts(watched).0; let tied = me.with_proc(|p| { (!p.dead).then(|| { let ties = p.ties(); ties.watching.push((watched, tag)); ties.tie(node) }) }); let Some(new) = tied else { return false; }; if new { list(sched, dist, me.pid, node); } true } /// `me` stops monitoring the remote `watched` on `tag`: its own half. /// From now on its `Down` is not delivered ([`super::inbound::down`]). /// False if there was no such monitor (its `Down` came already, or /// there never was one): the watched node has nothing to forget. The /// actor stays listed under the node ([`Dist`]). pub(crate) fn demonitor(me: &Actor, watched: i64, tag: i64) -> bool { me.with_proc(|p| p.unwatch(watched, tag)) } /// `me` unlinks the remote `other` as unlink `id`: its half waits for /// the acknowledgement of `id` (`Ties::unlinking`), and `send` queues /// the unlink frame, under its lock, as for a link ([`link`]): the /// frame is then ahead of any later link frame of `me`'s, and an exit /// of `me`'s finds no link to send through. From now on an exit /// through the link is ignored. Nothing if `me` has no link to `other` /// (or has exited: its exit took the link). If `send` fails, the node /// is not up and no acknowledgement can come: the half goes at once, /// and the node's loss ends the other's. The actor stays listed under /// the node ([`Dist`]). pub(crate) fn unlink(me: &Actor, other: i64, id: u64, send: impl FnOnce() -> bool) { me.with_proc(|p| { if p.unlink_remote(other, id) && !send() { p.unlink_acked(other, id); } }); } } /// What the transport calls with what peers send: from its own thread, or /// any thread that is not running an actor. A thread that delivers keeps /// up to 64 actor cells in its send cache until it stops (`sched::local`). #[cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] pub(crate) mod inbound { use super::{Dist, Signal, is_remote, list, parts}; use crate::abi::Value; use crate::process::signal_value; use crate::sched::{Exit, Linked, Shared, exit_actor, exit_through_link, propagate_exit}; /// A message for the local subject `(to, tag)`, made outside any /// actor's context (owned). Dropped if `to` is gone. pub(crate) fn deliver(sched: &Shared, to: i64, tag: i64, message: Value) { crate::process::deliver_made(sched, to, tag, message); } /// The remote `from` linked to the local `to`: the link's local half. /// If `to` is gone, `from` gets its exit, `Crashed("noproc")`, as a /// link to a pid that is gone does in Erlang: across nodes, it may have /// exited while the link was on its way. Ignored while `to`'s unlink /// of `from` waits for its acknowledgement (`Ties::linked_by`): the /// link left before that unlink reached `from`'s node, which removed /// `from`'s half. pub(crate) fn link(sched: &Shared, dist: &Dist, from: i64, to: i64) { debug_assert!(is_remote(from) && !is_remote(to)); let node = parts(from).0; let tied = sched.with_alive(to, |p| { let ties = p.ties(); ties.linked_by(from) && ties.tie(node) }); match tied { Some(true) => list(sched, dist, to, node), Some(false) => {} None => super::signal(to, from, Signal::Linked(noproc())), } } /// The remote `from` unlinked the local `to` (its own half is /// unlinking already): `to`'s half goes, unless `to` is unlinking /// `from` too, and `ack` answers, under `to`'s lock: the /// acknowledgement is then ahead of anything `to` sends that node /// after (a new link, which `from`'s side would otherwise ignore). /// Answered for a `to` that is gone too, so that `from` forgets its /// unlink. `to`'s exit frame, if it was linked, may then come after /// the acknowledgement (its exit sends it after its lock): `from` /// ignores it, having no link, unless it linked `to` again meanwhile, /// a link `to`'s real exit then ends instead of `noproc`. pub(crate) fn unlink(sched: &Shared, from: i64, to: i64, ack: impl FnOnce()) { debug_assert!(is_remote(from) && !is_remote(to)); let mut ack = Some(ack); sched.with_alive(to, |p| { p.unlink(from); if let Some(ack) = ack.take() { ack(); } }); if let Some(ack) = ack { ack(); } } /// The remote `from` acknowledged unlink `id` of the local `to`'s: `to` /// forgets it, unless it linked `from` again since. pub(crate) fn unlink_acked(sched: &Shared, from: i64, to: i64, id: u64) { debug_assert!(is_remote(from) && !is_remote(to)); sched.with_alive(to, |p| p.unlink_acked(from, id)); } /// The remote `watcher` monitors the local `watched`, its `Down` due on /// `tag`; if `watched` is gone, that `Down` goes at once (`noproc`). pub(crate) fn monitor(sched: &Shared, dist: &Dist, watcher: i64, tag: i64, watched: i64) { debug_assert!(is_remote(watcher) && !is_remote(watched)); let node = parts(watcher).0; let tied = sched.with_alive(watched, |p| { let ties = p.ties(); ties.monitors.push((watcher, tag)); ties.tie(node) }); match tied { Some(true) => list(sched, dist, watched, node), Some(false) => {} None => super::down(watched, watcher, tag, &noproc()), } } /// The remote `watcher` stops monitoring the local `watched` on `tag` /// (its own half is gone already): no `Down` is due to it. pub(crate) fn demonitor(sched: &Shared, watcher: i64, tag: i64, watched: i64) { debug_assert!(is_remote(watcher) && !is_remote(watched)); sched.with_alive(watched, |p| p.demonitor(watcher, tag)); } fn noproc() -> Exit { Exit::Crashed("noproc".into()) } /// An exit signal from the remote `from` to the local `to`. Through a /// link, only if `to` still has it: a lost node's fan-out may have /// taken it first. pub(crate) fn signal(sched: &Shared, from: i64, to: i64, signal: &Signal) { debug_assert!(is_remote(from) && !is_remote(to)); match signal { Signal::Kill => exit_actor(sched, to, Exit::Killed), Signal::Stop => crate::process::stop(sched, from, to), Signal::Linked(reason) => propagate_exit(sched, from, to, reason), } } /// The remote `pid`, monitored by the local `watcher` on `tag`, exited: /// `Down(pid, reason)`, unless the monitor is gone (a lost node's /// fan-out sent its `Down` already, or the watcher demonitored it). /// Delivered under the lock that ends the monitor. pub(crate) fn down(sched: &Shared, watcher: i64, tag: i64, pid: i64, reason: &Exit) { sched.with_alive_delivering(watcher, |p| { let watched = p.unwatch(pid, tag); let down = watched.then(|| (tag, signal_value(pid, reason))); ((), down.into_iter().collect()) }); } /// The remote `pid` was spawned for the local `watcher`, monitored on /// `tag` (`spawn_monitor_on`): the watcher's half of the monitor is /// made, listed under the node, and `answer()` (the spawn's answer, /// made outside any actor's context) delivered on `reply_tag`, under /// its lock. Made here, on the thread that then takes the `Down` the /// stream may hold next, not by the watcher, which may not run before /// that. False if the watcher is gone: nothing is made, and the /// monitor is the caller's to forget on `pid`'s node. pub(crate) fn watch_spawned( sched: &Shared, dist: &Dist, watcher: i64, pid: i64, tag: i64, reply_tag: i64, answer: impl FnOnce() -> Value, ) -> bool { debug_assert!(is_remote(pid) && !is_remote(watcher)); let node = parts(pid).0; let watched = sched.with_alive_delivering(watcher, |p| { let ties = p.ties(); ties.watching.push((pid, tag)); if ties.tie(node) { dist.tie(node, watcher); } ((), vec![(reply_tag, answer())]) }); watched.is_some() } /// Node-table entry `node` is lost: every local actor linked to one of /// its pids gets `Crashed("noconnection")` as that pid's exit, and /// every monitor of one gets `Down(pid, Crashed("noconnection"))`; the /// monitors its pids held on local actors are forgotten, and so are /// the unlinks waiting for its acknowledgement. It reaches the actors /// tied to `node` only, in pid order, each in the order of its links, /// then of its monitors: under the lock that ends them, as [`down`] /// (`exit_through_link`). An actor that does not trap exits dies of /// its first link instead, and gets no `Down`. pub(crate) fn node_down(sched: &Shared, dist: &Dist, node: u16) { let lost = Exit::Crashed("noconnection".into()); let on_node = |pid: i64| is_remote(pid) && parts(pid).0 == node; for local in dist.take(node) { exit_through_link(sched, local, |p| { let ties = p.ties(); // Unlisted above: a later tie to the node lists it again. ties.nodes.retain(|n| *n != node); let (links, watching) = ties.take(on_node); if !ties.trap && !links.is_empty() { return Some(Linked::Dies(lost.clone())); } let mut messages = Vec::new(); if !links.is_empty() { let exits = *ties.exits_tag.get_or_insert_with(|| sched.tag()); let signals = links.iter().map(|pid| (exits, signal_value(*pid, &lost))); messages.extend(signals); } let downs = watching.into_iter(); messages.extend(downs.map(|(pid, tag)| (tag, signal_value(pid, &lost)))); Some(Linked::Told(messages)) }); } } } #[cfg(test)] mod tests { use super::*; #[test] fn remote_pids_are_negative_and_round_trip() { let max_serial = (1i64 << SERIAL_BITS) - 1; for (node, serial) in [ (0, 0), (1, 7), (u16::MAX, 0), (0, max_serial), (u16::MAX, max_serial), ] { let pid = remote(node, serial).expect("in range"); assert!(is_remote(pid), "{node}/{serial}"); assert_eq!(parts(pid), (node, serial)); // A tagged Int carries it unchanged. assert_eq!(crate::abi::int_get(crate::abi::int(pid)), pid); } assert_eq!(remote(0, 0), Some(-1)); assert_eq!(remote(u16::MAX, max_serial), Some(-(1 << 62))); assert_ne!(remote(1, 0), remote(0, 1)); } #[test] fn serials_past_46_bits_or_negative_have_no_remote_pid() { assert_eq!(remote(0, 1 << SERIAL_BITS), None); assert_eq!(remote(3, -1), None); assert!(!is_remote(0)); assert!(!is_remote(1 << SERIAL_BITS)); } #[test] fn the_node_table_only_grows() { let dist = Dist::default(); let mut nodes = dist.nodes.write().expect("the table"); let a = nodes.index("a.example", 1).expect("room"); let b = nodes.index("b.example", 1).expect("room"); assert_ne!(a, b); assert_eq!(nodes.index("a.example", 1), Some(a), "the same entry"); // A restarted node is a new incarnation: a new entry, the old one kept. let a2 = nodes.index("a.example", 2).expect("room"); assert_ne!(a2, a); assert_eq!( nodes.get(a), Some(&Node { name: "a.example".into(), incarnation: 1 }) ); assert_eq!(nodes.get(a2).map(|n| n.incarnation), Some(2)); assert_eq!(nodes.get(a2 + 1), None); } #[test] fn the_node_table_holds_65536_entries() { let mut nodes = Nodes::default(); for i in 0..MAX_NODES as u64 { assert_eq!(nodes.index("n", i), Some(i as u16)); } assert_eq!(nodes.index("n", MAX_NODES as u64), None, "full"); assert_eq!(nodes.index("n", 5), Some(5), "known entries still found"); } }