| @@ -0,0 +1,2997 @@ |
| 1 | +//! This node (ADR 0072, `std/dist`): what `tl_dist_start` starts, and the |
| 2 | +//! glue between the scheduler (`dist`), the codec (`wire`) and the |
| 3 | +//! transport. |
| 4 | +//! |
| 5 | +//! - **Once per program.** `std/dist.start` builds the type registry from |
| 6 | +//! the program's definitions table, starts the transport with the |
| 7 | +//! program's schema hash, and installs the hooks through which `proc` |
| 8 | +//! operations on a remote pid reach it. Nothing here is reachable |
| 9 | +//! otherwise: a program that never starts distribution links none of it. |
| 10 | +//! - **Sends** to a `Remote` subject are encoded on the sender's thread |
| 11 | +//! (the hook borrows the message) and queued on the peer's connection. |
| 12 | +//! A message the program cannot encode (too large, too deep, over the |
| 13 | +//! peer's frame limit) panics in the sender, as the send walk's backstop |
| 14 | +//! does. While the peer's queue is full, the sender parks |
| 15 | +//! (`dist::send_parking`): the transport wakes it once the queue |
| 16 | +//! drains, and it queues the frame it encoded then. One to a node that |
| 17 | +//! is not up, or that goes down while its sender is parked, is dropped |
| 18 | +//! and counted: delivery is at most once. |
| 19 | +//! - **Messages in** are decoded with the receiver's own descriptor for |
| 20 | +//! the frame's type hash, beside the transport's thread (its relay), so |
| 21 | +//! a long decode holds up no heartbeat. A frame that does not decode is |
| 22 | +//! dropped and counted (the first one of a connection is logged). |
| 23 | +//! - **The node table only grows** (`dist::Nodes`): each peer name may add |
| 24 | +//! [`PEER_NODES`] entries for the whole run, its own incarnations and |
| 25 | +//! the nodes its frames name alike, so neither reconnecting nor |
| 26 | +//! restarting lets one peer fill the table for the others. |
| 27 | +//! - **Names.** `register` keeps a name, a local subject and its message |
| 28 | +//! type's hash; an actor that exited holds no name. `whereis` asks a node |
| 29 | +//! with a lookup frame (`docs/wire-format.md`, *Lookups*), and the answer |
| 30 | +//! arrives as a message on the asking actor's subject: `std/os.signals`' |
| 31 | +//! pattern, no new `proc` operation. The registered type is checked |
| 32 | +//! against the asker's: another type is an error value, not a crash. |
| 33 | +//! - **Links, monitors and exit signals** cross as signal frames |
| 34 | +//! (`docs/wire-format.md`, *Signals*; `ties`), queued behind the |
| 35 | +//! messages the same actor sent before. One to a node that is not up |
| 36 | +//! answers as the node's loss would: a link gets its exit and a monitor |
| 37 | +//! its `Down`, `Crashed("noconnection")`; `kill`, `stop`, an exit and a |
| 38 | +//! `Down` are dropped (the other side sees the loss), and an unlink |
| 39 | +//! ends the local half at once. What arrives goes through |
| 40 | +//! `dist::inbound`, which ties the local actor, or answers `noproc` for |
| 41 | +//! one that is gone; an unlink is acknowledged, whether the actor is |
| 42 | +//! alive or not. |
| 43 | +//! - **Ops a peer's runtime does not take** (its hello's capability |
| 44 | +//! flags, `docs/wire-format.md`) are never sent: the transport refuses |
| 45 | +//! them. A demonitor still ends the local half; an unlink ends it at |
| 46 | +//! once, as to a node that is not up; a linked or monitored spawn is |
| 47 | +//! refused before anything is pending (`std/dist`'s `Unsupported`). |
| 48 | +//! - **`monitor_node`** keeps (actor, tag, node name) subscriptions: the |
| 49 | +//! node's state at once (`NodeUp`, or `NodeDown` with why its last |
| 50 | +//! connection failed), then each change, a `NodeDown` after the lost |
| 51 | +//! node's links and monitors had theirs. |
| 52 | +//! - **Spawns.** `start` registers the argument types of the program's |
| 53 | +//! `@remote` functions (`std/wire.entries`), and gives the node a |
| 54 | +//! *spawner*, an actor of `std/dist`. `spawn_on` sends a spawn request |
| 55 | +//! (`docs/wire-format.md`, *Spawns*); the receiving node checks the key |
| 56 | +//! and the argument's type hash against its own entries before decoding |
| 57 | +//! anything, then hands the key and the decoded argument (a |
| 58 | +//! `std/wire.Arg`) to its spawner, which runs the compiler's dispatcher |
| 59 | +//! and hands the body to `tl_dist_spawn_for`, which spawns it and |
| 60 | +//! answers. No code address ever comes off the wire. The answer reaches |
| 61 | +//! the asker as `whereis`' does. `spawn_link_on` links the new actor to |
| 62 | +//! the asker before it can run, its link frame ahead of the answer. |
| 63 | +//! `spawn_monitor_on` has the asker monitor it before it can run, the |
| 64 | +//! answer ahead of its `Down`; the asker's node makes the asker's half |
| 65 | +//! of the monitor as the answer arrives. |
| 66 | +//! |
| 67 | +//! The answers `std/dist` receives are `Found(subject)` (`whereis`), |
| 68 | +//! `Found(pid)` (`spawn_on` and its linked and monitored forms) or |
| 69 | +//! `Failed(code, text)` (its `Answer` type); |
| 70 | +//! `tl_dist_register` returns a code. The codes are `std/dist`'s |
| 71 | +//! `failure`'s. Node events are `NodeUp(node)` and `NodeDown(node, why)` |
| 72 | +//! (its `NodeEvent`). |
| 73 | +//! `tl_dist_peers` reads the transport's statistics at once (`std/dist`'s |
| 74 | +//! `Peer`). `tl_dist_connect` hands the transport a node to stay |
| 75 | +//! connected to, as a seed. |
| 76 | + |
| 77 | +use crate::abi::{Ctx, Value, int}; |
| 78 | +use crate::values::{cell, string}; |
| 79 | + |
| 80 | +/// What `std/dist` turns into a `DistError` (its `failure`). |
| 81 | +#[cfg_attr(not(feature = "tls"), allow(dead_code))] |
| 82 | +mod code { |
| 83 | + pub const OK: i64 = 0; |
| 84 | + pub const NOT_STARTED: i64 = 1; |
| 85 | + pub const NOT_CONNECTED: i64 = 2; |
| 86 | + pub const NO_NAME: i64 = 3; |
| 87 | + pub const WRONG_TYPE: i64 = 4; |
| 88 | + pub const TAKEN: i64 = 5; |
| 89 | + pub const NOT_LOCAL: i64 = 6; |
| 90 | + pub const UNKNOWN_ENTRY: i64 = 7; |
| 91 | + pub const REFUSED: i64 = 8; |
| 92 | + /// `connect`: not a node name (`std/dist.connect`'s `Invalid`). |
| 93 | + pub const INVALID: i64 = 9; |
| 94 | + /// A linked or monitored spawn on a node whose runtime does not take |
| 95 | + /// it (its hello's capability flags). |
| 96 | + pub const UNSUPPORTED: i64 = 10; |
| 97 | +} |
| 98 | + |
| 99 | +/// The longest name `register` and `whereis` take, in bytes: a lookup |
| 100 | +/// frame gives it one byte. |
| 101 | +#[cfg_attr(not(feature = "tls"), allow(dead_code))] |
| 102 | +const MAX_NAME: usize = 255; |
| 103 | + |
| 104 | +/// `Failed(code, text)`, made outside any actor. |
| 105 | +fn failed(code: i64, text: &str) -> Value { |
| 106 | + cell( |
| 107 | + std::ptr::null_mut(), |
| 108 | + 1, |
| 109 | + &[int(code), string(std::ptr::null_mut(), text)], |
| 110 | + ) |
| 111 | +} |
| 112 | + |
| 113 | +/// `NodeUp(node)`, made outside any actor. |
| 114 | +#[cfg_attr(not(feature = "tls"), allow(dead_code))] |
| 115 | +fn node_up_event(node: &str) -> Value { |
| 116 | + cell( |
| 117 | + std::ptr::null_mut(), |
| 118 | + 0, |
| 119 | + &[string(std::ptr::null_mut(), node)], |
| 120 | + ) |
| 121 | +} |
| 122 | + |
| 123 | +/// `NodeDown(node, why)`, made outside any actor. |
| 124 | +fn node_down_event(node: &str, why: &str) -> Value { |
| 125 | + let null = std::ptr::null_mut(); |
| 126 | + cell(null, 1, &[string(null, node), string(null, why)]) |
| 127 | +} |
| 128 | + |
| 129 | +#[cfg(feature = "tls")] |
| 130 | +mod ties; |
| 131 | + |
| 132 | +#[cfg(feature = "tls")] |
| 133 | +pub use enabled::*; |
| 134 | + |
| 135 | +#[cfg(not(feature = "tls"))] |
| 136 | +pub use disabled::*; |
| 137 | + |
| 138 | +#[cfg(not(feature = "tls"))] |
| 139 | +mod disabled { |
| 140 | + use super::*; |
| 141 | + use crate::abi::UNIT; |
| 142 | + |
| 143 | + const NOT_BUILT: &str = "distribution needs TLS (louise_rt's `tls` feature)"; |
| 144 | + |
| 145 | + /// # Safety |
| 146 | + /// As the enabled version. |
| 147 | + #[unsafe(no_mangle)] |
| 148 | + #[allow(clippy::too_many_arguments)] |
| 149 | + pub unsafe extern "C" fn tl_dist_start( |
| 150 | + ctx: *mut Ctx, |
| 151 | + _node: Value, |
| 152 | + _cluster: Value, |
| 153 | + _listen: Value, |
| 154 | + _advertise: Value, |
| 155 | + _seeds: Value, |
| 156 | + _cert_file: Value, |
| 157 | + _key_file: Value, |
| 158 | + _ca_files: Value, |
| 159 | + _table: Value, |
| 160 | + _schema_hash: Value, |
| 161 | + _limits: Value, |
| 162 | + _entries: Value, |
| 163 | + _spawner: Value, |
| 164 | + ) -> Value { |
| 165 | + crate::values::error(ctx, NOT_BUILT) |
| 166 | + } |
| 167 | + |
| 168 | + /// # Safety |
| 169 | + /// As the enabled version. |
| 170 | + #[unsafe(no_mangle)] |
| 171 | + pub unsafe extern "C" fn tl_dist_peers(_ctx: *mut Ctx) -> Value { |
| 172 | + int(0) |
| 173 | + } |
| 174 | + |
| 175 | + /// # Safety |
| 176 | + /// As the enabled version. |
| 177 | + #[unsafe(no_mangle)] |
| 178 | + pub unsafe extern "C" fn tl_dist_connect(_ctx: *mut Ctx, _node: Value, _addr: Value) -> Value { |
| 179 | + int(code::NOT_STARTED) |
| 180 | + } |
| 181 | + |
| 182 | + /// # Safety |
| 183 | + /// As the enabled version. |
| 184 | + #[unsafe(no_mangle)] |
| 185 | + pub unsafe extern "C" fn tl_dist_register( |
| 186 | + _ctx: *mut Ctx, |
| 187 | + _name: Value, |
| 188 | + _desc: Value, |
| 189 | + _subject: Value, |
| 190 | + ) -> Value { |
| 191 | + int(code::NOT_STARTED) |
| 192 | + } |
| 193 | + |
| 194 | + /// # Safety |
| 195 | + /// As the enabled version. |
| 196 | + #[unsafe(no_mangle)] |
| 197 | + pub unsafe extern "C" fn tl_dist_whereis( |
| 198 | + ctx: *mut Ctx, |
| 199 | + tag: Value, |
| 200 | + _node: Value, |
| 201 | + _name: Value, |
| 202 | + _desc: Value, |
| 203 | + ) -> Value { |
| 204 | + // SAFETY: caller guarantees a running actor. |
| 205 | + let (a, sched) = unsafe { crate::sched::this(ctx) }; |
| 206 | + let tag = crate::abi::int_get(tag); |
| 207 | + crate::process::deliver_made(sched, a.pid, tag, failed(code::NOT_STARTED, NOT_BUILT)); |
| 208 | + UNIT |
| 209 | + } |
| 210 | + |
| 211 | + /// # Safety |
| 212 | + /// As the enabled version. |
| 213 | + #[unsafe(no_mangle)] |
| 214 | + pub unsafe extern "C" fn tl_dist_monitor_node(ctx: *mut Ctx, tag: Value, node: Value) -> Value { |
| 215 | + // SAFETY: caller guarantees a running actor and a live string. |
| 216 | + let (a, sched, node) = unsafe { |
| 217 | + let (a, sched) = crate::sched::this(ctx); |
| 218 | + (a, sched, crate::values::text(node)) |
| 219 | + }; |
| 220 | + let tag = crate::abi::int_get(tag); |
| 221 | + crate::process::deliver_made(sched, a.pid, tag, node_down_event(node, NOT_BUILT)); |
| 222 | + UNIT |
| 223 | + } |
| 224 | + |
| 225 | + /// # Safety |
| 226 | + /// As the enabled version. |
| 227 | + #[unsafe(no_mangle)] |
| 228 | + pub unsafe extern "C" fn tl_dist_spawn( |
| 229 | + ctx: *mut Ctx, |
| 230 | + tag: Value, |
| 231 | + _node: Value, |
| 232 | + _key: Value, |
| 233 | + _desc: Value, |
| 234 | + _args: Value, |
| 235 | + _tie: Value, |
| 236 | + _down: Value, |
| 237 | + ) -> Value { |
| 238 | + // SAFETY: caller guarantees a running actor. |
| 239 | + let (a, sched) = unsafe { crate::sched::this(ctx) }; |
| 240 | + let tag = crate::abi::int_get(tag); |
| 241 | + crate::process::deliver_made(sched, a.pid, tag, failed(code::NOT_STARTED, NOT_BUILT)); |
| 242 | + UNIT |
| 243 | + } |
| 244 | + |
| 245 | + /// # Safety |
| 246 | + /// As the enabled version. |
| 247 | + #[unsafe(no_mangle)] |
| 248 | + pub unsafe extern "C" fn tl_dist_spawn_for( |
| 249 | + ctx: *mut Ctx, |
| 250 | + _asker: Value, |
| 251 | + _tag: Value, |
| 252 | + _tie: Value, |
| 253 | + _down: Value, |
| 254 | + result: Value, |
| 255 | + ) -> Value { |
| 256 | + // SAFETY: owned (caller guarantee). |
| 257 | + unsafe { crate::heap::drop_value(ctx, result) }; |
| 258 | + UNIT |
| 259 | + } |
| 260 | + |
| 261 | + /// # Safety |
| 262 | + /// As the enabled version. |
| 263 | + #[unsafe(no_mangle)] |
| 264 | + pub unsafe extern "C" fn tl_dist_spawn_abandon(_ctx: *mut Ctx, _tag: Value) -> Value { |
| 265 | + // Nothing waits: `tl_dist_spawn` answered at once. |
| 266 | + int(1) |
| 267 | + } |
| 268 | +} |
| 269 | + |
| 270 | +#[cfg(feature = "tls")] |
| 271 | +mod enabled { |
| 272 | + use std::collections::HashMap; |
| 273 | + use std::ffi::CString; |
| 274 | + use std::net::SocketAddr; |
| 275 | + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 276 | + use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError, RwLock}; |
| 277 | + |
| 278 | + use louise_rt_prims::wire::{ |
| 279 | + HEADER_LEN, MAX_PAYLOAD, MAX_PID_SERIAL, MAX_TAG, MIN_FRAME, MessageHeader, |
| 280 | + }; |
| 281 | + |
| 282 | + use super::ties::{self, Op, Tie}; |
| 283 | + use super::*; |
| 284 | + use crate::abi::{Block, UNIT, int_get}; |
| 285 | + use crate::dist::{self, Dist, Hooks, Node, Signal, Try, Waiter, is_remote}; |
| 286 | + use crate::heap::{drop_value, dup_value}; |
| 287 | + use crate::process::deliver_made; |
| 288 | + // A spawned actor's tie to its parent; `Tie` is a tie frame. |
| 289 | + use crate::sched::Tie as ParentTie; |
| 290 | + use crate::sched::{ |
| 291 | + Actor, Exit, Shared, spawn_program_before, spawn_program_monitored, spawn_program_tied, |
| 292 | + this, |
| 293 | + }; |
| 294 | + use crate::transport::{self, Config, Inbound, Outbound, Reason, SendError, Throttle}; |
| 295 | + use crate::values::{list, list_items, string, text}; |
| 296 | + use crate::wire::{self, DecodeError, PEER_NODES, Registry}; |
| 297 | + |
| 298 | + /// The node the program started, if it did. Kept once the program |
| 299 | + /// ends (a later program in the same process, a test, starts its own): |
| 300 | + /// [`running`] checks it is the running transport's, and [`current`] |
| 301 | + /// that it belongs to the running scheduler. |
| 302 | + static NODE: RwLock<Option<Arc<State>>> = RwLock::new(None); |
| 303 | + |
| 304 | + /// The hooks `dist` calls for operations on remote pids. |
| 305 | + static HOOKS: Hooks = Hooks { |
| 306 | + send: send_hook, |
| 307 | + link: link_hook, |
| 308 | + monitor: monitor_hook, |
| 309 | + demonitor: demonitor_hook, |
| 310 | + unlink: unlink_hook, |
| 311 | + signal: signal_hook, |
| 312 | + down: down_hook, |
| 313 | + exit: exit_hook, |
| 314 | + }; |
| 315 | + |
| 316 | + /// The scheduler the node delivers to. |
| 317 | + struct Sched(*const Shared); |
| 318 | + |
| 319 | + // SAFETY: `Shared` is shared by every scheduler thread already; the |
| 320 | + // pointer is used only while the transport runs, which the scheduler |
| 321 | + // stops (joining its thread, `dist::shutdown`) before dropping it, and |
| 322 | + // by hooks, uninstalled first. |
| 323 | + unsafe impl Send for Sched {} |
| 324 | + // SAFETY: as above. |
| 325 | + unsafe impl Sync for Sched {} |
| 326 | + |
| 327 | + /// A started node: the transport's [`Inbound`] handler, and what the |
| 328 | + /// hooks and externs share. |
| 329 | + struct State { |
| 330 | + sched: Sched, |
| 331 | + /// The node table, and the local actors tied to each node. |
| 332 | + dist: Dist, |
| 333 | + registry: Registry, |
| 334 | + /// Name and incarnation, once the transport has drawn it. |
| 335 | + me: OnceLock<Node>, |
| 336 | + /// Registered names. |
| 337 | + names: Mutex<HashMap<String, Named>>, |
| 338 | + /// The peers that are up, by name (the transport's thread only). |
| 339 | + peers: Mutex<HashMap<String, Peer>>, |
| 340 | + /// The node-table entries each peer name may still add, for the |
| 341 | + /// whole run: [`PEER_NODES`] at first, never given back. |
| 342 | + quotas: Mutex<HashMap<String, u32>>, |
| 343 | + /// Lookups sent and not answered, by the asking actor's pid and |
| 344 | + /// reply tag. |
| 345 | + lookups: Mutex<HashMap<(i64, i64), Lookup>>, |
| 346 | + /// The program's `@remote` functions, by key. |
| 347 | + entries: HashMap<i64, RemoteEntry>, |
| 348 | + /// The spawner's subject: its pid and tag. |
| 349 | + spawner: (i64, i64), |
| 350 | + /// Spawns asked of a node and not answered, by the asking actor's |
| 351 | + /// pid and reply tag; and monitored ones asked of this node. |
| 352 | + spawns: Mutex<HashMap<(i64, i64), Asked>>, |
| 353 | + /// Why the last connection with a node failed, by node name. |
| 354 | + failures: Mutex<HashMap<String, String>>, |
| 355 | + /// Why the last connection to close did, by its label: the |
| 356 | + /// transport calls `node_down` right after `closed`. |
| 357 | + last_closed: Mutex<Option<(String, String)>>, |
| 358 | + /// Connections that failed before their hello: logged sparingly. |
| 359 | + unauthenticated: Mutex<Throttle>, |
| 360 | + /// Dials that failed to addresses only peers' lists gave: logged |
| 361 | + /// sparingly too, since the peers choose them. |
| 362 | + hearsay: Mutex<Throttle>, |
| 363 | + /// `monitor_node`'s subscriptions. Taken before `peers`, so a |
| 364 | + /// subscriber sees the state, then every change after it. |
| 365 | + node_watchers: Mutex<Vec<NodeWatcher>>, |
| 366 | + /// Spawn requests refused: an unknown key, another type, an |
| 367 | + /// argument that did not decode. |
| 368 | + refused: AtomicU64, |
| 369 | + /// Open once the hooks are installed ([`start`]). |
| 370 | + ready: Gate, |
| 371 | + } |
| 372 | + |
| 373 | + /// What peers send waits at it until the node is published and its |
| 374 | + /// hooks are installed: the transport starts first (it draws the |
| 375 | + /// incarnation), and a frame handled before the install would lose |
| 376 | + /// the answer a hook sends (a `noproc` exit or `Down` for a tie to an |
| 377 | + /// actor gone, an exit or `Down` of an actor tied meanwhile, a spawn's |
| 378 | + /// answer). The relay's thread waits, so frames keep their order. |
| 379 | + #[derive(Default)] |
| 380 | + struct Gate { |
| 381 | + open: AtomicBool, |
| 382 | + wait: Mutex<()>, |
| 383 | + opened: Condvar, |
| 384 | + } |
| 385 | + |
| 386 | + impl Gate { |
| 387 | + fn pass(&self) { |
| 388 | + if self.open.load(Ordering::Acquire) { |
| 389 | + return; |
| 390 | + } |
| 391 | + let mut guard = lock(&self.wait); |
| 392 | + while !self.open.load(Ordering::Acquire) { |
| 393 | + guard = self |
| 394 | + .opened |
| 395 | + .wait(guard) |
| 396 | + .unwrap_or_else(PoisonError::into_inner); |
| 397 | + } |
| 398 | + } |
| 399 | + |
| 400 | + fn open(&self) { |
| 401 | + let _guard = lock(&self.wait); |
| 402 | + self.open.store(true, Ordering::Release); |
| 403 | + self.opened.notify_all(); |
| 404 | + } |
| 405 | + } |
| 406 | + |
| 407 | + /// Opens the gate when dropped: on every way out of [`start`]. |
| 408 | + struct OpenOnDrop<'a>(&'a Gate); |
| 409 | + |
| 410 | + impl Drop for OpenOnDrop<'_> { |
| 411 | + fn drop(&mut self) { |
| 412 | + self.0.open(); |
| 413 | + } |
| 414 | + } |
| 415 | + |
| 416 | + /// A `@remote` function of the program (`std/wire.Entry`), its |
| 417 | + /// argument's type registered. |
| 418 | + struct RemoteEntry { |
| 419 | + descriptor: String, |
| 420 | + wire: u32, |
| 421 | + hash: u64, |
| 422 | + } |
| 423 | + |
| 424 | + /// A registered name: a local subject and its message type's hash. |
| 425 | + struct Named { |
| 426 | + pid: i64, |
| 427 | + tag: i64, |
| 428 | + hash: u64, |
| 429 | + } |
| 430 | + |
| 431 | + struct Peer { |
| 432 | + incarnation: u64, |
| 433 | + /// A dropped frame of this connection was logged. |
| 434 | + logged: bool, |
| 435 | + } |
| 436 | + |
| 437 | + /// An actor's `monitor_node` subscription: its subject's tag, and the |
| 438 | + /// node's name. |
| 439 | + struct NodeWatcher { |
| 440 | + pid: i64, |
| 441 | + tag: i64, |
| 442 | + node: String, |
| 443 | + } |
| 444 | + |
| 445 | + /// A lookup sent to `node`, for a subject of the type of `hash`. |
| 446 | + struct Lookup { |
| 447 | + node: Node, |
| 448 | + hash: u64, |
| 449 | + } |
| 450 | + |
| 451 | + /// A spawn asked of `node` and not answered. |
| 452 | + struct Asked { |
| 453 | + node: Node, |
| 454 | + /// Monitored (`spawn_monitor_on`): the tag its `Down` is due on. |
| 455 | + down: Option<i64>, |
| 456 | + /// The asker's wait timed out (`tl_dist_spawn_abandon`): the answer |
| 457 | + /// goes to nobody, and the new actor is not monitored. Only for a |
| 458 | + /// spawn asked of another node: one asked of this node is |
| 459 | + /// forgotten instead ([`State::abandon_spawn`]). |
| 460 | + abandoned: bool, |
| 461 | + } |
| 462 | + |
| 463 | + /// The most connection failures remembered: names come from peers |
| 464 | + /// too, so the map must not grow with them. |
| 465 | + const MAX_FAILURES: usize = 256; |
| 466 | + |
| 467 | + fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { |
| 468 | + m.lock().unwrap_or_else(PoisonError::into_inner) |
| 469 | + } |
| 470 | + |
| 471 | + impl State { |
| 472 | + fn sched(&self) -> &Shared { |
| 473 | + // SAFETY: see `Sched`. |
| 474 | + unsafe { &*self.sched.0 } |
| 475 | + } |
| 476 | + |
| 477 | + /// This node. Set right after the transport starts; a handler |
| 478 | + /// called before (the transport holds its lock until then) reads |
| 479 | + /// it from the transport. |
| 480 | + fn me(&self) -> Option<&Node> { |
| 481 | + if let Some(me) = self.me.get() { |
| 482 | + return Some(me); |
| 483 | + } |
| 484 | + let me = transport::with_program(|t| t.me().clone())?; |
| 485 | + Some(self.me.get_or_init(|| me)) |
| 486 | + } |
| 487 | + |
| 488 | + /// The live registered holder of `name`. |
| 489 | + fn named(&self, name: &str) -> Option<(i64, i64, u64)> { |
| 490 | + let names = lock(&self.names); |
| 491 | + let n = names.get(name)?; |
| 492 | + self.sched().exists(n.pid).then_some((n.pid, n.tag, n.hash)) |
| 493 | + } |
| 494 | + |
| 495 | + /// A frame from `from` is dropped: undecodable, of an unknown |
| 496 | + /// type, a malformed lookup, an answer to no lookup. Counted in |
| 497 | + /// its statistics (`std/dist.peers`), the first of a connection |
| 498 | + /// logged. |
| 499 | + fn drop_frame(&self, from: &Node, why: &dyn std::fmt::Display) { |
| 500 | + transport::with_program(|t| t.count_dropped(&from.name)); |
| 501 | + let mut peers = lock(&self.peers); |
| 502 | + if let Some(peer) = peers.get_mut(&from.name) |
| 503 | + && !peer.logged |
| 504 | + { |
| 505 | + peer.logged = true; |
| 506 | + eprintln!( |
| 507 | + "louise: dist: {}: dropped a frame ({why}); later ones are only counted", |
| 508 | + from.name |
| 509 | + ); |
| 510 | + } |
| 511 | + } |
| 512 | + |
| 513 | + /// The value `payload` holds, of the type of `hash`, from `from`, |
| 514 | + /// within its name's node-table quota. `None`: `from` is not up. |
| 515 | + fn decode( |
| 516 | + &self, |
| 517 | + from: &Node, |
| 518 | + me: &Node, |
| 519 | + hash: u64, |
| 520 | + payload: &[u8], |
| 521 | + ) -> Option<Result<Value, DecodeError>> { |
| 522 | + lock(&self.peers) |
| 523 | + .get(&from.name) |
| 524 | + .filter(|p| p.incarnation == from.incarnation)?; |
| 525 | + // Read, then written back: only the inbound thread spends it. |
| 526 | + let mut quota = *lock(&self.quotas) |
| 527 | + .entry(from.name.clone()) |
| 528 | + .or_insert(PEER_NODES); |
| 529 | + let decoded = wire::decode( |
| 530 | + &self.registry, |
| 531 | + hash, |
| 532 | + payload, |
| 533 | + me, |
| 534 | + &self.dist.nodes, |
| 535 | + &mut quota, |
| 536 | + Some(self.spawner), |
| 537 | + ); |
| 538 | + self.spent(&from.name, quota); |
| 539 | + Some(decoded) |
| 540 | + } |
| 541 | + |
| 542 | + /// `name`'s quota is now `left`: logged once when it runs out. |
| 543 | + fn spent(&self, name: &str, left: u32) { |
| 544 | + let mut quotas = lock(&self.quotas); |
| 545 | + let before = quotas.insert(name.to_owned(), left); |
| 546 | + if left == 0 && before != Some(0) { |
| 547 | + eprintln!( |
| 548 | + "louise: dist: {name}: it added {PEER_NODES} node-table entries (its \ |
| 549 | + incarnations and the nodes it names): new ones from it are refused" |
| 550 | + ); |
| 551 | + } |
| 552 | + } |
| 553 | + |
| 554 | + /// The node-table index of `from` (a peer that is or was up), added |
| 555 | + /// if new, charged to its name's quota. `Err`: why there is none. |
| 556 | + fn enter(&self, from: &Node) -> Result<u16, &'static str> { |
| 557 | + let nodes = &self.dist.nodes; |
| 558 | + let found = (nodes.read().unwrap_or_else(PoisonError::into_inner)) |
| 559 | + .find(&from.name, from.incarnation); |
| 560 | + if let Some(index) = found { |
| 561 | + return Ok(index); |
| 562 | + } |
| 563 | + let left = *lock(&self.quotas) |
| 564 | + .entry(from.name.clone()) |
| 565 | + .or_insert(PEER_NODES); |
| 566 | + if left == 0 { |
| 567 | + return Err("the peer's node-table quota is spent"); |
| 568 | + } |
| 569 | + let index = (nodes.write().unwrap_or_else(PoisonError::into_inner)) |
| 570 | + .index(&from.name, from.incarnation) |
| 571 | + .ok_or("the node table is full")?; |
| 572 | + self.spent(&from.name, left - 1); |
| 573 | + Ok(index) |
| 574 | + } |
| 575 | + |
| 576 | + /// A lookup from `from`: answer it from the registered names. |
| 577 | + fn lookup(&self, from: &Node, body: &[u8]) { |
| 578 | + let Some(request) = LookupRequest::decode(body) else { |
| 579 | + return self.drop_frame(from, &"a malformed lookup"); |
| 580 | + }; |
| 581 | + let reply = match std::str::from_utf8(request.name) |
| 582 | + .ok() |
| 583 | + .and_then(|name| self.named(name)) |
| 584 | + { |
| 585 | + None => LookupReply { |
| 586 | + asker: request.asker, |
| 587 | + reply_tag: request.reply_tag, |
| 588 | + result: NO_NAME, |
| 589 | + serial: 0, |
| 590 | + tag: 0, |
| 591 | + hash: 0, |
| 592 | + }, |
| 593 | + Some((pid, tag, hash)) if hash == request.hash => LookupReply { |
| 594 | + asker: request.asker, |
| 595 | + reply_tag: request.reply_tag, |
| 596 | + result: FOUND, |
| 597 | + serial: pid as u64, |
| 598 | + tag: tag as u64, |
| 599 | + hash, |
| 600 | + }, |
| 601 | + // The subject is given only to an asker of its type. |
| 602 | + Some((_, _, hash)) => LookupReply { |
| 603 | + asker: request.asker, |
| 604 | + reply_tag: request.reply_tag, |
| 605 | + result: OTHER_TYPE, |
| 606 | + serial: 0, |
| 607 | + tag: 0, |
| 608 | + hash, |
| 609 | + }, |
| 610 | + }; |
| 611 | + // Lost with the connection, if it is: the asker times out. |
| 612 | + let _ = transport::with_program(|t| t.send(from, Outbound::Signal(reply.encode()))); |
| 613 | + } |
| 614 | + |
| 615 | + /// The answer to a lookup this node sent. |
| 616 | + fn answered(&self, from: &Node, body: &[u8]) { |
| 617 | + let Some(reply) = LookupReply::decode(body) else { |
| 618 | + return self.drop_frame(from, &"a malformed lookup answer"); |
| 619 | + }; |
| 620 | + let key = (reply.asker as i64, reply.reply_tag as i64); |
| 621 | + let lookup = { |
| 622 | + let mut lookups = lock(&self.lookups); |
| 623 | + match lookups.get(&key) { |
| 624 | + Some(l) if l.node == *from => lookups.remove(&key), |
| 625 | + _ => None, |
| 626 | + } |
| 627 | + }; |
| 628 | + let Some(lookup) = lookup else { |
| 629 | + return self.drop_frame(from, &"an answer to no lookup"); |
| 630 | + }; |
| 631 | + let answer = match reply.result { |
| 632 | + FOUND if reply.hash == lookup.hash => self.found(from, &reply), |
| 633 | + FOUND | OTHER_TYPE => failed(code::WRONG_TYPE, ""), |
| 634 | + NO_NAME => failed(code::NO_NAME, ""), |
| 635 | + _ => failed(code::NOT_CONNECTED, "a malformed lookup answer"), |
| 636 | + }; |
| 637 | + deliver_made(self.sched(), key.0, key.1, answer); |
| 638 | + } |
| 639 | + |
| 640 | + /// `Found(Remote(owner, tag, wire))` for the subject `reply` names |
| 641 | + /// on `from`. |
| 642 | + fn found(&self, from: &Node, reply: &LookupReply) -> Value { |
| 643 | + // Registered when the lookup was sent. |
| 644 | + let wire = self.registry.by_hash(reply.hash); |
| 645 | + match (self.remote_pid(from, reply.serial), wire) { |
| 646 | + (Ok(owner), Some(wire)) => { |
| 647 | + let null = std::ptr::null_mut(); |
| 648 | + let subject = cell( |
| 649 | + null, |
| 650 | + 1, |
| 651 | + &[int(owner), int(reply.tag as i64), int(i64::from(wire))], |
| 652 | + ); |
| 653 | + cell(null, 0, &[subject]) |
| 654 | + } |
| 655 | + (Err(why), _) => failed(code::NOT_CONNECTED, why), |
| 656 | + (_, None) => failed(code::WRONG_TYPE, ""), |
| 657 | + } |
| 658 | + } |
| 659 | + |
| 660 | + /// The pid of actor `serial` (below 2^46, checked) of `from`, if |
| 661 | + /// the node table has (or makes) an entry for it ([`State::enter`]). |
| 662 | + fn remote_pid(&self, from: &Node, serial: u64) -> Result<i64, &'static str> { |
| 663 | + let node = self.enter(from)?; |
| 664 | + dist::remote(node, serial as i64).ok_or("a serial out of range") |
| 665 | + } |
| 666 | + |
| 667 | + /// A spawn request from `from`, of op `op` (plain, linked or |
| 668 | + /// monitored): answered here if refused, else by the spawner |
| 669 | + /// (`tl_dist_spawn_for`). |
| 670 | + fn spawn_asked(&self, from: &Node, op: u8, body: &[u8]) { |
| 671 | + let Some(request) = SpawnRequest::decode(op, body) else { |
| 672 | + return self.drop_frame(from, &"a malformed spawn request"); |
| 673 | + }; |
| 674 | + let result = match self.remote_pid(from, request.asker) { |
| 675 | + Ok(asker) => self.spawn(from, &request, asker), |
| 676 | + Err(_) => { |
| 677 | + self.refused.fetch_add(1, Ordering::Relaxed); |
| 678 | + Err(NOT_SPAWNED) |
| 679 | + } |
| 680 | + }; |
| 681 | + if let Err(result) = result { |
| 682 | + let reply = SpawnReply { |
| 683 | + asker: request.asker, |
| 684 | + reply_tag: request.reply_tag, |
| 685 | + result, |
| 686 | + serial: 0, |
| 687 | + }; |
| 688 | + // Lost with the connection, if it is: the asker is told so. |
| 689 | + let _ = transport::with_program(|t| t.send(from, Outbound::Signal(reply.encode()))); |
| 690 | + } |
| 691 | + } |
| 692 | + |
| 693 | + /// Give `request`, from `asker` of `from` (this node, for its own |
| 694 | + /// `spawn_on`), to the spawner, if the program has its entry for |
| 695 | + /// its type: checked before anything is decoded. `Err`: refused, |
| 696 | + /// the answer's result. |
| 697 | + fn spawn(&self, from: &Node, request: &SpawnRequest<'_>, asker: i64) -> Result<(), u8> { |
| 698 | + let refuse = |result| { |
| 699 | + self.refused.fetch_add(1, Ordering::Relaxed); |
| 700 | + Err(result) |
| 701 | + }; |
| 702 | + let Some(entry) = self.entries.get(&(request.key as i64)) else { |
| 703 | + return refuse(NO_ENTRY); |
| 704 | + }; |
| 705 | + if entry.hash != request.hash { |
| 706 | + return refuse(ENTRY_TYPE); |
| 707 | + } |
| 708 | + let (spawner, tag) = self.spawner; |
| 709 | + let Some(me) = self.me().filter(|_| self.sched().exists(spawner)) else { |
| 710 | + return refuse(NOT_SPAWNED); |
| 711 | + }; |
| 712 | + let decoded = if from == me { |
| 713 | + // This node's own value names no node it does not know. |
| 714 | + let nodes = &self.dist.nodes; |
| 715 | + wire::decode( |
| 716 | + &self.registry, |
| 717 | + entry.hash, |
| 718 | + request.payload, |
| 719 | + me, |
| 720 | + nodes, |
| 721 | + &mut 0, |
| 722 | + Some(self.spawner), |
| 723 | + ) |
| 724 | + } else { |
| 725 | + match self.decode(from, me, entry.hash, request.payload) { |
| 726 | + Some(decoded) => decoded, |
| 727 | + None => return refuse(NOT_SPAWNED), |
| 728 | + } |
| 729 | + }; |
| 730 | + let value = match decoded { |
| 731 | + Ok(value) => value, |
| 732 | + Err(e) => { |
| 733 | + self.drop_frame(from, &e); |
| 734 | + return refuse(NOT_SPAWNED); |
| 735 | + } |
| 736 | + }; |
| 737 | + // `std/wire.Arg(descriptor, value)`, then `std/dist.Request(key, |
| 738 | + // arg, asker, tag, tie, down)`. |
| 739 | + let null = std::ptr::null_mut(); |
| 740 | + let arg = cell(null, 0, &[string(null, &entry.descriptor), value]); |
| 741 | + let key = int(request.key as i64); |
| 742 | + let reply_tag = int(request.reply_tag as i64); |
| 743 | + let (tie, down) = request.tie.parts(); |
| 744 | + let message = cell( |
| 745 | + null, |
| 746 | + 0, |
| 747 | + &[key, arg, int(asker), reply_tag, int(tie), int(down)], |
| 748 | + ); |
| 749 | + dist::inbound::deliver(self.sched(), spawner, tag, message); |
| 750 | + Ok(()) |
| 751 | + } |
| 752 | + |
| 753 | + /// The answer to a spawn this node asked of `from`. |
| 754 | + fn spawn_answered(&self, from: &Node, body: &[u8]) { |
| 755 | + let Some(reply) = SpawnReply::decode(body) else { |
| 756 | + return self.drop_frame(from, &"a malformed spawn answer"); |
| 757 | + }; |
| 758 | + let key = (reply.asker as i64, reply.reply_tag as i64); |
| 759 | + let asked = { |
| 760 | + let mut spawns = lock(&self.spawns); |
| 761 | + match spawns.get(&key) { |
| 762 | + Some(asked) if asked.node == *from => spawns.remove(&key), |
| 763 | + _ => None, |
| 764 | + } |
| 765 | + }; |
| 766 | + let Some(asked) = asked else { |
| 767 | + return self.drop_frame(from, &"an answer to no spawn"); |
| 768 | + }; |
| 769 | + if let Some(unwatch) = self.settle_spawn(from, &reply, &asked) { |
| 770 | + // Lost with the connection, if it is: its loss forgets the |
| 771 | + // monitor there. |
| 772 | + let _ = |
| 773 | + transport::with_program(|t| t.send(from, Outbound::Signal(unwatch.encode()))); |
| 774 | + } |
| 775 | + } |
| 776 | + |
| 777 | + /// Hand `reply`, from `from`, to the asker of `asked`, if it still |
| 778 | + /// waits. For a monitored spawn, the asker's half of the monitor is |
| 779 | + /// made with it, under its lock (`dist::inbound::watch_spawned`): |
| 780 | + /// the new actor's `Down` may be the stream's next frame. The |
| 781 | + /// demonitor to send back when the new actor is monitored for an |
| 782 | + /// asker that is gone or gave up waiting, so `from` forgets it. |
| 783 | + fn settle_spawn(&self, from: &Node, reply: &SpawnReply, asked: &Asked) -> Option<Tie> { |
| 784 | + let (asker, reply_tag) = (reply.asker as i64, reply.reply_tag as i64); |
| 785 | + let unwatch = asked |
| 786 | + .down |
| 787 | + .filter(|_| reply.result == SPAWNED) |
| 788 | + .map(|down| Tie { |
| 789 | + from: reply.asker, |
| 790 | + to: reply.serial, |
| 791 | + op: Op::Demonitor { tag: down as u64 }, |
| 792 | + }); |
| 793 | + if asked.abandoned { |
| 794 | + return unwatch; |
| 795 | + } |
| 796 | + let answer = match reply.result { |
| 797 | + SPAWNED => match (self.remote_pid(from, reply.serial), asked.down) { |
| 798 | + (Ok(pid), Some(down)) => { |
| 799 | + let found = || cell(std::ptr::null_mut(), 0, &[int(pid)]); |
| 800 | + let sched = self.sched(); |
| 801 | + let dist = &self.dist; |
| 802 | + let watched = dist::inbound::watch_spawned( |
| 803 | + sched, dist, asker, pid, down, reply_tag, found, |
| 804 | + ); |
| 805 | + return unwatch.filter(|_| !watched); |
| 806 | + } |
| 807 | + (Ok(pid), None) => cell(std::ptr::null_mut(), 0, &[int(pid)]), |
| 808 | + (Err(why), _) => { |
| 809 | + deliver_made( |
| 810 | + self.sched(), |
| 811 | + asker, |
| 812 | + reply_tag, |
| 813 | + failed(code::NOT_CONNECTED, why), |
| 814 | + ); |
| 815 | + return unwatch; |
| 816 | + } |
| 817 | + }, |
| 818 | + refused => failed(spawn_failure(refused), ""), |
| 819 | + }; |
| 820 | + deliver_made(self.sched(), asker, reply_tag, answer); |
| 821 | + None |
| 822 | + } |
| 823 | + |
| 824 | + /// Answer every lookup and spawn sent to `peer`, now lost. |
| 825 | + fn lost(&self, peer: &Node) { |
| 826 | + let mut lost: Vec<(i64, i64)> = { |
| 827 | + let mut lookups = lock(&self.lookups); |
| 828 | + let keys: Vec<_> = lookups |
| 829 | + .iter() |
| 830 | + .filter(|(_, l)| l.node == *peer) |
| 831 | + .map(|(k, _)| *k) |
| 832 | + .collect(); |
| 833 | + keys.iter().for_each(|k| { |
| 834 | + lookups.remove(k); |
| 835 | + }); |
| 836 | + keys |
| 837 | + }; |
| 838 | + lock(&self.spawns).retain(|k, asked| { |
| 839 | + let keep = asked.node != *peer; |
| 840 | + // One whose asker gave up waiting goes to nobody. |
| 841 | + if !keep && !asked.abandoned { |
| 842 | + lost.push(*k); |
| 843 | + } |
| 844 | + keep |
| 845 | + }); |
| 846 | + for (pid, tag) in lost { |
| 847 | + let answer = failed(code::NOT_CONNECTED, "the connection was lost"); |
| 848 | + deliver_made(self.sched(), pid, tag, answer); |
| 849 | + } |
| 850 | + } |
| 851 | + |
| 852 | + /// A link, unlink, monitor, demonitor or exit signal from `from` |
| 853 | + /// (`docs/wire-format.md`, *Signals*): to the local actor it names, |
| 854 | + /// from the remote pid of `from` it names. |
| 855 | + fn tie(&self, from: &Node, op: u8, body: &[u8]) { |
| 856 | + let Some(tie) = Tie::decode(op, body) else { |
| 857 | + return self.drop_frame(from, &"a malformed link, monitor or exit signal"); |
| 858 | + }; |
| 859 | + let sched = self.sched(); |
| 860 | + // Below 2^46 (checked): a remote pid, and a local one. |
| 861 | + let remote = match self.remote_pid(from, tie.from) { |
| 862 | + Ok(remote) => remote, |
| 863 | + Err(why) => return self.drop_frame(from, &why), |
| 864 | + }; |
| 865 | + let local = tie.to as i64; |
| 866 | + match tie.op { |
| 867 | + Op::Link => dist::inbound::link(sched, &self.dist, remote, local), |
| 868 | + Op::Exit(reason) => { |
| 869 | + dist::inbound::signal(sched, remote, local, &Signal::Linked(reason)) |
| 870 | + } |
| 871 | + Op::Monitor { tag } => { |
| 872 | + dist::inbound::monitor(sched, &self.dist, remote, tag as i64, local) |
| 873 | + } |
| 874 | + Op::Down { tag, reason } => { |
| 875 | + dist::inbound::down(sched, local, tag as i64, remote, &reason) |
| 876 | + } |
| 877 | + Op::Demonitor { tag } => dist::inbound::demonitor(sched, remote, tag as i64, local), |
| 878 | + Op::Unlink { id } => dist::inbound::unlink(sched, remote, local, || { |
| 879 | + send_tie(self, local, remote, Op::UnlinkAck { id }); |
| 880 | + }), |
| 881 | + Op::UnlinkAck { id } => dist::inbound::unlink_acked(sched, remote, local, id), |
| 882 | + Op::Kill => dist::inbound::signal(sched, remote, local, &Signal::Kill), |
| 883 | + Op::Stop => dist::inbound::signal(sched, remote, local, &Signal::Stop), |
| 884 | + } |
| 885 | + } |
| 886 | + |
| 887 | + /// Deliver `event()` to every live subscriber to `node`'s events, |
| 888 | + /// forgetting those that exited. Under `node_watchers`' lock. |
| 889 | + fn tell(&self, watchers: &mut Vec<NodeWatcher>, node: &str, event: impl Fn() -> Value) { |
| 890 | + let sched = self.sched(); |
| 891 | + watchers.retain(|w| sched.exists(w.pid)); |
| 892 | + for w in watchers.iter().filter(|w| w.node == node) { |
| 893 | + deliver_made(sched, w.pid, w.tag, event()); |
| 894 | + } |
| 895 | + } |
| 896 | + } |
| 897 | + |
| 898 | + impl Inbound for State { |
| 899 | + fn node_up(&self, peer: &Node) { |
| 900 | + self.ready.pass(); |
| 901 | + let mut watchers = lock(&self.node_watchers); |
| 902 | + lock(&self.peers).insert( |
| 903 | + peer.name.clone(), |
| 904 | + Peer { |
| 905 | + incarnation: peer.incarnation, |
| 906 | + logged: false, |
| 907 | + }, |
| 908 | + ); |
| 909 | + lock(&self.failures).remove(&peer.name); |
| 910 | + self.tell(&mut watchers, &peer.name, || node_up_event(&peer.name)); |
| 911 | + } |
| 912 | + |
| 913 | + fn node_down(&self, peer: &Node) { |
| 914 | + self.ready.pass(); |
| 915 | + let mut watchers = lock(&self.node_watchers); |
| 916 | + let was_up = { |
| 917 | + let mut peers = lock(&self.peers); |
| 918 | + let up = peers.get(&peer.name).map(|p| p.incarnation) == Some(peer.incarnation); |
| 919 | + if up { |
| 920 | + peers.remove(&peer.name); |
| 921 | + } |
| 922 | + up |
| 923 | + }; |
| 924 | + self.lost(peer); |
| 925 | + let index = (self.dist.nodes.read()) |
| 926 | + .unwrap_or_else(PoisonError::into_inner) |
| 927 | + .find(&peer.name, peer.incarnation); |
| 928 | + // Not in the table: no pid of it was ever seen, nothing is tied. |
| 929 | + if let Some(index) = index { |
| 930 | + dist::inbound::node_down(self.sched(), &self.dist, index); |
| 931 | + } |
| 932 | + let why = lock(&self.last_closed) |
| 933 | + .take() |
| 934 | + .filter(|(label, _)| *label == peer.name) |
| 935 | + .map(|(_, why)| why) |
| 936 | + .unwrap_or_default(); |
| 937 | + if was_up { |
| 938 | + self.tell(&mut watchers, &peer.name, || { |
| 939 | + node_down_event(&peer.name, &why) |
| 940 | + }); |
| 941 | + } |
| 942 | + } |
| 943 | + |
| 944 | + fn message(&self, from: &Node, header: &MessageHeader, payload: &[u8]) { |
| 945 | + self.ready.pass(); |
| 946 | + let Some(me) = self.me() else { |
| 947 | + return; |
| 948 | + }; |
| 949 | + // The spawner's mailbox takes only the `Request`s this node |
| 950 | + // builds once it has checked their key and type: a message |
| 951 | + // naming its subject (a counter, easy to guess) would hand the |
| 952 | + // dispatcher an `Arg` whose descriptor is not its value's. |
| 953 | + if (header.serial as i64, header.tag as i64) == self.spawner { |
| 954 | + return self.drop_frame(from, &"a message to the spawner"); |
| 955 | + } |
| 956 | + let Some(decoded) = self.decode(from, me, header.type_hash, payload) else { |
| 957 | + return self.drop_frame(from, &"a message from a node that is not up"); |
| 958 | + }; |
| 959 | + match decoded { |
| 960 | + // The header's serial is below 2^46 (checked): a local pid. |
| 961 | + Ok(value) => dist::inbound::deliver( |
| 962 | + self.sched(), |
| 963 | + header.serial as i64, |
| 964 | + header.tag as i64, |
| 965 | + value, |
| 966 | + ), |
| 967 | + Err(e) => self.drop_frame(from, &e), |
| 968 | + } |
| 969 | + } |
| 970 | + |
| 971 | + fn signal(&self, from: &Node, body: &[u8]) { |
| 972 | + self.ready.pass(); |
| 973 | + match body.split_first() { |
| 974 | + Some((&LOOKUP, rest)) => self.lookup(from, rest), |
| 975 | + Some((&ANSWER, rest)) => self.answered(from, rest), |
| 976 | + Some((&op, rest)) if ties::is_tie(op) => self.tie(from, op, rest), |
| 977 | + Some((&op @ (SPAWN | SPAWN_LINKED | SPAWN_MONITORED), rest)) => { |
| 978 | + self.spawn_asked(from, op, rest) |
| 979 | + } |
| 980 | + Some((&SPAWN_ANSWER, rest)) => self.spawn_answered(from, rest), |
| 981 | + _ => self.drop_frame(from, &"an unknown signal"), |
| 982 | + } |
| 983 | + } |
| 984 | + |
| 985 | + fn drained(&self, _peer: &Node, waiters: &[Waiter]) { |
| 986 | + for waiter in waiters { |
| 987 | + dist::wake_sender(self.sched(), *waiter); |
| 988 | + } |
| 989 | + } |
| 990 | + |
| 991 | + fn closed(&self, peer: &str, reason: &Reason, hearsay: bool) { |
| 992 | + *lock(&self.last_closed) = Some((peer.to_owned(), reason.to_string())); |
| 993 | + if reason.routine() { |
| 994 | + return; |
| 995 | + } |
| 996 | + // Before its hello, a connection is labelled by its address: one |
| 997 | + // any host can open, at its own rate, so logged sparingly, and |
| 998 | + // remembered only by node name, for `whereis`'s error. A dial to |
| 999 | + // a name and address that only peers' lists gave: they choose |
| 1000 | + // how many fail, so the same, and kept out of `failures`, |
| 1001 | + // whose entries it would push out. |
| 1002 | + let throttle = if hearsay { |
| 1003 | + Some(&self.hearsay) |
| 1004 | + } else { |
| 1005 | + (!louise_rt_prims::wire::check_node_name(peer.as_bytes())) |
| 1006 | + .then_some(&self.unauthenticated) |
| 1007 | + }; |
| 1008 | + if let Some(throttle) = throttle { |
| 1009 | + let admitted = lock(throttle).admit(std::time::Instant::now()); |
| 1010 | + if let Some(held) = admitted { |
| 1011 | + let held = Throttle::held_back(held); |
| 1012 | + eprintln!("louise: dist: {peer}: {reason}{held}"); |
| 1013 | + } |
| 1014 | + return; |
| 1015 | + } |
| 1016 | + eprintln!("louise: dist: {peer}: {reason}"); |
| 1017 | + let mut failures = lock(&self.failures); |
| 1018 | + if failures.len() >= MAX_FAILURES { |
| 1019 | + failures.clear(); |
| 1020 | + } |
| 1021 | + failures.insert(peer.to_owned(), reason.to_string()); |
| 1022 | + } |
| 1023 | + } |
| 1024 | + |
| 1025 | + // ---- lookup frames (`docs/wire-format.md`, *Lookups*) ------------------------ |
| 1026 | + |
| 1027 | + /// A signal frame's first byte: a lookup, or its answer. |
| 1028 | + const LOOKUP: u8 = 1; |
| 1029 | + const ANSWER: u8 = 2; |
| 1030 | + |
| 1031 | + /// An answer's result. |
| 1032 | + const FOUND: u8 = 0; |
| 1033 | + const NO_NAME: u8 = 1; |
| 1034 | + const OTHER_TYPE: u8 = 2; |
| 1035 | + |
| 1036 | + struct LookupRequest<'a> { |
| 1037 | + /// The asking actor (a pid of the asking node) and its reply |
| 1038 | + /// subject's tag: echoed in the answer. |
| 1039 | + asker: u64, |
| 1040 | + reply_tag: u64, |
| 1041 | + /// The type the asker expects. |
| 1042 | + hash: u64, |
| 1043 | + name: &'a [u8], |
| 1044 | + } |
| 1045 | + |
| 1046 | + impl LookupRequest<'_> { |
| 1047 | + fn encode(&self) -> Vec<u8> { |
| 1048 | + let mut out = Vec::with_capacity(26 + self.name.len()); |
| 1049 | + out.push(LOOKUP); |
| 1050 | + out.extend_from_slice(&self.asker.to_le_bytes()); |
| 1051 | + out.extend_from_slice(&self.reply_tag.to_le_bytes()); |
| 1052 | + out.extend_from_slice(&self.hash.to_le_bytes()); |
| 1053 | + out.push(self.name.len() as u8); |
| 1054 | + out.extend_from_slice(self.name); |
| 1055 | + out |
| 1056 | + } |
| 1057 | + |
| 1058 | + /// From the bytes after the frame's first. |
| 1059 | + fn decode(body: &[u8]) -> Option<LookupRequest<'_>> { |
| 1060 | + let (fixed, name) = body.split_first_chunk::<25>()?; |
| 1061 | + let word = |i: usize| u64::from_le_bytes(fixed[i..i + 8].try_into().expect("8 bytes")); |
| 1062 | + let request = LookupRequest { |
| 1063 | + asker: word(0), |
| 1064 | + reply_tag: word(8), |
| 1065 | + hash: word(16), |
| 1066 | + name, |
| 1067 | + }; |
| 1068 | + (request.asker < MAX_PID_SERIAL |
| 1069 | + && request.reply_tag < MAX_TAG |
| 1070 | + && usize::from(fixed[24]) == name.len()) |
| 1071 | + .then_some(request) |
| 1072 | + } |
| 1073 | + } |
| 1074 | + |
| 1075 | + struct LookupReply { |
| 1076 | + asker: u64, |
| 1077 | + reply_tag: u64, |
| 1078 | + result: u8, |
| 1079 | + /// Found: the registered subject's owner (a pid of the answering |
| 1080 | + /// node) and tag; else 0. |
| 1081 | + serial: u64, |
| 1082 | + tag: u64, |
| 1083 | + /// The registered type's hash (found, or another type); else 0. |
| 1084 | + hash: u64, |
| 1085 | + } |
| 1086 | + |
| 1087 | + impl LookupReply { |
| 1088 | + const LEN: usize = 42; |
| 1089 | + |
| 1090 | + fn encode(&self) -> Vec<u8> { |
| 1091 | + let mut out = Vec::with_capacity(Self::LEN); |
| 1092 | + out.push(ANSWER); |
| 1093 | + out.extend_from_slice(&self.asker.to_le_bytes()); |
| 1094 | + out.extend_from_slice(&self.reply_tag.to_le_bytes()); |
| 1095 | + out.push(self.result); |
| 1096 | + out.extend_from_slice(&self.serial.to_le_bytes()); |
| 1097 | + out.extend_from_slice(&self.tag.to_le_bytes()); |
| 1098 | + out.extend_from_slice(&self.hash.to_le_bytes()); |
| 1099 | + out |
| 1100 | + } |
| 1101 | + |
| 1102 | + /// From the bytes after the frame's first. |
| 1103 | + fn decode(body: &[u8]) -> Option<LookupReply> { |
| 1104 | + let body: &[u8; Self::LEN - 1] = body.try_into().ok()?; |
| 1105 | + let word = |i: usize| u64::from_le_bytes(body[i..i + 8].try_into().expect("8 bytes")); |
| 1106 | + let reply = LookupReply { |
| 1107 | + asker: word(0), |
| 1108 | + reply_tag: word(8), |
| 1109 | + result: body[16], |
| 1110 | + serial: word(17), |
| 1111 | + tag: word(25), |
| 1112 | + hash: word(33), |
| 1113 | + }; |
| 1114 | + (reply.asker < MAX_PID_SERIAL |
| 1115 | + && reply.reply_tag < MAX_TAG |
| 1116 | + && reply.result <= OTHER_TYPE |
| 1117 | + && reply.serial < MAX_PID_SERIAL |
| 1118 | + && reply.tag < MAX_TAG) |
| 1119 | + .then_some(reply) |
| 1120 | + } |
| 1121 | + } |
| 1122 | + |
| 1123 | + // ---- spawn frames (`docs/wire-format.md`, *Spawns*) ---------------------------- |
| 1124 | + |
| 1125 | + /// A signal frame's first byte: a spawn request, its answer, a linked |
| 1126 | + /// spawn request, a monitored one. |
| 1127 | + const SPAWN: u8 = 0x20; |
| 1128 | + const SPAWN_ANSWER: u8 = 0x21; |
| 1129 | + const SPAWN_LINKED: u8 = 0x22; |
| 1130 | + const SPAWN_MONITORED: u8 = 0x23; |
| 1131 | + |
| 1132 | + /// A spawn answer's result. |
| 1133 | + const SPAWNED: u8 = 0; |
| 1134 | + const NO_ENTRY: u8 = 1; |
| 1135 | + const ENTRY_TYPE: u8 = 2; |
| 1136 | + const NOT_SPAWNED: u8 = 3; |
| 1137 | + |
| 1138 | + /// The `std/dist` code of a refused spawn's result. |
| 1139 | + fn spawn_failure(result: u8) -> i64 { |
| 1140 | + match result { |
| 1141 | + NO_ENTRY => code::UNKNOWN_ENTRY, |
| 1142 | + ENTRY_TYPE => code::WRONG_TYPE, |
| 1143 | + _ => code::REFUSED, |
| 1144 | + } |
| 1145 | + } |
| 1146 | + |
| 1147 | + /// How a spawn's new actor is tied to its asker: the request's op. |
| 1148 | + #[derive(Clone, Copy, Debug, PartialEq)] |
| 1149 | + enum SpawnTie { |
| 1150 | + /// `spawn_on` (op `0x20`). |
| 1151 | + Untied, |
| 1152 | + /// `spawn_link_on` (op `0x22`). |
| 1153 | + Link, |
| 1154 | + /// `spawn_monitor_on` (op `0x23`): the asker's `Down` is due on |
| 1155 | + /// this tag (below 2^62). |
| 1156 | + Monitor(u64), |
| 1157 | + } |
| 1158 | + |
| 1159 | + impl SpawnTie { |
| 1160 | + /// From `std/dist`'s `Tie` (its constructor's index: `Untied`, |
| 1161 | + /// `Linked`, `Monitored`) and the monitor's tag. `None` if out of |
| 1162 | + /// range. |
| 1163 | + fn from_parts(tie: i64, down: i64) -> Option<SpawnTie> { |
| 1164 | + match tie { |
| 1165 | + 0 => Some(SpawnTie::Untied), |
| 1166 | + 1 => Some(SpawnTie::Link), |
| 1167 | + 2 => u64::try_from(down) |
| 1168 | + .ok() |
| 1169 | + .filter(|d| *d < MAX_TAG) |
| 1170 | + .map(SpawnTie::Monitor), |
| 1171 | + _ => None, |
| 1172 | + } |
| 1173 | + } |
| 1174 | + |
| 1175 | + /// The op of a spawn request tied so. |
| 1176 | + fn op(self) -> u8 { |
| 1177 | + match self { |
| 1178 | + SpawnTie::Untied => SPAWN, |
| 1179 | + SpawnTie::Link => SPAWN_LINKED, |
| 1180 | + SpawnTie::Monitor(_) => SPAWN_MONITORED, |
| 1181 | + } |
| 1182 | + } |
| 1183 | + |
| 1184 | + /// `std/dist`'s `Tie`, and the monitor's tag (0 if none). |
| 1185 | + fn parts(self) -> (i64, i64) { |
| 1186 | + match self { |
| 1187 | + SpawnTie::Untied => (0, 0), |
| 1188 | + SpawnTie::Link => (1, 0), |
| 1189 | + SpawnTie::Monitor(down) => (2, down as i64), |
| 1190 | + } |
| 1191 | + } |
| 1192 | + } |
| 1193 | + |
| 1194 | + struct SpawnRequest<'a> { |
| 1195 | + /// The asking actor (a pid of the asking node) and its reply |
| 1196 | + /// subject's tag: echoed in the answer. |
| 1197 | + asker: u64, |
| 1198 | + reply_tag: u64, |
| 1199 | + /// The `@remote` function's key, its argument's type hash, and the |
| 1200 | + /// argument (a message payload). |
| 1201 | + key: u64, |
| 1202 | + hash: u64, |
| 1203 | + payload: &'a [u8], |
| 1204 | + tie: SpawnTie, |
| 1205 | + } |
| 1206 | + |
| 1207 | + impl SpawnRequest<'_> { |
| 1208 | + fn encode(&self) -> Vec<u8> { |
| 1209 | + let mut out = Vec::with_capacity(41 + self.payload.len()); |
| 1210 | + out.push(self.tie.op()); |
| 1211 | + out.extend_from_slice(&self.asker.to_le_bytes()); |
| 1212 | + out.extend_from_slice(&self.reply_tag.to_le_bytes()); |
| 1213 | + out.extend_from_slice(&self.key.to_le_bytes()); |
| 1214 | + out.extend_from_slice(&self.hash.to_le_bytes()); |
| 1215 | + if let SpawnTie::Monitor(down) = self.tie { |
| 1216 | + out.extend_from_slice(&down.to_le_bytes()); |
| 1217 | + } |
| 1218 | + out.extend_from_slice(self.payload); |
| 1219 | + out |
| 1220 | + } |
| 1221 | + |
| 1222 | + /// From the bytes after the frame's first, `op`: a monitored |
| 1223 | + /// spawn's fixed fields are 8 bytes longer, its down tag. |
| 1224 | + fn decode(op: u8, body: &[u8]) -> Option<SpawnRequest<'_>> { |
| 1225 | + let (fixed, rest) = body.split_first_chunk::<32>()?; |
| 1226 | + let word = |i: usize| u64::from_le_bytes(fixed[i..i + 8].try_into().expect("8 bytes")); |
| 1227 | + let (tie, payload) = match op { |
| 1228 | + SPAWN => (SpawnTie::Untied, rest), |
| 1229 | + SPAWN_LINKED => (SpawnTie::Link, rest), |
| 1230 | + SPAWN_MONITORED => { |
| 1231 | + let (down, payload) = rest.split_first_chunk::<8>()?; |
| 1232 | + let down = u64::from_le_bytes(*down); |
| 1233 | + (down < MAX_TAG).then_some((SpawnTie::Monitor(down), payload))? |
| 1234 | + } |
| 1235 | + _ => return None, |
| 1236 | + }; |
| 1237 | + let request = SpawnRequest { |
| 1238 | + asker: word(0), |
| 1239 | + reply_tag: word(8), |
| 1240 | + key: word(16), |
| 1241 | + hash: word(24), |
| 1242 | + payload, |
| 1243 | + tie, |
| 1244 | + }; |
| 1245 | + // A key is below 2^62, as a tag. |
| 1246 | + (request.asker < MAX_PID_SERIAL && request.reply_tag < MAX_TAG && request.key < MAX_TAG) |
| 1247 | + .then_some(request) |
| 1248 | + } |
| 1249 | + } |
| 1250 | + |
| 1251 | + struct SpawnReply { |
| 1252 | + asker: u64, |
| 1253 | + reply_tag: u64, |
| 1254 | + result: u8, |
| 1255 | + /// Spawned: the new actor (a pid of the answering node); else 0. |
| 1256 | + serial: u64, |
| 1257 | + } |
| 1258 | + |
| 1259 | + impl SpawnReply { |
| 1260 | + const LEN: usize = 26; |
| 1261 | + |
| 1262 | + fn encode(&self) -> Vec<u8> { |
| 1263 | + let mut out = Vec::with_capacity(Self::LEN); |
| 1264 | + out.push(SPAWN_ANSWER); |
| 1265 | + out.extend_from_slice(&self.asker.to_le_bytes()); |
| 1266 | + out.extend_from_slice(&self.reply_tag.to_le_bytes()); |
| 1267 | + out.push(self.result); |
| 1268 | + out.extend_from_slice(&self.serial.to_le_bytes()); |
| 1269 | + out |
| 1270 | + } |
| 1271 | + |
| 1272 | + /// From the bytes after the frame's first. |
| 1273 | + fn decode(body: &[u8]) -> Option<SpawnReply> { |
| 1274 | + let body: &[u8; Self::LEN - 1] = body.try_into().ok()?; |
| 1275 | + let word = |i: usize| u64::from_le_bytes(body[i..i + 8].try_into().expect("8 bytes")); |
| 1276 | + let reply = SpawnReply { |
| 1277 | + asker: word(0), |
| 1278 | + reply_tag: word(8), |
| 1279 | + result: body[16], |
| 1280 | + serial: word(17), |
| 1281 | + }; |
| 1282 | + (reply.asker < MAX_PID_SERIAL |
| 1283 | + && reply.reply_tag < MAX_TAG |
| 1284 | + && reply.result <= NOT_SPAWNED |
| 1285 | + && reply.serial < MAX_PID_SERIAL) |
| 1286 | + .then_some(reply) |
| 1287 | + } |
| 1288 | + } |
| 1289 | + |
| 1290 | + // ---- hooks --------------------------------------------------------------------- |
| 1291 | + |
| 1292 | + /// The node, if this program started one and it still runs: the |
| 1293 | + /// running transport's incarnation, not a node a program that ended |
| 1294 | + /// left in [`NODE`] while a new one starts its own. |
| 1295 | + fn running() -> Option<Arc<State>> { |
| 1296 | + let incarnation = transport::with_program(|t| t.me().incarnation)?; |
| 1297 | + NODE.read() |
| 1298 | + .unwrap_or_else(PoisonError::into_inner) |
| 1299 | + .clone() |
| 1300 | + .filter(|s| s.me.get().is_some_and(|me| me.incarnation == incarnation)) |
| 1301 | + } |
| 1302 | + |
| 1303 | + /// The node `sched`'s program started, while it runs. |
| 1304 | + fn current(sched: &Shared) -> Option<Arc<State>> { |
| 1305 | + running().filter(|s| std::ptr::eq(s.sched.0, sched)) |
| 1306 | + } |
| 1307 | + |
| 1308 | + fn send_hook( |
| 1309 | + ctx: *mut Ctx, |
| 1310 | + owner: i64, |
| 1311 | + tag: i64, |
| 1312 | + wire: i64, |
| 1313 | + message: Value, |
| 1314 | + ) -> Result<(), CString> { |
| 1315 | + send_message(ctx, owner, tag, wire, message).map_err(|why| dist::unsendable(&why)) |
| 1316 | + } |
| 1317 | + |
| 1318 | + /// [`send_hook`]'s work; an error is why the message cannot be sent. |
| 1319 | + fn send_message( |
| 1320 | + ctx: *mut Ctx, |
| 1321 | + owner: i64, |
| 1322 | + tag: i64, |
| 1323 | + wire: i64, |
| 1324 | + message: Value, |
| 1325 | + ) -> Result<(), String> { |
| 1326 | + // Stopping: as to a dead actor. |
| 1327 | + let Some(node) = running() else { |
| 1328 | + return Ok(()); |
| 1329 | + }; |
| 1330 | + let Some(me) = node.me() else { |
| 1331 | + return Ok(()); |
| 1332 | + }; |
| 1333 | + let (index, serial) = dist::parts(owner); |
| 1334 | + let to = (node.dist.nodes.read()) |
| 1335 | + .unwrap_or_else(PoisonError::into_inner) |
| 1336 | + .get(index) |
| 1337 | + .cloned(); |
| 1338 | + let to = to.ok_or("a remote pid of no known node")?; |
| 1339 | + let wire = u32::try_from(wire).map_err(|_| format!("no wire type {wire}"))?; |
| 1340 | + let hash = node |
| 1341 | + .registry |
| 1342 | + .hash(wire) |
| 1343 | + .ok_or_else(|| format!("no wire type {wire}"))?; |
| 1344 | + // SAFETY: `message` is live (borrowed), a value of the subject's |
| 1345 | + // message type, the type registered at `wire`. |
| 1346 | + let payload = unsafe { wire::encode(&node.registry, wire, message, me, &node.dist.nodes) } |
| 1347 | + .map_err(|e| e.to_string())?; |
| 1348 | + let header = MessageHeader { |
| 1349 | + incarnation: to.incarnation, |
| 1350 | + serial: serial as u64, |
| 1351 | + tag: tag as u64, |
| 1352 | + type_hash: hash, |
| 1353 | + payload_len: payload.len() as u32, |
| 1354 | + }; |
| 1355 | + let mut frame = Vec::with_capacity(HEADER_LEN + payload.len()); |
| 1356 | + frame.extend_from_slice(&header.encode()); |
| 1357 | + frame.extend_from_slice(&payload); |
| 1358 | + let size = frame.len(); |
| 1359 | + // At most once: as a message lost with a connection. |
| 1360 | + let unsent = || transport::with_program(|t| t.count_unsent(&to.name)); |
| 1361 | + let attempt = |frame, waiter| match transport::with_program(|t| t.queue(&to, frame, waiter)) |
| 1362 | + { |
| 1363 | + // Stopping: as to a dead actor. |
| 1364 | + None | Some(Ok(())) => Try::Done(Ok(())), |
| 1365 | + Some(Err((SendError::Full, frame))) => Try::Full(frame), |
| 1366 | + Some(Err((SendError::NotConnected, _))) => { |
| 1367 | + unsent(); |
| 1368 | + Try::Done(Ok(())) |
| 1369 | + } |
| 1370 | + Some(Err((SendError::TooLarge, _))) => Try::Done(Err(format!( |
| 1371 | + "a message of {size} bytes is over {}'s frame limit", |
| 1372 | + to.name |
| 1373 | + ))), |
| 1374 | + Some(Err((SendError::Malformed, _))) => { |
| 1375 | + Try::Done(Err("a malformed message frame".into())) |
| 1376 | + } |
| 1377 | + // Only signal frames need a capability flag. |
| 1378 | + Some(Err((SendError::Unsupported, _))) => { |
| 1379 | + Try::Done(Err("a message frame refused as a signal".into())) |
| 1380 | + } |
| 1381 | + }; |
| 1382 | + let unwait = |waiter: Waiter| { |
| 1383 | + transport::with_program(|t| t.unwait(&to, waiter)); |
| 1384 | + }; |
| 1385 | + // SAFETY: the hook runs on the running actor of `ctx`; nothing is |
| 1386 | + // locked across the parking. |
| 1387 | + let sent = unsafe { dist::send_parking(ctx, Outbound::Message(frame), attempt, unwait) }; |
| 1388 | + sent.unwrap_or_else(|| { |
| 1389 | + // The sender exited while parked: its frame is dropped. |
| 1390 | + unsent(); |
| 1391 | + Ok(()) |
| 1392 | + }) |
| 1393 | + } |
| 1394 | + |
| 1395 | + /// Queue a tie frame from the local `local` to the remote `remote`, on |
| 1396 | + /// its node's ordered stream: whether that incarnation is up and takes |
| 1397 | + /// the frame's op. One its runtime does not take (a demonitor, an |
| 1398 | + /// unlink, its flag unset in the hello) is not sent: the caller acts |
| 1399 | + /// as for a node that is not up. |
| 1400 | + fn send_tie(node: &State, local: i64, remote: i64, op: Op) -> bool { |
| 1401 | + let (index, serial) = dist::parts(remote); |
| 1402 | + let to = (node.dist.nodes.read()) |
| 1403 | + .unwrap_or_else(PoisonError::into_inner) |
| 1404 | + .get(index) |
| 1405 | + .cloned(); |
| 1406 | + // A local pid past 2^46 cannot be named on another node (`dist`). |
| 1407 | + let from = u64::try_from(local).ok().filter(|p| *p < MAX_PID_SERIAL); |
| 1408 | + let (Some(to), Some(from)) = (to, from) else { |
| 1409 | + return false; |
| 1410 | + }; |
| 1411 | + let tie = Tie { |
| 1412 | + from, |
| 1413 | + to: serial as u64, |
| 1414 | + op, |
| 1415 | + }; |
| 1416 | + // Never `TooLarge`: a tie frame fits the smallest frame limit. |
| 1417 | + transport::with_program(|t| t.send(&to, Outbound::Signal(tie.encode()))) == Some(Ok(())) |
| 1418 | + } |
| 1419 | + |
| 1420 | + fn noconnection() -> Exit { |
| 1421 | + Exit::Crashed("noconnection".into()) |
| 1422 | + } |
| 1423 | + |
| 1424 | + fn noproc() -> Exit { |
| 1425 | + Exit::Crashed("noproc".into()) |
| 1426 | + } |
| 1427 | + |
| 1428 | + /// `me`'s link to `other`: its own half and the link frame, under its |
| 1429 | + /// lock, so its exit cannot pass the frame. To a node that is not up, |
| 1430 | + /// `me` gets the exit the node's loss would have given it, on its own |
| 1431 | + /// thread (as `op_monitor`'s `noproc`: the local paths `dist::inbound` |
| 1432 | + /// takes are those a local exit takes). |
| 1433 | + fn link_hook(sched: &Shared, me: &Actor, other: i64) { |
| 1434 | + let Some(node) = running() else { |
| 1435 | + return; |
| 1436 | + }; |
| 1437 | + let send = || send_tie(&node, me.pid, other, Op::Link); |
| 1438 | + if dist::outbound::link(&node.dist, me, other, send) == Some(false) { |
| 1439 | + let lost = Signal::Linked(noconnection()); |
| 1440 | + dist::inbound::signal(sched, other, me.pid, &lost); |
| 1441 | + } |
| 1442 | + } |
| 1443 | + |
| 1444 | + /// `me`'s monitor of `watched`: its own half, then the monitor frame. |
| 1445 | + /// On a node that is not up, its `Down` at once, as the node's loss |
| 1446 | + /// would have given it. Stopping: none, as for a dead pid. |
| 1447 | + fn monitor_hook(sched: &Shared, me: &Actor, watched: i64, tag: i64) -> bool { |
| 1448 | + let Some(node) = running() else { |
| 1449 | + return false; |
| 1450 | + }; |
| 1451 | + if dist::outbound::monitor(sched, &node.dist, me, watched, tag) |
| 1452 | + && !send_tie(&node, me.pid, watched, Op::Monitor { tag: tag as u64 }) |
| 1453 | + { |
| 1454 | + dist::inbound::down(sched, me.pid, tag, watched, &noconnection()); |
| 1455 | + } |
| 1456 | + true |
| 1457 | + } |
| 1458 | + |
| 1459 | + /// `me`'s demonitor of `watched`: its own half, then, if it had the |
| 1460 | + /// monitor, the demonitor frame. Dropped if the node is not up: its |
| 1461 | + /// loss forgets the monitor there. Not sent to a node whose runtime |
| 1462 | + /// does not take it (`send_tie`): the monitor stays there, and its |
| 1463 | + /// `Down` is dropped here, `me` no longer watching. |
| 1464 | + fn demonitor_hook(me: &Actor, watched: i64, tag: i64) { |
| 1465 | + if dist::outbound::demonitor(me, watched, tag) |
| 1466 | + && let Some(node) = running() |
| 1467 | + { |
| 1468 | + send_tie(&node, me.pid, watched, Op::Demonitor { tag: tag as u64 }); |
| 1469 | + } |
| 1470 | + } |
| 1471 | + |
| 1472 | + /// `me`'s unlink of `other`: its own half goes to unlinking, and the |
| 1473 | + /// unlink frame is queued, under its lock. On a node that is not up, |
| 1474 | + /// or while stopping, the half goes at once: no acknowledgement can |
| 1475 | + /// come, and the node's loss ends the other side's. So it does on a |
| 1476 | + /// node whose runtime does not take an unlink (`send_tie`), which |
| 1477 | + /// keeps its half: an exit through it is ignored here, and the |
| 1478 | + /// connection's loss ends it there. |
| 1479 | + fn unlink_hook(me: &Actor, other: i64) { |
| 1480 | + let node = running(); |
| 1481 | + let id = node.as_ref().map_or(0, |n| n.dist.unlink_id()); |
| 1482 | + dist::outbound::unlink(me, other, id, || { |
| 1483 | + let unlink = Op::Unlink { id }; |
| 1484 | + node.is_some_and(|n| send_tie(&n, me.pid, other, unlink)) |
| 1485 | + }); |
| 1486 | + } |
| 1487 | + |
| 1488 | + /// `kill`, `stop` and a link's exit; dropped if the node is not up. |
| 1489 | + fn signal_hook(from: i64, to: i64, signal: &Signal) { |
| 1490 | + let op = match signal { |
| 1491 | + Signal::Kill => Op::Kill, |
| 1492 | + Signal::Stop => Op::Stop, |
| 1493 | + Signal::Linked(reason) => Op::Exit(reason.clone()), |
| 1494 | + }; |
| 1495 | + if let Some(node) = running() { |
| 1496 | + send_tie(&node, from, to, op); |
| 1497 | + } |
| 1498 | + } |
| 1499 | + |
| 1500 | + /// The `Down` of `watched` for its remote `watcher`; dropped if the |
| 1501 | + /// node is not up. |
| 1502 | + fn down_hook(watched: i64, watcher: i64, tag: i64, reason: &Exit) { |
| 1503 | + let op = Op::Down { |
| 1504 | + tag: tag as u64, |
| 1505 | + reason: reason.clone(), |
| 1506 | + }; |
| 1507 | + if let Some(node) = running() { |
| 1508 | + send_tie(&node, watched, watcher, op); |
| 1509 | + } |
| 1510 | + } |
| 1511 | + |
| 1512 | + /// The local `pid` exited: unlist it from the nodes it was tied to. |
| 1513 | + fn exit_hook(pid: i64, nodes: &[u16]) { |
| 1514 | + if let Some(node) = running() { |
| 1515 | + node.dist.untie(pid, nodes); |
| 1516 | + } |
| 1517 | + } |
| 1518 | + |
| 1519 | + // ---- externs --------------------------------------------------------------- |
| 1520 | + |
| 1521 | + /// Panic in the running actor with `why`. |
| 1522 | + fn panic(ctx: *mut Ctx, why: &str) -> Value { |
| 1523 | + let why = CString::new(format!("dist: {why}")).unwrap_or_default(); |
| 1524 | + // SAFETY: the running actor's context; `why` is NUL-terminated. |
| 1525 | + unsafe { crate::effects::tl_panic_str(ctx, why.as_ptr()) } |
| 1526 | + } |
| 1527 | + |
| 1528 | + /// `std/dist.start`: start this node (see the module's documentation). |
| 1529 | + /// `listen` and each seed's address are `ip:port`, `[ip6]:port`, and so |
| 1530 | + /// is `advertise`, or empty (`Config::advertise`'s `None`); |
| 1531 | + /// `seeds` a `List<(String, String)>` of node names and addresses; |
| 1532 | + /// `table` and `schema_hash` are `std/wire`'s; `limits` the heartbeat |
| 1533 | + /// and node-down delays in milliseconds, the largest message payload |
| 1534 | + /// this node accepts, the message bytes queued per peer and the |
| 1535 | + /// connections kept before a stranger is refused (`[cluster]`'s |
| 1536 | + /// `max_message_bytes`, `outbound_queue_bytes` and `max_peers`), and |
| 1537 | + /// the discovery (0 seeds, 1 mesh); |
| 1538 | + /// `entries` `std/wire.entries`; `spawner` the subject of the actor |
| 1539 | + /// that runs the spawns other nodes ask. `Ok(port)`, the port it |
| 1540 | + /// listens on, or `Error(why)`. Reads the |
| 1541 | + /// certificate files here, on the scheduler thread, once. |
| 1542 | + /// |
| 1543 | + /// # Safety |
| 1544 | + /// `ctx` must be the running actor's context, the arguments live values |
| 1545 | + /// of the types `std/dist` declares. |
| 1546 | + #[unsafe(no_mangle)] |
| 1547 | + #[allow(clippy::too_many_arguments)] |
| 1548 | + pub unsafe extern "C" fn tl_dist_start( |
| 1549 | + ctx: *mut Ctx, |
| 1550 | + node: Value, |
| 1551 | + cluster: Value, |
| 1552 | + listen: Value, |
| 1553 | + advertise: Value, |
| 1554 | + seeds: Value, |
| 1555 | + cert_file: Value, |
| 1556 | + key_file: Value, |
| 1557 | + ca_files: Value, |
| 1558 | + table: Value, |
| 1559 | + schema_hash: Value, |
| 1560 | + limits: Value, |
| 1561 | + entries: Value, |
| 1562 | + spawner: Value, |
| 1563 | + ) -> Value { |
| 1564 | + // SAFETY: caller guarantees the context and the types. |
| 1565 | + let started = unsafe { |
| 1566 | + let (_, sched) = this(ctx); |
| 1567 | + let address = |v: Value| { |
| 1568 | + text(v) |
| 1569 | + .parse::<SocketAddr>() |
| 1570 | + .map_err(|_| format!("{:?} is not an address and port", text(v))) |
| 1571 | + }; |
| 1572 | + let pair = |v: Value| { |
| 1573 | + let f = Block::fields_ptr(v as *mut Block); |
| 1574 | + (*f, *f.add(1)) |
| 1575 | + }; |
| 1576 | + (|| { |
| 1577 | + let mut config = Config::new(text(node), text(cluster), address(listen)?); |
| 1578 | + if !text(advertise).is_empty() { |
| 1579 | + config.advertise = Some(address(advertise)?); |
| 1580 | + } |
| 1581 | + for seed in list_items(seeds) { |
| 1582 | + let (name, at) = pair(seed); |
| 1583 | + config.seeds.push((text(name).to_owned(), address(at)?)); |
| 1584 | + } |
| 1585 | + config.cert_file = text(cert_file).to_owned(); |
| 1586 | + config.key_file = text(key_file).to_owned(); |
| 1587 | + config.ca_files = list_items(ca_files).map(|f| text(f).to_owned()).collect(); |
| 1588 | + config.schema_hash = u64::from_str_radix(text(schema_hash), 16) |
| 1589 | + .map_err(|_| "a malformed schema hash".to_string())?; |
| 1590 | + let limit = |i: usize, what: &str| { |
| 1591 | + // A big integer saturates (`Config::check` bounds it). |
| 1592 | + let v = crate::int::saturating(*Block::fields_ptr(limits as *mut Block).add(i)); |
| 1593 | + u64::try_from(v).map_err(|_| format!("{what} must not be negative")) |
| 1594 | + }; |
| 1595 | + config.heartbeat_ms = limit(0, "heartbeat_ms")?; |
| 1596 | + config.node_down_after_ms = limit(1, "node_down_after_ms")?; |
| 1597 | + // As `[cluster]` bounds it. The frame limit is a message |
| 1598 | + // frame's of the largest payload: its kind, its header and |
| 1599 | + // the payload. |
| 1600 | + let message = limit(2, "max_message_bytes")?; |
| 1601 | + if !(u64::from(MIN_FRAME)..=u64::from(MAX_PAYLOAD)).contains(&message) { |
| 1602 | + return Err(format!( |
| 1603 | + "max_message_bytes must be between {MIN_FRAME} and {MAX_PAYLOAD}" |
| 1604 | + )); |
| 1605 | + } |
| 1606 | + config.max_frame = (message + 1 + HEADER_LEN as u64) as u32; |
| 1607 | + config.max_queue = usize::try_from(limit(3, "outbound_queue_bytes")?) |
| 1608 | + .map_err(|_| "outbound_queue_bytes is too large".to_string())?; |
| 1609 | + // `Config::check` bounds it as `[cluster]` does. |
| 1610 | + config.max_peers = usize::try_from(limit(4, "max_peers")?).unwrap_or(usize::MAX); |
| 1611 | + config.mesh = match limit(5, "discovery")? { |
| 1612 | + 0 => false, |
| 1613 | + 1 => true, |
| 1614 | + _ => return Err("discovery must be 0 (seeds) or 1 (mesh)".into()), |
| 1615 | + }; |
| 1616 | + // `Entry(key, name, descriptor, hash)`. |
| 1617 | + let entries = list_items(entries) |
| 1618 | + .map(|e| { |
| 1619 | + let f = Block::fields_ptr(e as *mut Block); |
| 1620 | + let field = |i: usize| text(*f.add(i)).to_owned(); |
| 1621 | + (int_get(*f), field(1), field(2), field(3)) |
| 1622 | + }) |
| 1623 | + .collect(); |
| 1624 | + let spawner = crate::process::subject_parts(spawner); |
| 1625 | + start(sched, config, text(table), entries, spawner) |
| 1626 | + })() |
| 1627 | + }; |
| 1628 | + match started { |
| 1629 | + Ok(port) => crate::values::ok(ctx, int(i64::from(port))), |
| 1630 | + Err(why) => crate::values::error(ctx, &why), |
| 1631 | + } |
| 1632 | + } |
| 1633 | + |
| 1634 | + /// A `std/wire.Entry`: key, qualified name, descriptor, hash in hex. |
| 1635 | + type EntryParts = (i64, String, String, String); |
| 1636 | + |
| 1637 | + fn start( |
| 1638 | + sched: &Shared, |
| 1639 | + config: Config, |
| 1640 | + table: &str, |
| 1641 | + entries: Vec<EntryParts>, |
| 1642 | + spawner: (i64, i64), |
| 1643 | + ) -> Result<u16, String> { |
| 1644 | + let registry = |
| 1645 | + Registry::new(table).map_err(|e| format!("the program's wire types: {e}"))?; |
| 1646 | + let entries = remote_entries(®istry, entries)?; |
| 1647 | + let state = Arc::new(State { |
| 1648 | + sched: Sched(sched), |
| 1649 | + dist: Dist::default(), |
| 1650 | + registry, |
| 1651 | + me: OnceLock::new(), |
| 1652 | + names: Mutex::default(), |
| 1653 | + peers: Mutex::default(), |
| 1654 | + quotas: Mutex::default(), |
| 1655 | + lookups: Mutex::default(), |
| 1656 | + entries, |
| 1657 | + spawner, |
| 1658 | + spawns: Mutex::default(), |
| 1659 | + failures: Mutex::default(), |
| 1660 | + last_closed: Mutex::default(), |
| 1661 | + unauthenticated: Mutex::default(), |
| 1662 | + hearsay: Mutex::default(), |
| 1663 | + node_watchers: Mutex::default(), |
| 1664 | + refused: AtomicU64::new(0), |
| 1665 | + ready: Gate::default(), |
| 1666 | + }); |
| 1667 | + transport::start_program(sched, config, state.clone())?; |
| 1668 | + // What peers sent meanwhile is handled once the hooks are in. |
| 1669 | + let _ready = OpenOnDrop(&state.ready); |
| 1670 | + let (me, port) = transport::with_program(|t| (t.me().clone(), t.local_addr().port())) |
| 1671 | + .ok_or("distribution stopped")?; |
| 1672 | + let _ = state.me.set(me); |
| 1673 | + *NODE.write().unwrap_or_else(PoisonError::into_inner) = Some(state.clone()); |
| 1674 | + dist::install(&HOOKS); |
| 1675 | + Ok(port) |
| 1676 | + } |
| 1677 | + |
| 1678 | + /// The program's `@remote` functions, their arguments' types |
| 1679 | + /// registered. The compiler computed each hash from the same table: a |
| 1680 | + /// different one here is a bug. |
| 1681 | + fn remote_entries( |
| 1682 | + registry: &Registry, |
| 1683 | + entries: Vec<EntryParts>, |
| 1684 | + ) -> Result<HashMap<i64, RemoteEntry>, String> { |
| 1685 | + let mut by_key = HashMap::with_capacity(entries.len()); |
| 1686 | + for (key, name, descriptor, hash) in entries { |
| 1687 | + let r = registry |
| 1688 | + .register(&descriptor) |
| 1689 | + .map_err(|e| format!("internal error: `{name}`'s argument: {e}"))?; |
| 1690 | + if format!("{:016x}", r.hash) != hash { |
| 1691 | + return Err(format!( |
| 1692 | + "internal error: `{name}`'s argument hashes to {:016x}, {hash} when compiled", |
| 1693 | + r.hash |
| 1694 | + )); |
| 1695 | + } |
| 1696 | + let entry = RemoteEntry { |
| 1697 | + descriptor, |
| 1698 | + wire: r.index, |
| 1699 | + hash: r.hash, |
| 1700 | + }; |
| 1701 | + by_key.insert(key, entry); |
| 1702 | + } |
| 1703 | + Ok(by_key) |
| 1704 | + } |
| 1705 | + |
| 1706 | + /// Register `desc`, a `Wire` dictionary: its hash. A collision stops |
| 1707 | + /// the program (ADR 0072, *Settled*): `Err` is the panic's message. |
| 1708 | + fn register_type(node: &State, desc: &str) -> Result<wire::Registered, String> { |
| 1709 | + node.registry.register(desc).map_err(|e| e.to_string()) |
| 1710 | + } |
| 1711 | + |
| 1712 | + /// `std/dist.register`: `name` (with `desc`, its message type's |
| 1713 | + /// descriptor) now names `subject`, a local one. A code: `OK`, or why |
| 1714 | + /// not (`NOT_STARTED`, `TAKEN` by a live actor, `NOT_LOCAL`). |
| 1715 | + /// |
| 1716 | + /// # Safety |
| 1717 | + /// `ctx` must be the running actor's context; `name` and `desc` live |
| 1718 | + /// strings, `subject` a live subject. |
| 1719 | + #[unsafe(no_mangle)] |
| 1720 | + pub unsafe extern "C" fn tl_dist_register( |
| 1721 | + ctx: *mut Ctx, |
| 1722 | + name: Value, |
| 1723 | + desc: Value, |
| 1724 | + subject: Value, |
| 1725 | + ) -> Value { |
| 1726 | + // SAFETY: caller guarantees the context and the types. |
| 1727 | + let (sched, name, desc, (pid, tag), remote) = unsafe { |
| 1728 | + let (_, sched) = this(ctx); |
| 1729 | + let parts = crate::process::subject_parts(subject); |
| 1730 | + let remote = crate::process::subject_wire(subject).is_some(); |
| 1731 | + (sched, text(name), text(desc), parts, remote) |
| 1732 | + }; |
| 1733 | + let Some(node) = current(sched) else { |
| 1734 | + return int(code::NOT_STARTED); |
| 1735 | + }; |
| 1736 | + if name.len() > MAX_NAME { |
| 1737 | + return panic(ctx, &format!("a name is at most {MAX_NAME} bytes")); |
| 1738 | + } |
| 1739 | + if remote || is_remote(pid) { |
| 1740 | + return int(code::NOT_LOCAL); |
| 1741 | + } |
| 1742 | + let hash = match register_type(&node, desc) { |
| 1743 | + Ok(r) => r.hash, |
| 1744 | + Err(why) => return panic(ctx, &why), |
| 1745 | + }; |
| 1746 | + let mut names = lock(&node.names); |
| 1747 | + if let Some(n) = names.get(name) |
| 1748 | + && (n.pid, n.tag) != (pid, tag) |
| 1749 | + && sched.exists(n.pid) |
| 1750 | + { |
| 1751 | + return int(code::TAKEN); |
| 1752 | + } |
| 1753 | + names.insert(name.to_owned(), Named { pid, tag, hash }); |
| 1754 | + int(code::OK) |
| 1755 | + } |
| 1756 | + |
| 1757 | + /// `std/dist.whereis`: ask `node` which subject `name` names, for |
| 1758 | + /// messages of `desc`'s type. The answer comes on the running actor's |
| 1759 | + /// subject `tag`: at once if this node knows it (its own names, not |
| 1760 | + /// started, not connected), else when `node` answers. |
| 1761 | + /// |
| 1762 | + /// # Safety |
| 1763 | + /// `ctx` must be the running actor's context; `node`, `name` and |
| 1764 | + /// `desc` live strings. |
| 1765 | + #[unsafe(no_mangle)] |
| 1766 | + pub unsafe extern "C" fn tl_dist_whereis( |
| 1767 | + ctx: *mut Ctx, |
| 1768 | + tag: Value, |
| 1769 | + node: Value, |
| 1770 | + name: Value, |
| 1771 | + desc: Value, |
| 1772 | + ) -> Value { |
| 1773 | + // SAFETY: caller guarantees the context and the types. |
| 1774 | + let (asker, sched, node_name, name, desc) = unsafe { |
| 1775 | + let (a, sched) = this(ctx); |
| 1776 | + (a.pid, sched, text(node), text(name), text(desc)) |
| 1777 | + }; |
| 1778 | + let reply_tag = int_get(tag); |
| 1779 | + let answer = |v: Value| { |
| 1780 | + deliver_made(sched, asker, reply_tag, v); |
| 1781 | + UNIT |
| 1782 | + }; |
| 1783 | + let Some(state) = current(sched) else { |
| 1784 | + return answer(failed(code::NOT_STARTED, "")); |
| 1785 | + }; |
| 1786 | + if name.len() > MAX_NAME { |
| 1787 | + return panic(ctx, &format!("a name is at most {MAX_NAME} bytes")); |
| 1788 | + } |
| 1789 | + let hash = match register_type(&state, desc) { |
| 1790 | + Ok(r) => r.hash, |
| 1791 | + Err(why) => return panic(ctx, &why), |
| 1792 | + }; |
| 1793 | + let Some(me) = state.me() else { |
| 1794 | + return answer(failed(code::NOT_STARTED, "")); |
| 1795 | + }; |
| 1796 | + if node_name == me.name { |
| 1797 | + return answer(match state.named(name) { |
| 1798 | + None => failed(code::NO_NAME, ""), |
| 1799 | + Some((_, _, h)) if h != hash => failed(code::WRONG_TYPE, ""), |
| 1800 | + // A local subject is constructor 0, `Subject(owner, tag)`. |
| 1801 | + Some((pid, tag, _)) => { |
| 1802 | + let null = std::ptr::null_mut(); |
| 1803 | + cell(null, 0, &[cell(null, 0, &[int(pid), int(tag)])]) |
| 1804 | + } |
| 1805 | + }); |
| 1806 | + } |
| 1807 | + let peer = transport::with_program(|t| t.peers().into_iter().find(|p| p.name == node_name)) |
| 1808 | + .flatten(); |
| 1809 | + let Some(peer) = peer else { |
| 1810 | + let why = lock(&state.failures) |
| 1811 | + .get(node_name) |
| 1812 | + .cloned() |
| 1813 | + .unwrap_or_default(); |
| 1814 | + return answer(failed(code::NOT_CONNECTED, &why)); |
| 1815 | + }; |
| 1816 | + // Before sending: the answer may come at once. A node down after |
| 1817 | + // this answers it (`State::lost`); one down before, the send fails. |
| 1818 | + lock(&state.lookups).insert( |
| 1819 | + (asker, reply_tag), |
| 1820 | + Lookup { |
| 1821 | + node: peer.clone(), |
| 1822 | + hash, |
| 1823 | + }, |
| 1824 | + ); |
| 1825 | + let request = LookupRequest { |
| 1826 | + asker: asker as u64, |
| 1827 | + reply_tag: reply_tag as u64, |
| 1828 | + hash, |
| 1829 | + name: name.as_bytes(), |
| 1830 | + }; |
| 1831 | + let sent = transport::with_program(|t| t.send(&peer, Outbound::Signal(request.encode()))); |
| 1832 | + if sent != Some(Ok(())) && lock(&state.lookups).remove(&(asker, reply_tag)).is_some() { |
| 1833 | + return answer(failed(code::NOT_CONNECTED, "")); |
| 1834 | + } |
| 1835 | + UNIT |
| 1836 | + } |
| 1837 | + |
| 1838 | + /// `std/dist.monitor_node`: tell the running actor, on its subject |
| 1839 | + /// `tag`, whether `node` is up now, then each time it comes up or goes |
| 1840 | + /// down, until the actor exits. This node is up while it runs, and is |
| 1841 | + /// not followed; before `start`, every node is down, and nothing is |
| 1842 | + /// kept: there is no node to follow it. |
| 1843 | + /// |
| 1844 | + /// # Safety |
| 1845 | + /// `ctx` must be the running actor's context; `node` a live string. |
| 1846 | + #[unsafe(no_mangle)] |
| 1847 | + pub unsafe extern "C" fn tl_dist_monitor_node(ctx: *mut Ctx, tag: Value, node: Value) -> Value { |
| 1848 | + // SAFETY: caller guarantees the context and the type. |
| 1849 | + let (pid, sched, name) = unsafe { |
| 1850 | + let (a, sched) = this(ctx); |
| 1851 | + (a.pid, sched, text(node)) |
| 1852 | + }; |
| 1853 | + let tag = int_get(tag); |
| 1854 | + let Some(state) = current(sched) else { |
| 1855 | + deliver_made(sched, pid, tag, node_down_event(name, "not started")); |
| 1856 | + return UNIT; |
| 1857 | + }; |
| 1858 | + if state.me().is_some_and(|me| me.name == name) { |
| 1859 | + deliver_made(sched, pid, tag, node_up_event(name)); |
| 1860 | + return UNIT; |
| 1861 | + } |
| 1862 | + let mut watchers = lock(&state.node_watchers); |
| 1863 | + watchers.retain(|w| sched.exists(w.pid)); |
| 1864 | + let event = if lock(&state.peers).contains_key(name) { |
| 1865 | + node_up_event(name) |
| 1866 | + } else { |
| 1867 | + let why = lock(&state.failures).get(name).cloned().unwrap_or_default(); |
| 1868 | + node_down_event(name, &why) |
| 1869 | + }; |
| 1870 | + deliver_made(sched, pid, tag, event); |
| 1871 | + watchers.push(NodeWatcher { |
| 1872 | + pid, |
| 1873 | + tag, |
| 1874 | + node: name.to_owned(), |
| 1875 | + }); |
| 1876 | + UNIT |
| 1877 | + } |
| 1878 | + |
| 1879 | + /// `std/dist.spawn_on` (`spawn_link_on`, `spawn_monitor_on`, as `tie` |
| 1880 | + /// says): ask `node` to start the `@remote` function `key` on `args`, |
| 1881 | + /// a value of `desc`'s type (linked to the running actor, or monitored |
| 1882 | + /// by it on its subject `down`). The answer comes on the running |
| 1883 | + /// actor's subject `tag`: at once if this node knows it (not started, |
| 1884 | + /// not connected, no such entry, another argument type, a linked or |
| 1885 | + /// monitored spawn `node`'s runtime does not take), else when |
| 1886 | + /// `node`'s spawner or `node` answers. This node's own name goes to its |
| 1887 | + /// own spawner, as a peer's request does. An argument the program |
| 1888 | + /// cannot encode panics, as a message does; while `node`'s queue is |
| 1889 | + /// full, the actor parks, as a sender does. A monitored spawn is |
| 1890 | + /// remembered until answered, even when asked of this node, so an |
| 1891 | + /// asker that stops waiting can give it up (`tl_dist_spawn_abandon`). |
| 1892 | + /// |
| 1893 | + /// # Safety |
| 1894 | + /// `ctx` must be the running actor's context; `node` and `desc` live |
| 1895 | + /// strings, `key` an `Int`, `args` a live value of `desc`'s type |
| 1896 | + /// (borrowed), `tie` a `std/dist.Tie`, `down` an `Int`. |
| 1897 | + #[unsafe(no_mangle)] |
| 1898 | + #[allow(clippy::too_many_arguments)] |
| 1899 | + pub unsafe extern "C" fn tl_dist_spawn( |
| 1900 | + ctx: *mut Ctx, |
| 1901 | + tag: Value, |
| 1902 | + node: Value, |
| 1903 | + key: Value, |
| 1904 | + desc: Value, |
| 1905 | + args: Value, |
| 1906 | + tie: Value, |
| 1907 | + down: Value, |
| 1908 | + ) -> Value { |
| 1909 | + // SAFETY: caller guarantees the context and the types. |
| 1910 | + let (asker, sched, node_name, desc) = unsafe { |
| 1911 | + let (a, sched) = this(ctx); |
| 1912 | + (a.pid, sched, text(node), text(desc)) |
| 1913 | + }; |
| 1914 | + let (reply_tag, key) = (int_get(tag), int_get(key)); |
| 1915 | + let answer = |v: Value| { |
| 1916 | + deliver_made(sched, asker, reply_tag, v); |
| 1917 | + UNIT |
| 1918 | + }; |
| 1919 | + let Some(tie) = SpawnTie::from_parts(int_get(tie), int_get(down)) else { |
| 1920 | + return panic(ctx, "a spawn's tie or down tag is out of range"); |
| 1921 | + }; |
| 1922 | + let Some(state) = current(sched) else { |
| 1923 | + return answer(failed(code::NOT_STARTED, "")); |
| 1924 | + }; |
| 1925 | + // The compiler makes a `Remote<a>` from the program's own `@remote` |
| 1926 | + // function of argument `a`, but `a` is phantom: one that came off |
| 1927 | + // the wire may name any key, and be typed for any argument. Checked |
| 1928 | + // here, before anything is encoded or sent. |
| 1929 | + let Some(entry) = state.entries.get(&key) else { |
| 1930 | + return answer(failed(code::UNKNOWN_ENTRY, "")); |
| 1931 | + }; |
| 1932 | + if entry.descriptor != desc { |
| 1933 | + return answer(failed(code::WRONG_TYPE, "")); |
| 1934 | + } |
| 1935 | + let Some(me) = state.me() else { |
| 1936 | + return answer(failed(code::NOT_STARTED, "")); |
| 1937 | + }; |
| 1938 | + let peer = if node_name == me.name { |
| 1939 | + None |
| 1940 | + } else { |
| 1941 | + let peer = |
| 1942 | + transport::with_program(|t| t.peers().into_iter().find(|p| p.name == node_name)) |
| 1943 | + .flatten(); |
| 1944 | + let Some(peer) = peer else { |
| 1945 | + let why = lock(&state.failures) |
| 1946 | + .get(node_name) |
| 1947 | + .cloned() |
| 1948 | + .unwrap_or_default(); |
| 1949 | + return answer(failed(code::NOT_CONNECTED, &why)); |
| 1950 | + }; |
| 1951 | + // A runtime that does not take this op would drop it: refused |
| 1952 | + // here, before anything is pending. |
| 1953 | + if transport::with_program(|t| t.lacks(&peer, tie.op())).unwrap_or(false) { |
| 1954 | + return answer(failed(code::UNSUPPORTED, "")); |
| 1955 | + } |
| 1956 | + Some(peer) |
| 1957 | + }; |
| 1958 | + // SAFETY: `args` is live, a value of the entry's argument type, |
| 1959 | + // registered at `entry.wire`. |
| 1960 | + let encoded = |
| 1961 | + unsafe { wire::encode(&state.registry, entry.wire, args, me, &state.dist.nodes) }; |
| 1962 | + let payload = match encoded { |
| 1963 | + Ok(payload) => payload, |
| 1964 | + Err(e) => return panic(ctx, &e.to_string()), |
| 1965 | + }; |
| 1966 | + let request = SpawnRequest { |
| 1967 | + asker: asker as u64, |
| 1968 | + reply_tag: reply_tag as u64, |
| 1969 | + key: key as u64, |
| 1970 | + hash: entry.hash, |
| 1971 | + payload: &payload, |
| 1972 | + tie, |
| 1973 | + }; |
| 1974 | + let asked = |node: &Node| Asked { |
| 1975 | + node: node.clone(), |
| 1976 | + down: match tie { |
| 1977 | + SpawnTie::Monitor(down) => Some(down as i64), |
| 1978 | + _ => None, |
| 1979 | + }, |
| 1980 | + abandoned: false, |
| 1981 | + }; |
| 1982 | + let Some(peer) = peer else { |
| 1983 | + // Before the spawner can answer. |
| 1984 | + if matches!(tie, SpawnTie::Monitor(_)) { |
| 1985 | + lock(&state.spawns).insert((asker, reply_tag), asked(me)); |
| 1986 | + } |
| 1987 | + return match state.spawn(me, &request, asker) { |
| 1988 | + Ok(()) => UNIT, |
| 1989 | + Err(result) => { |
| 1990 | + lock(&state.spawns).remove(&(asker, reply_tag)); |
| 1991 | + answer(failed(spawn_failure(result), "")) |
| 1992 | + } |
| 1993 | + }; |
| 1994 | + }; |
| 1995 | + // Before sending, as a lookup. |
| 1996 | + lock(&state.spawns).insert((asker, reply_tag), asked(&peer)); |
| 1997 | + let frame = request.encode(); |
| 1998 | + let size = frame.len(); |
| 1999 | + // Its payload counts against the queue's cap as a message's does: |
| 2000 | + // the asker parks while the queue is full (`send_hook`). |
| 2001 | + let lost = std::cell::Cell::new(None); |
| 2002 | + let attempt = |
| 2003 | + |frame, waiter| match transport::with_program(|t| t.queue(&peer, frame, waiter)) { |
| 2004 | + Some(Ok(())) => Try::Done(Ok(())), |
| 2005 | + Some(Err((SendError::Full, frame))) => Try::Full(frame), |
| 2006 | + Some(Err((SendError::TooLarge, _))) => Try::Done(Err(format!( |
| 2007 | + "a spawn request of {size} bytes is over {}'s frame limit", |
| 2008 | + peer.name |
| 2009 | + ))), |
| 2010 | + // The node came back as the same incarnation, its runtime |
| 2011 | + // without the op, since it was checked. |
| 2012 | + Some(Err((SendError::Unsupported, _))) => { |
| 2013 | + lost.set(Some(code::UNSUPPORTED)); |
| 2014 | + Try::Done(Ok(())) |
| 2015 | + } |
| 2016 | + // Stopping, or the node is down: not connected. |
| 2017 | + _ => { |
| 2018 | + lost.set(Some(code::NOT_CONNECTED)); |
| 2019 | + Try::Done(Ok(())) |
| 2020 | + } |
| 2021 | + }; |
| 2022 | + let unwait = |waiter: Waiter| { |
| 2023 | + transport::with_program(|t| t.unwait(&peer, waiter)); |
| 2024 | + }; |
| 2025 | + // SAFETY: the running actor of `ctx`; nothing is locked across the |
| 2026 | + // parking. |
| 2027 | + let sent = unsafe { dist::send_parking(ctx, Outbound::Request(frame), attempt, unwait) }; |
| 2028 | + let asked = || lock(&state.spawns).remove(&(asker, reply_tag)).is_some(); |
| 2029 | + match (sent, lost.get()) { |
| 2030 | + (Some(Ok(())), None) => UNIT, |
| 2031 | + // The node's loss answered it already, if it did not. |
| 2032 | + (Some(Ok(())), Some(code)) if asked() => answer(failed(code, "")), |
| 2033 | + (Some(Ok(())), Some(_)) => UNIT, |
| 2034 | + (Some(Err(why)), _) => { |
| 2035 | + asked(); |
| 2036 | + panic(ctx, &why) |
| 2037 | + } |
| 2038 | + // The asker exited while parked: nobody waits for the answer. |
| 2039 | + (None, _) => { |
| 2040 | + asked(); |
| 2041 | + UNIT |
| 2042 | + } |
| 2043 | + } |
| 2044 | + } |
| 2045 | + |
| 2046 | + /// `std/dist.spawn_monitor_on` timed out waiting for the answer to its |
| 2047 | + /// spawn on its subject `tag`: whether it gave the spawn up. If so, the |
| 2048 | + /// answer goes to nobody, and the new actor is not monitored (the |
| 2049 | + /// asker's node sends a demonitor back once the answer comes). If not, |
| 2050 | + /// the answer came meanwhile: it is in the running actor's mailbox, or |
| 2051 | + /// about to be. |
| 2052 | + /// |
| 2053 | + /// # Safety |
| 2054 | + /// `ctx` must be the running actor's context; `tag` an `Int`. |
| 2055 | + #[unsafe(no_mangle)] |
| 2056 | + pub unsafe extern "C" fn tl_dist_spawn_abandon(ctx: *mut Ctx, tag: Value) -> Value { |
| 2057 | + // SAFETY: caller guarantees the context. |
| 2058 | + let (a, sched) = unsafe { this(ctx) }; |
| 2059 | + // Stopped: no answer will come. |
| 2060 | + let Some(state) = current(sched) else { |
| 2061 | + return int(1); |
| 2062 | + }; |
| 2063 | + int(i64::from(state.abandon_spawn(a.pid, int_get(tag)))) |
| 2064 | + } |
| 2065 | + |
| 2066 | + /// `std/dist`'s spawner starts the body the dispatcher gave for the |
| 2067 | + /// spawn `asker` asked on `tag`, and answers it: `result` is |
| 2068 | + /// `Ok(body)` or why the dispatcher refused. A local `asker` is this |
| 2069 | + /// node's own `spawn_on`; a remote one gets a spawn answer, lost if its |
| 2070 | + /// node is. Not linked, the new actor's parent is the spawner, as a |
| 2071 | + /// `process.spawn` of it would be. |
| 2072 | + /// |
| 2073 | + /// Linked (`spawn_link_on`), to a local asker: as `spawn_link` from |
| 2074 | + /// it, so an asker that already exited stops the new actor at once. |
| 2075 | + /// To a remote asker, in this order: the new actor is made, not |
| 2076 | + /// scheduled; its half of the link is made, listed under the asker's |
| 2077 | + /// node, and the link frame queued, under its lock; it is scheduled; |
| 2078 | + /// the answer is queued. Its exit then always follows the link frame |
| 2079 | + /// on the asker's node's ordered stream, and the answer follows both; |
| 2080 | + /// a loss of that node once the frame is queued finds it. An asker gone by the time the |
| 2081 | + /// link frame arrives answers it with `noproc`, and the new actor dies |
| 2082 | + /// of it; with the asker's node not up, it dies of `noconnection`. |
| 2083 | + /// |
| 2084 | + /// Monitored (`spawn_monitor_on`): see [`State::spawn_monitored`]. |
| 2085 | + /// |
| 2086 | + /// # Safety |
| 2087 | + /// `ctx` must be the running actor's context; `asker` a `Pid`, `tag` |
| 2088 | + /// an `Int`, `tie` a `std/dist.Tie`, `down` an `Int`, `result` a live |
| 2089 | + /// `Result<Dynamic, std/wire.Refused>` whose `Ok` holds an actor body |
| 2090 | + /// (a `send fn() -> ()` of `std/wire.dispatch`). Consumes them all. |
| 2091 | + #[unsafe(no_mangle)] |
| 2092 | + pub unsafe extern "C" fn tl_dist_spawn_for( |
| 2093 | + ctx: *mut Ctx, |
| 2094 | + asker: Value, |
| 2095 | + tag: Value, |
| 2096 | + tie: Value, |
| 2097 | + down: Value, |
| 2098 | + result: Value, |
| 2099 | + ) -> Value { |
| 2100 | + // SAFETY: caller guarantees the context. |
| 2101 | + let (spawner, sched) = unsafe { this(ctx) }; |
| 2102 | + let Some(state) = current(sched) else { |
| 2103 | + // SAFETY: owned. |
| 2104 | + unsafe { drop_value(ctx, result) }; |
| 2105 | + return UNIT; |
| 2106 | + }; |
| 2107 | + let (asker, reply_tag) = (int_get(asker), int_get(tag)); |
| 2108 | + // Made by `State::spawn` from a request it decoded. |
| 2109 | + let tie = SpawnTie::from_parts(int_get(tie), int_get(down)).unwrap_or(SpawnTie::Untied); |
| 2110 | + let monitored = matches!(tie, SpawnTie::Monitor(_)); |
| 2111 | + let answer = |
| 2112 | + |result: u8, pid: i64| state.spawn_answer(asker, reply_tag, monitored, result, pid); |
| 2113 | + // SAFETY: `Ok(body)` is constructor 0, `Error(why)` 1; `why` is |
| 2114 | + // `UnknownEntry` (0) or `WrongType` (1), an immediate. The body is |
| 2115 | + // taken out of the block, which is dropped. |
| 2116 | + let body = unsafe { |
| 2117 | + let b = result as *mut Block; |
| 2118 | + let field = *Block::fields_ptr(b); |
| 2119 | + if (*b).header.tag != 0 { |
| 2120 | + drop_value(ctx, result); |
| 2121 | + answer( |
| 2122 | + if int_get(field) == 0 { |
| 2123 | + NO_ENTRY |
| 2124 | + } else { |
| 2125 | + ENTRY_TYPE |
| 2126 | + }, |
| 2127 | + 0, |
| 2128 | + ); |
| 2129 | + return UNIT; |
| 2130 | + } |
| 2131 | + let body = dup_value(field); |
| 2132 | + drop_value(ctx, result); |
| 2133 | + body |
| 2134 | + }; |
| 2135 | + // SAFETY: the running actor's context; `body` is owned. |
| 2136 | + let body = match unsafe { crate::send::transfer(ctx, body) } { |
| 2137 | + Ok(body) => body, |
| 2138 | + Err((crate::send::NotSendable(why), body)) => { |
| 2139 | + answer(NOT_SPAWNED, 0); |
| 2140 | + // SAFETY: as above; `why` is NUL-terminated. |
| 2141 | + return unsafe { |
| 2142 | + drop_value(ctx, body); |
| 2143 | + crate::effects::tl_panic_str(ctx, why.as_ptr()) |
| 2144 | + }; |
| 2145 | + } |
| 2146 | + }; |
| 2147 | + let pid = match (tie, is_remote(asker)) { |
| 2148 | + (SpawnTie::Untied, _) => { |
| 2149 | + spawn_program_tied(sched, body, spawner.pid, ParentTie::None).0 |
| 2150 | + } |
| 2151 | + (SpawnTie::Link, false) => spawn_program_tied(sched, body, asker, ParentTie::Link).0, |
| 2152 | + (SpawnTie::Link, true) => state.spawn_linked(body, asker), |
| 2153 | + // Answered there, in its order. |
| 2154 | + (SpawnTie::Monitor(down), _) => { |
| 2155 | + state.spawn_monitored(body, asker, reply_tag, down as i64); |
| 2156 | + return UNIT; |
| 2157 | + } |
| 2158 | + }; |
| 2159 | + answer(SPAWNED, pid); |
| 2160 | + UNIT |
| 2161 | + } |
| 2162 | + |
| 2163 | + impl State { |
| 2164 | + /// Spawn `body` (owned) linked to the remote `asker`: see |
| 2165 | + /// [`tl_dist_spawn_for`]. Its pid. |
| 2166 | + fn spawn_linked(&self, body: Value, asker: i64) -> i64 { |
| 2167 | + let sched = self.sched(); |
| 2168 | + let mut linked = None; |
| 2169 | + let pid = spawn_program_before(sched, body, |child| { |
| 2170 | + let send = || send_tie(self, child, asker, Op::Link); |
| 2171 | + linked = Some(dist::outbound::link_spawned( |
| 2172 | + sched, &self.dist, child, asker, send, |
| 2173 | + )); |
| 2174 | + }); |
| 2175 | + match linked.flatten() { |
| 2176 | + Some(true) => {} |
| 2177 | + // The asker's node is not up: as its loss would. |
| 2178 | + Some(false) => { |
| 2179 | + let lost = Signal::Linked(noconnection()); |
| 2180 | + dist::inbound::signal(sched, asker, pid, &lost); |
| 2181 | + } |
| 2182 | + // Already gone (a peer killed it by its serial), unlinked: |
| 2183 | + // the asker links and is told so, as by a link to an actor |
| 2184 | + // that is gone. |
| 2185 | + None => { |
| 2186 | + send_tie(self, pid, asker, Op::Link); |
| 2187 | + send_tie(self, pid, asker, Op::Exit(noproc())); |
| 2188 | + } |
| 2189 | + } |
| 2190 | + pid |
| 2191 | + } |
| 2192 | + |
| 2193 | + /// Spawn `body` (owned) monitored by `asker`, its `Down` due on |
| 2194 | + /// `down`, and answer the spawn it asked on `reply_tag`. |
| 2195 | + /// |
| 2196 | + /// A local asker: as `spawn_monitor` from it, unless it gave up |
| 2197 | + /// waiting (`tl_dist_spawn_abandon`); then the new actor is not |
| 2198 | + /// monitored and the answer goes to nobody. |
| 2199 | + /// |
| 2200 | + /// A remote asker, in this order: the new actor is made, not |
| 2201 | + /// scheduled; the monitor is made, listed under the asker's node, |
| 2202 | + /// and the answer queued, under its lock |
| 2203 | + /// (`dist::outbound::monitor_spawned`); it is scheduled. So the |
| 2204 | + /// answer reaches the asker's node ahead of the actor's `Down`, |
| 2205 | + /// and the asker's half of the monitor is there for it |
| 2206 | + /// ([`State::settle_spawn`]). One a peer killed by its serial |
| 2207 | + /// before its monitor is made is answered, then reported gone |
| 2208 | + /// (`noproc`), as a monitor of an actor that is gone. |
| 2209 | + fn spawn_monitored(&self, body: Value, asker: i64, reply_tag: i64, down: i64) { |
| 2210 | + let sched = self.sched(); |
| 2211 | + if !is_remote(asker) { |
| 2212 | + let waiting = lock(&self.spawns) |
| 2213 | + .remove(&(asker, reply_tag)) |
| 2214 | + .is_some_and(|asked| !asked.abandoned); |
| 2215 | + if waiting { |
| 2216 | + let pid = spawn_program_monitored(sched, body, asker, down); |
| 2217 | + let answer = cell(std::ptr::null_mut(), 0, &[int(pid)]); |
| 2218 | + deliver_made(sched, asker, reply_tag, answer); |
| 2219 | + } else { |
| 2220 | + spawn_program_tied(sched, body, self.spawner.0, ParentTie::None); |
| 2221 | + } |
| 2222 | + return; |
| 2223 | + } |
| 2224 | + // A pid past 2^46 cannot be named on another node (`dist`): |
| 2225 | + // answered as not spawned, not monitored. |
| 2226 | + let nameable = |pid: i64| u64::try_from(pid).is_ok_and(|p| p < MAX_PID_SERIAL); |
| 2227 | + let mut gone = false; |
| 2228 | + let pid = spawn_program_before(sched, body, |child| { |
| 2229 | + if nameable(child) { |
| 2230 | + let send = || self.answer_remote(asker, reply_tag, SPAWNED, child); |
| 2231 | + let made = dist::outbound::monitor_spawned( |
| 2232 | + sched, &self.dist, child, asker, down, send, |
| 2233 | + ); |
| 2234 | + gone = made.is_none(); |
| 2235 | + } |
| 2236 | + }); |
| 2237 | + if !nameable(pid) { |
| 2238 | + self.answer_remote(asker, reply_tag, NOT_SPAWNED, 0); |
| 2239 | + } else if gone { |
| 2240 | + self.answer_remote(asker, reply_tag, SPAWNED, pid); |
| 2241 | + let tag = down as u64; |
| 2242 | + send_tie( |
| 2243 | + self, |
| 2244 | + pid, |
| 2245 | + asker, |
| 2246 | + Op::Down { |
| 2247 | + tag, |
| 2248 | + reason: noproc(), |
| 2249 | + }, |
| 2250 | + ); |
| 2251 | + } |
| 2252 | + } |
| 2253 | + |
| 2254 | + /// The asker `asker` gives up waiting for the monitored spawn it |
| 2255 | + /// asked on `reply_tag` (`tl_dist_spawn_abandon`): whether it did, |
| 2256 | + /// or it was answered meanwhile. One asked of another node is |
| 2257 | + /// marked, so that its answer goes to nobody and the new actor is |
| 2258 | + /// demonitored there ([`State::settle_spawn`]); one asked of this |
| 2259 | + /// node is forgotten, so that the spawner, which looks it up, |
| 2260 | + /// answers nobody (`spawn_monitored`, `spawn_answer`). No node's |
| 2261 | + /// loss forgets that one: if the spawner died with the request |
| 2262 | + /// queued, it would stay (SR3-3). |
| 2263 | + fn abandon_spawn(&self, asker: i64, reply_tag: i64) -> bool { |
| 2264 | + let me = self.me().cloned(); |
| 2265 | + let mut spawns = lock(&self.spawns); |
| 2266 | + let key = (asker, reply_tag); |
| 2267 | + match spawns.get_mut(&key) { |
| 2268 | + Some(asked) if me.as_ref() == Some(&asked.node) => { |
| 2269 | + spawns.remove(&key); |
| 2270 | + true |
| 2271 | + } |
| 2272 | + Some(asked) => { |
| 2273 | + asked.abandoned = true; |
| 2274 | + true |
| 2275 | + } |
| 2276 | + // Taken by what answers it, which delivers it next. |
| 2277 | + None => false, |
| 2278 | + } |
| 2279 | + } |
| 2280 | + |
| 2281 | + /// Answer the spawn `asker` asked on `tag` with `result`, and the |
| 2282 | + /// new actor's `pid` if spawned. A local asker gets a monitored |
| 2283 | + /// spawn's answer only while it is pending: one that gave up |
| 2284 | + /// waiting (`abandon_spawn`) gets nothing. |
| 2285 | + fn spawn_answer(&self, asker: i64, reply_tag: i64, monitored: bool, result: u8, pid: i64) { |
| 2286 | + if !is_remote(asker) { |
| 2287 | + let asked = lock(&self.spawns).remove(&(asker, reply_tag)); |
| 2288 | + if monitored && asked.is_none_or(|a| a.abandoned) { |
| 2289 | + return; |
| 2290 | + } |
| 2291 | + let answer = match result { |
| 2292 | + SPAWNED => cell(std::ptr::null_mut(), 0, &[int(pid)]), |
| 2293 | + refused => failed(spawn_failure(refused), ""), |
| 2294 | + }; |
| 2295 | + deliver_made(self.sched(), asker, reply_tag, answer); |
| 2296 | + return; |
| 2297 | + } |
| 2298 | + self.answer_remote(asker, reply_tag, result, pid); |
| 2299 | + } |
| 2300 | + |
| 2301 | + /// Queue the answer to the spawn the remote `asker` asked on |
| 2302 | + /// `reply_tag`: whether it was queued (its node is up). |
| 2303 | + fn answer_remote(&self, asker: i64, reply_tag: i64, result: u8, pid: i64) -> bool { |
| 2304 | + let (index, serial) = dist::parts(asker); |
| 2305 | + let node = (self.dist.nodes.read()) |
| 2306 | + .unwrap_or_else(PoisonError::into_inner) |
| 2307 | + .get(index) |
| 2308 | + .cloned(); |
| 2309 | + // A pid past 2^46 cannot be named on another node (`dist`). |
| 2310 | + let pid = u64::try_from(pid).ok().filter(|p| *p < MAX_PID_SERIAL); |
| 2311 | + let (result, pid) = match pid { |
| 2312 | + Some(pid) => (result, pid), |
| 2313 | + None => (NOT_SPAWNED, 0), |
| 2314 | + }; |
| 2315 | + let Some(node) = node else { |
| 2316 | + return false; |
| 2317 | + }; |
| 2318 | + let reply = SpawnReply { |
| 2319 | + asker: serial as u64, |
| 2320 | + reply_tag: reply_tag as u64, |
| 2321 | + result, |
| 2322 | + serial: pid, |
| 2323 | + }; |
| 2324 | + // Lost with the connection, if it is: the asker is told so. |
| 2325 | + transport::with_program(|t| t.send(&node, Outbound::Signal(reply.encode()))) |
| 2326 | + == Some(Ok(())) |
| 2327 | + } |
| 2328 | + } |
| 2329 | + |
| 2330 | + /// `std/dist.peers`: every node this node knows (a seed, a node it was |
| 2331 | + /// connected to, a node it sent to), by name, as `std/dist`'s `Peer` |
| 2332 | + /// (`Peer(node, incarnation, state, rtt_us, queued_bytes, sent, |
| 2333 | + /// received, unsent, parked, dropped)`, `state` being `Up` or |
| 2334 | + /// `Down(why)`); `[]` before `start`. A snapshot, read without waiting |
| 2335 | + /// for the transport. |
| 2336 | + /// |
| 2337 | + /// # Safety |
| 2338 | + /// `ctx` must be the running actor's context. |
| 2339 | + #[unsafe(no_mangle)] |
| 2340 | + pub unsafe extern "C" fn tl_dist_peers(ctx: *mut Ctx) -> Value { |
| 2341 | + // SAFETY: caller guarantees the context. |
| 2342 | + let (_, sched) = unsafe { this(ctx) }; |
| 2343 | + let Some(state) = current(sched) else { |
| 2344 | + return list(ctx, std::iter::empty()); |
| 2345 | + }; |
| 2346 | + let report = transport::with_program(|t| t.report()).unwrap_or_default(); |
| 2347 | + let failures = lock(&state.failures); |
| 2348 | + // Counts stay small `Int`s. |
| 2349 | + let count = |n: u64| int(n.min((1 << 62) - 1) as i64); |
| 2350 | + let some = |v: Value| cell(ctx, 1, &[v]); |
| 2351 | + let peers: Vec<Value> = report |
| 2352 | + .iter() |
| 2353 | + .map(|r| { |
| 2354 | + let incarnation = r |
| 2355 | + .incarnation |
| 2356 | + .map_or(int(0), |i| some(string(ctx, &format!("{i:016x}")))); |
| 2357 | + let status = if r.up { |
| 2358 | + int(0) |
| 2359 | + } else { |
| 2360 | + let why = failures.get(&r.node).map_or("", String::as_str); |
| 2361 | + cell(ctx, 1, &[string(ctx, why)]) |
| 2362 | + }; |
| 2363 | + let fields = [ |
| 2364 | + string(ctx, &r.node), |
| 2365 | + incarnation, |
| 2366 | + status, |
| 2367 | + r.rtt_us.map_or(int(0), |t| some(count(t))), |
| 2368 | + count(r.queued as u64), |
| 2369 | + count(r.sent), |
| 2370 | + count(r.received), |
| 2371 | + count(r.unsent), |
| 2372 | + count(r.parked), |
| 2373 | + count(r.dropped), |
| 2374 | + ]; |
| 2375 | + cell(ctx, 0, &fields) |
| 2376 | + }) |
| 2377 | + .collect(); |
| 2378 | + list(ctx, peers.into_iter()) |
| 2379 | + } |
| 2380 | + |
| 2381 | + /// `std/dist.connect`: stay connected to `node` at `addr` (`ip:port`, |
| 2382 | + /// `[ip6]:port`) from now on, as to a seed ([`transport::Transport:: |
| 2383 | + /// connect`]). A code: `OK` (this node's own name too, which does |
| 2384 | + /// nothing), `NOT_STARTED`, or `INVALID`, not a node name or an |
| 2385 | + /// address. |
| 2386 | + /// |
| 2387 | + /// # Safety |
| 2388 | + /// `ctx` must be the running actor's context; `node` and `addr` live |
| 2389 | + /// strings. |
| 2390 | + #[unsafe(no_mangle)] |
| 2391 | + pub unsafe extern "C" fn tl_dist_connect(ctx: *mut Ctx, node: Value, addr: Value) -> Value { |
| 2392 | + // SAFETY: caller guarantees the context and the types. |
| 2393 | + let (sched, name, addr) = unsafe { |
| 2394 | + let (_, sched) = this(ctx); |
| 2395 | + (sched, text(node), text(addr)) |
| 2396 | + }; |
| 2397 | + let Some(state) = current(sched) else { |
| 2398 | + return int(code::NOT_STARTED); |
| 2399 | + }; |
| 2400 | + let Ok(addr) = addr.parse::<SocketAddr>() else { |
| 2401 | + return int(code::INVALID); |
| 2402 | + }; |
| 2403 | + if !louise_rt_prims::wire::check_node_name(name.as_bytes()) { |
| 2404 | + return int(code::INVALID); |
| 2405 | + } |
| 2406 | + if state.me().is_some_and(|me| me.name == name) { |
| 2407 | + return int(code::OK); |
| 2408 | + } |
| 2409 | + match transport::with_program(|t| t.connect(name, addr)) { |
| 2410 | + Some(()) => int(code::OK), |
| 2411 | + None => int(code::NOT_STARTED), |
| 2412 | + } |
| 2413 | + } |
| 2414 | + |
| 2415 | + #[cfg(test)] |
| 2416 | + mod tests { |
| 2417 | + use super::*; |
| 2418 | + use louise_rt_prims::wire::write_uvarint; |
| 2419 | + |
| 2420 | + /// A node of no running program, with the types `()` and `Pid`. |
| 2421 | + fn state(sched: &Shared) -> State { |
| 2422 | + let state = State { |
| 2423 | + sched: Sched(sched), |
| 2424 | + dist: Dist::default(), |
| 2425 | + registry: Registry::new("").expect("an empty table"), |
| 2426 | + me: OnceLock::new(), |
| 2427 | + names: Mutex::default(), |
| 2428 | + peers: Mutex::default(), |
| 2429 | + quotas: Mutex::default(), |
| 2430 | + lookups: Mutex::default(), |
| 2431 | + entries: HashMap::new(), |
| 2432 | + spawner: (0, 0), |
| 2433 | + spawns: Mutex::default(), |
| 2434 | + failures: Mutex::default(), |
| 2435 | + last_closed: Mutex::default(), |
| 2436 | + unauthenticated: Mutex::default(), |
| 2437 | + hearsay: Mutex::default(), |
| 2438 | + node_watchers: Mutex::default(), |
| 2439 | + refused: AtomicU64::new(0), |
| 2440 | + ready: Gate::default(), |
| 2441 | + }; |
| 2442 | + state.ready.open(); |
| 2443 | + let _ = state.me.set(Node { |
| 2444 | + name: "a.example".into(), |
| 2445 | + incarnation: 1, |
| 2446 | + }); |
| 2447 | + state |
| 2448 | + } |
| 2449 | + |
| 2450 | + /// A message frame of `()` to actor 1 of `state`, whose node list |
| 2451 | + /// names `n` nodes `{prefix}-{i}.example`. |
| 2452 | + fn naming(state: &State, prefix: &str, n: u32) -> (MessageHeader, Vec<u8>) { |
| 2453 | + let mut payload = Vec::new(); |
| 2454 | + write_uvarint(&mut payload, u64::from(n)); |
| 2455 | + for i in 0..n { |
| 2456 | + let name = format!("{prefix}-{i}.example"); |
| 2457 | + write_uvarint(&mut payload, name.len() as u64); |
| 2458 | + payload.extend_from_slice(name.as_bytes()); |
| 2459 | + payload.extend_from_slice(&1u64.to_le_bytes()); |
| 2460 | + } |
| 2461 | + payload.push(0); |
| 2462 | + let header = MessageHeader { |
| 2463 | + incarnation: 1, |
| 2464 | + serial: 1, |
| 2465 | + tag: 1, |
| 2466 | + type_hash: state.registry.register("u").expect("()").hash, |
| 2467 | + payload_len: payload.len() as u32, |
| 2468 | + }; |
| 2469 | + (header, payload) |
| 2470 | + } |
| 2471 | + |
| 2472 | + /// How many entries the node table holds. |
| 2473 | + fn entries(state: &State) -> usize { |
| 2474 | + let nodes = state.dist.nodes.read().expect("the table"); |
| 2475 | + (0..=u16::MAX) |
| 2476 | + .take_while(|&i| nodes.get(i).is_some()) |
| 2477 | + .count() |
| 2478 | + } |
| 2479 | + |
| 2480 | + /// One peer name adds [`PEER_NODES`] node-table entries for the |
| 2481 | + /// whole run: reconnecting (a fresh budget per connection, before) |
| 2482 | + /// or restarting (each incarnation an entry, uncounted, before) let |
| 2483 | + /// one peer fill the table in 64 connections (#404's security |
| 2484 | + /// review, SEC-5). |
| 2485 | + #[test] |
| 2486 | + fn a_reconnecting_peer_adds_its_quota_of_nodes_at_most() { |
| 2487 | + let _turn = crate::sched::test_turn(); |
| 2488 | + let sched = Shared::new(1); |
| 2489 | + let state = state(&sched); |
| 2490 | + let link = |from| { |
| 2491 | + Tie { |
| 2492 | + from, |
| 2493 | + to: 1, |
| 2494 | + op: Op::Link, |
| 2495 | + } |
| 2496 | + .encode() |
| 2497 | + }; |
| 2498 | + for i in 0..64 { |
| 2499 | + let b = Node { |
| 2500 | + name: "b.example".into(), |
| 2501 | + incarnation: 100 + i, |
| 2502 | + }; |
| 2503 | + state.node_up(&b); |
| 2504 | + // A link from its actor 1 (its own incarnation's entry), |
| 2505 | + // then a frame naming 128 new nodes: 8,256 entries in all. |
| 2506 | + state.signal(&b, &link(1)); |
| 2507 | + let (header, payload) = naming(&state, &format!("c{i}"), PEER_NODES / 8); |
| 2508 | + state.message(&b, &header, &payload); |
| 2509 | + state.node_down(&b); |
| 2510 | + } |
| 2511 | + // 64 incarnations and 7 frames' 896 nodes; past those, each |
| 2512 | + // frame is refused whole. |
| 2513 | + let used = entries(&state); |
| 2514 | + assert_eq!(used, 64 + 7 * 128); |
| 2515 | + assert!(used <= PEER_NODES as usize); |
| 2516 | + // Another peer still has its own. |
| 2517 | + let c = Node { |
| 2518 | + name: "c.example".into(), |
| 2519 | + incarnation: 7, |
| 2520 | + }; |
| 2521 | + state.node_up(&c); |
| 2522 | + state.signal(&c, &link(1)); |
| 2523 | + let (header, payload) = naming(&state, "d", PEER_NODES - 1); |
| 2524 | + state.message(&c, &header, &payload); |
| 2525 | + assert_eq!(entries(&state), used + PEER_NODES as usize); |
| 2526 | + state.node_down(&c); |
| 2527 | + } |
| 2528 | + |
| 2529 | + /// What peers send waits until the node's hooks are installed: |
| 2530 | + /// `start` starts the transport first, and a tie to an actor gone, |
| 2531 | + /// or one whose actor exits, handled before the install lost the |
| 2532 | + /// answer a hook sends (#404's second security review, SR2-7). |
| 2533 | + #[test] |
| 2534 | + fn peers_frames_wait_for_the_hooks() { |
| 2535 | + let _turn = crate::sched::test_turn(); |
| 2536 | + let sched = Shared::new(1); |
| 2537 | + let state = state(&sched); |
| 2538 | + let state = State { |
| 2539 | + ready: Gate::default(), |
| 2540 | + ..state |
| 2541 | + }; |
| 2542 | + let b = Node { |
| 2543 | + name: "b.example".into(), |
| 2544 | + incarnation: 1, |
| 2545 | + }; |
| 2546 | + std::thread::scope(|scope| { |
| 2547 | + let relay = scope.spawn(|| state.node_up(&b)); |
| 2548 | + std::thread::sleep(std::time::Duration::from_millis(50)); |
| 2549 | + assert!(!relay.is_finished(), "handled before the install"); |
| 2550 | + assert!(lock(&state.peers).is_empty()); |
| 2551 | + state.ready.open(); |
| 2552 | + relay.join().expect("the relay"); |
| 2553 | + }); |
| 2554 | + assert!(lock(&state.peers).contains_key("b.example")); |
| 2555 | + } |
| 2556 | + |
| 2557 | + /// A dial that failed to an address only peers' lists gave |
| 2558 | + /// (*hearsay*): the peers choose the names, and how many fail, so |
| 2559 | + /// it stays out of `failures` (whose 256 entries it would push |
| 2560 | + /// out) and is logged sparingly. #404's second security review, |
| 2561 | + /// SR2-3: each was a line, and an entry. |
| 2562 | + #[test] |
| 2563 | + fn failed_dials_peers_listed_are_not_failures() { |
| 2564 | + let _turn = crate::sched::test_turn(); |
| 2565 | + let sched = Shared::new(1); |
| 2566 | + let state = state(&sched); |
| 2567 | + let refused = Reason::Closed("connection refused".into()); |
| 2568 | + for i in 0..2 * MAX_FAILURES { |
| 2569 | + state.closed(&format!("j{i}.example"), &refused, true); |
| 2570 | + } |
| 2571 | + assert!(lock(&state.failures).is_empty()); |
| 2572 | + // Logged once, the others held back for the period. |
| 2573 | + let now = std::time::Instant::now(); |
| 2574 | + assert_eq!(lock(&state.hearsay).admit(now), None); |
| 2575 | + // A seed's, or a confirmed node's, is one. |
| 2576 | + state.closed("b.example", &refused, false); |
| 2577 | + let failures = lock(&state.failures); |
| 2578 | + assert_eq!(failures.keys().collect::<Vec<_>>(), ["b.example"]); |
| 2579 | + } |
| 2580 | + |
| 2581 | + /// #423: the ops added since stage 1 each need their capability |
| 2582 | + /// flag in the peer's hello, which the transport checks: no frame |
| 2583 | + /// of them goes to a runtime that would drop it. The others go to |
| 2584 | + /// every peer. |
| 2585 | + #[test] |
| 2586 | + fn ops_since_stage_one_need_the_peers_flag() { |
| 2587 | + use transport::needs; |
| 2588 | + for (tie, flagged) in [ |
| 2589 | + (SpawnTie::Untied, false), |
| 2590 | + (SpawnTie::Link, true), |
| 2591 | + (SpawnTie::Monitor(1), true), |
| 2592 | + ] { |
| 2593 | + let request = SpawnRequest { |
| 2594 | + asker: 1, |
| 2595 | + reply_tag: 2, |
| 2596 | + key: 3, |
| 2597 | + hash: 4, |
| 2598 | + payload: &[0], |
| 2599 | + tie, |
| 2600 | + }; |
| 2601 | + assert_eq!(request.encode()[0], tie.op()); |
| 2602 | + assert_eq!(needs(tie.op()) != 0, flagged, "{tie:?}"); |
| 2603 | + } |
| 2604 | + let flagged = [ |
| 2605 | + ties::DEMONITOR, |
| 2606 | + ties::UNLINK, |
| 2607 | + ties::UNLINK_ACK, |
| 2608 | + SPAWN_LINKED, |
| 2609 | + SPAWN_MONITORED, |
| 2610 | + ]; |
| 2611 | + let flags: std::collections::HashSet<u64> = |
| 2612 | + flagged.iter().map(|op| needs(*op)).collect(); |
| 2613 | + // Unlink and its answer share one; the others have their own. |
| 2614 | + assert_eq!(needs(ties::UNLINK), needs(ties::UNLINK_ACK)); |
| 2615 | + assert_eq!(flags.len(), 4); |
| 2616 | + assert!(!flags.contains(&0)); |
| 2617 | + for op in [ |
| 2618 | + LOOKUP, |
| 2619 | + ANSWER, |
| 2620 | + ties::LINK, |
| 2621 | + ties::EXIT, |
| 2622 | + ties::MONITOR, |
| 2623 | + ties::DOWN, |
| 2624 | + ties::KILL, |
| 2625 | + ties::STOP, |
| 2626 | + SPAWN, |
| 2627 | + SPAWN_ANSWER, |
| 2628 | + ] { |
| 2629 | + assert_eq!(needs(op), 0, "op {op:02x}"); |
| 2630 | + } |
| 2631 | + } |
| 2632 | + |
| 2633 | + /// `docs/wire-format.md`'s example: actor 7 asks, on tag 3, for |
| 2634 | + /// "counter" with the hash `994947b873cb1aa7`; actor 12 holds it on |
| 2635 | + /// tag 40. |
| 2636 | + #[test] |
| 2637 | + fn lookup_frames_are_the_documented_bytes() { |
| 2638 | + let request = LookupRequest { |
| 2639 | + asker: 7, |
| 2640 | + reply_tag: 3, |
| 2641 | + hash: 0x9949_47b8_73cb_1aa7, |
| 2642 | + name: b"counter", |
| 2643 | + }; |
| 2644 | + let bytes = request.encode(); |
| 2645 | + assert_eq!( |
| 2646 | + bytes, |
| 2647 | + [ |
| 2648 | + &[1, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0][..], |
| 2649 | + &[0xa7, 0x1a, 0xcb, 0x73, 0xb8, 0x47, 0x49, 0x99, 7], |
| 2650 | + b"counter", |
| 2651 | + ] |
| 2652 | + .concat() |
| 2653 | + ); |
| 2654 | + let back = LookupRequest::decode(&bytes[1..]).expect("well formed"); |
| 2655 | + assert_eq!( |
| 2656 | + (back.asker, back.reply_tag, back.hash), |
| 2657 | + (7, 3, request.hash) |
| 2658 | + ); |
| 2659 | + assert_eq!(back.name, b"counter"); |
| 2660 | + // The name's length is checked, and the ranges. |
| 2661 | + assert!(LookupRequest::decode(&bytes[1..bytes.len() - 1]).is_none()); |
| 2662 | + let mut far = bytes.clone(); |
| 2663 | + far[8] = 0x40; |
| 2664 | + assert!(LookupRequest::decode(&far[1..]).is_none()); |
| 2665 | + |
| 2666 | + let reply = LookupReply { |
| 2667 | + asker: 7, |
| 2668 | + reply_tag: 3, |
| 2669 | + result: FOUND, |
| 2670 | + serial: 12, |
| 2671 | + tag: 40, |
| 2672 | + hash: 0x9949_47b8_73cb_1aa7, |
| 2673 | + }; |
| 2674 | + let bytes = reply.encode(); |
| 2675 | + assert_eq!(bytes.len(), LookupReply::LEN); |
| 2676 | + assert_eq!( |
| 2677 | + &bytes[..18], |
| 2678 | + &[2, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0] |
| 2679 | + ); |
| 2680 | + assert_eq!(&bytes[18..26], &[12, 0, 0, 0, 0, 0, 0, 0]); |
| 2681 | + assert_eq!(&bytes[26..34], &[40, 0, 0, 0, 0, 0, 0, 0]); |
| 2682 | + assert_eq!( |
| 2683 | + &bytes[34..], |
| 2684 | + &[0xa7, 0x1a, 0xcb, 0x73, 0xb8, 0x47, 0x49, 0x99] |
| 2685 | + ); |
| 2686 | + let back = LookupReply::decode(&bytes[1..]).expect("well formed"); |
| 2687 | + assert_eq!( |
| 2688 | + ( |
| 2689 | + back.asker, |
| 2690 | + back.reply_tag, |
| 2691 | + back.result, |
| 2692 | + back.serial, |
| 2693 | + back.tag |
| 2694 | + ), |
| 2695 | + (7, 3, FOUND, 12, 40) |
| 2696 | + ); |
| 2697 | + assert!(LookupReply::decode(&bytes[2..]).is_none(), "too short"); |
| 2698 | + let mut bad = bytes.clone(); |
| 2699 | + bad[17] = 3; |
| 2700 | + assert!(LookupReply::decode(&bad[1..]).is_none(), "no result 3"); |
| 2701 | + } |
| 2702 | + |
| 2703 | + /// `docs/wire-format.md`'s example: actor 7 asks, on tag 3, to spawn |
| 2704 | + /// `remote_dispatch.hello` on `()`; the node starts actor 12. |
| 2705 | + #[test] |
| 2706 | + fn spawn_frames_are_the_documented_bytes() { |
| 2707 | + let key = louise_rt_prims::wire::remote_key("remote_dispatch.hello") as u64; |
| 2708 | + assert_eq!(key, 0x3b95_3bf0_e57c_a31d); |
| 2709 | + let request = SpawnRequest { |
| 2710 | + asker: 7, |
| 2711 | + reply_tag: 3, |
| 2712 | + key, |
| 2713 | + hash: 0x4433_df13_a578_0ab1, |
| 2714 | + payload: &[0, 0], |
| 2715 | + tie: SpawnTie::Untied, |
| 2716 | + }; |
| 2717 | + let bytes = request.encode(); |
| 2718 | + assert_eq!( |
| 2719 | + bytes, |
| 2720 | + [ |
| 2721 | + &[0x20, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0][..], |
| 2722 | + &[0x1d, 0xa3, 0x7c, 0xe5, 0xf0, 0x3b, 0x95, 0x3b], |
| 2723 | + &[0xb1, 0x0a, 0x78, 0xa5, 0x13, 0xdf, 0x33, 0x44], |
| 2724 | + &[0, 0], |
| 2725 | + ] |
| 2726 | + .concat() |
| 2727 | + ); |
| 2728 | + let back = SpawnRequest::decode(SPAWN, &bytes[1..]).expect("well formed"); |
| 2729 | + assert_eq!( |
| 2730 | + (back.asker, back.reply_tag, back.key, back.hash, back.tie), |
| 2731 | + (7, 3, key, request.hash, SpawnTie::Untied) |
| 2732 | + ); |
| 2733 | + assert_eq!(back.payload, [0, 0]); |
| 2734 | + assert!( |
| 2735 | + SpawnRequest::decode(SPAWN, &bytes[1..32]).is_none(), |
| 2736 | + "too short" |
| 2737 | + ); |
| 2738 | + let mut far = bytes.clone(); |
| 2739 | + far[24] = 0x40; |
| 2740 | + assert!( |
| 2741 | + SpawnRequest::decode(SPAWN, &far[1..]).is_none(), |
| 2742 | + "a key past 2^62" |
| 2743 | + ); |
| 2744 | + // Linked: op 0x22, the same fields. |
| 2745 | + let linked = SpawnRequest { |
| 2746 | + tie: SpawnTie::Link, |
| 2747 | + ..request |
| 2748 | + }; |
| 2749 | + let linked_bytes = linked.encode(); |
| 2750 | + assert_eq!(linked_bytes[0], 0x22); |
| 2751 | + assert_eq!(linked_bytes[1..], bytes[1..]); |
| 2752 | + let back = SpawnRequest::decode(SPAWN_LINKED, &linked_bytes[1..]).expect("well formed"); |
| 2753 | + assert_eq!(back.tie, SpawnTie::Link); |
| 2754 | + assert!( |
| 2755 | + SpawnRequest::decode(0x24, &bytes[1..]).is_none(), |
| 2756 | + "no op 24" |
| 2757 | + ); |
| 2758 | + |
| 2759 | + let reply = SpawnReply { |
| 2760 | + asker: 7, |
| 2761 | + reply_tag: 3, |
| 2762 | + result: SPAWNED, |
| 2763 | + serial: 12, |
| 2764 | + }; |
| 2765 | + let bytes = reply.encode(); |
| 2766 | + assert_eq!( |
| 2767 | + bytes, |
| 2768 | + [ |
| 2769 | + &[0x21, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0][..], |
| 2770 | + &[12, 0, 0, 0, 0, 0, 0, 0], |
| 2771 | + ] |
| 2772 | + .concat() |
| 2773 | + ); |
| 2774 | + let back = SpawnReply::decode(&bytes[1..]).expect("well formed"); |
| 2775 | + assert_eq!( |
| 2776 | + (back.asker, back.reply_tag, back.result, back.serial), |
| 2777 | + (7, 3, SPAWNED, 12) |
| 2778 | + ); |
| 2779 | + assert!(SpawnReply::decode(&bytes[2..]).is_none(), "too short"); |
| 2780 | + let mut bad = bytes.clone(); |
| 2781 | + bad[17] = 4; |
| 2782 | + assert!(SpawnReply::decode(&bad[1..]).is_none(), "no result 4"); |
| 2783 | + assert_eq!( |
| 2784 | + [NO_ENTRY, ENTRY_TYPE, NOT_SPAWNED].map(spawn_failure), |
| 2785 | + [code::UNKNOWN_ENTRY, code::WRONG_TYPE, code::REFUSED] |
| 2786 | + ); |
| 2787 | + } |
| 2788 | + |
| 2789 | + /// `docs/wire-format.md`'s monitored spawn: as the example's, the |
| 2790 | + /// `Down` due on tag 5. Its fixed fields are 40 bytes: a frame |
| 2791 | + /// cut in its down tag, or a down tag past 2^62, is dropped. |
| 2792 | + #[test] |
| 2793 | + fn a_monitored_spawn_carries_its_down_tag() { |
| 2794 | + let request = SpawnRequest { |
| 2795 | + asker: 7, |
| 2796 | + reply_tag: 3, |
| 2797 | + key: 0x3b95_3bf0_e57c_a31d, |
| 2798 | + hash: 0x4433_df13_a578_0ab1, |
| 2799 | + payload: &[0, 0], |
| 2800 | + tie: SpawnTie::Monitor(5), |
| 2801 | + }; |
| 2802 | + let bytes = request.encode(); |
| 2803 | + let plain = SpawnRequest { |
| 2804 | + tie: SpawnTie::Untied, |
| 2805 | + ..request |
| 2806 | + } |
| 2807 | + .encode(); |
| 2808 | + assert_eq!( |
| 2809 | + bytes, |
| 2810 | + [ |
| 2811 | + &[0x23][..], |
| 2812 | + &plain[1..33], |
| 2813 | + &[5, 0, 0, 0, 0, 0, 0, 0], |
| 2814 | + &[0, 0], |
| 2815 | + ] |
| 2816 | + .concat() |
| 2817 | + ); |
| 2818 | + let back = SpawnRequest::decode(SPAWN_MONITORED, &bytes[1..]).expect("well formed"); |
| 2819 | + assert_eq!( |
| 2820 | + (back.asker, back.reply_tag, back.key, back.hash, back.tie), |
| 2821 | + (7, 3, request.key, request.hash, SpawnTie::Monitor(5)) |
| 2822 | + ); |
| 2823 | + assert_eq!(back.payload, [0, 0]); |
| 2824 | + // The fixed fields alone: an empty payload, which no type |
| 2825 | + // decodes from (the node refuses it, `03`). |
| 2826 | + let fixed = SpawnRequest::decode(SPAWN_MONITORED, &bytes[1..41]).expect("40 bytes"); |
| 2827 | + assert!(fixed.payload.is_empty()); |
| 2828 | + for short in [0, 7, 32, 39] { |
| 2829 | + assert!( |
| 2830 | + SpawnRequest::decode(SPAWN_MONITORED, &bytes[1..1 + short]).is_none(), |
| 2831 | + "{short} bytes" |
| 2832 | + ); |
| 2833 | + } |
| 2834 | + let mut far = bytes.clone(); |
| 2835 | + far[40] = 0x40; |
| 2836 | + assert!( |
| 2837 | + SpawnRequest::decode(SPAWN_MONITORED, &far[1..]).is_none(), |
| 2838 | + "a down tag past 2^62" |
| 2839 | + ); |
| 2840 | + // Read as a plain spawn, the down tag is the payload's start. |
| 2841 | + let plain = SpawnRequest::decode(SPAWN, &bytes[1..]).expect("as op 20"); |
| 2842 | + assert_eq!(plain.payload.len(), 10); |
| 2843 | + // `std/dist`'s `Tie` and the down tag, both ways. |
| 2844 | + for tie in [SpawnTie::Untied, SpawnTie::Link, SpawnTie::Monitor(5)] { |
| 2845 | + let (code, down) = tie.parts(); |
| 2846 | + assert_eq!(SpawnTie::from_parts(code, down), Some(tie)); |
| 2847 | + } |
| 2848 | + assert_eq!(SpawnTie::from_parts(3, 0), None); |
| 2849 | + assert_eq!(SpawnTie::from_parts(2, -1), None); |
| 2850 | + assert_eq!(SpawnTie::from_parts(2, MAX_TAG as i64), None); |
| 2851 | + } |
| 2852 | + |
| 2853 | + /// A monitored spawn's answer, from node b, for an asker that is |
| 2854 | + /// gone or that gave up waiting: nothing is delivered or watched, |
| 2855 | + /// and node b is sent a demonitor of the new actor, so it forgets |
| 2856 | + /// the monitor (`docs/wire-format.md`, *Spawns*). An answer |
| 2857 | + /// refusing the spawn, or one to a spawn that was not monitored, |
| 2858 | + /// asks nothing back. |
| 2859 | + #[test] |
| 2860 | + fn a_monitored_spawn_nobody_waits_for_is_demonitored() { |
| 2861 | + let _turn = crate::sched::test_turn(); |
| 2862 | + let sched = Shared::new(1); |
| 2863 | + let state = state(&sched); |
| 2864 | + let b = Node { |
| 2865 | + name: "b.example".into(), |
| 2866 | + incarnation: 1, |
| 2867 | + }; |
| 2868 | + state.node_up(&b); |
| 2869 | + let reply = |asker, result| SpawnReply { |
| 2870 | + asker, |
| 2871 | + reply_tag: 3, |
| 2872 | + result, |
| 2873 | + serial: 12, |
| 2874 | + }; |
| 2875 | + let asked = |down, abandoned| Asked { |
| 2876 | + node: b.clone(), |
| 2877 | + down, |
| 2878 | + abandoned, |
| 2879 | + }; |
| 2880 | + let unwatch = |asker| Tie { |
| 2881 | + from: asker, |
| 2882 | + to: 12, |
| 2883 | + op: Op::Demonitor { tag: 5 }, |
| 2884 | + }; |
| 2885 | + // Actor 7 never existed on this scheduler: gone. |
| 2886 | + let gone = state.settle_spawn(&b, &reply(7, SPAWNED), &asked(Some(5), false)); |
| 2887 | + assert_eq!(gone, Some(unwatch(7))); |
| 2888 | + let abandoned = state.settle_spawn(&b, &reply(8, SPAWNED), &asked(Some(5), true)); |
| 2889 | + assert_eq!(abandoned, Some(unwatch(8))); |
| 2890 | + let refused = state.settle_spawn(&b, &reply(9, NOT_SPAWNED), &asked(Some(5), true)); |
| 2891 | + assert_eq!(refused, None); |
| 2892 | + let plain = state.settle_spawn(&b, &reply(10, SPAWNED), &asked(None, false)); |
| 2893 | + assert_eq!(plain, None); |
| 2894 | + // Through the relay: the answer settles its pending spawn, |
| 2895 | + // once; another is dropped. |
| 2896 | + lock(&state.spawns).insert((7, 3), asked(Some(5), true)); |
| 2897 | + state.signal(&b, &reply(7, SPAWNED).encode()); |
| 2898 | + assert!(lock(&state.spawns).is_empty()); |
| 2899 | + // A lost node answers nobody for an abandoned spawn, and |
| 2900 | + // forgets it. |
| 2901 | + lock(&state.spawns).insert((8, 3), asked(Some(5), true)); |
| 2902 | + state.node_down(&b); |
| 2903 | + assert!(lock(&state.spawns).is_empty()); |
| 2904 | + } |
| 2905 | + |
| 2906 | + /// Pinned (`dist/secreview3`): a spawn answer (op `21`) settles only |
| 2907 | + /// a spawn this node asked of its sender. One from b for a spawn |
| 2908 | + /// asked of c, or for a monitored spawn asked of this node itself |
| 2909 | + /// (#421 keeps those pending too), is dropped and leaves the entry: |
| 2910 | + /// b can neither answer another node's spawn nor have the relay |
| 2911 | + /// watch for an asker or a down tag of its choice (the watch's pid |
| 2912 | + /// and tag are the pending spawn's). A lost node forgets only its |
| 2913 | + /// own; this node's are forgotten when its spawner takes them, or |
| 2914 | + /// when their asker gives up waiting (SR3-3, |
| 2915 | + /// `an_abandoned_spawn_asked_of_this_node_is_forgotten`). |
| 2916 | + #[test] |
| 2917 | + fn secreview3_a_spawn_answer_settles_only_a_spawn_asked_of_its_sender() { |
| 2918 | + let _turn = crate::sched::test_turn(); |
| 2919 | + let sched = Shared::new(1); |
| 2920 | + let state = state(&sched); |
| 2921 | + let node = |name: &str| Node { |
| 2922 | + name: name.into(), |
| 2923 | + incarnation: 1, |
| 2924 | + }; |
| 2925 | + let (b, c) = (node("b.example"), node("c.example")); |
| 2926 | + let me = state.me().expect("this node").clone(); |
| 2927 | + state.node_up(&b); |
| 2928 | + state.node_up(&c); |
| 2929 | + let asked = |node: &Node| Asked { |
| 2930 | + node: node.clone(), |
| 2931 | + down: Some(5), |
| 2932 | + abandoned: false, |
| 2933 | + }; |
| 2934 | + lock(&state.spawns).insert((7, 3), asked(&c)); |
| 2935 | + lock(&state.spawns).insert((8, 3), asked(&me)); |
| 2936 | + let answer = |asker| { |
| 2937 | + SpawnReply { |
| 2938 | + asker, |
| 2939 | + reply_tag: 3, |
| 2940 | + result: SPAWNED, |
| 2941 | + serial: 12, |
| 2942 | + } |
| 2943 | + .encode() |
| 2944 | + }; |
| 2945 | + let pending = || { |
| 2946 | + let mut keys: Vec<(i64, i64)> = lock(&state.spawns).keys().copied().collect(); |
| 2947 | + keys.sort_unstable(); |
| 2948 | + keys |
| 2949 | + }; |
| 2950 | + state.signal(&b, &answer(7)); |
| 2951 | + state.signal(&b, &answer(8)); |
| 2952 | + assert_eq!(pending(), [(7, 3), (8, 3)], "b answered others' spawns"); |
| 2953 | + state.node_down(&b); |
| 2954 | + assert_eq!(pending(), [(7, 3), (8, 3)], "b's loss"); |
| 2955 | + // c's own answer settles it (actor 7 is gone: nothing watched). |
| 2956 | + state.signal(&c, &answer(7)); |
| 2957 | + assert_eq!(pending(), [(8, 3)]); |
| 2958 | + state.node_down(&c); |
| 2959 | + assert_eq!(pending(), [(8, 3)], "this node's own spawn stays"); |
| 2960 | + } |
| 2961 | + |
| 2962 | + /// SR3-3: a monitored spawn asked of this node stayed pending |
| 2963 | + /// forever when its spawner died with the request queued: no |
| 2964 | + /// node's loss forgets it, and the asker's timeout only marked it. |
| 2965 | + /// The timeout forgets it now (the spawner, if it ever takes the |
| 2966 | + /// request, answers nobody and monitors nothing); one asked of |
| 2967 | + /// another node is still only marked, for its answer to settle. |
| 2968 | + #[test] |
| 2969 | + fn an_abandoned_spawn_asked_of_this_node_is_forgotten() { |
| 2970 | + let _turn = crate::sched::test_turn(); |
| 2971 | + let sched = Shared::new(1); |
| 2972 | + let state = state(&sched); |
| 2973 | + let b = Node { |
| 2974 | + name: "b.example".into(), |
| 2975 | + incarnation: 1, |
| 2976 | + }; |
| 2977 | + let me = state.me().expect("this node").clone(); |
| 2978 | + state.node_up(&b); |
| 2979 | + let asked = |node: &Node| Asked { |
| 2980 | + node: node.clone(), |
| 2981 | + down: Some(5), |
| 2982 | + abandoned: false, |
| 2983 | + }; |
| 2984 | + lock(&state.spawns).insert((7, 3), asked(&b)); |
| 2985 | + lock(&state.spawns).insert((8, 3), asked(&me)); |
| 2986 | + assert!(state.abandon_spawn(8, 3)); |
| 2987 | + assert!(state.abandon_spawn(7, 3)); |
| 2988 | + assert!(!state.abandon_spawn(9, 3), "answered meanwhile"); |
| 2989 | + let spawns = lock(&state.spawns); |
| 2990 | + assert!(!spawns.contains_key(&(8, 3)), "this node's is forgotten"); |
| 2991 | + assert!( |
| 2992 | + spawns.get(&(7, 3)).is_some_and(|a| a.abandoned), |
| 2993 | + "b's waits" |
| 2994 | + ); |
| 2995 | + } |
| 2996 | + } |
| 2997 | +} |