//! This node (ADR 0072, `std/dist`): what `tl_dist_start` starts, and the //! glue between the scheduler (`dist`), the codec (`wire`) and the //! transport. //! //! - **Once per program.** `std/dist.start` builds the type registry from //! the program's definitions table, starts the transport with the //! program's schema hash, and installs the hooks through which `proc` //! operations on a remote pid reach it. Nothing here is reachable //! otherwise: a program that never starts distribution links none of it. //! - **Sends** to a `Remote` subject are encoded on the sender's thread //! (the hook borrows the message) and queued on the peer's connection. //! A message the program cannot encode (too large, too deep, over the //! peer's frame limit) panics in the sender, as the send walk's backstop //! does. While the peer's queue is full, the sender parks //! (`dist::send_parking`): the transport wakes it once the queue //! drains, and it queues the frame it encoded then. One to a node that //! is not up, or that goes down while its sender is parked, is dropped //! and counted: delivery is at most once. //! - **Messages in** are decoded with the receiver's own descriptor for //! the frame's type hash, beside the transport's thread (its relay), so //! a long decode holds up no heartbeat. A frame that does not decode is //! dropped and counted (the first one of a connection is logged). //! - **The node table only grows** (`dist::Nodes`): each peer name may add //! [`PEER_NODES`] entries for the whole run, its own incarnations and //! the nodes its frames name alike, so neither reconnecting nor //! restarting lets one peer fill the table for the others. //! - **Names.** `register` keeps a name, a local subject and its message //! type's hash; an actor that exited holds no name. `whereis` asks a node //! with a lookup frame (`docs/wire-format.md`, *Lookups*), and the answer //! arrives as a message on the asking actor's subject: `std/os.signals`' //! pattern, no new `proc` operation. The registered type is checked //! against the asker's: another type is an error value, not a crash. //! - **Links, monitors and exit signals** cross as signal frames //! (`docs/wire-format.md`, *Signals*; `ties`), queued behind the //! messages the same actor sent before. One to a node that is not up //! answers as the node's loss would: a link gets its exit and a monitor //! its `Down`, `Crashed("noconnection")`; `kill`, `stop`, an exit and a //! `Down` are dropped (the other side sees the loss), and an unlink //! ends the local half at once. What arrives goes through //! `dist::inbound`, which ties the local actor, or answers `noproc` for //! one that is gone; an unlink is acknowledged, whether the actor is //! alive or not. //! - **Ops a peer's runtime does not take** (its hello's capability //! flags, `docs/wire-format.md`) are never sent: the transport refuses //! them. A demonitor still ends the local half; an unlink ends it at //! once, as to a node that is not up; a linked or monitored spawn is //! refused before anything is pending (`std/dist`'s `Unsupported`). //! - **`monitor_node`** keeps (actor, tag, node name) subscriptions: the //! node's state at once (`NodeUp`, or `NodeDown` with why its last //! connection failed), then each change, a `NodeDown` after the lost //! node's links and monitors had theirs. //! - **Spawns.** `start` registers the argument types of the program's //! `@remote` functions (`std/wire.entries`), and gives the node a //! *spawner*, an actor of `std/dist`. `spawn_on` sends a spawn request //! (`docs/wire-format.md`, *Spawns*); the receiving node checks the key //! and the argument's type hash against its own entries before decoding //! anything, then hands the key and the decoded argument (a //! `std/wire.Arg`) to its spawner, which runs the compiler's dispatcher //! and hands the body to `tl_dist_spawn_for`, which spawns it and //! answers. No code address ever comes off the wire. The answer reaches //! the asker as `whereis`' does. `spawn_link_on` links the new actor to //! the asker before it can run, its link frame ahead of the answer. //! `spawn_monitor_on` has the asker monitor it before it can run, the //! answer ahead of its `Down`; the asker's node makes the asker's half //! of the monitor as the answer arrives. //! //! The answers `std/dist` receives are `Found(subject)` (`whereis`), //! `Found(pid)` (`spawn_on` and its linked and monitored forms) or //! `Failed(code, text)` (its `Answer` type); //! `tl_dist_register` returns a code. The codes are `std/dist`'s //! `failure`'s. Node events are `NodeUp(node)` and `NodeDown(node, why)` //! (its `NodeEvent`). //! `tl_dist_peers` reads the transport's statistics at once (`std/dist`'s //! `Peer`). `tl_dist_connect` hands the transport a node to stay //! connected to, as a seed. use crate::abi::{Ctx, Value, int}; use crate::values::{cell, string}; /// What `std/dist` turns into a `DistError` (its `failure`). #[cfg_attr(not(feature = "tls"), allow(dead_code))] mod code { pub const OK: i64 = 0; pub const NOT_STARTED: i64 = 1; pub const NOT_CONNECTED: i64 = 2; pub const NO_NAME: i64 = 3; pub const WRONG_TYPE: i64 = 4; pub const TAKEN: i64 = 5; pub const NOT_LOCAL: i64 = 6; pub const UNKNOWN_ENTRY: i64 = 7; pub const REFUSED: i64 = 8; /// `connect`: not a node name (`std/dist.connect`'s `Invalid`). pub const INVALID: i64 = 9; /// A linked or monitored spawn on a node whose runtime does not take /// it (its hello's capability flags). pub const UNSUPPORTED: i64 = 10; } /// The longest name `register` and `whereis` take, in bytes: a lookup /// frame gives it one byte. #[cfg_attr(not(feature = "tls"), allow(dead_code))] const MAX_NAME: usize = 255; /// `Failed(code, text)`, made outside any actor. fn failed(code: i64, text: &str) -> Value { cell( std::ptr::null_mut(), 1, &[int(code), string(std::ptr::null_mut(), text)], ) } /// `NodeUp(node)`, made outside any actor. #[cfg_attr(not(feature = "tls"), allow(dead_code))] fn node_up_event(node: &str) -> Value { cell( std::ptr::null_mut(), 0, &[string(std::ptr::null_mut(), node)], ) } /// `NodeDown(node, why)`, made outside any actor. fn node_down_event(node: &str, why: &str) -> Value { let null = std::ptr::null_mut(); cell(null, 1, &[string(null, node), string(null, why)]) } #[cfg(feature = "tls")] mod ties; #[cfg(feature = "tls")] pub use enabled::*; #[cfg(not(feature = "tls"))] pub use disabled::*; #[cfg(not(feature = "tls"))] mod disabled { use super::*; use crate::abi::UNIT; const NOT_BUILT: &str = "distribution needs TLS (louise_rt's `tls` feature)"; /// # Safety /// As the enabled version. #[unsafe(no_mangle)] #[allow(clippy::too_many_arguments)] pub unsafe extern "C" fn tl_dist_start( ctx: *mut Ctx, _node: Value, _cluster: Value, _listen: Value, _advertise: Value, _seeds: Value, _cert_file: Value, _key_file: Value, _ca_files: Value, _table: Value, _schema_hash: Value, _limits: Value, _entries: Value, _spawner: Value, ) -> Value { crate::values::error(ctx, NOT_BUILT) } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_peers(_ctx: *mut Ctx) -> Value { int(0) } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_connect(_ctx: *mut Ctx, _node: Value, _addr: Value) -> Value { int(code::NOT_STARTED) } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_register( _ctx: *mut Ctx, _name: Value, _desc: Value, _subject: Value, ) -> Value { int(code::NOT_STARTED) } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_whereis( ctx: *mut Ctx, tag: Value, _node: Value, _name: Value, _desc: Value, ) -> Value { // SAFETY: caller guarantees a running actor. let (a, sched) = unsafe { crate::sched::this(ctx) }; let tag = crate::abi::int_get(tag); crate::process::deliver_made(sched, a.pid, tag, failed(code::NOT_STARTED, NOT_BUILT)); UNIT } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_monitor_node(ctx: *mut Ctx, tag: Value, node: Value) -> Value { // SAFETY: caller guarantees a running actor and a live string. let (a, sched, node) = unsafe { let (a, sched) = crate::sched::this(ctx); (a, sched, crate::values::text(node)) }; let tag = crate::abi::int_get(tag); crate::process::deliver_made(sched, a.pid, tag, node_down_event(node, NOT_BUILT)); UNIT } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_spawn( ctx: *mut Ctx, tag: Value, _node: Value, _key: Value, _desc: Value, _args: Value, _tie: Value, _down: Value, ) -> Value { // SAFETY: caller guarantees a running actor. let (a, sched) = unsafe { crate::sched::this(ctx) }; let tag = crate::abi::int_get(tag); crate::process::deliver_made(sched, a.pid, tag, failed(code::NOT_STARTED, NOT_BUILT)); UNIT } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_spawn_for( ctx: *mut Ctx, _asker: Value, _tag: Value, _tie: Value, _down: Value, result: Value, ) -> Value { // SAFETY: owned (caller guarantee). unsafe { crate::heap::drop_value(ctx, result) }; UNIT } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_spawn_abandon(_ctx: *mut Ctx, _tag: Value) -> Value { // Nothing waits: `tl_dist_spawn` answered at once. int(1) } } #[cfg(feature = "tls")] mod enabled { use std::collections::HashMap; use std::ffi::CString; use std::net::SocketAddr; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError, RwLock}; use louise_rt_prims::wire::{ HEADER_LEN, MAX_PAYLOAD, MAX_PID_SERIAL, MAX_TAG, MIN_FRAME, MessageHeader, }; use super::ties::{self, Op, Tie}; use super::*; use crate::abi::{Block, UNIT, int_get}; use crate::dist::{self, Dist, Hooks, Node, Signal, Try, Waiter, is_remote}; use crate::heap::{drop_value, dup_value}; use crate::process::deliver_made; // A spawned actor's tie to its parent; `Tie` is a tie frame. use crate::sched::Tie as ParentTie; use crate::sched::{ Actor, Exit, Shared, spawn_program_before, spawn_program_monitored, spawn_program_tied, this, }; use crate::transport::{self, Config, Inbound, Outbound, Reason, SendError, Throttle}; use crate::values::{list, list_items, string, text}; use crate::wire::{self, DecodeError, PEER_NODES, Registry}; /// The node the program started, if it did. Kept once the program /// ends (a later program in the same process, a test, starts its own): /// [`running`] checks it is the running transport's, and [`current`] /// that it belongs to the running scheduler. static NODE: RwLock>> = RwLock::new(None); /// The hooks `dist` calls for operations on remote pids. static HOOKS: Hooks = Hooks { send: send_hook, link: link_hook, monitor: monitor_hook, demonitor: demonitor_hook, unlink: unlink_hook, signal: signal_hook, down: down_hook, exit: exit_hook, }; /// The scheduler the node delivers to. struct Sched(*const Shared); // SAFETY: `Shared` is shared by every scheduler thread already; the // pointer is used only while the transport runs, which the scheduler // stops (joining its thread, `dist::shutdown`) before dropping it, and // by hooks, uninstalled first. unsafe impl Send for Sched {} // SAFETY: as above. unsafe impl Sync for Sched {} /// A started node: the transport's [`Inbound`] handler, and what the /// hooks and externs share. struct State { sched: Sched, /// The node table, and the local actors tied to each node. dist: Dist, registry: Registry, /// Name and incarnation, once the transport has drawn it. me: OnceLock, /// Registered names. names: Mutex>, /// The peers that are up, by name (the transport's thread only). peers: Mutex>, /// The node-table entries each peer name may still add, for the /// whole run: [`PEER_NODES`] at first, never given back. quotas: Mutex>, /// Lookups sent and not answered, by the asking actor's pid and /// reply tag. lookups: Mutex>, /// The program's `@remote` functions, by key. entries: HashMap, /// The spawner's subject: its pid and tag. spawner: (i64, i64), /// Spawns asked of a node and not answered, by the asking actor's /// pid and reply tag; and monitored ones asked of this node. spawns: Mutex>, /// Why the last connection with a node failed, by node name. failures: Mutex>, /// Why the last connection to close did, by its label: the /// transport calls `node_down` right after `closed`. last_closed: Mutex>, /// Connections that failed before their hello: logged sparingly. unauthenticated: Mutex, /// Dials that failed to addresses only peers' lists gave: logged /// sparingly too, since the peers choose them. hearsay: Mutex, /// `monitor_node`'s subscriptions. Taken before `peers`, so a /// subscriber sees the state, then every change after it. node_watchers: Mutex>, /// Spawn requests refused: an unknown key, another type, an /// argument that did not decode. refused: AtomicU64, /// Open once the hooks are installed ([`start`]). ready: Gate, } /// What peers send waits at it until the node is published and its /// hooks are installed: the transport starts first (it draws the /// incarnation), and a frame handled before the install would lose /// the answer a hook sends (a `noproc` exit or `Down` for a tie to an /// actor gone, an exit or `Down` of an actor tied meanwhile, a spawn's /// answer). The relay's thread waits, so frames keep their order. #[derive(Default)] struct Gate { open: AtomicBool, wait: Mutex<()>, opened: Condvar, } impl Gate { fn pass(&self) { if self.open.load(Ordering::Acquire) { return; } let mut guard = lock(&self.wait); while !self.open.load(Ordering::Acquire) { guard = self .opened .wait(guard) .unwrap_or_else(PoisonError::into_inner); } } fn open(&self) { let _guard = lock(&self.wait); self.open.store(true, Ordering::Release); self.opened.notify_all(); } } /// Opens the gate when dropped: on every way out of [`start`]. struct OpenOnDrop<'a>(&'a Gate); impl Drop for OpenOnDrop<'_> { fn drop(&mut self) { self.0.open(); } } /// A `@remote` function of the program (`std/wire.Entry`), its /// argument's type registered. struct RemoteEntry { descriptor: String, wire: u32, hash: u64, } /// A registered name: a local subject and its message type's hash. struct Named { pid: i64, tag: i64, hash: u64, } struct Peer { incarnation: u64, /// A dropped frame of this connection was logged. logged: bool, } /// An actor's `monitor_node` subscription: its subject's tag, and the /// node's name. struct NodeWatcher { pid: i64, tag: i64, node: String, } /// A lookup sent to `node`, for a subject of the type of `hash`. struct Lookup { node: Node, hash: u64, } /// A spawn asked of `node` and not answered. struct Asked { node: Node, /// Monitored (`spawn_monitor_on`): the tag its `Down` is due on. down: Option, /// The asker's wait timed out (`tl_dist_spawn_abandon`): the answer /// goes to nobody, and the new actor is not monitored. Only for a /// spawn asked of another node: one asked of this node is /// forgotten instead ([`State::abandon_spawn`]). abandoned: bool, } /// The most connection failures remembered: names come from peers /// too, so the map must not grow with them. const MAX_FAILURES: usize = 256; fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(PoisonError::into_inner) } impl State { fn sched(&self) -> &Shared { // SAFETY: see `Sched`. unsafe { &*self.sched.0 } } /// This node. Set right after the transport starts; a handler /// called before (the transport holds its lock until then) reads /// it from the transport. fn me(&self) -> Option<&Node> { if let Some(me) = self.me.get() { return Some(me); } let me = transport::with_program(|t| t.me().clone())?; Some(self.me.get_or_init(|| me)) } /// The live registered holder of `name`. fn named(&self, name: &str) -> Option<(i64, i64, u64)> { let names = lock(&self.names); let n = names.get(name)?; self.sched().exists(n.pid).then_some((n.pid, n.tag, n.hash)) } /// A frame from `from` is dropped: undecodable, of an unknown /// type, a malformed lookup, an answer to no lookup. Counted in /// its statistics (`std/dist.peers`), the first of a connection /// logged. fn drop_frame(&self, from: &Node, why: &dyn std::fmt::Display) { transport::with_program(|t| t.count_dropped(&from.name)); let mut peers = lock(&self.peers); if let Some(peer) = peers.get_mut(&from.name) && !peer.logged { peer.logged = true; eprintln!( "louise: dist: {}: dropped a frame ({why}); later ones are only counted", from.name ); } } /// The value `payload` holds, of the type of `hash`, from `from`, /// within its name's node-table quota. `None`: `from` is not up. fn decode( &self, from: &Node, me: &Node, hash: u64, payload: &[u8], ) -> Option> { lock(&self.peers) .get(&from.name) .filter(|p| p.incarnation == from.incarnation)?; // Read, then written back: only the inbound thread spends it. let mut quota = *lock(&self.quotas) .entry(from.name.clone()) .or_insert(PEER_NODES); let decoded = wire::decode( &self.registry, hash, payload, me, &self.dist.nodes, &mut quota, Some(self.spawner), ); self.spent(&from.name, quota); Some(decoded) } /// `name`'s quota is now `left`: logged once when it runs out. fn spent(&self, name: &str, left: u32) { let mut quotas = lock(&self.quotas); let before = quotas.insert(name.to_owned(), left); if left == 0 && before != Some(0) { eprintln!( "louise: dist: {name}: it added {PEER_NODES} node-table entries (its \ incarnations and the nodes it names): new ones from it are refused" ); } } /// The node-table index of `from` (a peer that is or was up), added /// if new, charged to its name's quota. `Err`: why there is none. fn enter(&self, from: &Node) -> Result { let nodes = &self.dist.nodes; let found = (nodes.read().unwrap_or_else(PoisonError::into_inner)) .find(&from.name, from.incarnation); if let Some(index) = found { return Ok(index); } let left = *lock(&self.quotas) .entry(from.name.clone()) .or_insert(PEER_NODES); if left == 0 { return Err("the peer's node-table quota is spent"); } let index = (nodes.write().unwrap_or_else(PoisonError::into_inner)) .index(&from.name, from.incarnation) .ok_or("the node table is full")?; self.spent(&from.name, left - 1); Ok(index) } /// A lookup from `from`: answer it from the registered names. fn lookup(&self, from: &Node, body: &[u8]) { let Some(request) = LookupRequest::decode(body) else { return self.drop_frame(from, &"a malformed lookup"); }; let reply = match std::str::from_utf8(request.name) .ok() .and_then(|name| self.named(name)) { None => LookupReply { asker: request.asker, reply_tag: request.reply_tag, result: NO_NAME, serial: 0, tag: 0, hash: 0, }, Some((pid, tag, hash)) if hash == request.hash => LookupReply { asker: request.asker, reply_tag: request.reply_tag, result: FOUND, serial: pid as u64, tag: tag as u64, hash, }, // The subject is given only to an asker of its type. Some((_, _, hash)) => LookupReply { asker: request.asker, reply_tag: request.reply_tag, result: OTHER_TYPE, serial: 0, tag: 0, hash, }, }; // Lost with the connection, if it is: the asker times out. let _ = transport::with_program(|t| t.send(from, Outbound::Signal(reply.encode()))); } /// The answer to a lookup this node sent. fn answered(&self, from: &Node, body: &[u8]) { let Some(reply) = LookupReply::decode(body) else { return self.drop_frame(from, &"a malformed lookup answer"); }; let key = (reply.asker as i64, reply.reply_tag as i64); let lookup = { let mut lookups = lock(&self.lookups); match lookups.get(&key) { Some(l) if l.node == *from => lookups.remove(&key), _ => None, } }; let Some(lookup) = lookup else { return self.drop_frame(from, &"an answer to no lookup"); }; let answer = match reply.result { FOUND if reply.hash == lookup.hash => self.found(from, &reply), FOUND | OTHER_TYPE => failed(code::WRONG_TYPE, ""), NO_NAME => failed(code::NO_NAME, ""), _ => failed(code::NOT_CONNECTED, "a malformed lookup answer"), }; deliver_made(self.sched(), key.0, key.1, answer); } /// `Found(Remote(owner, tag, wire))` for the subject `reply` names /// on `from`. fn found(&self, from: &Node, reply: &LookupReply) -> Value { // Registered when the lookup was sent. let wire = self.registry.by_hash(reply.hash); match (self.remote_pid(from, reply.serial), wire) { (Ok(owner), Some(wire)) => { let null = std::ptr::null_mut(); let subject = cell( null, 1, &[int(owner), int(reply.tag as i64), int(i64::from(wire))], ); cell(null, 0, &[subject]) } (Err(why), _) => failed(code::NOT_CONNECTED, why), (_, None) => failed(code::WRONG_TYPE, ""), } } /// The pid of actor `serial` (below 2^46, checked) of `from`, if /// the node table has (or makes) an entry for it ([`State::enter`]). fn remote_pid(&self, from: &Node, serial: u64) -> Result { let node = self.enter(from)?; dist::remote(node, serial as i64).ok_or("a serial out of range") } /// A spawn request from `from`, of op `op` (plain, linked or /// monitored): answered here if refused, else by the spawner /// (`tl_dist_spawn_for`). fn spawn_asked(&self, from: &Node, op: u8, body: &[u8]) { let Some(request) = SpawnRequest::decode(op, body) else { return self.drop_frame(from, &"a malformed spawn request"); }; let result = match self.remote_pid(from, request.asker) { Ok(asker) => self.spawn(from, &request, asker), Err(_) => { self.refused.fetch_add(1, Ordering::Relaxed); Err(NOT_SPAWNED) } }; if let Err(result) = result { let reply = SpawnReply { asker: request.asker, reply_tag: request.reply_tag, result, serial: 0, }; // Lost with the connection, if it is: the asker is told so. let _ = transport::with_program(|t| t.send(from, Outbound::Signal(reply.encode()))); } } /// Give `request`, from `asker` of `from` (this node, for its own /// `spawn_on`), to the spawner, if the program has its entry for /// its type: checked before anything is decoded. `Err`: refused, /// the answer's result. fn spawn(&self, from: &Node, request: &SpawnRequest<'_>, asker: i64) -> Result<(), u8> { let refuse = |result| { self.refused.fetch_add(1, Ordering::Relaxed); Err(result) }; let Some(entry) = self.entries.get(&(request.key as i64)) else { return refuse(NO_ENTRY); }; if entry.hash != request.hash { return refuse(ENTRY_TYPE); } let (spawner, tag) = self.spawner; let Some(me) = self.me().filter(|_| self.sched().exists(spawner)) else { return refuse(NOT_SPAWNED); }; let decoded = if from == me { // This node's own value names no node it does not know. let nodes = &self.dist.nodes; wire::decode( &self.registry, entry.hash, request.payload, me, nodes, &mut 0, Some(self.spawner), ) } else { match self.decode(from, me, entry.hash, request.payload) { Some(decoded) => decoded, None => return refuse(NOT_SPAWNED), } }; let value = match decoded { Ok(value) => value, Err(e) => { self.drop_frame(from, &e); return refuse(NOT_SPAWNED); } }; // `std/wire.Arg(descriptor, value)`, then `std/dist.Request(key, // arg, asker, tag, tie, down)`. let null = std::ptr::null_mut(); let arg = cell(null, 0, &[string(null, &entry.descriptor), value]); let key = int(request.key as i64); let reply_tag = int(request.reply_tag as i64); let (tie, down) = request.tie.parts(); let message = cell( null, 0, &[key, arg, int(asker), reply_tag, int(tie), int(down)], ); dist::inbound::deliver(self.sched(), spawner, tag, message); Ok(()) } /// The answer to a spawn this node asked of `from`. fn spawn_answered(&self, from: &Node, body: &[u8]) { let Some(reply) = SpawnReply::decode(body) else { return self.drop_frame(from, &"a malformed spawn answer"); }; let key = (reply.asker as i64, reply.reply_tag as i64); let asked = { let mut spawns = lock(&self.spawns); match spawns.get(&key) { Some(asked) if asked.node == *from => spawns.remove(&key), _ => None, } }; let Some(asked) = asked else { return self.drop_frame(from, &"an answer to no spawn"); }; if let Some(unwatch) = self.settle_spawn(from, &reply, &asked) { // Lost with the connection, if it is: its loss forgets the // monitor there. let _ = transport::with_program(|t| t.send(from, Outbound::Signal(unwatch.encode()))); } } /// Hand `reply`, from `from`, to the asker of `asked`, if it still /// waits. For a monitored spawn, the asker's half of the monitor is /// made with it, under its lock (`dist::inbound::watch_spawned`): /// the new actor's `Down` may be the stream's next frame. The /// demonitor to send back when the new actor is monitored for an /// asker that is gone or gave up waiting, so `from` forgets it. fn settle_spawn(&self, from: &Node, reply: &SpawnReply, asked: &Asked) -> Option { let (asker, reply_tag) = (reply.asker as i64, reply.reply_tag as i64); let unwatch = asked .down .filter(|_| reply.result == SPAWNED) .map(|down| Tie { from: reply.asker, to: reply.serial, op: Op::Demonitor { tag: down as u64 }, }); if asked.abandoned { return unwatch; } let answer = match reply.result { SPAWNED => match (self.remote_pid(from, reply.serial), asked.down) { (Ok(pid), Some(down)) => { let found = || cell(std::ptr::null_mut(), 0, &[int(pid)]); let sched = self.sched(); let dist = &self.dist; let watched = dist::inbound::watch_spawned( sched, dist, asker, pid, down, reply_tag, found, ); return unwatch.filter(|_| !watched); } (Ok(pid), None) => cell(std::ptr::null_mut(), 0, &[int(pid)]), (Err(why), _) => { deliver_made( self.sched(), asker, reply_tag, failed(code::NOT_CONNECTED, why), ); return unwatch; } }, refused => failed(spawn_failure(refused), ""), }; deliver_made(self.sched(), asker, reply_tag, answer); None } /// Answer every lookup and spawn sent to `peer`, now lost. fn lost(&self, peer: &Node) { let mut lost: Vec<(i64, i64)> = { let mut lookups = lock(&self.lookups); let keys: Vec<_> = lookups .iter() .filter(|(_, l)| l.node == *peer) .map(|(k, _)| *k) .collect(); keys.iter().for_each(|k| { lookups.remove(k); }); keys }; lock(&self.spawns).retain(|k, asked| { let keep = asked.node != *peer; // One whose asker gave up waiting goes to nobody. if !keep && !asked.abandoned { lost.push(*k); } keep }); for (pid, tag) in lost { let answer = failed(code::NOT_CONNECTED, "the connection was lost"); deliver_made(self.sched(), pid, tag, answer); } } /// A link, unlink, monitor, demonitor or exit signal from `from` /// (`docs/wire-format.md`, *Signals*): to the local actor it names, /// from the remote pid of `from` it names. fn tie(&self, from: &Node, op: u8, body: &[u8]) { let Some(tie) = Tie::decode(op, body) else { return self.drop_frame(from, &"a malformed link, monitor or exit signal"); }; let sched = self.sched(); // Below 2^46 (checked): a remote pid, and a local one. let remote = match self.remote_pid(from, tie.from) { Ok(remote) => remote, Err(why) => return self.drop_frame(from, &why), }; let local = tie.to as i64; match tie.op { Op::Link => dist::inbound::link(sched, &self.dist, remote, local), Op::Exit(reason) => { dist::inbound::signal(sched, remote, local, &Signal::Linked(reason)) } Op::Monitor { tag } => { dist::inbound::monitor(sched, &self.dist, remote, tag as i64, local) } Op::Down { tag, reason } => { dist::inbound::down(sched, local, tag as i64, remote, &reason) } Op::Demonitor { tag } => dist::inbound::demonitor(sched, remote, tag as i64, local), Op::Unlink { id } => dist::inbound::unlink(sched, remote, local, || { send_tie(self, local, remote, Op::UnlinkAck { id }); }), Op::UnlinkAck { id } => dist::inbound::unlink_acked(sched, remote, local, id), Op::Kill => dist::inbound::signal(sched, remote, local, &Signal::Kill), Op::Stop => dist::inbound::signal(sched, remote, local, &Signal::Stop), } } /// Deliver `event()` to every live subscriber to `node`'s events, /// forgetting those that exited. Under `node_watchers`' lock. fn tell(&self, watchers: &mut Vec, node: &str, event: impl Fn() -> Value) { let sched = self.sched(); watchers.retain(|w| sched.exists(w.pid)); for w in watchers.iter().filter(|w| w.node == node) { deliver_made(sched, w.pid, w.tag, event()); } } } impl Inbound for State { fn node_up(&self, peer: &Node) { self.ready.pass(); let mut watchers = lock(&self.node_watchers); lock(&self.peers).insert( peer.name.clone(), Peer { incarnation: peer.incarnation, logged: false, }, ); lock(&self.failures).remove(&peer.name); self.tell(&mut watchers, &peer.name, || node_up_event(&peer.name)); } fn node_down(&self, peer: &Node) { self.ready.pass(); let mut watchers = lock(&self.node_watchers); let was_up = { let mut peers = lock(&self.peers); let up = peers.get(&peer.name).map(|p| p.incarnation) == Some(peer.incarnation); if up { peers.remove(&peer.name); } up }; self.lost(peer); let index = (self.dist.nodes.read()) .unwrap_or_else(PoisonError::into_inner) .find(&peer.name, peer.incarnation); // Not in the table: no pid of it was ever seen, nothing is tied. if let Some(index) = index { dist::inbound::node_down(self.sched(), &self.dist, index); } let why = lock(&self.last_closed) .take() .filter(|(label, _)| *label == peer.name) .map(|(_, why)| why) .unwrap_or_default(); if was_up { self.tell(&mut watchers, &peer.name, || { node_down_event(&peer.name, &why) }); } } fn message(&self, from: &Node, header: &MessageHeader, payload: &[u8]) { self.ready.pass(); let Some(me) = self.me() else { return; }; // The spawner's mailbox takes only the `Request`s this node // builds once it has checked their key and type: a message // naming its subject (a counter, easy to guess) would hand the // dispatcher an `Arg` whose descriptor is not its value's. if (header.serial as i64, header.tag as i64) == self.spawner { return self.drop_frame(from, &"a message to the spawner"); } let Some(decoded) = self.decode(from, me, header.type_hash, payload) else { return self.drop_frame(from, &"a message from a node that is not up"); }; match decoded { // The header's serial is below 2^46 (checked): a local pid. Ok(value) => dist::inbound::deliver( self.sched(), header.serial as i64, header.tag as i64, value, ), Err(e) => self.drop_frame(from, &e), } } fn signal(&self, from: &Node, body: &[u8]) { self.ready.pass(); match body.split_first() { Some((&LOOKUP, rest)) => self.lookup(from, rest), Some((&ANSWER, rest)) => self.answered(from, rest), Some((&op, rest)) if ties::is_tie(op) => self.tie(from, op, rest), Some((&op @ (SPAWN | SPAWN_LINKED | SPAWN_MONITORED), rest)) => { self.spawn_asked(from, op, rest) } Some((&SPAWN_ANSWER, rest)) => self.spawn_answered(from, rest), _ => self.drop_frame(from, &"an unknown signal"), } } fn drained(&self, _peer: &Node, waiters: &[Waiter]) { for waiter in waiters { dist::wake_sender(self.sched(), *waiter); } } fn closed(&self, peer: &str, reason: &Reason, hearsay: bool) { *lock(&self.last_closed) = Some((peer.to_owned(), reason.to_string())); if reason.routine() { return; } // Before its hello, a connection is labelled by its address: one // any host can open, at its own rate, so logged sparingly, and // remembered only by node name, for `whereis`'s error. A dial to // a name and address that only peers' lists gave: they choose // how many fail, so the same, and kept out of `failures`, // whose entries it would push out. let throttle = if hearsay { Some(&self.hearsay) } else { (!louise_rt_prims::wire::check_node_name(peer.as_bytes())) .then_some(&self.unauthenticated) }; if let Some(throttle) = throttle { let admitted = lock(throttle).admit(std::time::Instant::now()); if let Some(held) = admitted { let held = Throttle::held_back(held); eprintln!("louise: dist: {peer}: {reason}{held}"); } return; } eprintln!("louise: dist: {peer}: {reason}"); let mut failures = lock(&self.failures); if failures.len() >= MAX_FAILURES { failures.clear(); } failures.insert(peer.to_owned(), reason.to_string()); } } // ---- lookup frames (`docs/wire-format.md`, *Lookups*) ------------------------ /// A signal frame's first byte: a lookup, or its answer. const LOOKUP: u8 = 1; const ANSWER: u8 = 2; /// An answer's result. const FOUND: u8 = 0; const NO_NAME: u8 = 1; const OTHER_TYPE: u8 = 2; struct LookupRequest<'a> { /// The asking actor (a pid of the asking node) and its reply /// subject's tag: echoed in the answer. asker: u64, reply_tag: u64, /// The type the asker expects. hash: u64, name: &'a [u8], } impl LookupRequest<'_> { fn encode(&self) -> Vec { let mut out = Vec::with_capacity(26 + self.name.len()); out.push(LOOKUP); out.extend_from_slice(&self.asker.to_le_bytes()); out.extend_from_slice(&self.reply_tag.to_le_bytes()); out.extend_from_slice(&self.hash.to_le_bytes()); out.push(self.name.len() as u8); out.extend_from_slice(self.name); out } /// From the bytes after the frame's first. fn decode(body: &[u8]) -> Option> { let (fixed, name) = body.split_first_chunk::<25>()?; let word = |i: usize| u64::from_le_bytes(fixed[i..i + 8].try_into().expect("8 bytes")); let request = LookupRequest { asker: word(0), reply_tag: word(8), hash: word(16), name, }; (request.asker < MAX_PID_SERIAL && request.reply_tag < MAX_TAG && usize::from(fixed[24]) == name.len()) .then_some(request) } } struct LookupReply { asker: u64, reply_tag: u64, result: u8, /// Found: the registered subject's owner (a pid of the answering /// node) and tag; else 0. serial: u64, tag: u64, /// The registered type's hash (found, or another type); else 0. hash: u64, } impl LookupReply { const LEN: usize = 42; fn encode(&self) -> Vec { let mut out = Vec::with_capacity(Self::LEN); out.push(ANSWER); out.extend_from_slice(&self.asker.to_le_bytes()); out.extend_from_slice(&self.reply_tag.to_le_bytes()); out.push(self.result); out.extend_from_slice(&self.serial.to_le_bytes()); out.extend_from_slice(&self.tag.to_le_bytes()); out.extend_from_slice(&self.hash.to_le_bytes()); out } /// From the bytes after the frame's first. fn decode(body: &[u8]) -> Option { let body: &[u8; Self::LEN - 1] = body.try_into().ok()?; let word = |i: usize| u64::from_le_bytes(body[i..i + 8].try_into().expect("8 bytes")); let reply = LookupReply { asker: word(0), reply_tag: word(8), result: body[16], serial: word(17), tag: word(25), hash: word(33), }; (reply.asker < MAX_PID_SERIAL && reply.reply_tag < MAX_TAG && reply.result <= OTHER_TYPE && reply.serial < MAX_PID_SERIAL && reply.tag < MAX_TAG) .then_some(reply) } } // ---- spawn frames (`docs/wire-format.md`, *Spawns*) ---------------------------- /// A signal frame's first byte: a spawn request, its answer, a linked /// spawn request, a monitored one. const SPAWN: u8 = 0x20; const SPAWN_ANSWER: u8 = 0x21; const SPAWN_LINKED: u8 = 0x22; const SPAWN_MONITORED: u8 = 0x23; /// A spawn answer's result. const SPAWNED: u8 = 0; const NO_ENTRY: u8 = 1; const ENTRY_TYPE: u8 = 2; const NOT_SPAWNED: u8 = 3; /// The `std/dist` code of a refused spawn's result. fn spawn_failure(result: u8) -> i64 { match result { NO_ENTRY => code::UNKNOWN_ENTRY, ENTRY_TYPE => code::WRONG_TYPE, _ => code::REFUSED, } } /// How a spawn's new actor is tied to its asker: the request's op. #[derive(Clone, Copy, Debug, PartialEq)] enum SpawnTie { /// `spawn_on` (op `0x20`). Untied, /// `spawn_link_on` (op `0x22`). Link, /// `spawn_monitor_on` (op `0x23`): the asker's `Down` is due on /// this tag (below 2^62). Monitor(u64), } impl SpawnTie { /// From `std/dist`'s `Tie` (its constructor's index: `Untied`, /// `Linked`, `Monitored`) and the monitor's tag. `None` if out of /// range. fn from_parts(tie: i64, down: i64) -> Option { match tie { 0 => Some(SpawnTie::Untied), 1 => Some(SpawnTie::Link), 2 => u64::try_from(down) .ok() .filter(|d| *d < MAX_TAG) .map(SpawnTie::Monitor), _ => None, } } /// The op of a spawn request tied so. fn op(self) -> u8 { match self { SpawnTie::Untied => SPAWN, SpawnTie::Link => SPAWN_LINKED, SpawnTie::Monitor(_) => SPAWN_MONITORED, } } /// `std/dist`'s `Tie`, and the monitor's tag (0 if none). fn parts(self) -> (i64, i64) { match self { SpawnTie::Untied => (0, 0), SpawnTie::Link => (1, 0), SpawnTie::Monitor(down) => (2, down as i64), } } } struct SpawnRequest<'a> { /// The asking actor (a pid of the asking node) and its reply /// subject's tag: echoed in the answer. asker: u64, reply_tag: u64, /// The `@remote` function's key, its argument's type hash, and the /// argument (a message payload). key: u64, hash: u64, payload: &'a [u8], tie: SpawnTie, } impl SpawnRequest<'_> { fn encode(&self) -> Vec { let mut out = Vec::with_capacity(41 + self.payload.len()); out.push(self.tie.op()); out.extend_from_slice(&self.asker.to_le_bytes()); out.extend_from_slice(&self.reply_tag.to_le_bytes()); out.extend_from_slice(&self.key.to_le_bytes()); out.extend_from_slice(&self.hash.to_le_bytes()); if let SpawnTie::Monitor(down) = self.tie { out.extend_from_slice(&down.to_le_bytes()); } out.extend_from_slice(self.payload); out } /// From the bytes after the frame's first, `op`: a monitored /// spawn's fixed fields are 8 bytes longer, its down tag. fn decode(op: u8, body: &[u8]) -> Option> { let (fixed, rest) = body.split_first_chunk::<32>()?; let word = |i: usize| u64::from_le_bytes(fixed[i..i + 8].try_into().expect("8 bytes")); let (tie, payload) = match op { SPAWN => (SpawnTie::Untied, rest), SPAWN_LINKED => (SpawnTie::Link, rest), SPAWN_MONITORED => { let (down, payload) = rest.split_first_chunk::<8>()?; let down = u64::from_le_bytes(*down); (down < MAX_TAG).then_some((SpawnTie::Monitor(down), payload))? } _ => return None, }; let request = SpawnRequest { asker: word(0), reply_tag: word(8), key: word(16), hash: word(24), payload, tie, }; // A key is below 2^62, as a tag. (request.asker < MAX_PID_SERIAL && request.reply_tag < MAX_TAG && request.key < MAX_TAG) .then_some(request) } } struct SpawnReply { asker: u64, reply_tag: u64, result: u8, /// Spawned: the new actor (a pid of the answering node); else 0. serial: u64, } impl SpawnReply { const LEN: usize = 26; fn encode(&self) -> Vec { let mut out = Vec::with_capacity(Self::LEN); out.push(SPAWN_ANSWER); out.extend_from_slice(&self.asker.to_le_bytes()); out.extend_from_slice(&self.reply_tag.to_le_bytes()); out.push(self.result); out.extend_from_slice(&self.serial.to_le_bytes()); out } /// From the bytes after the frame's first. fn decode(body: &[u8]) -> Option { let body: &[u8; Self::LEN - 1] = body.try_into().ok()?; let word = |i: usize| u64::from_le_bytes(body[i..i + 8].try_into().expect("8 bytes")); let reply = SpawnReply { asker: word(0), reply_tag: word(8), result: body[16], serial: word(17), }; (reply.asker < MAX_PID_SERIAL && reply.reply_tag < MAX_TAG && reply.result <= NOT_SPAWNED && reply.serial < MAX_PID_SERIAL) .then_some(reply) } } // ---- hooks --------------------------------------------------------------------- /// The node, if this program started one and it still runs: the /// running transport's incarnation, not a node a program that ended /// left in [`NODE`] while a new one starts its own. fn running() -> Option> { let incarnation = transport::with_program(|t| t.me().incarnation)?; NODE.read() .unwrap_or_else(PoisonError::into_inner) .clone() .filter(|s| s.me.get().is_some_and(|me| me.incarnation == incarnation)) } /// The node `sched`'s program started, while it runs. fn current(sched: &Shared) -> Option> { running().filter(|s| std::ptr::eq(s.sched.0, sched)) } fn send_hook( ctx: *mut Ctx, owner: i64, tag: i64, wire: i64, message: Value, ) -> Result<(), CString> { send_message(ctx, owner, tag, wire, message).map_err(|why| dist::unsendable(&why)) } /// [`send_hook`]'s work; an error is why the message cannot be sent. fn send_message( ctx: *mut Ctx, owner: i64, tag: i64, wire: i64, message: Value, ) -> Result<(), String> { // Stopping: as to a dead actor. let Some(node) = running() else { return Ok(()); }; let Some(me) = node.me() else { return Ok(()); }; let (index, serial) = dist::parts(owner); let to = (node.dist.nodes.read()) .unwrap_or_else(PoisonError::into_inner) .get(index) .cloned(); let to = to.ok_or("a remote pid of no known node")?; let wire = u32::try_from(wire).map_err(|_| format!("no wire type {wire}"))?; let hash = node .registry .hash(wire) .ok_or_else(|| format!("no wire type {wire}"))?; // SAFETY: `message` is live (borrowed), a value of the subject's // message type, the type registered at `wire`. let payload = unsafe { wire::encode(&node.registry, wire, message, me, &node.dist.nodes) } .map_err(|e| e.to_string())?; let header = MessageHeader { incarnation: to.incarnation, serial: serial as u64, tag: tag as u64, type_hash: hash, payload_len: payload.len() as u32, }; let mut frame = Vec::with_capacity(HEADER_LEN + payload.len()); frame.extend_from_slice(&header.encode()); frame.extend_from_slice(&payload); let size = frame.len(); // At most once: as a message lost with a connection. let unsent = || transport::with_program(|t| t.count_unsent(&to.name)); let attempt = |frame, waiter| match transport::with_program(|t| t.queue(&to, frame, waiter)) { // Stopping: as to a dead actor. None | Some(Ok(())) => Try::Done(Ok(())), Some(Err((SendError::Full, frame))) => Try::Full(frame), Some(Err((SendError::NotConnected, _))) => { unsent(); Try::Done(Ok(())) } Some(Err((SendError::TooLarge, _))) => Try::Done(Err(format!( "a message of {size} bytes is over {}'s frame limit", to.name ))), Some(Err((SendError::Malformed, _))) => { Try::Done(Err("a malformed message frame".into())) } // Only signal frames need a capability flag. Some(Err((SendError::Unsupported, _))) => { Try::Done(Err("a message frame refused as a signal".into())) } }; let unwait = |waiter: Waiter| { transport::with_program(|t| t.unwait(&to, waiter)); }; // SAFETY: the hook runs on the running actor of `ctx`; nothing is // locked across the parking. let sent = unsafe { dist::send_parking(ctx, Outbound::Message(frame), attempt, unwait) }; sent.unwrap_or_else(|| { // The sender exited while parked: its frame is dropped. unsent(); Ok(()) }) } /// Queue a tie frame from the local `local` to the remote `remote`, on /// its node's ordered stream: whether that incarnation is up and takes /// the frame's op. One its runtime does not take (a demonitor, an /// unlink, its flag unset in the hello) is not sent: the caller acts /// as for a node that is not up. fn send_tie(node: &State, local: i64, remote: i64, op: Op) -> bool { let (index, serial) = dist::parts(remote); let to = (node.dist.nodes.read()) .unwrap_or_else(PoisonError::into_inner) .get(index) .cloned(); // A local pid past 2^46 cannot be named on another node (`dist`). let from = u64::try_from(local).ok().filter(|p| *p < MAX_PID_SERIAL); let (Some(to), Some(from)) = (to, from) else { return false; }; let tie = Tie { from, to: serial as u64, op, }; // Never `TooLarge`: a tie frame fits the smallest frame limit. transport::with_program(|t| t.send(&to, Outbound::Signal(tie.encode()))) == Some(Ok(())) } fn noconnection() -> Exit { Exit::Crashed("noconnection".into()) } fn noproc() -> Exit { Exit::Crashed("noproc".into()) } /// `me`'s link to `other`: its own half and the link frame, under its /// lock, so its exit cannot pass the frame. To a node that is not up, /// `me` gets the exit the node's loss would have given it, on its own /// thread (as `op_monitor`'s `noproc`: the local paths `dist::inbound` /// takes are those a local exit takes). fn link_hook(sched: &Shared, me: &Actor, other: i64) { let Some(node) = running() else { return; }; let send = || send_tie(&node, me.pid, other, Op::Link); if dist::outbound::link(&node.dist, me, other, send) == Some(false) { let lost = Signal::Linked(noconnection()); dist::inbound::signal(sched, other, me.pid, &lost); } } /// `me`'s monitor of `watched`: its own half, then the monitor frame. /// On a node that is not up, its `Down` at once, as the node's loss /// would have given it. Stopping: none, as for a dead pid. fn monitor_hook(sched: &Shared, me: &Actor, watched: i64, tag: i64) -> bool { let Some(node) = running() else { return false; }; if dist::outbound::monitor(sched, &node.dist, me, watched, tag) && !send_tie(&node, me.pid, watched, Op::Monitor { tag: tag as u64 }) { dist::inbound::down(sched, me.pid, tag, watched, &noconnection()); } true } /// `me`'s demonitor of `watched`: its own half, then, if it had the /// monitor, the demonitor frame. Dropped if the node is not up: its /// loss forgets the monitor there. Not sent to a node whose runtime /// does not take it (`send_tie`): the monitor stays there, and its /// `Down` is dropped here, `me` no longer watching. fn demonitor_hook(me: &Actor, watched: i64, tag: i64) { if dist::outbound::demonitor(me, watched, tag) && let Some(node) = running() { send_tie(&node, me.pid, watched, Op::Demonitor { tag: tag as u64 }); } } /// `me`'s unlink of `other`: its own half goes to unlinking, and the /// unlink frame is queued, under its lock. On a node that is not up, /// or while stopping, the half goes at once: no acknowledgement can /// come, and the node's loss ends the other side's. So it does on a /// node whose runtime does not take an unlink (`send_tie`), which /// keeps its half: an exit through it is ignored here, and the /// connection's loss ends it there. fn unlink_hook(me: &Actor, other: i64) { let node = running(); let id = node.as_ref().map_or(0, |n| n.dist.unlink_id()); dist::outbound::unlink(me, other, id, || { let unlink = Op::Unlink { id }; node.is_some_and(|n| send_tie(&n, me.pid, other, unlink)) }); } /// `kill`, `stop` and a link's exit; dropped if the node is not up. fn signal_hook(from: i64, to: i64, signal: &Signal) { let op = match signal { Signal::Kill => Op::Kill, Signal::Stop => Op::Stop, Signal::Linked(reason) => Op::Exit(reason.clone()), }; if let Some(node) = running() { send_tie(&node, from, to, op); } } /// The `Down` of `watched` for its remote `watcher`; dropped if the /// node is not up. fn down_hook(watched: i64, watcher: i64, tag: i64, reason: &Exit) { let op = Op::Down { tag: tag as u64, reason: reason.clone(), }; if let Some(node) = running() { send_tie(&node, watched, watcher, op); } } /// The local `pid` exited: unlist it from the nodes it was tied to. fn exit_hook(pid: i64, nodes: &[u16]) { if let Some(node) = running() { node.dist.untie(pid, nodes); } } // ---- externs --------------------------------------------------------------- /// Panic in the running actor with `why`. fn panic(ctx: *mut Ctx, why: &str) -> Value { let why = CString::new(format!("dist: {why}")).unwrap_or_default(); // SAFETY: the running actor's context; `why` is NUL-terminated. unsafe { crate::effects::tl_panic_str(ctx, why.as_ptr()) } } /// `std/dist.start`: start this node (see the module's documentation). /// `listen` and each seed's address are `ip:port`, `[ip6]:port`, and so /// is `advertise`, or empty (`Config::advertise`'s `None`); /// `seeds` a `List<(String, String)>` of node names and addresses; /// `table` and `schema_hash` are `std/wire`'s; `limits` the heartbeat /// and node-down delays in milliseconds, the largest message payload /// this node accepts, the message bytes queued per peer and the /// connections kept before a stranger is refused (`[cluster]`'s /// `max_message_bytes`, `outbound_queue_bytes` and `max_peers`), and /// the discovery (0 seeds, 1 mesh); /// `entries` `std/wire.entries`; `spawner` the subject of the actor /// that runs the spawns other nodes ask. `Ok(port)`, the port it /// listens on, or `Error(why)`. Reads the /// certificate files here, on the scheduler thread, once. /// /// # Safety /// `ctx` must be the running actor's context, the arguments live values /// of the types `std/dist` declares. #[unsafe(no_mangle)] #[allow(clippy::too_many_arguments)] pub unsafe extern "C" fn tl_dist_start( ctx: *mut Ctx, node: Value, cluster: Value, listen: Value, advertise: Value, seeds: Value, cert_file: Value, key_file: Value, ca_files: Value, table: Value, schema_hash: Value, limits: Value, entries: Value, spawner: Value, ) -> Value { // SAFETY: caller guarantees the context and the types. let started = unsafe { let (_, sched) = this(ctx); let address = |v: Value| { text(v) .parse::() .map_err(|_| format!("{:?} is not an address and port", text(v))) }; let pair = |v: Value| { let f = Block::fields_ptr(v as *mut Block); (*f, *f.add(1)) }; (|| { let mut config = Config::new(text(node), text(cluster), address(listen)?); if !text(advertise).is_empty() { config.advertise = Some(address(advertise)?); } for seed in list_items(seeds) { let (name, at) = pair(seed); config.seeds.push((text(name).to_owned(), address(at)?)); } config.cert_file = text(cert_file).to_owned(); config.key_file = text(key_file).to_owned(); config.ca_files = list_items(ca_files).map(|f| text(f).to_owned()).collect(); config.schema_hash = u64::from_str_radix(text(schema_hash), 16) .map_err(|_| "a malformed schema hash".to_string())?; let limit = |i: usize, what: &str| { // A big integer saturates (`Config::check` bounds it). let v = crate::int::saturating(*Block::fields_ptr(limits as *mut Block).add(i)); u64::try_from(v).map_err(|_| format!("{what} must not be negative")) }; config.heartbeat_ms = limit(0, "heartbeat_ms")?; config.node_down_after_ms = limit(1, "node_down_after_ms")?; // As `[cluster]` bounds it. The frame limit is a message // frame's of the largest payload: its kind, its header and // the payload. let message = limit(2, "max_message_bytes")?; if !(u64::from(MIN_FRAME)..=u64::from(MAX_PAYLOAD)).contains(&message) { return Err(format!( "max_message_bytes must be between {MIN_FRAME} and {MAX_PAYLOAD}" )); } config.max_frame = (message + 1 + HEADER_LEN as u64) as u32; config.max_queue = usize::try_from(limit(3, "outbound_queue_bytes")?) .map_err(|_| "outbound_queue_bytes is too large".to_string())?; // `Config::check` bounds it as `[cluster]` does. config.max_peers = usize::try_from(limit(4, "max_peers")?).unwrap_or(usize::MAX); config.mesh = match limit(5, "discovery")? { 0 => false, 1 => true, _ => return Err("discovery must be 0 (seeds) or 1 (mesh)".into()), }; // `Entry(key, name, descriptor, hash)`. let entries = list_items(entries) .map(|e| { let f = Block::fields_ptr(e as *mut Block); let field = |i: usize| text(*f.add(i)).to_owned(); (int_get(*f), field(1), field(2), field(3)) }) .collect(); let spawner = crate::process::subject_parts(spawner); start(sched, config, text(table), entries, spawner) })() }; match started { Ok(port) => crate::values::ok(ctx, int(i64::from(port))), Err(why) => crate::values::error(ctx, &why), } } /// A `std/wire.Entry`: key, qualified name, descriptor, hash in hex. type EntryParts = (i64, String, String, String); fn start( sched: &Shared, config: Config, table: &str, entries: Vec, spawner: (i64, i64), ) -> Result { let registry = Registry::new(table).map_err(|e| format!("the program's wire types: {e}"))?; let entries = remote_entries(®istry, entries)?; let state = Arc::new(State { sched: Sched(sched), dist: Dist::default(), registry, me: OnceLock::new(), names: Mutex::default(), peers: Mutex::default(), quotas: Mutex::default(), lookups: Mutex::default(), entries, spawner, spawns: Mutex::default(), failures: Mutex::default(), last_closed: Mutex::default(), unauthenticated: Mutex::default(), hearsay: Mutex::default(), node_watchers: Mutex::default(), refused: AtomicU64::new(0), ready: Gate::default(), }); transport::start_program(sched, config, state.clone())?; // What peers sent meanwhile is handled once the hooks are in. let _ready = OpenOnDrop(&state.ready); let (me, port) = transport::with_program(|t| (t.me().clone(), t.local_addr().port())) .ok_or("distribution stopped")?; let _ = state.me.set(me); *NODE.write().unwrap_or_else(PoisonError::into_inner) = Some(state.clone()); dist::install(&HOOKS); Ok(port) } /// The program's `@remote` functions, their arguments' types /// registered. The compiler computed each hash from the same table: a /// different one here is a bug. fn remote_entries( registry: &Registry, entries: Vec, ) -> Result, String> { let mut by_key = HashMap::with_capacity(entries.len()); for (key, name, descriptor, hash) in entries { let r = registry .register(&descriptor) .map_err(|e| format!("internal error: `{name}`'s argument: {e}"))?; if format!("{:016x}", r.hash) != hash { return Err(format!( "internal error: `{name}`'s argument hashes to {:016x}, {hash} when compiled", r.hash )); } let entry = RemoteEntry { descriptor, wire: r.index, hash: r.hash, }; by_key.insert(key, entry); } Ok(by_key) } /// Register `desc`, a `Wire` dictionary: its hash. A collision stops /// the program (ADR 0072, *Settled*): `Err` is the panic's message. fn register_type(node: &State, desc: &str) -> Result { node.registry.register(desc).map_err(|e| e.to_string()) } /// `std/dist.register`: `name` (with `desc`, its message type's /// descriptor) now names `subject`, a local one. A code: `OK`, or why /// not (`NOT_STARTED`, `TAKEN` by a live actor, `NOT_LOCAL`). /// /// # Safety /// `ctx` must be the running actor's context; `name` and `desc` live /// strings, `subject` a live subject. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_register( ctx: *mut Ctx, name: Value, desc: Value, subject: Value, ) -> Value { // SAFETY: caller guarantees the context and the types. let (sched, name, desc, (pid, tag), remote) = unsafe { let (_, sched) = this(ctx); let parts = crate::process::subject_parts(subject); let remote = crate::process::subject_wire(subject).is_some(); (sched, text(name), text(desc), parts, remote) }; let Some(node) = current(sched) else { return int(code::NOT_STARTED); }; if name.len() > MAX_NAME { return panic(ctx, &format!("a name is at most {MAX_NAME} bytes")); } if remote || is_remote(pid) { return int(code::NOT_LOCAL); } let hash = match register_type(&node, desc) { Ok(r) => r.hash, Err(why) => return panic(ctx, &why), }; let mut names = lock(&node.names); if let Some(n) = names.get(name) && (n.pid, n.tag) != (pid, tag) && sched.exists(n.pid) { return int(code::TAKEN); } names.insert(name.to_owned(), Named { pid, tag, hash }); int(code::OK) } /// `std/dist.whereis`: ask `node` which subject `name` names, for /// messages of `desc`'s type. The answer comes on the running actor's /// subject `tag`: at once if this node knows it (its own names, not /// started, not connected), else when `node` answers. /// /// # Safety /// `ctx` must be the running actor's context; `node`, `name` and /// `desc` live strings. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_whereis( ctx: *mut Ctx, tag: Value, node: Value, name: Value, desc: Value, ) -> Value { // SAFETY: caller guarantees the context and the types. let (asker, sched, node_name, name, desc) = unsafe { let (a, sched) = this(ctx); (a.pid, sched, text(node), text(name), text(desc)) }; let reply_tag = int_get(tag); let answer = |v: Value| { deliver_made(sched, asker, reply_tag, v); UNIT }; let Some(state) = current(sched) else { return answer(failed(code::NOT_STARTED, "")); }; if name.len() > MAX_NAME { return panic(ctx, &format!("a name is at most {MAX_NAME} bytes")); } let hash = match register_type(&state, desc) { Ok(r) => r.hash, Err(why) => return panic(ctx, &why), }; let Some(me) = state.me() else { return answer(failed(code::NOT_STARTED, "")); }; if node_name == me.name { return answer(match state.named(name) { None => failed(code::NO_NAME, ""), Some((_, _, h)) if h != hash => failed(code::WRONG_TYPE, ""), // A local subject is constructor 0, `Subject(owner, tag)`. Some((pid, tag, _)) => { let null = std::ptr::null_mut(); cell(null, 0, &[cell(null, 0, &[int(pid), int(tag)])]) } }); } let peer = transport::with_program(|t| t.peers().into_iter().find(|p| p.name == node_name)) .flatten(); let Some(peer) = peer else { let why = lock(&state.failures) .get(node_name) .cloned() .unwrap_or_default(); return answer(failed(code::NOT_CONNECTED, &why)); }; // Before sending: the answer may come at once. A node down after // this answers it (`State::lost`); one down before, the send fails. lock(&state.lookups).insert( (asker, reply_tag), Lookup { node: peer.clone(), hash, }, ); let request = LookupRequest { asker: asker as u64, reply_tag: reply_tag as u64, hash, name: name.as_bytes(), }; let sent = transport::with_program(|t| t.send(&peer, Outbound::Signal(request.encode()))); if sent != Some(Ok(())) && lock(&state.lookups).remove(&(asker, reply_tag)).is_some() { return answer(failed(code::NOT_CONNECTED, "")); } UNIT } /// `std/dist.monitor_node`: tell the running actor, on its subject /// `tag`, whether `node` is up now, then each time it comes up or goes /// down, until the actor exits. This node is up while it runs, and is /// not followed; before `start`, every node is down, and nothing is /// kept: there is no node to follow it. /// /// # Safety /// `ctx` must be the running actor's context; `node` a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_monitor_node(ctx: *mut Ctx, tag: Value, node: Value) -> Value { // SAFETY: caller guarantees the context and the type. let (pid, sched, name) = unsafe { let (a, sched) = this(ctx); (a.pid, sched, text(node)) }; let tag = int_get(tag); let Some(state) = current(sched) else { deliver_made(sched, pid, tag, node_down_event(name, "not started")); return UNIT; }; if state.me().is_some_and(|me| me.name == name) { deliver_made(sched, pid, tag, node_up_event(name)); return UNIT; } let mut watchers = lock(&state.node_watchers); watchers.retain(|w| sched.exists(w.pid)); let event = if lock(&state.peers).contains_key(name) { node_up_event(name) } else { let why = lock(&state.failures).get(name).cloned().unwrap_or_default(); node_down_event(name, &why) }; deliver_made(sched, pid, tag, event); watchers.push(NodeWatcher { pid, tag, node: name.to_owned(), }); UNIT } /// `std/dist.spawn_on` (`spawn_link_on`, `spawn_monitor_on`, as `tie` /// says): ask `node` to start the `@remote` function `key` on `args`, /// a value of `desc`'s type (linked to the running actor, or monitored /// by it on its subject `down`). The answer comes on the running /// actor's subject `tag`: at once if this node knows it (not started, /// not connected, no such entry, another argument type, a linked or /// monitored spawn `node`'s runtime does not take), else when /// `node`'s spawner or `node` answers. This node's own name goes to its /// own spawner, as a peer's request does. An argument the program /// cannot encode panics, as a message does; while `node`'s queue is /// full, the actor parks, as a sender does. A monitored spawn is /// remembered until answered, even when asked of this node, so an /// asker that stops waiting can give it up (`tl_dist_spawn_abandon`). /// /// # Safety /// `ctx` must be the running actor's context; `node` and `desc` live /// strings, `key` an `Int`, `args` a live value of `desc`'s type /// (borrowed), `tie` a `std/dist.Tie`, `down` an `Int`. #[unsafe(no_mangle)] #[allow(clippy::too_many_arguments)] pub unsafe extern "C" fn tl_dist_spawn( ctx: *mut Ctx, tag: Value, node: Value, key: Value, desc: Value, args: Value, tie: Value, down: Value, ) -> Value { // SAFETY: caller guarantees the context and the types. let (asker, sched, node_name, desc) = unsafe { let (a, sched) = this(ctx); (a.pid, sched, text(node), text(desc)) }; let (reply_tag, key) = (int_get(tag), int_get(key)); let answer = |v: Value| { deliver_made(sched, asker, reply_tag, v); UNIT }; let Some(tie) = SpawnTie::from_parts(int_get(tie), int_get(down)) else { return panic(ctx, "a spawn's tie or down tag is out of range"); }; let Some(state) = current(sched) else { return answer(failed(code::NOT_STARTED, "")); }; // The compiler makes a `Remote` from the program's own `@remote` // function of argument `a`, but `a` is phantom: one that came off // the wire may name any key, and be typed for any argument. Checked // here, before anything is encoded or sent. let Some(entry) = state.entries.get(&key) else { return answer(failed(code::UNKNOWN_ENTRY, "")); }; if entry.descriptor != desc { return answer(failed(code::WRONG_TYPE, "")); } let Some(me) = state.me() else { return answer(failed(code::NOT_STARTED, "")); }; let peer = if node_name == me.name { None } else { let peer = transport::with_program(|t| t.peers().into_iter().find(|p| p.name == node_name)) .flatten(); let Some(peer) = peer else { let why = lock(&state.failures) .get(node_name) .cloned() .unwrap_or_default(); return answer(failed(code::NOT_CONNECTED, &why)); }; // A runtime that does not take this op would drop it: refused // here, before anything is pending. if transport::with_program(|t| t.lacks(&peer, tie.op())).unwrap_or(false) { return answer(failed(code::UNSUPPORTED, "")); } Some(peer) }; // SAFETY: `args` is live, a value of the entry's argument type, // registered at `entry.wire`. let encoded = unsafe { wire::encode(&state.registry, entry.wire, args, me, &state.dist.nodes) }; let payload = match encoded { Ok(payload) => payload, Err(e) => return panic(ctx, &e.to_string()), }; let request = SpawnRequest { asker: asker as u64, reply_tag: reply_tag as u64, key: key as u64, hash: entry.hash, payload: &payload, tie, }; let asked = |node: &Node| Asked { node: node.clone(), down: match tie { SpawnTie::Monitor(down) => Some(down as i64), _ => None, }, abandoned: false, }; let Some(peer) = peer else { // Before the spawner can answer. if matches!(tie, SpawnTie::Monitor(_)) { lock(&state.spawns).insert((asker, reply_tag), asked(me)); } return match state.spawn(me, &request, asker) { Ok(()) => UNIT, Err(result) => { lock(&state.spawns).remove(&(asker, reply_tag)); answer(failed(spawn_failure(result), "")) } }; }; // Before sending, as a lookup. lock(&state.spawns).insert((asker, reply_tag), asked(&peer)); let frame = request.encode(); let size = frame.len(); // Its payload counts against the queue's cap as a message's does: // the asker parks while the queue is full (`send_hook`). let lost = std::cell::Cell::new(None); let attempt = |frame, waiter| match transport::with_program(|t| t.queue(&peer, frame, waiter)) { Some(Ok(())) => Try::Done(Ok(())), Some(Err((SendError::Full, frame))) => Try::Full(frame), Some(Err((SendError::TooLarge, _))) => Try::Done(Err(format!( "a spawn request of {size} bytes is over {}'s frame limit", peer.name ))), // The node came back as the same incarnation, its runtime // without the op, since it was checked. Some(Err((SendError::Unsupported, _))) => { lost.set(Some(code::UNSUPPORTED)); Try::Done(Ok(())) } // Stopping, or the node is down: not connected. _ => { lost.set(Some(code::NOT_CONNECTED)); Try::Done(Ok(())) } }; let unwait = |waiter: Waiter| { transport::with_program(|t| t.unwait(&peer, waiter)); }; // SAFETY: the running actor of `ctx`; nothing is locked across the // parking. let sent = unsafe { dist::send_parking(ctx, Outbound::Request(frame), attempt, unwait) }; let asked = || lock(&state.spawns).remove(&(asker, reply_tag)).is_some(); match (sent, lost.get()) { (Some(Ok(())), None) => UNIT, // The node's loss answered it already, if it did not. (Some(Ok(())), Some(code)) if asked() => answer(failed(code, "")), (Some(Ok(())), Some(_)) => UNIT, (Some(Err(why)), _) => { asked(); panic(ctx, &why) } // The asker exited while parked: nobody waits for the answer. (None, _) => { asked(); UNIT } } } /// `std/dist.spawn_monitor_on` timed out waiting for the answer to its /// spawn on its subject `tag`: whether it gave the spawn up. If so, the /// answer goes to nobody, and the new actor is not monitored (the /// asker's node sends a demonitor back once the answer comes). If not, /// the answer came meanwhile: it is in the running actor's mailbox, or /// about to be. /// /// # Safety /// `ctx` must be the running actor's context; `tag` an `Int`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_spawn_abandon(ctx: *mut Ctx, tag: Value) -> Value { // SAFETY: caller guarantees the context. let (a, sched) = unsafe { this(ctx) }; // Stopped: no answer will come. let Some(state) = current(sched) else { return int(1); }; int(i64::from(state.abandon_spawn(a.pid, int_get(tag)))) } /// `std/dist`'s spawner starts the body the dispatcher gave for the /// spawn `asker` asked on `tag`, and answers it: `result` is /// `Ok(body)` or why the dispatcher refused. A local `asker` is this /// node's own `spawn_on`; a remote one gets a spawn answer, lost if its /// node is. Not linked, the new actor's parent is the spawner, as a /// `process.spawn` of it would be. /// /// Linked (`spawn_link_on`), to a local asker: as `spawn_link` from /// it, so an asker that already exited stops the new actor at once. /// To a remote asker, in this order: the new actor is made, not /// scheduled; its half of the link is made, listed under the asker's /// node, and the link frame queued, under its lock; it is scheduled; /// the answer is queued. Its exit then always follows the link frame /// on the asker's node's ordered stream, and the answer follows both; /// a loss of that node once the frame is queued finds it. An asker gone by the time the /// link frame arrives answers it with `noproc`, and the new actor dies /// of it; with the asker's node not up, it dies of `noconnection`. /// /// Monitored (`spawn_monitor_on`): see [`State::spawn_monitored`]. /// /// # Safety /// `ctx` must be the running actor's context; `asker` a `Pid`, `tag` /// an `Int`, `tie` a `std/dist.Tie`, `down` an `Int`, `result` a live /// `Result` whose `Ok` holds an actor body /// (a `send fn() -> ()` of `std/wire.dispatch`). Consumes them all. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_spawn_for( ctx: *mut Ctx, asker: Value, tag: Value, tie: Value, down: Value, result: Value, ) -> Value { // SAFETY: caller guarantees the context. let (spawner, sched) = unsafe { this(ctx) }; let Some(state) = current(sched) else { // SAFETY: owned. unsafe { drop_value(ctx, result) }; return UNIT; }; let (asker, reply_tag) = (int_get(asker), int_get(tag)); // Made by `State::spawn` from a request it decoded. let tie = SpawnTie::from_parts(int_get(tie), int_get(down)).unwrap_or(SpawnTie::Untied); let monitored = matches!(tie, SpawnTie::Monitor(_)); let answer = |result: u8, pid: i64| state.spawn_answer(asker, reply_tag, monitored, result, pid); // SAFETY: `Ok(body)` is constructor 0, `Error(why)` 1; `why` is // `UnknownEntry` (0) or `WrongType` (1), an immediate. The body is // taken out of the block, which is dropped. let body = unsafe { let b = result as *mut Block; let field = *Block::fields_ptr(b); if (*b).header.tag != 0 { drop_value(ctx, result); answer( if int_get(field) == 0 { NO_ENTRY } else { ENTRY_TYPE }, 0, ); return UNIT; } let body = dup_value(field); drop_value(ctx, result); body }; // SAFETY: the running actor's context; `body` is owned. let body = match unsafe { crate::send::transfer(ctx, body) } { Ok(body) => body, Err((crate::send::NotSendable(why), body)) => { answer(NOT_SPAWNED, 0); // SAFETY: as above; `why` is NUL-terminated. return unsafe { drop_value(ctx, body); crate::effects::tl_panic_str(ctx, why.as_ptr()) }; } }; let pid = match (tie, is_remote(asker)) { (SpawnTie::Untied, _) => { spawn_program_tied(sched, body, spawner.pid, ParentTie::None).0 } (SpawnTie::Link, false) => spawn_program_tied(sched, body, asker, ParentTie::Link).0, (SpawnTie::Link, true) => state.spawn_linked(body, asker), // Answered there, in its order. (SpawnTie::Monitor(down), _) => { state.spawn_monitored(body, asker, reply_tag, down as i64); return UNIT; } }; answer(SPAWNED, pid); UNIT } impl State { /// Spawn `body` (owned) linked to the remote `asker`: see /// [`tl_dist_spawn_for`]. Its pid. fn spawn_linked(&self, body: Value, asker: i64) -> i64 { let sched = self.sched(); let mut linked = None; let pid = spawn_program_before(sched, body, |child| { let send = || send_tie(self, child, asker, Op::Link); linked = Some(dist::outbound::link_spawned( sched, &self.dist, child, asker, send, )); }); match linked.flatten() { Some(true) => {} // The asker's node is not up: as its loss would. Some(false) => { let lost = Signal::Linked(noconnection()); dist::inbound::signal(sched, asker, pid, &lost); } // Already gone (a peer killed it by its serial), unlinked: // the asker links and is told so, as by a link to an actor // that is gone. None => { send_tie(self, pid, asker, Op::Link); send_tie(self, pid, asker, Op::Exit(noproc())); } } pid } /// Spawn `body` (owned) monitored by `asker`, its `Down` due on /// `down`, and answer the spawn it asked on `reply_tag`. /// /// A local asker: as `spawn_monitor` from it, unless it gave up /// waiting (`tl_dist_spawn_abandon`); then the new actor is not /// monitored and the answer goes to nobody. /// /// A remote asker, in this order: the new actor is made, not /// scheduled; the monitor is made, listed under the asker's node, /// and the answer queued, under its lock /// (`dist::outbound::monitor_spawned`); it is scheduled. So the /// answer reaches the asker's node ahead of the actor's `Down`, /// and the asker's half of the monitor is there for it /// ([`State::settle_spawn`]). One a peer killed by its serial /// before its monitor is made is answered, then reported gone /// (`noproc`), as a monitor of an actor that is gone. fn spawn_monitored(&self, body: Value, asker: i64, reply_tag: i64, down: i64) { let sched = self.sched(); if !is_remote(asker) { let waiting = lock(&self.spawns) .remove(&(asker, reply_tag)) .is_some_and(|asked| !asked.abandoned); if waiting { let pid = spawn_program_monitored(sched, body, asker, down); let answer = cell(std::ptr::null_mut(), 0, &[int(pid)]); deliver_made(sched, asker, reply_tag, answer); } else { spawn_program_tied(sched, body, self.spawner.0, ParentTie::None); } return; } // A pid past 2^46 cannot be named on another node (`dist`): // answered as not spawned, not monitored. let nameable = |pid: i64| u64::try_from(pid).is_ok_and(|p| p < MAX_PID_SERIAL); let mut gone = false; let pid = spawn_program_before(sched, body, |child| { if nameable(child) { let send = || self.answer_remote(asker, reply_tag, SPAWNED, child); let made = dist::outbound::monitor_spawned( sched, &self.dist, child, asker, down, send, ); gone = made.is_none(); } }); if !nameable(pid) { self.answer_remote(asker, reply_tag, NOT_SPAWNED, 0); } else if gone { self.answer_remote(asker, reply_tag, SPAWNED, pid); let tag = down as u64; send_tie( self, pid, asker, Op::Down { tag, reason: noproc(), }, ); } } /// The asker `asker` gives up waiting for the monitored spawn it /// asked on `reply_tag` (`tl_dist_spawn_abandon`): whether it did, /// or it was answered meanwhile. One asked of another node is /// marked, so that its answer goes to nobody and the new actor is /// demonitored there ([`State::settle_spawn`]); one asked of this /// node is forgotten, so that the spawner, which looks it up, /// answers nobody (`spawn_monitored`, `spawn_answer`). No node's /// loss forgets that one: if the spawner died with the request /// queued, it would stay (SR3-3). fn abandon_spawn(&self, asker: i64, reply_tag: i64) -> bool { let me = self.me().cloned(); let mut spawns = lock(&self.spawns); let key = (asker, reply_tag); match spawns.get_mut(&key) { Some(asked) if me.as_ref() == Some(&asked.node) => { spawns.remove(&key); true } Some(asked) => { asked.abandoned = true; true } // Taken by what answers it, which delivers it next. None => false, } } /// Answer the spawn `asker` asked on `tag` with `result`, and the /// new actor's `pid` if spawned. A local asker gets a monitored /// spawn's answer only while it is pending: one that gave up /// waiting (`abandon_spawn`) gets nothing. fn spawn_answer(&self, asker: i64, reply_tag: i64, monitored: bool, result: u8, pid: i64) { if !is_remote(asker) { let asked = lock(&self.spawns).remove(&(asker, reply_tag)); if monitored && asked.is_none_or(|a| a.abandoned) { return; } let answer = match result { SPAWNED => cell(std::ptr::null_mut(), 0, &[int(pid)]), refused => failed(spawn_failure(refused), ""), }; deliver_made(self.sched(), asker, reply_tag, answer); return; } self.answer_remote(asker, reply_tag, result, pid); } /// Queue the answer to the spawn the remote `asker` asked on /// `reply_tag`: whether it was queued (its node is up). fn answer_remote(&self, asker: i64, reply_tag: i64, result: u8, pid: i64) -> bool { let (index, serial) = dist::parts(asker); let node = (self.dist.nodes.read()) .unwrap_or_else(PoisonError::into_inner) .get(index) .cloned(); // A pid past 2^46 cannot be named on another node (`dist`). let pid = u64::try_from(pid).ok().filter(|p| *p < MAX_PID_SERIAL); let (result, pid) = match pid { Some(pid) => (result, pid), None => (NOT_SPAWNED, 0), }; let Some(node) = node else { return false; }; let reply = SpawnReply { asker: serial as u64, reply_tag: reply_tag as u64, result, serial: pid, }; // Lost with the connection, if it is: the asker is told so. transport::with_program(|t| t.send(&node, Outbound::Signal(reply.encode()))) == Some(Ok(())) } } /// `std/dist.peers`: every node this node knows (a seed, a node it was /// connected to, a node it sent to), by name, as `std/dist`'s `Peer` /// (`Peer(node, incarnation, state, rtt_us, queued_bytes, sent, /// received, unsent, parked, dropped)`, `state` being `Up` or /// `Down(why)`); `[]` before `start`. A snapshot, read without waiting /// for the transport. /// /// # Safety /// `ctx` must be the running actor's context. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_peers(ctx: *mut Ctx) -> Value { // SAFETY: caller guarantees the context. let (_, sched) = unsafe { this(ctx) }; let Some(state) = current(sched) else { return list(ctx, std::iter::empty()); }; let report = transport::with_program(|t| t.report()).unwrap_or_default(); let failures = lock(&state.failures); // Counts stay small `Int`s. let count = |n: u64| int(n.min((1 << 62) - 1) as i64); let some = |v: Value| cell(ctx, 1, &[v]); let peers: Vec = report .iter() .map(|r| { let incarnation = r .incarnation .map_or(int(0), |i| some(string(ctx, &format!("{i:016x}")))); let status = if r.up { int(0) } else { let why = failures.get(&r.node).map_or("", String::as_str); cell(ctx, 1, &[string(ctx, why)]) }; let fields = [ string(ctx, &r.node), incarnation, status, r.rtt_us.map_or(int(0), |t| some(count(t))), count(r.queued as u64), count(r.sent), count(r.received), count(r.unsent), count(r.parked), count(r.dropped), ]; cell(ctx, 0, &fields) }) .collect(); list(ctx, peers.into_iter()) } /// `std/dist.connect`: stay connected to `node` at `addr` (`ip:port`, /// `[ip6]:port`) from now on, as to a seed ([`transport::Transport:: /// connect`]). A code: `OK` (this node's own name too, which does /// nothing), `NOT_STARTED`, or `INVALID`, not a node name or an /// address. /// /// # Safety /// `ctx` must be the running actor's context; `node` and `addr` live /// strings. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dist_connect(ctx: *mut Ctx, node: Value, addr: Value) -> Value { // SAFETY: caller guarantees the context and the types. let (sched, name, addr) = unsafe { let (_, sched) = this(ctx); (sched, text(node), text(addr)) }; let Some(state) = current(sched) else { return int(code::NOT_STARTED); }; let Ok(addr) = addr.parse::() else { return int(code::INVALID); }; if !louise_rt_prims::wire::check_node_name(name.as_bytes()) { return int(code::INVALID); } if state.me().is_some_and(|me| me.name == name) { return int(code::OK); } match transport::with_program(|t| t.connect(name, addr)) { Some(()) => int(code::OK), None => int(code::NOT_STARTED), } } #[cfg(test)] mod tests { use super::*; use louise_rt_prims::wire::write_uvarint; /// A node of no running program, with the types `()` and `Pid`. fn state(sched: &Shared) -> State { let state = State { sched: Sched(sched), dist: Dist::default(), registry: Registry::new("").expect("an empty table"), me: OnceLock::new(), names: Mutex::default(), peers: Mutex::default(), quotas: Mutex::default(), lookups: Mutex::default(), entries: HashMap::new(), spawner: (0, 0), spawns: Mutex::default(), failures: Mutex::default(), last_closed: Mutex::default(), unauthenticated: Mutex::default(), hearsay: Mutex::default(), node_watchers: Mutex::default(), refused: AtomicU64::new(0), ready: Gate::default(), }; state.ready.open(); let _ = state.me.set(Node { name: "a.example".into(), incarnation: 1, }); state } /// A message frame of `()` to actor 1 of `state`, whose node list /// names `n` nodes `{prefix}-{i}.example`. fn naming(state: &State, prefix: &str, n: u32) -> (MessageHeader, Vec) { let mut payload = Vec::new(); write_uvarint(&mut payload, u64::from(n)); for i in 0..n { let name = format!("{prefix}-{i}.example"); write_uvarint(&mut payload, name.len() as u64); payload.extend_from_slice(name.as_bytes()); payload.extend_from_slice(&1u64.to_le_bytes()); } payload.push(0); let header = MessageHeader { incarnation: 1, serial: 1, tag: 1, type_hash: state.registry.register("u").expect("()").hash, payload_len: payload.len() as u32, }; (header, payload) } /// How many entries the node table holds. fn entries(state: &State) -> usize { let nodes = state.dist.nodes.read().expect("the table"); (0..=u16::MAX) .take_while(|&i| nodes.get(i).is_some()) .count() } /// One peer name adds [`PEER_NODES`] node-table entries for the /// whole run: reconnecting (a fresh budget per connection, before) /// or restarting (each incarnation an entry, uncounted, before) let /// one peer fill the table in 64 connections (#404's security /// review, SEC-5). #[test] fn a_reconnecting_peer_adds_its_quota_of_nodes_at_most() { let _turn = crate::sched::test_turn(); let sched = Shared::new(1); let state = state(&sched); let link = |from| { Tie { from, to: 1, op: Op::Link, } .encode() }; for i in 0..64 { let b = Node { name: "b.example".into(), incarnation: 100 + i, }; state.node_up(&b); // A link from its actor 1 (its own incarnation's entry), // then a frame naming 128 new nodes: 8,256 entries in all. state.signal(&b, &link(1)); let (header, payload) = naming(&state, &format!("c{i}"), PEER_NODES / 8); state.message(&b, &header, &payload); state.node_down(&b); } // 64 incarnations and 7 frames' 896 nodes; past those, each // frame is refused whole. let used = entries(&state); assert_eq!(used, 64 + 7 * 128); assert!(used <= PEER_NODES as usize); // Another peer still has its own. let c = Node { name: "c.example".into(), incarnation: 7, }; state.node_up(&c); state.signal(&c, &link(1)); let (header, payload) = naming(&state, "d", PEER_NODES - 1); state.message(&c, &header, &payload); assert_eq!(entries(&state), used + PEER_NODES as usize); state.node_down(&c); } /// What peers send waits until the node's hooks are installed: /// `start` starts the transport first, and a tie to an actor gone, /// or one whose actor exits, handled before the install lost the /// answer a hook sends (#404's second security review, SR2-7). #[test] fn peers_frames_wait_for_the_hooks() { let _turn = crate::sched::test_turn(); let sched = Shared::new(1); let state = state(&sched); let state = State { ready: Gate::default(), ..state }; let b = Node { name: "b.example".into(), incarnation: 1, }; std::thread::scope(|scope| { let relay = scope.spawn(|| state.node_up(&b)); std::thread::sleep(std::time::Duration::from_millis(50)); assert!(!relay.is_finished(), "handled before the install"); assert!(lock(&state.peers).is_empty()); state.ready.open(); relay.join().expect("the relay"); }); assert!(lock(&state.peers).contains_key("b.example")); } /// A dial that failed to an address only peers' lists gave /// (*hearsay*): the peers choose the names, and how many fail, so /// it stays out of `failures` (whose 256 entries it would push /// out) and is logged sparingly. #404's second security review, /// SR2-3: each was a line, and an entry. #[test] fn failed_dials_peers_listed_are_not_failures() { let _turn = crate::sched::test_turn(); let sched = Shared::new(1); let state = state(&sched); let refused = Reason::Closed("connection refused".into()); for i in 0..2 * MAX_FAILURES { state.closed(&format!("j{i}.example"), &refused, true); } assert!(lock(&state.failures).is_empty()); // Logged once, the others held back for the period. let now = std::time::Instant::now(); assert_eq!(lock(&state.hearsay).admit(now), None); // A seed's, or a confirmed node's, is one. state.closed("b.example", &refused, false); let failures = lock(&state.failures); assert_eq!(failures.keys().collect::>(), ["b.example"]); } /// #423: the ops added since stage 1 each need their capability /// flag in the peer's hello, which the transport checks: no frame /// of them goes to a runtime that would drop it. The others go to /// every peer. #[test] fn ops_since_stage_one_need_the_peers_flag() { use transport::needs; for (tie, flagged) in [ (SpawnTie::Untied, false), (SpawnTie::Link, true), (SpawnTie::Monitor(1), true), ] { let request = SpawnRequest { asker: 1, reply_tag: 2, key: 3, hash: 4, payload: &[0], tie, }; assert_eq!(request.encode()[0], tie.op()); assert_eq!(needs(tie.op()) != 0, flagged, "{tie:?}"); } let flagged = [ ties::DEMONITOR, ties::UNLINK, ties::UNLINK_ACK, SPAWN_LINKED, SPAWN_MONITORED, ]; let flags: std::collections::HashSet = flagged.iter().map(|op| needs(*op)).collect(); // Unlink and its answer share one; the others have their own. assert_eq!(needs(ties::UNLINK), needs(ties::UNLINK_ACK)); assert_eq!(flags.len(), 4); assert!(!flags.contains(&0)); for op in [ LOOKUP, ANSWER, ties::LINK, ties::EXIT, ties::MONITOR, ties::DOWN, ties::KILL, ties::STOP, SPAWN, SPAWN_ANSWER, ] { assert_eq!(needs(op), 0, "op {op:02x}"); } } /// `docs/wire-format.md`'s example: actor 7 asks, on tag 3, for /// "counter" with the hash `994947b873cb1aa7`; actor 12 holds it on /// tag 40. #[test] fn lookup_frames_are_the_documented_bytes() { let request = LookupRequest { asker: 7, reply_tag: 3, hash: 0x9949_47b8_73cb_1aa7, name: b"counter", }; let bytes = request.encode(); assert_eq!( bytes, [ &[1, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0][..], &[0xa7, 0x1a, 0xcb, 0x73, 0xb8, 0x47, 0x49, 0x99, 7], b"counter", ] .concat() ); let back = LookupRequest::decode(&bytes[1..]).expect("well formed"); assert_eq!( (back.asker, back.reply_tag, back.hash), (7, 3, request.hash) ); assert_eq!(back.name, b"counter"); // The name's length is checked, and the ranges. assert!(LookupRequest::decode(&bytes[1..bytes.len() - 1]).is_none()); let mut far = bytes.clone(); far[8] = 0x40; assert!(LookupRequest::decode(&far[1..]).is_none()); let reply = LookupReply { asker: 7, reply_tag: 3, result: FOUND, serial: 12, tag: 40, hash: 0x9949_47b8_73cb_1aa7, }; let bytes = reply.encode(); assert_eq!(bytes.len(), LookupReply::LEN); assert_eq!( &bytes[..18], &[2, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0] ); assert_eq!(&bytes[18..26], &[12, 0, 0, 0, 0, 0, 0, 0]); assert_eq!(&bytes[26..34], &[40, 0, 0, 0, 0, 0, 0, 0]); assert_eq!( &bytes[34..], &[0xa7, 0x1a, 0xcb, 0x73, 0xb8, 0x47, 0x49, 0x99] ); let back = LookupReply::decode(&bytes[1..]).expect("well formed"); assert_eq!( ( back.asker, back.reply_tag, back.result, back.serial, back.tag ), (7, 3, FOUND, 12, 40) ); assert!(LookupReply::decode(&bytes[2..]).is_none(), "too short"); let mut bad = bytes.clone(); bad[17] = 3; assert!(LookupReply::decode(&bad[1..]).is_none(), "no result 3"); } /// `docs/wire-format.md`'s example: actor 7 asks, on tag 3, to spawn /// `remote_dispatch.hello` on `()`; the node starts actor 12. #[test] fn spawn_frames_are_the_documented_bytes() { let key = louise_rt_prims::wire::remote_key("remote_dispatch.hello") as u64; assert_eq!(key, 0x3b95_3bf0_e57c_a31d); let request = SpawnRequest { asker: 7, reply_tag: 3, key, hash: 0x4433_df13_a578_0ab1, payload: &[0, 0], tie: SpawnTie::Untied, }; let bytes = request.encode(); assert_eq!( bytes, [ &[0x20, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0][..], &[0x1d, 0xa3, 0x7c, 0xe5, 0xf0, 0x3b, 0x95, 0x3b], &[0xb1, 0x0a, 0x78, 0xa5, 0x13, 0xdf, 0x33, 0x44], &[0, 0], ] .concat() ); let back = SpawnRequest::decode(SPAWN, &bytes[1..]).expect("well formed"); assert_eq!( (back.asker, back.reply_tag, back.key, back.hash, back.tie), (7, 3, key, request.hash, SpawnTie::Untied) ); assert_eq!(back.payload, [0, 0]); assert!( SpawnRequest::decode(SPAWN, &bytes[1..32]).is_none(), "too short" ); let mut far = bytes.clone(); far[24] = 0x40; assert!( SpawnRequest::decode(SPAWN, &far[1..]).is_none(), "a key past 2^62" ); // Linked: op 0x22, the same fields. let linked = SpawnRequest { tie: SpawnTie::Link, ..request }; let linked_bytes = linked.encode(); assert_eq!(linked_bytes[0], 0x22); assert_eq!(linked_bytes[1..], bytes[1..]); let back = SpawnRequest::decode(SPAWN_LINKED, &linked_bytes[1..]).expect("well formed"); assert_eq!(back.tie, SpawnTie::Link); assert!( SpawnRequest::decode(0x24, &bytes[1..]).is_none(), "no op 24" ); let reply = SpawnReply { asker: 7, reply_tag: 3, result: SPAWNED, serial: 12, }; let bytes = reply.encode(); assert_eq!( bytes, [ &[0x21, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0][..], &[12, 0, 0, 0, 0, 0, 0, 0], ] .concat() ); let back = SpawnReply::decode(&bytes[1..]).expect("well formed"); assert_eq!( (back.asker, back.reply_tag, back.result, back.serial), (7, 3, SPAWNED, 12) ); assert!(SpawnReply::decode(&bytes[2..]).is_none(), "too short"); let mut bad = bytes.clone(); bad[17] = 4; assert!(SpawnReply::decode(&bad[1..]).is_none(), "no result 4"); assert_eq!( [NO_ENTRY, ENTRY_TYPE, NOT_SPAWNED].map(spawn_failure), [code::UNKNOWN_ENTRY, code::WRONG_TYPE, code::REFUSED] ); } /// `docs/wire-format.md`'s monitored spawn: as the example's, the /// `Down` due on tag 5. Its fixed fields are 40 bytes: a frame /// cut in its down tag, or a down tag past 2^62, is dropped. #[test] fn a_monitored_spawn_carries_its_down_tag() { let request = SpawnRequest { asker: 7, reply_tag: 3, key: 0x3b95_3bf0_e57c_a31d, hash: 0x4433_df13_a578_0ab1, payload: &[0, 0], tie: SpawnTie::Monitor(5), }; let bytes = request.encode(); let plain = SpawnRequest { tie: SpawnTie::Untied, ..request } .encode(); assert_eq!( bytes, [ &[0x23][..], &plain[1..33], &[5, 0, 0, 0, 0, 0, 0, 0], &[0, 0], ] .concat() ); let back = SpawnRequest::decode(SPAWN_MONITORED, &bytes[1..]).expect("well formed"); assert_eq!( (back.asker, back.reply_tag, back.key, back.hash, back.tie), (7, 3, request.key, request.hash, SpawnTie::Monitor(5)) ); assert_eq!(back.payload, [0, 0]); // The fixed fields alone: an empty payload, which no type // decodes from (the node refuses it, `03`). let fixed = SpawnRequest::decode(SPAWN_MONITORED, &bytes[1..41]).expect("40 bytes"); assert!(fixed.payload.is_empty()); for short in [0, 7, 32, 39] { assert!( SpawnRequest::decode(SPAWN_MONITORED, &bytes[1..1 + short]).is_none(), "{short} bytes" ); } let mut far = bytes.clone(); far[40] = 0x40; assert!( SpawnRequest::decode(SPAWN_MONITORED, &far[1..]).is_none(), "a down tag past 2^62" ); // Read as a plain spawn, the down tag is the payload's start. let plain = SpawnRequest::decode(SPAWN, &bytes[1..]).expect("as op 20"); assert_eq!(plain.payload.len(), 10); // `std/dist`'s `Tie` and the down tag, both ways. for tie in [SpawnTie::Untied, SpawnTie::Link, SpawnTie::Monitor(5)] { let (code, down) = tie.parts(); assert_eq!(SpawnTie::from_parts(code, down), Some(tie)); } assert_eq!(SpawnTie::from_parts(3, 0), None); assert_eq!(SpawnTie::from_parts(2, -1), None); assert_eq!(SpawnTie::from_parts(2, MAX_TAG as i64), None); } /// A monitored spawn's answer, from node b, for an asker that is /// gone or that gave up waiting: nothing is delivered or watched, /// and node b is sent a demonitor of the new actor, so it forgets /// the monitor (`docs/wire-format.md`, *Spawns*). An answer /// refusing the spawn, or one to a spawn that was not monitored, /// asks nothing back. #[test] fn a_monitored_spawn_nobody_waits_for_is_demonitored() { let _turn = crate::sched::test_turn(); let sched = Shared::new(1); let state = state(&sched); let b = Node { name: "b.example".into(), incarnation: 1, }; state.node_up(&b); let reply = |asker, result| SpawnReply { asker, reply_tag: 3, result, serial: 12, }; let asked = |down, abandoned| Asked { node: b.clone(), down, abandoned, }; let unwatch = |asker| Tie { from: asker, to: 12, op: Op::Demonitor { tag: 5 }, }; // Actor 7 never existed on this scheduler: gone. let gone = state.settle_spawn(&b, &reply(7, SPAWNED), &asked(Some(5), false)); assert_eq!(gone, Some(unwatch(7))); let abandoned = state.settle_spawn(&b, &reply(8, SPAWNED), &asked(Some(5), true)); assert_eq!(abandoned, Some(unwatch(8))); let refused = state.settle_spawn(&b, &reply(9, NOT_SPAWNED), &asked(Some(5), true)); assert_eq!(refused, None); let plain = state.settle_spawn(&b, &reply(10, SPAWNED), &asked(None, false)); assert_eq!(plain, None); // Through the relay: the answer settles its pending spawn, // once; another is dropped. lock(&state.spawns).insert((7, 3), asked(Some(5), true)); state.signal(&b, &reply(7, SPAWNED).encode()); assert!(lock(&state.spawns).is_empty()); // A lost node answers nobody for an abandoned spawn, and // forgets it. lock(&state.spawns).insert((8, 3), asked(Some(5), true)); state.node_down(&b); assert!(lock(&state.spawns).is_empty()); } /// Pinned (`dist/secreview3`): a spawn answer (op `21`) settles only /// a spawn this node asked of its sender. One from b for a spawn /// asked of c, or for a monitored spawn asked of this node itself /// (#421 keeps those pending too), is dropped and leaves the entry: /// b can neither answer another node's spawn nor have the relay /// watch for an asker or a down tag of its choice (the watch's pid /// and tag are the pending spawn's). A lost node forgets only its /// own; this node's are forgotten when its spawner takes them, or /// when their asker gives up waiting (SR3-3, /// `an_abandoned_spawn_asked_of_this_node_is_forgotten`). #[test] fn secreview3_a_spawn_answer_settles_only_a_spawn_asked_of_its_sender() { let _turn = crate::sched::test_turn(); let sched = Shared::new(1); let state = state(&sched); let node = |name: &str| Node { name: name.into(), incarnation: 1, }; let (b, c) = (node("b.example"), node("c.example")); let me = state.me().expect("this node").clone(); state.node_up(&b); state.node_up(&c); let asked = |node: &Node| Asked { node: node.clone(), down: Some(5), abandoned: false, }; lock(&state.spawns).insert((7, 3), asked(&c)); lock(&state.spawns).insert((8, 3), asked(&me)); let answer = |asker| { SpawnReply { asker, reply_tag: 3, result: SPAWNED, serial: 12, } .encode() }; let pending = || { let mut keys: Vec<(i64, i64)> = lock(&state.spawns).keys().copied().collect(); keys.sort_unstable(); keys }; state.signal(&b, &answer(7)); state.signal(&b, &answer(8)); assert_eq!(pending(), [(7, 3), (8, 3)], "b answered others' spawns"); state.node_down(&b); assert_eq!(pending(), [(7, 3), (8, 3)], "b's loss"); // c's own answer settles it (actor 7 is gone: nothing watched). state.signal(&c, &answer(7)); assert_eq!(pending(), [(8, 3)]); state.node_down(&c); assert_eq!(pending(), [(8, 3)], "this node's own spawn stays"); } /// SR3-3: a monitored spawn asked of this node stayed pending /// forever when its spawner died with the request queued: no /// node's loss forgets it, and the asker's timeout only marked it. /// The timeout forgets it now (the spawner, if it ever takes the /// request, answers nobody and monitors nothing); one asked of /// another node is still only marked, for its answer to settle. #[test] fn an_abandoned_spawn_asked_of_this_node_is_forgotten() { let _turn = crate::sched::test_turn(); let sched = Shared::new(1); let state = state(&sched); let b = Node { name: "b.example".into(), incarnation: 1, }; let me = state.me().expect("this node").clone(); state.node_up(&b); let asked = |node: &Node| Asked { node: node.clone(), down: Some(5), abandoned: false, }; lock(&state.spawns).insert((7, 3), asked(&b)); lock(&state.spawns).insert((8, 3), asked(&me)); assert!(state.abandon_spawn(8, 3)); assert!(state.abandon_spawn(7, 3)); assert!(!state.abandon_spawn(9, 3), "answered meanwhile"); let spawns = lock(&state.spawns); assert!(!spawns.contains_key(&(8, 3)), "this node's is forgotten"); assert!( spawns.get(&(7, 3)).is_some_and(|a| a.abandoned), "b's waits" ); } } }