//! Distribution's codec (ADR 0072, *The wire*): the type registry, and //! the encoder and decoder of message payloads. [`docs/wire-format.md`] //! is normative; `louise_rt_prims::wire` holds its kernel (descriptors, //! the table, hashes, varints), this module walks heap values with it. //! //! Only distribution reaches it: the transport's hooks and `std/dist`'s //! externs. A program that never starts distribution links none of it //! (`--gc-sections`; the size test of ADR 0042 checks the kernel). //! //! - **The registry** is built once from the program's definitions table. //! A type is *registered* from its descriptor: it gets an index, the //! `wire` a `Remote` subject holds and the send hook gets, and its hash, //! which frames carry. Registering a type registers at once the message //! type of every subject it reaches: encoding a local `Subject` then //! needs no registration (ADR 0072: replies of type `r` are not dropped //! as unknown), and decoding one finds its `Remote`'s `wire`. A hash //! registered for another canonical form is a collision, refused: the //! caller stops the program. //! - **Types are hash-consed**: equal types are one [`Ty`], so a //! back-reference's type check compares two integers, and each instance //! of a data type (its constructors' field types, instantiated) is //! computed once, when it is first reached. Regular types reach finitely //! many instances (`Table::parse` refuses nested ones), each built from //! its descriptor's subterms and the table's field types. //! - **Bounds.** The registry only grows, by the types the program itself //! registers (a peer never adds one: an unknown hash is dropped): the //! program's message types and what they reach, at most [`MAX_TYPES`]. //! The node table grows by what peers name, at most [`PEER_NODES`] new //! entries per peer name for the run (the caller keeps the count). //! - **Threads.** Senders encode on their scheduler threads and the //! transport decodes on its own, both under the registry's read lock; //! registering, rare, takes the write lock. Encoding and decoding take //! the node table's lock while they hold the registry's: a caller must //! never take the registry's while it holds the node table's. //! - **Walks are iterative**, the last child of a node in tail position: //! a list is as deep as a constructor (the format's depth rule). //! - **Ownership.** The decoder builds its value outside any actor (null //! context, as `process::deliver_made`'s messages), storing each block //! in its parent as soon as it is allocated, its unfilled fields unit: //! on an error the partial value is released whole, and nothing leaks. //! //! [`docs/wire-format.md`]: ../../../docs/wire-format.md #![cfg_attr( not(any(test, feature = "tls")), allow( dead_code, reason = "without TLS nothing starts distribution (node.rs)" ) )] use std::collections::{HashMap, HashSet}; use std::fmt; use std::hash::BuildHasherDefault; use std::sync::atomic::{AtomicI32, Ordering}; use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}; use louise_rt_prims::wire::{ Desc, Head, IntHead, MAX_NODE_NAME, MAX_PAYLOAD, MAX_PID_SERIAL, MAX_TAG, MAX_VALUE_DEPTH, Reader, Table, WireError, check_node_name, hash_canonical, write_float, write_head, write_int, write_small_int, write_uvarint, write_uvarint128, zigzag, }; use crate::abi::{ Block, SCAN_LARGE, TAG_ARRAY, TAG_BIGINT, TAG_BYTES, TAG_DEC, TAG_FLOAT, TAG_STRING, TAG_U64, UNIT, Value, int, int_get, is_ptr, }; use crate::dist::{MAX_NODES, Node, Nodes, is_remote, parts, remote}; use crate::sched::IdHasher; /// The most type instances a registry holds (types the program registers /// and every instance they reach). Past it, registering fails. pub(crate) const MAX_TYPES: usize = 1 << 20; /// The node-table entries one peer name may add for the whole run, its /// own incarnations included (ADR 0072, *Trust*), the start of the count /// [`decode`] takes: a frame naming more new nodes than its peer has left /// is dropped and counted. A peer forwards the pids of its cluster, a few /// per node and incarnation; the count is never given back, so no peer, /// reconnecting or restarting, fills the table (2^16 entries) alone. pub(crate) const PEER_NODES: u32 = 1 << 10; const NONE: u32 = u32::MAX; /// A type instance: an index into the registry's instances. Equal types, /// equal indices. type Ty = u32; /// A type's structure, its components interned: hash-consing's key. #[derive(Clone, Debug, PartialEq, Eq, Hash)] enum Key { Int, Float, String, Bytes, U64, Dec, Pid, Unit, Subject(Ty), Array(Ty), Tuple(Box<[Ty]>), /// A data type (by index in the table), applied to arguments. Adt(u32, Box<[Ty]>), } struct Inst { key: Key, /// A data type's constructors, in index order: each one's field types /// at this instance (none: nullary). ctors: Box<[Box<[Ty]>]>, /// A subject's message type's registry index, once registered. wire: u32, /// Its registry index, if registered. entry: u32, /// Every subject it reaches has its `wire`: a registration walked it. closed: bool, } /// A registered type. struct Entry { ty: Ty, hash: u64, canonical: Box, } /// What [`Registry::register`] gives: the type's registry index (a /// `Remote` subject's `wire`) and its hash (what its frames carry). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Registered { pub(crate) index: u32, pub(crate) hash: u64, } #[derive(Debug, PartialEq, Eq)] pub(crate) enum RegisterError { /// The descriptor is malformed, or names no type of the table. Desc(WireError), /// Two types have one hash, `known` registered first: refused (ADR /// 0072, *Settled*), and the caller stops the program. Collision { hash: u64, known: String, new: String, }, /// More than [`MAX_TYPES`] instances. Full, } impl fmt::Display for RegisterError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { RegisterError::Desc(e) => write!(f, "bad type descriptor: {e}"), RegisterError::Collision { hash, known, new } => write!( f, "two types have the wire hash {hash:016x}: `{known}` and `{new}`" ), RegisterError::Full => write!(f, "more than {MAX_TYPES} wire types"), } } } #[derive(Default)] struct Types { insts: Vec, by_key: HashMap, /// Data type instances whose constructors are still to compute. pending: Vec, entries: Vec, by_hash: HashMap, } /// A program's registry of wire types (see the module's documentation). pub(crate) struct Registry { table: Table, defs: HashMap, types: RwLock, /// The type hash of a canonical form: `hash_canonical`, but for the /// collision tests. hash: fn(&[u8]) -> u64, } impl Registry { /// The registry of the program whose definitions table is `table` /// (`Table::write`'s text), checked by `Table::parse`. Nothing is /// registered yet. pub(crate) fn new(table: &str) -> Result { let table = Table::parse(table)?; let defs = table .defs() .iter() .enumerate() .map(|(i, d)| (d.name.clone(), i as u32)) .collect(); Ok(Registry { table, defs, types: RwLock::default(), hash: hash_canonical, }) } fn read(&self) -> RwLockReadGuard<'_, Types> { self.types.read().unwrap_or_else(PoisonError::into_inner) } fn write(&self) -> RwLockWriteGuard<'_, Types> { self.types.write().unwrap_or_else(PoisonError::into_inner) } /// Register the type a program's descriptor names (a `Wire` /// dictionary's text), and the message type of every subject it /// reaches. Registering a type again gives the same answer. pub(crate) fn register(&self, desc: &str) -> Result { let ty = self.table.parse_desc(desc).map_err(RegisterError::Desc)?; { let types = self.read(); if let Some(r) = types .find(&self.defs, &ty) .and_then(|t| types.registered(t)) { return Ok(r); } } let mut types = self.write(); let start = types.insts.len(); let result = types.register(self, &ty); if result.is_err() { types.truncate(start); } result } /// The registry index of the type framed with `hash`, if registered. pub(crate) fn by_hash(&self, hash: u64) -> Option { self.read().by_hash.get(&hash).copied() } /// The hash of the type registered at `index` (a `Remote` subject's /// `wire`): what a frame of its messages carries. pub(crate) fn hash(&self, index: u32) -> Option { self.read().entries.get(index as usize).map(|e| e.hash) } } impl Types { fn registered(&self, t: Ty) -> Option { let index = self.insts[t as usize].entry; (index != NONE).then(|| Registered { index, hash: self.entries[index as usize].hash, }) } /// The instance of a closed descriptor, if it exists already. fn find(&self, defs: &HashMap, d: &Desc) -> Option { let key = match d { Desc::Subject(m) => Key::Subject(self.find(defs, m)?), Desc::Array(e) => Key::Array(self.find(defs, e)?), Desc::Tuple(ds) => Key::Tuple( ds.iter() .map(|d| self.find(defs, d)) .collect::>()?, ), Desc::Adt { name, args } => Key::Adt( defs[name], args.iter() .map(|d| self.find(defs, d)) .collect::>()?, ), Desc::Param(_) => return None, leaf => leaf_key(leaf), }; self.by_key.get(&key).copied() } /// The instance of `d`, its parameters standing for `env` (a field /// type at an instance), made if new. fn intern(&mut self, reg: &Registry, d: &Desc, env: &[Ty]) -> Result { let key = match d { Desc::Param(i) => return Ok(env[*i as usize]), Desc::Subject(m) => Key::Subject(self.intern(reg, m, env)?), Desc::Array(e) => Key::Array(self.intern(reg, e, env)?), Desc::Tuple(ds) => Key::Tuple( ds.iter() .map(|d| self.intern(reg, d, env)) .collect::>()?, ), Desc::Adt { name, args } => Key::Adt( reg.defs[name], args.iter() .map(|d| self.intern(reg, d, env)) .collect::>()?, ), leaf => leaf_key(leaf), }; if let Some(&t) = self.by_key.get(&key) { return Ok(t); } if self.insts.len() >= MAX_TYPES { return Err(RegisterError::Full); } let t = self.insts.len() as Ty; if matches!(key, Key::Adt(..)) { self.pending.push(t); } self.by_key.insert(key.clone(), t); self.insts.push(Inst { key, ctors: Box::default(), wire: NONE, entry: NONE, closed: false, }); Ok(t) } /// Compute the constructors of the data type instances made since the /// last call (each may make more: finitely many, for regular types). fn instantiate(&mut self, reg: &Registry) -> Result<(), RegisterError> { while let Some(t) = self.pending.pop() { let Key::Adt(def, args) = self.insts[t as usize].key.clone() else { unreachable!("only data types are pending"); }; let ctors = reg.table.defs()[def as usize] .ctors .iter() .map(|c| { c.fields .iter() .map(|f| self.intern(reg, &f.ty, &args)) .collect::, _>>() }) .collect::>()?; self.insts[t as usize].ctors = ctors; } Ok(()) } /// The instances `t` refers to: a subject's message type, components, /// field types. fn children(&self, t: Ty) -> Vec { let inst = &self.insts[t as usize]; match &inst.key { Key::Subject(c) | Key::Array(c) => vec![*c], Key::Tuple(cs) => cs.to_vec(), Key::Adt(..) => inst.ctors.iter().flatten().copied().collect(), _ => Vec::new(), } } /// The descriptor of an instance. fn desc(&self, reg: &Registry, t: Ty) -> Desc { match &self.insts[t as usize].key { Key::Int => Desc::Int, Key::Float => Desc::Float, Key::String => Desc::String, Key::Bytes => Desc::Bytes, Key::U64 => Desc::U64, Key::Dec => Desc::Dec, Key::Pid => Desc::Pid, Key::Unit => Desc::Unit, Key::Subject(m) => Desc::Subject(Box::new(self.desc(reg, *m))), Key::Array(e) => Desc::Array(Box::new(self.desc(reg, *e))), Key::Tuple(cs) => Desc::Tuple(cs.iter().map(|c| self.desc(reg, *c)).collect()), Key::Adt(def, args) => Desc::Adt { name: reg.table.defs()[*def as usize].name.clone(), args: args.iter().map(|a| self.desc(reg, *a)).collect(), }, } } /// See [`Registry::register`]. On an error, the caller truncates the /// instances made: nothing was committed. fn register(&mut self, reg: &Registry, ty: &Desc) -> Result { let root = self.intern(reg, ty, &[])?; self.instantiate(reg)?; if let Some(r) = self.registered(root) { return Ok(r); } // The instances it reaches that no registration walked, and the // types to register: it, and its subjects' message types. let mut walk = vec![root]; let mut seen = HashSet::from([root]); let mut new = vec![root]; let mut i = 0; while let Some(&t) = walk.get(i) { i += 1; if let Key::Subject(m) = self.insts[t as usize].key && self.insts[m as usize].entry == NONE && !new.contains(&m) { new.push(m); } for c in self.children(t) { if !self.insts[c as usize].closed && seen.insert(c) { walk.push(c); } } } // Hash them all, and refuse a collision before committing any. let mut batch: Vec<(u64, Ty, String)> = Vec::with_capacity(new.len()); for &t in &new { let desc = self.desc(reg, t); let canonical = reg.table.canonical(&desc).map_err(RegisterError::Desc)?; let hash = (reg.hash)(canonical.as_bytes()); let known = self .by_hash .get(&hash) .map(|&e| self.entries[e as usize].canonical.as_ref()) .or_else(|| batch.iter().find(|b| b.0 == hash).map(|b| b.2.as_str())); if let Some(known) = known && *known != canonical { return Err(RegisterError::Collision { hash, known: desc_line(known).to_owned(), new: desc.to_string(), }); } batch.push((hash, t, canonical)); } for (hash, t, canonical) in batch { let index = self.entries.len() as u32; self.entries.push(Entry { ty: t, hash, canonical: canonical.into(), }); self.by_hash.insert(hash, index); self.insts[t as usize].entry = index; } for t in walk { if let Key::Subject(m) = self.insts[t as usize].key { self.insts[t as usize].wire = self.insts[m as usize].entry; } self.insts[t as usize].closed = true; } Ok(self.registered(root).expect("registered above")) } /// Forget the instances from `start` on (a failed registration's). fn truncate(&mut self, start: usize) { for inst in self.insts.drain(start..) { self.by_key.remove(&inst.key); } self.pending.clear(); } } fn leaf_key(d: &Desc) -> Key { match d { Desc::Int => Key::Int, Desc::Float => Key::Float, Desc::String => Key::String, Desc::Bytes => Key::Bytes, Desc::U64 => Key::U64, Desc::Dec => Key::Dec, Desc::Pid => Key::Pid, Desc::Unit => Key::Unit, _ => unreachable!("not a leaf: {d}"), } } /// The descriptor line of a canonical form. fn desc_line(canonical: &str) -> &str { canonical.lines().nth(1).unwrap_or(canonical) } // ---- walks ---------------------------------------------------------------------- /// A node whose children are being walked, the next one at `next`. The /// walk takes its last child after popping it (tail position), so the /// stack holds only nodes with a child left after the current one: the /// format's depth. struct Frame<'a> { fields: *mut Value, tys: Tys<'a>, next: u32, len: u32, /// The decoder's number for it. node: u64, } #[derive(Clone, Copy)] enum Tys<'a> { /// A tuple's components, a constructor's fields. Each(&'a [Ty]), /// An array's elements. All(Ty), } impl Frame<'_> { fn at(&self, i: u32) -> (*mut Value, Ty) { let ty = match self.tys { Tys::Each(ts) => ts[i as usize], Tys::All(t) => t, }; (self.fields.wrapping_add(i as usize), ty) } } /// What a walk does after a node: its first child, after pushing it if it /// has more, or the next child of the nearest node that has one left. fn next_child<'a>( stack: &mut Vec>, children: Option>, ) -> Result, &'static str> { if let Some(mut f) = children.filter(|f| f.len > 0) { let first = f.at(0); if f.len > 1 { if stack.len() >= MAX_VALUE_DEPTH as usize { return Err("value nested too deeply"); } f.next = 1; stack.push(f); } return Ok(Some(first)); } let Some(f) = stack.last_mut() else { return Ok(None); }; let child = f.at(f.next); f.next += 1; if f.next == f.len { stack.pop(); } Ok(Some(child)) } // ---- encoding ----------------------------------------------------------------------- /// Why a value cannot be encoded: a bug in the sending program, which the /// caller turns into a panic in the sender (ADR 0072, *Settled*). #[derive(Debug, PartialEq, Eq)] pub(crate) enum EncodeError { /// No type is registered at this index. UnknownType(u32), /// The payload would pass [`MAX_PAYLOAD`]. TooLarge, /// The value is nested past [`MAX_VALUE_DEPTH`]. TooDeep, /// A local pid at or past 2^46 cannot be named on another node. PidSerial(i64), /// A subject's tag is not in `0 .. 2^62`. Tag(i64), /// The value is not represented as its type is: a compiler or runtime /// bug. Malformed(&'static str), } impl fmt::Display for EncodeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { EncodeError::UnknownType(i) => write!(f, "no wire type registered at {i}"), EncodeError::TooLarge => write!(f, "message larger than {MAX_PAYLOAD} bytes"), EncodeError::TooDeep => write!(f, "message nested deeper than {MAX_VALUE_DEPTH}"), EncodeError::PidSerial(p) => write!(f, "pid {p} cannot be named on another node"), EncodeError::Tag(t) => write!(f, "subject tag {t} out of range"), EncodeError::Malformed(what) => write!(f, "malformed message: {what}"), } } } /// A block at a type: the encoder's sharing key, hashed as two words. #[derive(PartialEq, Eq)] struct Seen(usize, Ty); impl std::hash::Hash for Seen { fn hash(&self, state: &mut H) { state.write_usize(self.0); state.write_u64(u64::from(self.1)); } } /// The key of this node in a frame's node list. const ME: u32 = u32::MAX; struct Encoder<'a> { types: &'a Types, out: Vec, /// The number of the next node. count: u64, /// The nodes of blocks that may be reached again (not unique), by /// (block, type). shared: HashMap>, me: &'a Node, nodes: &'a RwLock, /// The frame's node list: its entries' bytes, and which node each one /// is (a node-table index, or [`ME`]). list: Vec, listed: Vec, } /// The payload of a message of the type registered at `wire`: the /// frame's node list, then `value` (`docs/wire-format.md`, *Value /// encoding*, *Frames*). Local pids are named as `me`'s, remote ones by /// their entry in `nodes`. On the sender's thread; an error is the /// sender's panic. /// /// # Safety /// `value` must be live (borrowed), a value of that type. pub(crate) unsafe fn encode( registry: &Registry, wire: u32, value: Value, me: &Node, nodes: &RwLock, ) -> Result, EncodeError> { let types = registry.read(); let Some(entry) = types.entries.get(wire as usize) else { return Err(EncodeError::UnknownType(wire)); }; let mut e = Encoder { types: &types, out: Vec::with_capacity(256), count: 0, shared: HashMap::default(), me, nodes, list: Vec::new(), listed: Vec::new(), }; let mut stack = Vec::new(); let mut root = value; let mut next = Some((&raw mut root, entry.ty)); while let Some((slot, t)) = next { // SAFETY: `slot` is the root or a field of a live block of the // value (caller guarantee), of type `t`. let children = unsafe { e.value(*slot, t)? }; if e.out.len() > MAX_PAYLOAD as usize { return Err(EncodeError::TooLarge); } next = next_child(&mut stack, children).map_err(|_| EncodeError::TooDeep)?; } let mut payload = Vec::with_capacity(10 + e.list.len() + e.out.len()); write_uvarint(&mut payload, e.listed.len() as u64); payload.extend_from_slice(&e.list); payload.extend_from_slice(&e.out); if payload.len() > MAX_PAYLOAD as usize { return Err(EncodeError::TooLarge); } Ok(payload) } impl<'a> Encoder<'a> { /// Write `v`, of type `t`, up to its children: those to write next. /// /// # Safety /// `v` must be live, of type `t`. unsafe fn value(&mut self, v: Value, t: Ty) -> Result>, EncodeError> { let types = self.types; let inst = &types.insts[t as usize]; let b = v as *mut Block; // A block's tag and number of scanned fields; (0, 0) for an // immediate, which no arm below reads as a block. let (tag, scan) = if is_ptr(v) { // SAFETY: a pointer value is a live block (caller guarantee). unsafe { ((*b).header.tag, (*b).header.scan_fsize) } } else { (0, 0) }; let kind = |runtime_tag: u16| is_ptr(v) && tag == runtime_tag; let malformed = |what| Err(EncodeError::Malformed(what)); match &inst.key { Key::Unit => self.out.push(0), Key::Int if !is_ptr(v) => write_small_int(&mut self.out, int_get(v)), Key::Int if kind(TAG_BIGINT) => { if !self.seen(b, t) { // SAFETY: a live big integer. let n = unsafe { crate::int::to_big(v) }; write_int(&mut self.out, &n); } } Key::Float if kind(TAG_FLOAT) => { // SAFETY: a live Float. write_float(&mut self.out, unsafe { crate::prims::tl_float_get(v) }); } Key::U64 if kind(TAG_U64) => { // SAFETY: a live U64. write_uvarint(&mut self.out, unsafe { crate::u64::get(v) }); } Key::Dec if kind(TAG_DEC) => { // SAFETY: a live Dec. write_uvarint128(&mut self.out, zigzag(unsafe { crate::dec::get(v) })); } Key::Pid if !is_ptr(v) => self.pid(int_get(v))?, Key::String if kind(TAG_STRING) => self.bytes(b, t)?, Key::Bytes if kind(TAG_BYTES) => self.bytes(b, t)?, Key::Array(elem) if kind(TAG_ARRAY) => { if self.seen(b, t) { return Ok(None); } // SAFETY: a live array: its count, then its elements. let (fields, len) = unsafe { crate::heap::scanned_fields(b) }; // Each element takes a byte at least; and a frame counts // its children in a `u32`. if len > MAX_PAYLOAD as usize { return Err(EncodeError::TooLarge); } write_head(&mut self.out, Head::New(len as u64)); return Ok(Some(frame(fields, Tys::All(*elem), len))); } Key::Tuple(cs) if is_ptr(v) => { if tag != 0 || usize::from(scan) != cs.len() { return malformed("a tuple of another arity"); } if self.seen(b, t) { return Ok(None); } write_head(&mut self.out, Head::New(0)); return Ok(Some(frame(Block::fields_ptr(b), Tys::Each(cs), cs.len()))); } Key::Subject(_) if is_ptr(v) => { if !matches!((tag, scan), (0, 2) | (1, 3)) { return malformed("a subject of another shape"); } if self.seen(b, t) { return Ok(None); } // SAFETY: a subject block has its owner and tag first. let (owner, tag) = unsafe { let f = Block::fields_ptr(b); (*f, *f.add(1)) }; if is_ptr(owner) || is_ptr(tag) { return malformed("a subject's owner or tag is not an Int"); } write_head(&mut self.out, Head::New(0)); self.pid(int_get(owner))?; let tag = int_get(tag); if !(0..MAX_TAG as i64).contains(&tag) { return Err(EncodeError::Tag(tag)); } write_uvarint(&mut self.out, tag as u64); } Key::Adt(..) if !is_ptr(v) => { let c = int_get(v); let nullary = usize::try_from(c) .ok() .and_then(|c| inst.ctors.get(c)) .is_some_and(|fields| fields.is_empty()); if !nullary { return malformed("not a nullary constructor of its type"); } write_head(&mut self.out, Head::New(c as u64)); } Key::Adt(..) => { let fields = inst.ctors.get(usize::from(tag)); let Some(fields) = fields.filter(|f| { !f.is_empty() && scan != SCAN_LARGE && usize::from(scan) == f.len() }) else { return malformed("not a constructor of its type"); }; if self.seen(b, t) { return Ok(None); } write_head(&mut self.out, Head::New(u64::from(tag))); return Ok(Some(frame( Block::fields_ptr(b), Tys::Each(fields), fields.len(), ))); } _ => return malformed("a value of another kind than its type"), } Ok(None) } /// Whether `b` was written at type `t` already: then a back-reference /// to it is written. Otherwise `b` is a new node. A unique block is /// reached once: it is not recorded. fn seen(&mut self, b: *mut Block, t: Ty) -> bool { let n = self.count; // SAFETY: `b` is live (the caller's guarantee). A shared block's // count (negative) changes on other threads meanwhile: read // atomically, though no change makes it 1. let rc = unsafe { AtomicI32::from_ptr(&raw mut (*b).header.rc) }; if rc.load(Ordering::Relaxed) != 1 { if let Some(&back) = self.shared.get(&Seen(b as usize, t)) { write_head(&mut self.out, Head::Back(back)); return true; } self.shared.insert(Seen(b as usize, t), n); } self.count += 1; false } /// A `String` or `Bytes` (same layout up to the NUL). One past the /// payload's limit is refused before it is copied. fn bytes(&mut self, b: *mut Block, t: Ty) -> Result<(), EncodeError> { if self.seen(b, t) { return Ok(()); } // SAFETY: `b` is a live string or byte string. let bytes = unsafe { crate::values::bytes_of(b as Value) }; if self.out.len() + bytes.len() > MAX_PAYLOAD as usize { return Err(EncodeError::TooLarge); } write_head(&mut self.out, Head::New(bytes.len() as u64)); self.out.extend_from_slice(bytes); Ok(()) } /// A pid: its node's entry in the frame's list, then its serial. fn pid(&mut self, pid: i64) -> Result<(), EncodeError> { let (node, serial) = if is_remote(pid) { let (node, serial) = parts(pid); (u32::from(node), serial as u64) } else if (pid as u64) < MAX_PID_SERIAL { (ME, pid as u64) } else { return Err(EncodeError::PidSerial(pid)); }; let entry = match self.listed.iter().position(|n| *n == node) { Some(i) => i, None => self.list_node(node)?, }; write_uvarint(&mut self.out, entry as u64); write_uvarint(&mut self.out, serial); Ok(()) } /// Add `node` to the frame's node list; its entry. fn list_node(&mut self, node: u32) -> Result { let mut write = |name: &str, incarnation: u64| { write_uvarint(&mut self.list, name.len() as u64); self.list.extend_from_slice(name.as_bytes()); self.list.extend_from_slice(&incarnation.to_le_bytes()); }; if node == ME { write(&self.me.name, self.me.incarnation); } else { let nodes = self.nodes.read().unwrap_or_else(PoisonError::into_inner); let Some(n) = nodes.get(node as u16) else { return Err(EncodeError::Malformed("a remote pid of no known node")); }; write(&n.name, n.incarnation); } self.listed.push(node); Ok(self.listed.len() - 1) } } fn frame(fields: *mut Value, tys: Tys<'_>, len: usize) -> Frame<'_> { Frame { fields, tys, next: 0, len: len as u32, node: 0, } } // ---- decoding ------------------------------------------------------------------------- /// Why a frame's payload is refused: the frame is dropped and counted /// (ADR 0072). #[derive(Debug, PartialEq, Eq)] pub(crate) enum DecodeError { /// No type is registered under the frame's hash. UnknownType(u64), /// The payload is malformed (`docs/wire-format.md`, *Validation*). Malformed(WireError), /// The frame names more new nodes than its peer may still add. PeerNodes, /// The node table is full (2^16 entries). NodesFull, } impl From for DecodeError { fn from(e: WireError) -> Self { DecodeError::Malformed(e) } } impl fmt::Display for DecodeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { DecodeError::UnknownType(h) => write!(f, "no wire type has the hash {h:016x}"), DecodeError::Malformed(e) => write!(f, "{e}"), DecodeError::PeerNodes => write!(f, "the peer names too many new nodes"), DecodeError::NodesFull => write!(f, "the node table is full"), } } } /// Whose pids a node list entry names. #[derive(Clone, Copy)] enum Owner { Local, Remote(u16), } struct Decoded { /// Owned by the value being built. value: Value, ty: Ty, /// Not an ancestor of what is being read. complete: bool, } struct Decoder<'a> { types: &'a Types, r: Reader<'a>, owners: Vec, /// Every node read, by number. nodes: Vec, /// The nodes not complete, by number (increasing): the ancestors of /// what is being read. open: Vec, /// A local subject no payload may name ([`decode`]). reserved: Option<(i64, i64)>, } /// The value of a payload framed with `type_hash` (the frame's node list, /// then the value), owned, made outside any actor: what /// `dist::inbound::deliver` hands over. Every check of /// `docs/wire-format.md`'s *Validation* is made before allocating for the /// part at fault; on an error nothing is left allocated. /// /// The node list's entries that name `me` make local pids; the others /// are entered in `nodes`. `peer_nodes` is how many new entries the /// sending peer may still add (start it at [`PEER_NODES`]); a frame /// naming more is refused before adding any, and those it adds are /// counted down, whether the value decodes or not. /// /// `reserved` is a local subject (owner, tag) that no payload may name, /// the node's spawner's: only the node itself hands it a value (ADR 0072, /// *Spawning*). A subject naming it is malformed. pub(crate) fn decode( registry: &Registry, type_hash: u64, payload: &[u8], me: &Node, nodes: &RwLock, peer_nodes: &mut u32, reserved: Option<(i64, i64)>, ) -> Result { let types = registry.read(); let Some(&index) = types.by_hash.get(&type_hash) else { return Err(DecodeError::UnknownType(type_hash)); }; if payload.len() > MAX_PAYLOAD as usize { return Err(WireError { at: 0, what: "payload too large", } .into()); } let mut r = Reader::new(payload); let owners = node_list(&mut r, me, nodes, peer_nodes)?; let mut d = Decoder { types: &types, r, owners, nodes: Vec::new(), open: Vec::new(), reserved, }; let mut root = UNIT; // SAFETY: `root` is owned here, and holds every block the decoder // makes; released whole on an error. match unsafe { d.run(&raw mut root, types.entries[index as usize].ty) } { Ok(()) => Ok(root), Err(e) => { // SAFETY: `root` is owned and well formed (unfilled fields are // unit). unsafe { crate::heap::drop_detached(root) }; Err(e.into()) } } } /// The frame's node list (`docs/wire-format.md`, *Frames*): each entry's /// owner, new entries entered in `nodes`. fn node_list( r: &mut Reader<'_>, me: &Node, nodes: &RwLock, peer_nodes: &mut u32, ) -> Result, DecodeError> { let fail = |r: &Reader<'_>, what| Err(DecodeError::Malformed(WireError { at: r.at(), what })); let count = r.uvarint()?; // An entry takes at least 10 bytes; distinct entries name this node // or one of the node table's. if count > (r.left() / 10) as u64 { return fail(r, "count past the end of the payload"); } if count > MAX_NODES as u64 + 1 { return fail(r, "too many node list entries"); } let mut entries: Vec<(&str, u64)> = Vec::with_capacity(count as usize); let mut distinct = HashSet::with_capacity(count as usize); for _ in 0..count { let len = r.uvarint()?; if len > MAX_NODE_NAME as u64 { return fail(r, "node name too long"); } let name = r.take(len)?; if !check_node_name(name) { return fail(r, "bad node name"); } let name = std::str::from_utf8(name).expect("node names are ASCII"); let incarnation = r.u64_le()?; if !distinct.insert((name, incarnation)) { return fail(r, "node list entry repeated"); } entries.push((name, incarnation)); } let is_me = |(name, incarnation): (&str, u64)| name == me.name && incarnation == me.incarnation; let mut owners = Vec::with_capacity(entries.len()); let mut missing = false; { let table = nodes.read().unwrap_or_else(PoisonError::into_inner); for &e in &entries { owners.push(match table.find(e.0, e.1) { _ if is_me(e) => Owner::Local, Some(i) => Owner::Remote(i), None => { missing = true; Owner::Local } }); } } if missing { let mut table = nodes.write().unwrap_or_else(PoisonError::into_inner); let new = entries .iter() .filter(|&&e| !is_me(e) && table.find(e.0, e.1).is_none()) .count(); if new > *peer_nodes as usize { return Err(DecodeError::PeerNodes); } for (owner, &e) in owners.iter_mut().zip(&entries) { if is_me(e) { continue; } let known = table.find(e.0, e.1); let index = known.or_else(|| table.index(e.0, e.1)); *owner = Owner::Remote(index.ok_or(DecodeError::NodesFull)?); if known.is_none() { *peer_nodes -= 1; } } } Ok(owners) } impl<'a> Decoder<'a> { fn fail(&self, what: &'static str) -> Result { Err(WireError { at: self.r.at(), what, }) } /// Read the value of type `t` into `root`. /// /// # Safety /// `root` must be owned by the caller; on an error, it holds what was /// read, well formed. unsafe fn run(&mut self, root: *mut Value, t: Ty) -> Result<(), WireError> { let mut stack: Vec> = Vec::new(); let mut next = Some((root, t)); while let Some((slot, t)) = next { // SAFETY: `slot` is `root` or an unfilled field of a block it // holds. let children = unsafe { self.value(slot, t)? }; if children.is_none() || children.as_ref().is_some_and(|f| f.len == 0) { // Back to the nearest node with a child left: every node // read after it is complete. if let Some(top) = stack.last() { while self.open.last().is_some_and(|&n| n > top.node) { let n = self.open.pop().expect("open"); self.nodes[n as usize].complete = true; } } } next = next_child(&mut stack, children).or_else(|what| self.fail(what))?; } if !self.r.is_empty() { return self.fail("bytes left after the value"); } Ok(()) } /// A new node: its number. fn node(&mut self, value: Value, ty: Ty, children: bool) -> u64 { let n = self.nodes.len() as u64; self.nodes.push(Decoded { value, ty, complete: !children, }); if children { self.open.push(n); } n } /// A back-reference to node `n`, at type `t`. fn back(&self, n: u64, t: Ty) -> Result { match self.nodes.get(n as usize) { None => self.fail("back-reference to a node not read yet"), Some(d) if d.ty != t => self.fail("back-reference to a node of another type"), Some(d) if !d.complete => self.fail("back-reference to an enclosing node"), // SAFETY: a node's value is live: the value being built holds // it. Some(d) => Ok(unsafe { crate::heap::dup_value(d.value) }), } } /// A pid: its node's entry in the frame's list, then its serial. fn pid(&mut self) -> Result<(i64, bool), WireError> { let entry = self.r.uvarint()?; let Some(&owner) = self.owners.get(entry as usize) else { return self.fail("pid of no node list entry"); }; let serial = self.r.uvarint()?; if serial >= MAX_PID_SERIAL { return self.fail("pid serial out of range"); } Ok(match owner { Owner::Local => (serial as i64, true), Owner::Remote(node) => (remote(node, serial as i64).expect("serial in range"), false), }) } /// Read a value of type `t` into `slot`, up to its children: those to /// read next, into its fields. /// /// # Safety /// `slot` must be an unfilled (unit) slot of the value being built. unsafe fn value(&mut self, slot: *mut Value, t: Ty) -> Result>, WireError> { let types = self.types; let inst = &types.insts[t as usize]; let null = std::ptr::null_mut(); let v = match &inst.key { Key::Unit => match self.r.byte()? { 0 => UNIT, _ => return self.fail("unit is not 00"), }, Key::Int => match self.r.int()? { IntHead::Small(n) => int(n), IntHead::Big(n) => { let v = crate::int::from_big(null, &n); self.node(v, t, false); v } IntHead::Back(n) => self.back(n, t)?, }, Key::Float => crate::prims::tl_float_from(null, self.r.float()?), Key::U64 => crate::u64::u64_value(null, self.r.uvarint()?), Key::Dec => crate::dec::dec_value(null, self.r.dec()?), Key::Pid => int(self.pid()?.0), Key::String | Key::Bytes => match self.r.head()? { Head::Back(n) => self.back(n, t)?, Head::New(len) => { let bytes = self.r.take(len)?; let (v, raw) = if inst.key == Key::String { if std::str::from_utf8(bytes).is_err() { return self.fail("string not UTF-8"); } crate::values::string_uninit(null, bytes.len()) } else { crate::values::bytes_uninit(null, bytes.len()) }; // SAFETY: `raw` has room for `bytes.len()` bytes. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), raw, bytes.len()) }; self.node(v, t, false); v } }, Key::Subject(_) => match self.r.head()? { Head::Back(n) => self.back(n, t)?, Head::New(0) => { let (owner, local) = self.pid()?; let tag = self.r.uvarint()?; if tag >= MAX_TAG { return self.fail("subject tag out of range"); } if local && self.reserved == Some((owner, tag as i64)) { return self.fail("subject of the node's spawner"); } // A local owner's subject is a `Subject`, never a // `Remote` (`dist`). let v = if local { crate::values::cell(null, 0, &[int(owner), int(tag as i64)]) } else { debug_assert_ne!(inst.wire, NONE, "registered with its type"); let wire = i64::from(inst.wire); crate::values::cell(null, 1, &[int(owner), int(tag as i64), int(wire)]) }; self.node(v, t, false); v } Head::New(_) => return self.fail("subject head not 0"), }, Key::Array(elem) => match self.r.head()? { Head::Back(n) => self.back(n, t)?, Head::New(len) => { // Each element takes a byte at least. if len > self.r.left() as u64 { return self.fail("count past the end of the payload"); } let len = len as usize; let v = crate::array::alloc(null, len, len) as Value; // SAFETY: as every store below: `slot` is unfilled. unsafe { *slot = v }; let node = self.node(v, t, len > 0); let elems = crate::array::elems(v); return Ok(Some(Frame { node, ..frame(elems, Tys::All(*elem), len) })); } }, Key::Tuple(cs) => match self.r.head()? { Head::Back(n) => self.back(n, t)?, // SAFETY: `slot` is unfilled (caller guarantee). Head::New(0) => return unsafe { self.block(slot, t, 0, cs) }.map(Some), Head::New(_) => return self.fail("tuple head not 0"), }, Key::Adt(..) => match self.r.head()? { Head::Back(n) => self.back(n, t)?, Head::New(c) => { let Some(fields) = inst.ctors.get(c as usize) else { return self.fail("constructor out of range"); }; if fields.is_empty() { int(c as i64) } else { // SAFETY: `slot` is unfilled (caller guarantee). return unsafe { self.block(slot, t, c as u16, fields) }.map(Some); } } }, }; // SAFETY: `slot` is unfilled (caller guarantee). unsafe { *slot = v }; Ok(None) } /// A tuple or constructor block of `fields`, stored in `slot`, its /// fields to read next. Each takes a byte at least: checked first. /// /// # Safety /// `slot` must be an unfilled slot of the value being built. unsafe fn block( &mut self, slot: *mut Value, t: Ty, tag: u16, fields: &'a [Ty], ) -> Result, WireError> { if fields.len() > self.r.left() { return self.fail("fields past the end of the payload"); } let b = crate::heap::tl_alloc(std::ptr::null_mut(), tag, fields.len() as u8, 0); // SAFETY: forwarded caller guarantee. unsafe { *slot = b as Value }; let node = self.node(b as Value, t, true); Ok(Frame { node, ..frame(Block::fields_ptr(b), Tys::Each(fields), fields.len()) }) } } #[cfg(test)] mod tests;