tobogganSe connecter

louise

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

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