tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

1063 lignes · 42727 octetsBrut · Historique
1//! Distribution's runtime side (ADR 0072, *Pids* and *Transport*): remote
2//! pids, the node table, and the hooks through which `proc` operations on
3//! a remote pid reach the transport. No network here: `tl_dist_start`
4//! (`node.rs`) runs the transport and installs its [`Hooks`]; the
5//! transport comes back in through [`inbound`].
6//!
7//! - **Pids.** A local pid is the scheduler's counter: 0 or more. A remote
8//! pid is negative, `-1 - (node << 46 | serial)`: an index into the node
9//! table (16 bits) and the pid on that node (its serial, 46 bits). Both
10//! fit in a tagged `Int`'s 63 bits, so equality stays word equality, and
11//! every operation on a pid tells the two apart with one sign test.
12//! - **No hooks, no distribution.** Until hooks are installed, an operation
13//! on a remote pid does what it does on a dead pid: a send is dropped, a
14//! link is not made, a monitor gets `Down(pid, Crashed("noproc"))` at
15//! once, `demonitor`, `unlink`, `kill` and `stop` are ignored. A program
16//! that never starts distribution links nothing of the transport, nor
17//! the remote halves of links and monitors: the hooks make those
18//! ([`outbound`]).
19//! - **Ties across nodes.** A local actor keeps its links to remote pids
20//! with its other links (whichever side made them), the remote pids it
21//! monitors in `Ties::watching` (a local monitor is kept by the watched
22//! actor, which a remote one cannot be), and the remote actors that
23//! monitor it with its other monitors. The started node's [`Dist`]
24//! (`node.rs`) lists, per node, the local actors tied to it, so a lost
25//! node reaches only those
26//! ([`inbound::node_down`]). A tie is made, and a remote exit or `Down`
27//! counts, only under the local actor's lock while it is alive: an exit
28//! then always finds the tie, or the tie is never made. A `Down` goes
29//! into the watcher's inbox under the same lock that ends its monitor,
30//! so a `demonitor` (which ends it under that lock too) either ends it
31//! first, or finds its `Down` delivered: none comes after it.
32//! - **Unlink across nodes** is Erlang's (`erl_dist_protocol`, *Link
33//! Protocol*, OTP 23). The unlinker's half goes at once to *unlinking*
34//! (`Ties::unlinking`), with an id, and the unlink goes to the other
35//! node, which removes its half (unless it is unlinking too) and
36//! acknowledges the id, under its actor's lock, so ahead of anything the
37//! actor sends after. The unlinker forgets the unlink at the
38//! acknowledgement of the same id. Meanwhile an exit through the link is
39//! ignored, and a link from the other side too (it left before the
40//! unlink arrived, so the other side ends unlinked); a link from the
41//! unlinker's side is a new link. So crossing links and unlinks leave
42//! both sides agreeing.
43//! - **A `Remote` subject's owner is always a remote pid**: a subject whose
44//! owner is local is a `Subject` (constructor 0), however it was made.
45//! `receive` relies on it to refuse a `Remote` subject (its owner is never
46//! the receiver), and `send` to route it by its owner's sign.
47//! - **Back-pressure.** A send to a peer whose outbound queue is full
48//! parks the sending actor ([`send_parking`]) until the transport's
49//! thread finds the queue drained ([`wake_sender`]): the actor waits,
50//! never its scheduler thread. It cannot send anything else meanwhile,
51//! so its messages keep their order.
52
53use std::collections::{HashMap, HashSet};
54use std::ffi::CString;
55use std::hash::BuildHasherDefault;
56use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering};
57use std::sync::{Mutex, MutexGuard, RwLock};
58
59use crate::abi::{Ctx, Value, YIELD_NONE};
60use crate::otp::Wait;
61use crate::sched::{Actor, Exit, IdHasher, Proc, Shared, park, this};
62
63/// Bits of a remote pid's node-table index.
64pub(crate) const NODE_BITS: u32 = 16;
65/// Bits of a remote pid's serial: the pid on its own node. A node's pids
66/// at or past `1 << 46` (70 trillion spawns) cannot be named on another
67/// node: [`remote`] refuses them, and the codec with it.
68pub(crate) const SERIAL_BITS: u32 = 46;
69/// The most nodes a node ever knows: the table only grows, one entry per
70/// incarnation of a peer.
71pub(crate) const MAX_NODES: usize = 1 << NODE_BITS;
72
73const SERIAL_MASK: u64 = (1 << SERIAL_BITS) - 1;
74
75/// Whether `pid` is on another node.
76#[inline]
77pub(crate) fn is_remote(pid: i64) -> bool {
78 pid < 0
79}
80
81/// The remote pid of `serial` on node-table entry `node`, if `serial` fits
82/// in [`SERIAL_BITS`] (a local pid of that node is never negative).
83#[cfg_attr(
84 not(any(test, feature = "tls")),
85 allow(
86 dead_code,
87 reason = "without TLS nothing starts distribution (node.rs)"
88 )
89)]
90pub(crate) fn remote(node: u16, serial: i64) -> Option<i64> {
91 let serial = u64::try_from(serial).ok().filter(|s| *s <= SERIAL_MASK)?;
92 // At most 2^62 - 1: the result is at least -2^62, a tagged Int's least.
93 let bits = (u64::from(node) << SERIAL_BITS) | serial;
94 Some(-1 - bits as i64)
95}
96
97/// A remote pid's node-table entry and serial.
98pub(crate) fn parts(pid: i64) -> (u16, i64) {
99 debug_assert!(is_remote(pid));
100 let bits = (-1 - pid) as u64;
101 ((bits >> SERIAL_BITS) as u16, (bits & SERIAL_MASK) as i64)
102}
103
104/// A node as the table knows it: its name and its incarnation (Erlang's
105/// *creation*), random at each start, so a restarted node is a new entry.
106#[derive(Clone, Debug, PartialEq)]
107pub(crate) struct Node {
108 pub(crate) name: String,
109 pub(crate) incarnation: u64,
110}
111
112/// The node table: append-only, so a remote pid names the same incarnation
113/// for as long as the program runs, and an index is never reused. Its
114/// limit is a run's: once full, no new node or restarted peer can be
115/// reached until the program restarts. Logged when 3/4 full and when full;
116/// each peer name may add a share of it only (`node.rs`).
117#[derive(Default)]
118pub(crate) struct Nodes {
119 entries: Vec<Node>,
120 index: HashMap<(String, u64), u16>,
121 /// A node was refused for want of room: logged once.
122 full: bool,
123}
124
125#[cfg_attr(
126 not(any(test, feature = "tls")),
127 allow(
128 dead_code,
129 reason = "without TLS nothing starts distribution (node.rs)"
130 )
131)]
132impl Nodes {
133 /// The index of `name`'s `incarnation`, added if new; `None` once the
134 /// table holds [`MAX_NODES`].
135 pub(crate) fn index(&mut self, name: &str, incarnation: u64) -> Option<u16> {
136 let key = (name.to_owned(), incarnation);
137 if let Some(i) = self.index.get(&key) {
138 return Some(*i);
139 }
140 if self.entries.len() >= MAX_NODES {
141 if !std::mem::replace(&mut self.full, true) {
142 eprintln!(
143 "louise: dist: the node table is full ({MAX_NODES} nodes and incarnations): \
144 no new node or restarted peer can be reached until this program restarts"
145 );
146 }
147 return None;
148 }
149 let i = self.entries.len() as u16;
150 self.entries.push(Node {
151 name: key.0.clone(),
152 incarnation,
153 });
154 self.index.insert(key, i);
155 if self.entries.len() == MAX_NODES / 4 * 3 {
156 eprintln!(
157 "louise: dist: the node table is 3/4 full: it holds every incarnation of every \
158 node this program has known, and only grows"
159 );
160 }
161 Some(i)
162 }
163
164 /// The index of `name`'s `incarnation`, if the table has it.
165 pub(crate) fn find(&self, name: &str, incarnation: u64) -> Option<u16> {
166 self.index.get(&(name.to_owned(), incarnation)).copied()
167 }
168
169 pub(crate) fn get(&self, index: u16) -> Option<&Node> {
170 self.entries.get(usize::from(index))
171 }
172}
173
174/// What distribution keeps beside the scheduler: the node table, and the
175/// local actors tied to each node. The started node owns it (`node.rs`):
176/// only the hooks and the transport reach it, so a program that does not
177/// start distribution has none. Each lock is held for one operation, never
178/// while taking another; the codec takes the node table's under the
179/// registry's (`wire`). The ties' lock is a leaf: a link takes it under
180/// the linking actor's lock ([`outbound::link`]), a monitored spawn under
181/// the new actor's or the asker's ([`outbound::monitor_spawned`],
182/// [`inbound::watch_spawned`]), and nothing takes an actor's lock under
183/// it. So does a link's frame, or a monitored spawn's answer, queued
184/// under the same lock, with the node table's read lock and the
185/// transport's queue.
186#[derive(Default)]
187#[cfg_attr(
188 not(any(test, feature = "tls")),
189 allow(
190 dead_code,
191 reason = "without TLS nothing starts distribution (node.rs)"
192 )
193)]
194pub(crate) struct Dist {
195 pub(crate) nodes: RwLock<Nodes>,
196 /// By node-table index: the local actors that linked or monitored one
197 /// of its pids, or that one of its pids linked or monitored (each also
198 /// notes the node, in `Ties::nodes`). An actor stays listed until it
199 /// exits or the node is lost, even if a remote exit or `Down` already
200 /// took its ties: the fan-out then finds nothing to do for it, and its
201 /// exit still unlists it.
202 tied: Mutex<HashMap<u16, Pids, BuildHasherDefault<IdHasher>>>,
203 /// The last unlink's id ([`Dist::unlink_id`]).
204 unlinks: AtomicU64,
205}
206
207type Pids = HashSet<i64, BuildHasherDefault<IdHasher>>;
208
209#[cfg_attr(
210 not(any(test, feature = "tls")),
211 allow(
212 dead_code,
213 reason = "without TLS nothing starts distribution (node.rs)"
214 )
215)]
216impl Dist {
217 fn tied(&self) -> MutexGuard<'_, HashMap<u16, Pids, BuildHasherDefault<IdHasher>>> {
218 self.tied
219 .lock()
220 .unwrap_or_else(std::sync::PoisonError::into_inner)
221 }
222
223 /// `local` linked or monitored a pid of `node`.
224 fn tie(&self, node: u16, local: i64) {
225 self.tied().entry(node).or_default().insert(local);
226 }
227
228 /// A new unlink's id: unique among this node's, so among the unlinks
229 /// one actor has waiting for the same pid's node, as Erlang requires.
230 pub(crate) fn unlink_id(&self) -> u64 {
231 self.unlinks.fetch_add(1, Ordering::Relaxed) + 1
232 }
233
234 /// `local` exited, listed under `nodes` (`Ties::nodes`): unlist it
235 /// (`Hooks::exit`).
236 pub(crate) fn untie(&self, local: i64, nodes: &[u16]) {
237 let mut tied = self.tied();
238 for node in nodes {
239 if let Some(set) = tied.get_mut(node) {
240 set.remove(&local);
241 }
242 }
243 }
244
245 /// The local actors tied to `node`, in pid order, unlisted.
246 fn take(&self, node: u16) -> Vec<i64> {
247 let mut pids: Vec<i64> = self
248 .tied()
249 .remove(&node)
250 .unwrap_or_default()
251 .into_iter()
252 .collect();
253 pids.sort_unstable();
254 pids
255 }
256
257 /// The local actors listed as tied to `node`, in pid order.
258 #[cfg(test)]
259 pub(crate) fn tied_to(&self, node: u16) -> Vec<i64> {
260 let mut pids: Vec<i64> = self
261 .tied()
262 .get(&node)
263 .into_iter()
264 .flatten()
265 .copied()
266 .collect();
267 pids.sort_unstable();
268 pids
269 }
270}
271
272/// An exit signal across nodes.
273#[derive(Clone, Debug, PartialEq)]
274pub(crate) enum Signal {
275 /// `kill`: the target stops with `Killed`, trapping or not.
276 Kill,
277 /// `stop` (ADR 0060): an `ExitSignal(from, Shutdown)` if the target
278 /// traps exits, else it stops with `Shutdown`.
279 Stop,
280 /// `from`, linked to the target, exited with this reason.
281 Linked(Exit),
282}
283
284/// The transport, as `proc` operations reach it. Each hook runs on the
285/// thread of the actor performing the operation (or exiting), which it
286/// must not unwind, nor park but through [`send_parking`]. The hooks do the
287/// whole remote job, the local halves of ties and the node's [`Dist`]
288/// included: the scheduler only tests a pid's sign and calls them. A hook
289/// answers asynchronously, through [`inbound`]: a link to a pid that is
290/// gone, or on a node that is not connected, with an exit signal
291/// (`noproc`, `noconnection`); a monitor with a `Down`.
292pub(crate) struct Hooks {
293 /// Send `message` to `(owner, tag)`, whose message type is `wire` in
294 /// the type registry, from the running actor of `ctx`. The message is
295 /// borrowed: the hook encodes it, and the caller drops it once it
296 /// returns. While the peer's queue is full, the hook parks the actor
297 /// ([`send_parking`]); on return, `yielding` may be set (it exited
298 /// meanwhile). An error is a message the sender cannot encode, a bug
299 /// in the program: the caller panics with it (ADR 0072, *Settled*), a
300 /// panic message the hook made ([`unsendable`]).
301 pub(crate) send:
302 fn(ctx: *mut Ctx, owner: i64, tag: i64, wire: i64, message: Value) -> Result<(), CString>,
303 /// The running actor `me` links to the remote `other`: its own half
304 /// and the link frame, under its lock ([`outbound::link`]).
305 pub(crate) link: fn(sched: &Shared, me: &Actor, other: i64),
306 /// The running actor `me` monitors the remote `watched`, its `Down`
307 /// due on `tag`: its own half ([`outbound::monitor`]), then the
308 /// monitor. False if it makes none: the caller answers `noproc`, as
309 /// for a dead pid.
310 pub(crate) monitor: fn(sched: &Shared, me: &Actor, watched: i64, tag: i64) -> bool,
311 /// The running actor `me` stops monitoring the remote `watched` on
312 /// `tag`: its own half first ([`outbound::demonitor`]), after which
313 /// no `Down` of it is delivered, then the watched node's.
314 pub(crate) demonitor: fn(me: &Actor, watched: i64, tag: i64),
315 /// The running actor `me` unlinks the remote `other`: its own half
316 /// goes to unlinking and the unlink frame is queued, under its lock
317 /// ([`outbound::unlink`]); from then on no exit through the link
318 /// counts.
319 pub(crate) unlink: fn(me: &Actor, other: i64),
320 /// An exit signal from `from` (local) to `to` (remote).
321 pub(crate) signal: fn(from: i64, to: i64, signal: &Signal),
322 /// `watched` (local), monitored by `watcher` (remote) on `tag`, exited.
323 pub(crate) down: fn(watched: i64, watcher: i64, tag: i64, reason: &Exit),
324 /// The local `pid` exited, listed under `nodes` (`Ties::nodes`, never
325 /// empty): unlist it from the node's [`Dist`].
326 pub(crate) exit: fn(pid: i64, nodes: &[u16]),
327}
328
329/// The installed hooks: null until the transport starts.
330static HOOKS: AtomicPtr<Hooks> = AtomicPtr::new(std::ptr::null_mut());
331
332fn hooks() -> Option<&'static Hooks> {
333 // SAFETY: only `install` stores a non-null pointer, from a `'static`.
334 unsafe { HOOKS.load(Ordering::Acquire).as_ref() }
335}
336
337/// Whether distribution runs: a peer may still wake an actor, so every
338/// actor waiting is no deadlock.
339pub(crate) fn running() -> bool {
340 hooks().is_some() || TRANSPORT.load(Ordering::Acquire)
341}
342
343/// A transport runs (`transport::start_program`).
344static TRANSPORT: AtomicBool = AtomicBool::new(false);
345
346/// How to stop the running transport and join its thread: set only by
347/// `transport::start_program`, so a program that never starts
348/// distribution reaches no transport code through [`shutdown`].
349static STOP: Mutex<Option<fn()>> = Mutex::new(None);
350
351/// The transport started; `stop` stops it.
352// Only the transport calls it, tests included: none without TLS.
353#[cfg_attr(
354 not(feature = "tls"),
355 allow(
356 dead_code,
357 reason = "without TLS nothing starts distribution (node.rs)"
358 )
359)]
360pub(crate) fn transport_started(stop: fn()) {
361 // Opaque to the optimizer, as in `install`: `shutdown` must not call
362 // the one function it could be.
363 *STOP
364 .lock()
365 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::hint::black_box(stop));
366 TRANSPORT.store(true, Ordering::Release);
367}
368
369/// The transport stopped, its thread joined.
370// Only the transport calls it, tests included: none without TLS.
371#[cfg_attr(
372 not(feature = "tls"),
373 allow(
374 dead_code,
375 reason = "without TLS nothing starts distribution (node.rs)"
376 )
377)]
378pub(crate) fn transport_stopped() {
379 TRANSPORT.store(false, Ordering::Release);
380}
381
382/// Stop the transport, if one runs, and join its thread: the scheduler
383/// calls it once its threads are done, before its shared state (which the
384/// transport's inbound handler delivers to) is dropped.
385pub(crate) fn shutdown() {
386 let stop = STOP
387 .lock()
388 .unwrap_or_else(std::sync::PoisonError::into_inner)
389 .take();
390 if let Some(stop) = stop {
391 stop();
392 }
393}
394
395/// Route remote operations to `hooks` from now on.
396#[cfg_attr(
397 not(any(test, feature = "tls")),
398 allow(
399 dead_code,
400 reason = "without TLS nothing starts distribution (node.rs)"
401 )
402)]
403pub(crate) fn install(hooks: &'static Hooks) {
404 // Opaque to the optimizer: with one caller, whole-program LTO would
405 // otherwise know the only table `HOOKS` can hold, and call its hooks
406 // directly from `op_send` and `op_monitor`, linking the transport into
407 // every program (the size test of ADR 0042 checks it does not).
408 let hooks = std::hint::black_box(std::ptr::from_ref(hooks).cast_mut());
409 HOOKS.store(hooks, Ordering::Release);
410}
411
412/// Back to no distribution (the transport stopped).
413#[cfg_attr(
414 not(any(test, feature = "tls")),
415 allow(
416 dead_code,
417 reason = "without TLS nothing starts distribution (node.rs)"
418 )
419)]
420pub(crate) fn uninstall() {
421 HOOKS.store(std::ptr::null_mut(), Ordering::Release);
422}
423
424// ---- outbound: `proc` operations on a remote pid -------------------------------
425
426/// `send` to a remote subject: `message` is borrowed. Dropped without
427/// hooks, as a send to a dead actor; an error is the sender's panic. May
428/// park the running actor (back-pressure).
429pub(crate) fn send(
430 ctx: *mut Ctx,
431 owner: i64,
432 tag: i64,
433 wire: i64,
434 message: Value,
435) -> Result<(), CString> {
436 match hooks() {
437 Some(h) => (h.send)(ctx, owner, tag, wire, message),
438 None => Ok(()),
439 }
440}
441
442/// The sender's panic message for a message it cannot send, `why`
443/// ([`Hooks::send`]). Made by the hooks, so a program that never starts
444/// distribution links none of it.
445#[cfg_attr(
446 not(any(test, feature = "tls")),
447 allow(
448 dead_code,
449 reason = "without TLS nothing starts distribution (node.rs)"
450 )
451)]
452pub(crate) fn unsendable(why: &str) -> CString {
453 CString::new(format!("send to another node: {why}")).unwrap_or_default()
454}
455
456/// An actor parked on a peer's full queue: its pid and its wait's number,
457/// so that a late wake reaches no later wait ([`wake_sender`]).
458#[derive(Clone, Copy, Debug, PartialEq, Eq)]
459pub(crate) struct Waiter {
460 pub(crate) pid: i64,
461 pub(crate) wait: u64,
462}
463
464/// One try of [`send_parking`]'s.
465pub(crate) enum Try<F> {
466 /// Sent, or refused for good: what the send returns.
467 Done(Result<(), String>),
468 /// The queue is full: the frame, given back.
469 Full(F),
470}
471
472/// Send `frame` from the running actor of `ctx`, parking it while the
473/// peer's queue is full (ADR 0072, *Back-pressure*). `attempt` queues the
474/// frame or gives it back; given a [`Waiter`], it registers it under the
475/// queue's lock when full, and the transport wakes it ([`wake_sender`])
476/// once the queue drains or its node is down; `unwait` forgets a waiter
477/// that something else woke. The actor waits as on a socket (`Wait::Io`),
478/// set before the registered try, so a drain between that try and the
479/// parking is not lost; a woken actor tries again, unregistered first.
480/// `None` if the actor exited while parked: the frame is dropped (at most
481/// once), `yielding` is set, and the caller unwinds.
482///
483/// # Safety
484/// `ctx` must be the running actor's context.
485#[cfg_attr(
486 not(any(test, feature = "tls")),
487 allow(
488 dead_code,
489 reason = "without TLS nothing starts distribution (node.rs)"
490 )
491)]
492pub(crate) unsafe fn send_parking<F>(
493 ctx: *mut Ctx,
494 mut frame: F,
495 mut attempt: impl FnMut(F, Option<Waiter>) -> Try<F>,
496 unwait: impl Fn(Waiter),
497) -> Option<Result<(), String>> {
498 // SAFETY: forwarded caller guarantee.
499 let (a, _) = unsafe { this(ctx) };
500 let mut waiter = None;
501 loop {
502 match attempt(frame, waiter) {
503 Try::Done(done) => {
504 if waiter.is_some() {
505 a.with_proc(|p| p.wait = Wait::Ready);
506 }
507 return Some(done);
508 }
509 Try::Full(back) => {
510 frame = back;
511 let Some(w) = waiter else {
512 let wait = a.with_proc(|p| p.park_as(Wait::Io));
513 waiter = Some(Waiter { pid: a.pid, wait });
514 continue;
515 };
516 // SAFETY: forwarded caller guarantee; its wait is set.
517 let exited = unsafe {
518 let woke = park(ctx);
519 crate::heap::drop_value(ctx, woke);
520 (*ctx).yielding != YIELD_NONE
521 };
522 unwait(w);
523 if exited {
524 return None;
525 }
526 waiter = None;
527 }
528 }
529 }
530}
531
532/// Resume `waiter`, parked by [`send_parking`], if it still waits there:
533/// its peer's queue drained, or its node is down. From any thread.
534#[cfg_attr(
535 not(any(test, feature = "tls")),
536 allow(
537 dead_code,
538 reason = "without TLS nothing starts distribution (node.rs)"
539 )
540)]
541pub(crate) fn wake_sender(sched: &Shared, waiter: Waiter) {
542 if sched.with_proc(waiter.pid, |p| p.resume(waiter.wait)) == Some(true) {
543 sched.schedule(waiter.pid);
544 }
545}
546
547/// `link` from the running actor `me` to the remote `other`: no link
548/// without hooks, as with a dead pid.
549pub(crate) fn link(sched: &Shared, me: &Actor, other: i64) {
550 if let Some(h) = hooks() {
551 (h.link)(sched, me, other);
552 }
553}
554
555/// `monitor` from the running actor `me` of the remote `watched`, its
556/// `Down` due on `tag`. Without hooks, false: the caller answers
557/// `noproc`, as for a dead pid.
558pub(crate) fn monitor(sched: &Shared, me: &Actor, watched: i64, tag: i64) -> bool {
559 hooks().is_some_and(|h| (h.monitor)(sched, me, watched, tag))
560}
561
562/// `demonitor` from the running actor `me` of the remote `watched` on
563/// `tag`. Without hooks, nothing: no `Down` can come from a transport.
564pub(crate) fn demonitor(me: &Actor, watched: i64, tag: i64) {
565 if let Some(h) = hooks() {
566 (h.demonitor)(me, watched, tag);
567 }
568}
569
570/// `unlink` from the running actor `me` of the remote `other`. Without
571/// hooks, nothing: only hooks link to a remote pid.
572pub(crate) fn unlink(me: &Actor, other: i64) {
573 if let Some(h) = hooks() {
574 (h.unlink)(me, other);
575 }
576}
577
578/// The local `pid`, listed under `nodes` (`Ties::nodes`), exited. Only a
579/// hook or the transport ties an actor to a node: without distribution,
580/// `nodes` is empty and the caller never calls this.
581pub(crate) fn exit(pid: i64, nodes: &[u16]) {
582 if let Some(h) = hooks() {
583 (h.exit)(pid, nodes);
584 }
585}
586
587/// The local half of a link to the remote `other`, of node `node`, made by
588/// the local actor (a new link, whatever unlink of `other` it still has
589/// waiting): whether `dist` must list the actor under the node.
590#[cfg_attr(
591 not(any(test, feature = "tls")),
592 allow(
593 dead_code,
594 reason = "without TLS nothing starts distribution (node.rs)"
595 )
596)]
597fn link_half(p: &mut Proc, other: i64, node: u16) -> bool {
598 let ties = p.ties();
599 ties.link_remote(other);
600 ties.tie(node)
601}
602
603/// List the local `pid` under `node` in `dist`, its ties having named the
604/// node for the first time. Outside the actor's lock ([`Dist`]'s lock
605/// order), so an exit may have taken its ties meanwhile and unlisted it
606/// before this: then unlist it again. An exit after the check below
607/// unlists it itself ([`Hooks::exit`]).
608#[cfg_attr(
609 not(any(test, feature = "tls")),
610 allow(
611 dead_code,
612 reason = "without TLS nothing starts distribution (node.rs)"
613 )
614)]
615fn list(sched: &Shared, dist: &Dist, pid: i64, node: u16) {
616 dist.tie(node, pid);
617 if sched.with_proc(pid, |p| p.dead) != Some(false) {
618 dist.untie(pid, &[node]);
619 }
620}
621
622/// An exit signal from `from` (local) to the remote `to`: ignored without
623/// hooks, as for a dead pid.
624pub(crate) fn signal(from: i64, to: i64, signal: Signal) {
625 if let Some(h) = hooks() {
626 (h.signal)(from, to, &signal);
627 }
628}
629
630/// The local `watched`, monitored by the remote `watcher` on `tag`, exited
631/// with `reason`: its `Down` goes to the watcher's node. Out of line: an
632/// exit with only local watchers never calls it.
633#[cold]
634#[inline(never)]
635pub(crate) fn down(watched: i64, watcher: i64, tag: i64, reason: &Exit) {
636 if let Some(h) = hooks() {
637 (h.down)(watched, watcher, tag, reason);
638 }
639}
640
641/// The local halves of the ties a running actor makes to a remote pid, for
642/// the hooks to make before they send the link or monitor: the actor's
643/// own half, listed in the node's [`Dist`]. Only the hooks reach it, so a
644/// program that never starts distribution links none of it.
645#[cfg_attr(
646 not(any(test, feature = "tls")),
647 allow(
648 dead_code,
649 reason = "without TLS nothing starts distribution (node.rs)"
650 )
651)]
652pub(crate) mod outbound {
653 use super::{Dist, Proc, link_half, list, parts};
654 use crate::sched::{Actor, Shared};
655
656 /// `me` links to the remote `other`: its own half, listed under the
657 /// node if it names the node first, then `send`, which queues the link
658 /// frame, all under its lock. `None` if it has already exited (killed
659 /// while running): as from a dead pid, no link is due, and nothing is
660 /// sent. Else whether `send` queued the frame.
661 ///
662 /// Under the lock, because an exit takes it to take the links, and
663 /// sends their exits after: the link frame is then always ahead of
664 /// `me`'s exit on the node's ordered stream. Queued after the lock, an
665 /// exit in between (a `kill` from another thread) could pass it, be
666 /// ignored for want of a link, and leave `other` linked to a pid that
667 /// is gone.
668 ///
669 /// Listed before the frame is queued, under the same lock: a node lost
670 /// once the frame is queued then finds `me` in its fan-out
671 /// ([`super::inbound::node_down`]), which waits for the lock and ends
672 /// the link with `noconnection`. Listed after the lock, a loss in
673 /// between would find nothing, and the link would outlive its node.
674 /// A loss before the frame is queued makes `send` fail.
675 pub(crate) fn link(
676 dist: &Dist,
677 me: &Actor,
678 other: i64,
679 send: impl FnOnce() -> bool,
680 ) -> Option<bool> {
681 let node = parts(other).0;
682 me.with_proc(|p| (!p.dead).then(|| half(dist, p, me.pid, other, node, send)))
683 }
684
685 /// The new actor `child`, not yet scheduled, links to the remote
686 /// `asker` of its spawn (`spawn_link_on`): as [`link`], so its link
687 /// frame leaves before anything it does, and a loss of the asker's
688 /// node finds it. `None` if it has already exited (a peer killed it by
689 /// its serial).
690 #[cfg_attr(
691 not(feature = "tls"),
692 allow(dead_code, reason = "only a started node spawns for a peer")
693 )]
694 pub(crate) fn link_spawned(
695 sched: &Shared,
696 dist: &Dist,
697 child: i64,
698 asker: i64,
699 send: impl FnOnce() -> bool,
700 ) -> Option<bool> {
701 let node = parts(asker).0;
702 sched.with_alive(child, |p| half(dist, p, child, asker, node, send))
703 }
704
705 /// The new actor `child`, not yet scheduled, is monitored by the remote
706 /// `asker` of its spawn, its `Down` due on `tag` (`spawn_monitor_on`):
707 /// the monitor is made and listed under the asker's node, then `send`
708 /// queues the spawn's answer, under its lock. Its `Down` then always
709 /// follows the answer on the node's ordered stream, so the asker's node
710 /// has the monitor when the `Down` arrives; and a loss of that node once
711 /// the answer is queued finds `child` and forgets the monitor. If
712 /// `send` fails (the node is not up), the monitor is forgotten at once.
713 /// `None` if `child` has already exited (a peer killed it by its
714 /// serial): nothing was sent. Else whether `send` queued the answer.
715 #[cfg_attr(
716 not(feature = "tls"),
717 allow(dead_code, reason = "only a started node spawns for a peer")
718 )]
719 pub(crate) fn monitor_spawned(
720 sched: &Shared,
721 dist: &Dist,
722 child: i64,
723 asker: i64,
724 tag: i64,
725 send: impl FnOnce() -> bool,
726 ) -> Option<bool> {
727 let node = parts(asker).0;
728 sched.with_alive(child, |p| {
729 let ties = p.ties();
730 ties.monitors.push((asker, tag));
731 if ties.tie(node) {
732 dist.tie(node, child);
733 }
734 let sent = send();
735 if !sent {
736 p.demonitor(asker, tag);
737 }
738 sent
739 })
740 }
741
742 /// `pid`'s half of its link to `other`, of node `node`, listed under
743 /// the node if new to it, then the frame: whether it was queued. Under
744 /// the actor's lock, which may take the ties' ([`Dist`]).
745 fn half(
746 dist: &Dist,
747 p: &mut Proc,
748 pid: i64,
749 other: i64,
750 node: u16,
751 send: impl FnOnce() -> bool,
752 ) -> bool {
753 if link_half(p, other, node) {
754 dist.tie(node, pid);
755 }
756 send()
757 }
758
759 /// `me` monitors the remote `watched`, its `Down` due on `tag`: its
760 /// own half. False if it has already exited (killed while running):
761 /// no `Down` is due to it.
762 pub(crate) fn monitor(sched: &Shared, dist: &Dist, me: &Actor, watched: i64, tag: i64) -> bool {
763 let node = parts(watched).0;
764 let tied = me.with_proc(|p| {
765 (!p.dead).then(|| {
766 let ties = p.ties();
767 ties.watching.push((watched, tag));
768 ties.tie(node)
769 })
770 });
771 let Some(new) = tied else {
772 return false;
773 };
774 if new {
775 list(sched, dist, me.pid, node);
776 }
777 true
778 }
779
780 /// `me` stops monitoring the remote `watched` on `tag`: its own half.
781 /// From now on its `Down` is not delivered ([`super::inbound::down`]).
782 /// False if there was no such monitor (its `Down` came already, or
783 /// there never was one): the watched node has nothing to forget. The
784 /// actor stays listed under the node ([`Dist`]).
785 pub(crate) fn demonitor(me: &Actor, watched: i64, tag: i64) -> bool {
786 me.with_proc(|p| p.unwatch(watched, tag))
787 }
788
789 /// `me` unlinks the remote `other` as unlink `id`: its half waits for
790 /// the acknowledgement of `id` (`Ties::unlinking`), and `send` queues
791 /// the unlink frame, under its lock, as for a link ([`link`]): the
792 /// frame is then ahead of any later link frame of `me`'s, and an exit
793 /// of `me`'s finds no link to send through. From now on an exit
794 /// through the link is ignored. Nothing if `me` has no link to `other`
795 /// (or has exited: its exit took the link). If `send` fails, the node
796 /// is not up and no acknowledgement can come: the half goes at once,
797 /// and the node's loss ends the other's. The actor stays listed under
798 /// the node ([`Dist`]).
799 pub(crate) fn unlink(me: &Actor, other: i64, id: u64, send: impl FnOnce() -> bool) {
800 me.with_proc(|p| {
801 if p.unlink_remote(other, id) && !send() {
802 p.unlink_acked(other, id);
803 }
804 });
805 }
806}
807
808/// What the transport calls with what peers send: from its own thread, or
809/// any thread that is not running an actor. A thread that delivers keeps
810/// up to 64 actor cells in its send cache until it stops (`sched::local`).
811#[cfg_attr(
812 not(any(test, feature = "tls")),
813 allow(
814 dead_code,
815 reason = "without TLS nothing starts distribution (node.rs)"
816 )
817)]
818pub(crate) mod inbound {
819 use super::{Dist, Signal, is_remote, list, parts};
820 use crate::abi::Value;
821 use crate::process::signal_value;
822 use crate::sched::{Exit, Linked, Shared, exit_actor, exit_through_link, propagate_exit};
823
824 /// A message for the local subject `(to, tag)`, made outside any
825 /// actor's context (owned). Dropped if `to` is gone.
826 pub(crate) fn deliver(sched: &Shared, to: i64, tag: i64, message: Value) {
827 crate::process::deliver_made(sched, to, tag, message);
828 }
829
830 /// The remote `from` linked to the local `to`: the link's local half.
831 /// If `to` is gone, `from` gets its exit, `Crashed("noproc")`, as a
832 /// link to a pid that is gone does in Erlang: across nodes, it may have
833 /// exited while the link was on its way. Ignored while `to`'s unlink
834 /// of `from` waits for its acknowledgement (`Ties::linked_by`): the
835 /// link left before that unlink reached `from`'s node, which removed
836 /// `from`'s half.
837 pub(crate) fn link(sched: &Shared, dist: &Dist, from: i64, to: i64) {
838 debug_assert!(is_remote(from) && !is_remote(to));
839 let node = parts(from).0;
840 let tied = sched.with_alive(to, |p| {
841 let ties = p.ties();
842 ties.linked_by(from) && ties.tie(node)
843 });
844 match tied {
845 Some(true) => list(sched, dist, to, node),
846 Some(false) => {}
847 None => super::signal(to, from, Signal::Linked(noproc())),
848 }
849 }
850
851 /// The remote `from` unlinked the local `to` (its own half is
852 /// unlinking already): `to`'s half goes, unless `to` is unlinking
853 /// `from` too, and `ack` answers, under `to`'s lock: the
854 /// acknowledgement is then ahead of anything `to` sends that node
855 /// after (a new link, which `from`'s side would otherwise ignore).
856 /// Answered for a `to` that is gone too, so that `from` forgets its
857 /// unlink. `to`'s exit frame, if it was linked, may then come after
858 /// the acknowledgement (its exit sends it after its lock): `from`
859 /// ignores it, having no link, unless it linked `to` again meanwhile,
860 /// a link `to`'s real exit then ends instead of `noproc`.
861 pub(crate) fn unlink(sched: &Shared, from: i64, to: i64, ack: impl FnOnce()) {
862 debug_assert!(is_remote(from) && !is_remote(to));
863 let mut ack = Some(ack);
864 sched.with_alive(to, |p| {
865 p.unlink(from);
866 if let Some(ack) = ack.take() {
867 ack();
868 }
869 });
870 if let Some(ack) = ack {
871 ack();
872 }
873 }
874
875 /// The remote `from` acknowledged unlink `id` of the local `to`'s: `to`
876 /// forgets it, unless it linked `from` again since.
877 pub(crate) fn unlink_acked(sched: &Shared, from: i64, to: i64, id: u64) {
878 debug_assert!(is_remote(from) && !is_remote(to));
879 sched.with_alive(to, |p| p.unlink_acked(from, id));
880 }
881
882 /// The remote `watcher` monitors the local `watched`, its `Down` due on
883 /// `tag`; if `watched` is gone, that `Down` goes at once (`noproc`).
884 pub(crate) fn monitor(sched: &Shared, dist: &Dist, watcher: i64, tag: i64, watched: i64) {
885 debug_assert!(is_remote(watcher) && !is_remote(watched));
886 let node = parts(watcher).0;
887 let tied = sched.with_alive(watched, |p| {
888 let ties = p.ties();
889 ties.monitors.push((watcher, tag));
890 ties.tie(node)
891 });
892 match tied {
893 Some(true) => list(sched, dist, watched, node),
894 Some(false) => {}
895 None => super::down(watched, watcher, tag, &noproc()),
896 }
897 }
898
899 /// The remote `watcher` stops monitoring the local `watched` on `tag`
900 /// (its own half is gone already): no `Down` is due to it.
901 pub(crate) fn demonitor(sched: &Shared, watcher: i64, tag: i64, watched: i64) {
902 debug_assert!(is_remote(watcher) && !is_remote(watched));
903 sched.with_alive(watched, |p| p.demonitor(watcher, tag));
904 }
905
906 fn noproc() -> Exit {
907 Exit::Crashed("noproc".into())
908 }
909
910 /// An exit signal from the remote `from` to the local `to`. Through a
911 /// link, only if `to` still has it: a lost node's fan-out may have
912 /// taken it first.
913 pub(crate) fn signal(sched: &Shared, from: i64, to: i64, signal: &Signal) {
914 debug_assert!(is_remote(from) && !is_remote(to));
915 match signal {
916 Signal::Kill => exit_actor(sched, to, Exit::Killed),
917 Signal::Stop => crate::process::stop(sched, from, to),
918 Signal::Linked(reason) => propagate_exit(sched, from, to, reason),
919 }
920 }
921
922 /// The remote `pid`, monitored by the local `watcher` on `tag`, exited:
923 /// `Down(pid, reason)`, unless the monitor is gone (a lost node's
924 /// fan-out sent its `Down` already, or the watcher demonitored it).
925 /// Delivered under the lock that ends the monitor.
926 pub(crate) fn down(sched: &Shared, watcher: i64, tag: i64, pid: i64, reason: &Exit) {
927 sched.with_alive_delivering(watcher, |p| {
928 let watched = p.unwatch(pid, tag);
929 let down = watched.then(|| (tag, signal_value(pid, reason)));
930 ((), down.into_iter().collect())
931 });
932 }
933
934 /// The remote `pid` was spawned for the local `watcher`, monitored on
935 /// `tag` (`spawn_monitor_on`): the watcher's half of the monitor is
936 /// made, listed under the node, and `answer()` (the spawn's answer,
937 /// made outside any actor's context) delivered on `reply_tag`, under
938 /// its lock. Made here, on the thread that then takes the `Down` the
939 /// stream may hold next, not by the watcher, which may not run before
940 /// that. False if the watcher is gone: nothing is made, and the
941 /// monitor is the caller's to forget on `pid`'s node.
942 pub(crate) fn watch_spawned(
943 sched: &Shared,
944 dist: &Dist,
945 watcher: i64,
946 pid: i64,
947 tag: i64,
948 reply_tag: i64,
949 answer: impl FnOnce() -> Value,
950 ) -> bool {
951 debug_assert!(is_remote(pid) && !is_remote(watcher));
952 let node = parts(pid).0;
953 let watched = sched.with_alive_delivering(watcher, |p| {
954 let ties = p.ties();
955 ties.watching.push((pid, tag));
956 if ties.tie(node) {
957 dist.tie(node, watcher);
958 }
959 ((), vec![(reply_tag, answer())])
960 });
961 watched.is_some()
962 }
963
964 /// Node-table entry `node` is lost: every local actor linked to one of
965 /// its pids gets `Crashed("noconnection")` as that pid's exit, and
966 /// every monitor of one gets `Down(pid, Crashed("noconnection"))`; the
967 /// monitors its pids held on local actors are forgotten, and so are
968 /// the unlinks waiting for its acknowledgement. It reaches the actors
969 /// tied to `node` only, in pid order, each in the order of its links,
970 /// then of its monitors: under the lock that ends them, as [`down`]
971 /// (`exit_through_link`). An actor that does not trap exits dies of
972 /// its first link instead, and gets no `Down`.
973 pub(crate) fn node_down(sched: &Shared, dist: &Dist, node: u16) {
974 let lost = Exit::Crashed("noconnection".into());
975 let on_node = |pid: i64| is_remote(pid) && parts(pid).0 == node;
976 for local in dist.take(node) {
977 exit_through_link(sched, local, |p| {
978 let ties = p.ties();
979 // Unlisted above: a later tie to the node lists it again.
980 ties.nodes.retain(|n| *n != node);
981 let (links, watching) = ties.take(on_node);
982 if !ties.trap && !links.is_empty() {
983 return Some(Linked::Dies(lost.clone()));
984 }
985 let mut messages = Vec::new();
986 if !links.is_empty() {
987 let exits = *ties.exits_tag.get_or_insert_with(|| sched.tag());
988 let signals = links.iter().map(|pid| (exits, signal_value(*pid, &lost)));
989 messages.extend(signals);
990 }
991 let downs = watching.into_iter();
992 messages.extend(downs.map(|(pid, tag)| (tag, signal_value(pid, &lost))));
993 Some(Linked::Told(messages))
994 });
995 }
996 }
997}
998
999#[cfg(test)]
1000mod tests {
1001 use super::*;
1002
1003 #[test]
1004 fn remote_pids_are_negative_and_round_trip() {
1005 let max_serial = (1i64 << SERIAL_BITS) - 1;
1006 for (node, serial) in [
1007 (0, 0),
1008 (1, 7),
1009 (u16::MAX, 0),
1010 (0, max_serial),
1011 (u16::MAX, max_serial),
1012 ] {
1013 let pid = remote(node, serial).expect("in range");
1014 assert!(is_remote(pid), "{node}/{serial}");
1015 assert_eq!(parts(pid), (node, serial));
1016 // A tagged Int carries it unchanged.
1017 assert_eq!(crate::abi::int_get(crate::abi::int(pid)), pid);
1018 }
1019 assert_eq!(remote(0, 0), Some(-1));
1020 assert_eq!(remote(u16::MAX, max_serial), Some(-(1 << 62)));
1021 assert_ne!(remote(1, 0), remote(0, 1));
1022 }
1023
1024 #[test]
1025 fn serials_past_46_bits_or_negative_have_no_remote_pid() {
1026 assert_eq!(remote(0, 1 << SERIAL_BITS), None);
1027 assert_eq!(remote(3, -1), None);
1028 assert!(!is_remote(0));
1029 assert!(!is_remote(1 << SERIAL_BITS));
1030 }
1031
1032 #[test]
1033 fn the_node_table_only_grows() {
1034 let dist = Dist::default();
1035 let mut nodes = dist.nodes.write().expect("the table");
1036 let a = nodes.index("a.example", 1).expect("room");
1037 let b = nodes.index("b.example", 1).expect("room");
1038 assert_ne!(a, b);
1039 assert_eq!(nodes.index("a.example", 1), Some(a), "the same entry");
1040 // A restarted node is a new incarnation: a new entry, the old one kept.
1041 let a2 = nodes.index("a.example", 2).expect("room");
1042 assert_ne!(a2, a);
1043 assert_eq!(
1044 nodes.get(a),
1045 Some(&Node {
1046 name: "a.example".into(),
1047 incarnation: 1
1048 })
1049 );
1050 assert_eq!(nodes.get(a2).map(|n| n.incarnation), Some(2));
1051 assert_eq!(nodes.get(a2 + 1), None);
1052 }
1053
1054 #[test]
1055 fn the_node_table_holds_65536_entries() {
1056 let mut nodes = Nodes::default();
1057 for i in 0..MAX_NODES as u64 {
1058 assert_eq!(nodes.index("n", i), Some(i as u16));
1059 }
1060 assert_eq!(nodes.index("n", MAX_NODES as u64), None, "full");
1061 assert_eq!(nodes.index("n", 5), Some(5), "known entries still found");
1062 }
1063}