tobogganSe connecter

louise

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

1274 lignes · 47755 octetsBrut · Historique
1//! Distribution's codec (ADR 0072, *The wire*): the type registry, and
2//! the encoder and decoder of message payloads. [`docs/wire-format.md`]
3//! is normative; `louise_rt_prims::wire` holds its kernel (descriptors,
4//! the table, hashes, varints), this module walks heap values with it.
5//!
6//! Only distribution reaches it: the transport's hooks and `std/dist`'s
7//! externs. A program that never starts distribution links none of it
8//! (`--gc-sections`; the size test of ADR 0042 checks the kernel).
9//!
10//! - **The registry** is built once from the program's definitions table.
11//! A type is *registered* from its descriptor: it gets an index, the
12//! `wire` a `Remote` subject holds and the send hook gets, and its hash,
13//! which frames carry. Registering a type registers at once the message
14//! type of every subject it reaches: encoding a local `Subject<r>` then
15//! needs no registration (ADR 0072: replies of type `r` are not dropped
16//! as unknown), and decoding one finds its `Remote`'s `wire`. A hash
17//! registered for another canonical form is a collision, refused: the
18//! caller stops the program.
19//! - **Types are hash-consed**: equal types are one [`Ty`], so a
20//! back-reference's type check compares two integers, and each instance
21//! of a data type (its constructors' field types, instantiated) is
22//! computed once, when it is first reached. Regular types reach finitely
23//! many instances (`Table::parse` refuses nested ones), each built from
24//! its descriptor's subterms and the table's field types.
25//! - **Bounds.** The registry only grows, by the types the program itself
26//! registers (a peer never adds one: an unknown hash is dropped): the
27//! program's message types and what they reach, at most [`MAX_TYPES`].
28//! The node table grows by what peers name, at most [`PEER_NODES`] new
29//! entries per peer name for the run (the caller keeps the count).
30//! - **Threads.** Senders encode on their scheduler threads and the
31//! transport decodes on its own, both under the registry's read lock;
32//! registering, rare, takes the write lock. Encoding and decoding take
33//! the node table's lock while they hold the registry's: a caller must
34//! never take the registry's while it holds the node table's.
35//! - **Walks are iterative**, the last child of a node in tail position:
36//! a list is as deep as a constructor (the format's depth rule).
37//! - **Ownership.** The decoder builds its value outside any actor (null
38//! context, as `process::deliver_made`'s messages), storing each block
39//! in its parent as soon as it is allocated, its unfilled fields unit:
40//! on an error the partial value is released whole, and nothing leaks.
41//!
42//! [`docs/wire-format.md`]: ../../../docs/wire-format.md
43
44#![cfg_attr(
45 not(any(test, feature = "tls")),
46 allow(
47 dead_code,
48 reason = "without TLS nothing starts distribution (node.rs)"
49 )
50)]
51
52use std::collections::{HashMap, HashSet};
53use std::fmt;
54use std::hash::BuildHasherDefault;
55use std::sync::atomic::{AtomicI32, Ordering};
56use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
57
58use louise_rt_prims::wire::{
59 Desc, Head, IntHead, MAX_NODE_NAME, MAX_PAYLOAD, MAX_PID_SERIAL, MAX_TAG, MAX_VALUE_DEPTH,
60 Reader, Table, WireError, check_node_name, hash_canonical, write_float, write_head, write_int,
61 write_small_int, write_uvarint, write_uvarint128, zigzag,
62};
63
64use crate::abi::{
65 Block, SCAN_LARGE, TAG_ARRAY, TAG_BIGINT, TAG_BYTES, TAG_DEC, TAG_FLOAT, TAG_STRING, TAG_U64,
66 UNIT, Value, int, int_get, is_ptr,
67};
68use crate::dist::{MAX_NODES, Node, Nodes, is_remote, parts, remote};
69use crate::sched::IdHasher;
70
71/// The most type instances a registry holds (types the program registers
72/// and every instance they reach). Past it, registering fails.
73pub(crate) const MAX_TYPES: usize = 1 << 20;
74
75/// The node-table entries one peer name may add for the whole run, its
76/// own incarnations included (ADR 0072, *Trust*), the start of the count
77/// [`decode`] takes: a frame naming more new nodes than its peer has left
78/// is dropped and counted. A peer forwards the pids of its cluster, a few
79/// per node and incarnation; the count is never given back, so no peer,
80/// reconnecting or restarting, fills the table (2^16 entries) alone.
81pub(crate) const PEER_NODES: u32 = 1 << 10;
82
83const NONE: u32 = u32::MAX;
84
85/// A type instance: an index into the registry's instances. Equal types,
86/// equal indices.
87type Ty = u32;
88
89/// A type's structure, its components interned: hash-consing's key.
90#[derive(Clone, Debug, PartialEq, Eq, Hash)]
91enum Key {
92 Int,
93 Float,
94 String,
95 Bytes,
96 U64,
97 Dec,
98 Pid,
99 Unit,
100 Subject(Ty),
101 Array(Ty),
102 Tuple(Box<[Ty]>),
103 /// A data type (by index in the table), applied to arguments.
104 Adt(u32, Box<[Ty]>),
105}
106
107struct Inst {
108 key: Key,
109 /// A data type's constructors, in index order: each one's field types
110 /// at this instance (none: nullary).
111 ctors: Box<[Box<[Ty]>]>,
112 /// A subject's message type's registry index, once registered.
113 wire: u32,
114 /// Its registry index, if registered.
115 entry: u32,
116 /// Every subject it reaches has its `wire`: a registration walked it.
117 closed: bool,
118}
119
120/// A registered type.
121struct Entry {
122 ty: Ty,
123 hash: u64,
124 canonical: Box<str>,
125}
126
127/// What [`Registry::register`] gives: the type's registry index (a
128/// `Remote` subject's `wire`) and its hash (what its frames carry).
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub(crate) struct Registered {
131 pub(crate) index: u32,
132 pub(crate) hash: u64,
133}
134
135#[derive(Debug, PartialEq, Eq)]
136pub(crate) enum RegisterError {
137 /// The descriptor is malformed, or names no type of the table.
138 Desc(WireError),
139 /// Two types have one hash, `known` registered first: refused (ADR
140 /// 0072, *Settled*), and the caller stops the program.
141 Collision {
142 hash: u64,
143 known: String,
144 new: String,
145 },
146 /// More than [`MAX_TYPES`] instances.
147 Full,
148}
149
150impl fmt::Display for RegisterError {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 match self {
153 RegisterError::Desc(e) => write!(f, "bad type descriptor: {e}"),
154 RegisterError::Collision { hash, known, new } => write!(
155 f,
156 "two types have the wire hash {hash:016x}: `{known}` and `{new}`"
157 ),
158 RegisterError::Full => write!(f, "more than {MAX_TYPES} wire types"),
159 }
160 }
161}
162
163#[derive(Default)]
164struct Types {
165 insts: Vec<Inst>,
166 by_key: HashMap<Key, Ty>,
167 /// Data type instances whose constructors are still to compute.
168 pending: Vec<Ty>,
169 entries: Vec<Entry>,
170 by_hash: HashMap<u64, u32>,
171}
172
173/// A program's registry of wire types (see the module's documentation).
174pub(crate) struct Registry {
175 table: Table,
176 defs: HashMap<String, u32>,
177 types: RwLock<Types>,
178 /// The type hash of a canonical form: `hash_canonical`, but for the
179 /// collision tests.
180 hash: fn(&[u8]) -> u64,
181}
182
183impl Registry {
184 /// The registry of the program whose definitions table is `table`
185 /// (`Table::write`'s text), checked by `Table::parse`. Nothing is
186 /// registered yet.
187 pub(crate) fn new(table: &str) -> Result<Registry, WireError> {
188 let table = Table::parse(table)?;
189 let defs = table
190 .defs()
191 .iter()
192 .enumerate()
193 .map(|(i, d)| (d.name.clone(), i as u32))
194 .collect();
195 Ok(Registry {
196 table,
197 defs,
198 types: RwLock::default(),
199 hash: hash_canonical,
200 })
201 }
202
203 fn read(&self) -> RwLockReadGuard<'_, Types> {
204 self.types.read().unwrap_or_else(PoisonError::into_inner)
205 }
206
207 fn write(&self) -> RwLockWriteGuard<'_, Types> {
208 self.types.write().unwrap_or_else(PoisonError::into_inner)
209 }
210
211 /// Register the type a program's descriptor names (a `Wire`
212 /// dictionary's text), and the message type of every subject it
213 /// reaches. Registering a type again gives the same answer.
214 pub(crate) fn register(&self, desc: &str) -> Result<Registered, RegisterError> {
215 let ty = self.table.parse_desc(desc).map_err(RegisterError::Desc)?;
216 {
217 let types = self.read();
218 if let Some(r) = types
219 .find(&self.defs, &ty)
220 .and_then(|t| types.registered(t))
221 {
222 return Ok(r);
223 }
224 }
225 let mut types = self.write();
226 let start = types.insts.len();
227 let result = types.register(self, &ty);
228 if result.is_err() {
229 types.truncate(start);
230 }
231 result
232 }
233
234 /// The registry index of the type framed with `hash`, if registered.
235 pub(crate) fn by_hash(&self, hash: u64) -> Option<u32> {
236 self.read().by_hash.get(&hash).copied()
237 }
238
239 /// The hash of the type registered at `index` (a `Remote` subject's
240 /// `wire`): what a frame of its messages carries.
241 pub(crate) fn hash(&self, index: u32) -> Option<u64> {
242 self.read().entries.get(index as usize).map(|e| e.hash)
243 }
244}
245
246impl Types {
247 fn registered(&self, t: Ty) -> Option<Registered> {
248 let index = self.insts[t as usize].entry;
249 (index != NONE).then(|| Registered {
250 index,
251 hash: self.entries[index as usize].hash,
252 })
253 }
254
255 /// The instance of a closed descriptor, if it exists already.
256 fn find(&self, defs: &HashMap<String, u32>, d: &Desc) -> Option<Ty> {
257 let key = match d {
258 Desc::Subject(m) => Key::Subject(self.find(defs, m)?),
259 Desc::Array(e) => Key::Array(self.find(defs, e)?),
260 Desc::Tuple(ds) => Key::Tuple(
261 ds.iter()
262 .map(|d| self.find(defs, d))
263 .collect::<Option<_>>()?,
264 ),
265 Desc::Adt { name, args } => Key::Adt(
266 defs[name],
267 args.iter()
268 .map(|d| self.find(defs, d))
269 .collect::<Option<_>>()?,
270 ),
271 Desc::Param(_) => return None,
272 leaf => leaf_key(leaf),
273 };
274 self.by_key.get(&key).copied()
275 }
276
277 /// The instance of `d`, its parameters standing for `env` (a field
278 /// type at an instance), made if new.
279 fn intern(&mut self, reg: &Registry, d: &Desc, env: &[Ty]) -> Result<Ty, RegisterError> {
280 let key = match d {
281 Desc::Param(i) => return Ok(env[*i as usize]),
282 Desc::Subject(m) => Key::Subject(self.intern(reg, m, env)?),
283 Desc::Array(e) => Key::Array(self.intern(reg, e, env)?),
284 Desc::Tuple(ds) => Key::Tuple(
285 ds.iter()
286 .map(|d| self.intern(reg, d, env))
287 .collect::<Result<_, _>>()?,
288 ),
289 Desc::Adt { name, args } => Key::Adt(
290 reg.defs[name],
291 args.iter()
292 .map(|d| self.intern(reg, d, env))
293 .collect::<Result<_, _>>()?,
294 ),
295 leaf => leaf_key(leaf),
296 };
297 if let Some(&t) = self.by_key.get(&key) {
298 return Ok(t);
299 }
300 if self.insts.len() >= MAX_TYPES {
301 return Err(RegisterError::Full);
302 }
303 let t = self.insts.len() as Ty;
304 if matches!(key, Key::Adt(..)) {
305 self.pending.push(t);
306 }
307 self.by_key.insert(key.clone(), t);
308 self.insts.push(Inst {
309 key,
310 ctors: Box::default(),
311 wire: NONE,
312 entry: NONE,
313 closed: false,
314 });
315 Ok(t)
316 }
317
318 /// Compute the constructors of the data type instances made since the
319 /// last call (each may make more: finitely many, for regular types).
320 fn instantiate(&mut self, reg: &Registry) -> Result<(), RegisterError> {
321 while let Some(t) = self.pending.pop() {
322 let Key::Adt(def, args) = self.insts[t as usize].key.clone() else {
323 unreachable!("only data types are pending");
324 };
325 let ctors = reg.table.defs()[def as usize]
326 .ctors
327 .iter()
328 .map(|c| {
329 c.fields
330 .iter()
331 .map(|f| self.intern(reg, &f.ty, &args))
332 .collect::<Result<Box<[Ty]>, _>>()
333 })
334 .collect::<Result<_, _>>()?;
335 self.insts[t as usize].ctors = ctors;
336 }
337 Ok(())
338 }
339
340 /// The instances `t` refers to: a subject's message type, components,
341 /// field types.
342 fn children(&self, t: Ty) -> Vec<Ty> {
343 let inst = &self.insts[t as usize];
344 match &inst.key {
345 Key::Subject(c) | Key::Array(c) => vec![*c],
346 Key::Tuple(cs) => cs.to_vec(),
347 Key::Adt(..) => inst.ctors.iter().flatten().copied().collect(),
348 _ => Vec::new(),
349 }
350 }
351
352 /// The descriptor of an instance.
353 fn desc(&self, reg: &Registry, t: Ty) -> Desc {
354 match &self.insts[t as usize].key {
355 Key::Int => Desc::Int,
356 Key::Float => Desc::Float,
357 Key::String => Desc::String,
358 Key::Bytes => Desc::Bytes,
359 Key::U64 => Desc::U64,
360 Key::Dec => Desc::Dec,
361 Key::Pid => Desc::Pid,
362 Key::Unit => Desc::Unit,
363 Key::Subject(m) => Desc::Subject(Box::new(self.desc(reg, *m))),
364 Key::Array(e) => Desc::Array(Box::new(self.desc(reg, *e))),
365 Key::Tuple(cs) => Desc::Tuple(cs.iter().map(|c| self.desc(reg, *c)).collect()),
366 Key::Adt(def, args) => Desc::Adt {
367 name: reg.table.defs()[*def as usize].name.clone(),
368 args: args.iter().map(|a| self.desc(reg, *a)).collect(),
369 },
370 }
371 }
372
373 /// See [`Registry::register`]. On an error, the caller truncates the
374 /// instances made: nothing was committed.
375 fn register(&mut self, reg: &Registry, ty: &Desc) -> Result<Registered, RegisterError> {
376 let root = self.intern(reg, ty, &[])?;
377 self.instantiate(reg)?;
378 if let Some(r) = self.registered(root) {
379 return Ok(r);
380 }
381 // The instances it reaches that no registration walked, and the
382 // types to register: it, and its subjects' message types.
383 let mut walk = vec![root];
384 let mut seen = HashSet::from([root]);
385 let mut new = vec![root];
386 let mut i = 0;
387 while let Some(&t) = walk.get(i) {
388 i += 1;
389 if let Key::Subject(m) = self.insts[t as usize].key
390 && self.insts[m as usize].entry == NONE
391 && !new.contains(&m)
392 {
393 new.push(m);
394 }
395 for c in self.children(t) {
396 if !self.insts[c as usize].closed && seen.insert(c) {
397 walk.push(c);
398 }
399 }
400 }
401 // Hash them all, and refuse a collision before committing any.
402 let mut batch: Vec<(u64, Ty, String)> = Vec::with_capacity(new.len());
403 for &t in &new {
404 let desc = self.desc(reg, t);
405 let canonical = reg.table.canonical(&desc).map_err(RegisterError::Desc)?;
406 let hash = (reg.hash)(canonical.as_bytes());
407 let known = self
408 .by_hash
409 .get(&hash)
410 .map(|&e| self.entries[e as usize].canonical.as_ref())
411 .or_else(|| batch.iter().find(|b| b.0 == hash).map(|b| b.2.as_str()));
412 if let Some(known) = known
413 && *known != canonical
414 {
415 return Err(RegisterError::Collision {
416 hash,
417 known: desc_line(known).to_owned(),
418 new: desc.to_string(),
419 });
420 }
421 batch.push((hash, t, canonical));
422 }
423 for (hash, t, canonical) in batch {
424 let index = self.entries.len() as u32;
425 self.entries.push(Entry {
426 ty: t,
427 hash,
428 canonical: canonical.into(),
429 });
430 self.by_hash.insert(hash, index);
431 self.insts[t as usize].entry = index;
432 }
433 for t in walk {
434 if let Key::Subject(m) = self.insts[t as usize].key {
435 self.insts[t as usize].wire = self.insts[m as usize].entry;
436 }
437 self.insts[t as usize].closed = true;
438 }
439 Ok(self.registered(root).expect("registered above"))
440 }
441
442 /// Forget the instances from `start` on (a failed registration's).
443 fn truncate(&mut self, start: usize) {
444 for inst in self.insts.drain(start..) {
445 self.by_key.remove(&inst.key);
446 }
447 self.pending.clear();
448 }
449}
450
451fn leaf_key(d: &Desc) -> Key {
452 match d {
453 Desc::Int => Key::Int,
454 Desc::Float => Key::Float,
455 Desc::String => Key::String,
456 Desc::Bytes => Key::Bytes,
457 Desc::U64 => Key::U64,
458 Desc::Dec => Key::Dec,
459 Desc::Pid => Key::Pid,
460 Desc::Unit => Key::Unit,
461 _ => unreachable!("not a leaf: {d}"),
462 }
463}
464
465/// The descriptor line of a canonical form.
466fn desc_line(canonical: &str) -> &str {
467 canonical.lines().nth(1).unwrap_or(canonical)
468}
469
470// ---- walks ----------------------------------------------------------------------
471
472/// A node whose children are being walked, the next one at `next`. The
473/// walk takes its last child after popping it (tail position), so the
474/// stack holds only nodes with a child left after the current one: the
475/// format's depth.
476struct Frame<'a> {
477 fields: *mut Value,
478 tys: Tys<'a>,
479 next: u32,
480 len: u32,
481 /// The decoder's number for it.
482 node: u64,
483}
484
485#[derive(Clone, Copy)]
486enum Tys<'a> {
487 /// A tuple's components, a constructor's fields.
488 Each(&'a [Ty]),
489 /// An array's elements.
490 All(Ty),
491}
492
493impl Frame<'_> {
494 fn at(&self, i: u32) -> (*mut Value, Ty) {
495 let ty = match self.tys {
496 Tys::Each(ts) => ts[i as usize],
497 Tys::All(t) => t,
498 };
499 (self.fields.wrapping_add(i as usize), ty)
500 }
501}
502
503/// What a walk does after a node: its first child, after pushing it if it
504/// has more, or the next child of the nearest node that has one left.
505fn next_child<'a>(
506 stack: &mut Vec<Frame<'a>>,
507 children: Option<Frame<'a>>,
508) -> Result<Option<(*mut Value, Ty)>, &'static str> {
509 if let Some(mut f) = children.filter(|f| f.len > 0) {
510 let first = f.at(0);
511 if f.len > 1 {
512 if stack.len() >= MAX_VALUE_DEPTH as usize {
513 return Err("value nested too deeply");
514 }
515 f.next = 1;
516 stack.push(f);
517 }
518 return Ok(Some(first));
519 }
520 let Some(f) = stack.last_mut() else {
521 return Ok(None);
522 };
523 let child = f.at(f.next);
524 f.next += 1;
525 if f.next == f.len {
526 stack.pop();
527 }
528 Ok(Some(child))
529}
530
531// ---- encoding -----------------------------------------------------------------------
532
533/// Why a value cannot be encoded: a bug in the sending program, which the
534/// caller turns into a panic in the sender (ADR 0072, *Settled*).
535#[derive(Debug, PartialEq, Eq)]
536pub(crate) enum EncodeError {
537 /// No type is registered at this index.
538 UnknownType(u32),
539 /// The payload would pass [`MAX_PAYLOAD`].
540 TooLarge,
541 /// The value is nested past [`MAX_VALUE_DEPTH`].
542 TooDeep,
543 /// A local pid at or past 2^46 cannot be named on another node.
544 PidSerial(i64),
545 /// A subject's tag is not in `0 .. 2^62`.
546 Tag(i64),
547 /// The value is not represented as its type is: a compiler or runtime
548 /// bug.
549 Malformed(&'static str),
550}
551
552impl fmt::Display for EncodeError {
553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554 match self {
555 EncodeError::UnknownType(i) => write!(f, "no wire type registered at {i}"),
556 EncodeError::TooLarge => write!(f, "message larger than {MAX_PAYLOAD} bytes"),
557 EncodeError::TooDeep => write!(f, "message nested deeper than {MAX_VALUE_DEPTH}"),
558 EncodeError::PidSerial(p) => write!(f, "pid {p} cannot be named on another node"),
559 EncodeError::Tag(t) => write!(f, "subject tag {t} out of range"),
560 EncodeError::Malformed(what) => write!(f, "malformed message: {what}"),
561 }
562 }
563}
564
565/// A block at a type: the encoder's sharing key, hashed as two words.
566#[derive(PartialEq, Eq)]
567struct Seen(usize, Ty);
568
569impl std::hash::Hash for Seen {
570 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
571 state.write_usize(self.0);
572 state.write_u64(u64::from(self.1));
573 }
574}
575
576/// The key of this node in a frame's node list.
577const ME: u32 = u32::MAX;
578
579struct Encoder<'a> {
580 types: &'a Types,
581 out: Vec<u8>,
582 /// The number of the next node.
583 count: u64,
584 /// The nodes of blocks that may be reached again (not unique), by
585 /// (block, type).
586 shared: HashMap<Seen, u64, BuildHasherDefault<IdHasher>>,
587 me: &'a Node,
588 nodes: &'a RwLock<Nodes>,
589 /// The frame's node list: its entries' bytes, and which node each one
590 /// is (a node-table index, or [`ME`]).
591 list: Vec<u8>,
592 listed: Vec<u32>,
593}
594
595/// The payload of a message of the type registered at `wire`: the
596/// frame's node list, then `value` (`docs/wire-format.md`, *Value
597/// encoding*, *Frames*). Local pids are named as `me`'s, remote ones by
598/// their entry in `nodes`. On the sender's thread; an error is the
599/// sender's panic.
600///
601/// # Safety
602/// `value` must be live (borrowed), a value of that type.
603pub(crate) unsafe fn encode(
604 registry: &Registry,
605 wire: u32,
606 value: Value,
607 me: &Node,
608 nodes: &RwLock<Nodes>,
609) -> Result<Vec<u8>, EncodeError> {
610 let types = registry.read();
611 let Some(entry) = types.entries.get(wire as usize) else {
612 return Err(EncodeError::UnknownType(wire));
613 };
614 let mut e = Encoder {
615 types: &types,
616 out: Vec::with_capacity(256),
617 count: 0,
618 shared: HashMap::default(),
619 me,
620 nodes,
621 list: Vec::new(),
622 listed: Vec::new(),
623 };
624 let mut stack = Vec::new();
625 let mut root = value;
626 let mut next = Some((&raw mut root, entry.ty));
627 while let Some((slot, t)) = next {
628 // SAFETY: `slot` is the root or a field of a live block of the
629 // value (caller guarantee), of type `t`.
630 let children = unsafe { e.value(*slot, t)? };
631 if e.out.len() > MAX_PAYLOAD as usize {
632 return Err(EncodeError::TooLarge);
633 }
634 next = next_child(&mut stack, children).map_err(|_| EncodeError::TooDeep)?;
635 }
636 let mut payload = Vec::with_capacity(10 + e.list.len() + e.out.len());
637 write_uvarint(&mut payload, e.listed.len() as u64);
638 payload.extend_from_slice(&e.list);
639 payload.extend_from_slice(&e.out);
640 if payload.len() > MAX_PAYLOAD as usize {
641 return Err(EncodeError::TooLarge);
642 }
643 Ok(payload)
644}
645
646impl<'a> Encoder<'a> {
647 /// Write `v`, of type `t`, up to its children: those to write next.
648 ///
649 /// # Safety
650 /// `v` must be live, of type `t`.
651 unsafe fn value(&mut self, v: Value, t: Ty) -> Result<Option<Frame<'a>>, EncodeError> {
652 let types = self.types;
653 let inst = &types.insts[t as usize];
654 let b = v as *mut Block;
655 // A block's tag and number of scanned fields; (0, 0) for an
656 // immediate, which no arm below reads as a block.
657 let (tag, scan) = if is_ptr(v) {
658 // SAFETY: a pointer value is a live block (caller guarantee).
659 unsafe { ((*b).header.tag, (*b).header.scan_fsize) }
660 } else {
661 (0, 0)
662 };
663 let kind = |runtime_tag: u16| is_ptr(v) && tag == runtime_tag;
664 let malformed = |what| Err(EncodeError::Malformed(what));
665 match &inst.key {
666 Key::Unit => self.out.push(0),
667 Key::Int if !is_ptr(v) => write_small_int(&mut self.out, int_get(v)),
668 Key::Int if kind(TAG_BIGINT) => {
669 if !self.seen(b, t) {
670 // SAFETY: a live big integer.
671 let n = unsafe { crate::int::to_big(v) };
672 write_int(&mut self.out, &n);
673 }
674 }
675 Key::Float if kind(TAG_FLOAT) => {
676 // SAFETY: a live Float.
677 write_float(&mut self.out, unsafe { crate::prims::tl_float_get(v) });
678 }
679 Key::U64 if kind(TAG_U64) => {
680 // SAFETY: a live U64.
681 write_uvarint(&mut self.out, unsafe { crate::u64::get(v) });
682 }
683 Key::Dec if kind(TAG_DEC) => {
684 // SAFETY: a live Dec.
685 write_uvarint128(&mut self.out, zigzag(unsafe { crate::dec::get(v) }));
686 }
687 Key::Pid if !is_ptr(v) => self.pid(int_get(v))?,
688 Key::String if kind(TAG_STRING) => self.bytes(b, t)?,
689 Key::Bytes if kind(TAG_BYTES) => self.bytes(b, t)?,
690 Key::Array(elem) if kind(TAG_ARRAY) => {
691 if self.seen(b, t) {
692 return Ok(None);
693 }
694 // SAFETY: a live array: its count, then its elements.
695 let (fields, len) = unsafe { crate::heap::scanned_fields(b) };
696 // Each element takes a byte at least; and a frame counts
697 // its children in a `u32`.
698 if len > MAX_PAYLOAD as usize {
699 return Err(EncodeError::TooLarge);
700 }
701 write_head(&mut self.out, Head::New(len as u64));
702 return Ok(Some(frame(fields, Tys::All(*elem), len)));
703 }
704 Key::Tuple(cs) if is_ptr(v) => {
705 if tag != 0 || usize::from(scan) != cs.len() {
706 return malformed("a tuple of another arity");
707 }
708 if self.seen(b, t) {
709 return Ok(None);
710 }
711 write_head(&mut self.out, Head::New(0));
712 return Ok(Some(frame(Block::fields_ptr(b), Tys::Each(cs), cs.len())));
713 }
714 Key::Subject(_) if is_ptr(v) => {
715 if !matches!((tag, scan), (0, 2) | (1, 3)) {
716 return malformed("a subject of another shape");
717 }
718 if self.seen(b, t) {
719 return Ok(None);
720 }
721 // SAFETY: a subject block has its owner and tag first.
722 let (owner, tag) = unsafe {
723 let f = Block::fields_ptr(b);
724 (*f, *f.add(1))
725 };
726 if is_ptr(owner) || is_ptr(tag) {
727 return malformed("a subject's owner or tag is not an Int");
728 }
729 write_head(&mut self.out, Head::New(0));
730 self.pid(int_get(owner))?;
731 let tag = int_get(tag);
732 if !(0..MAX_TAG as i64).contains(&tag) {
733 return Err(EncodeError::Tag(tag));
734 }
735 write_uvarint(&mut self.out, tag as u64);
736 }
737 Key::Adt(..) if !is_ptr(v) => {
738 let c = int_get(v);
739 let nullary = usize::try_from(c)
740 .ok()
741 .and_then(|c| inst.ctors.get(c))
742 .is_some_and(|fields| fields.is_empty());
743 if !nullary {
744 return malformed("not a nullary constructor of its type");
745 }
746 write_head(&mut self.out, Head::New(c as u64));
747 }
748 Key::Adt(..) => {
749 let fields = inst.ctors.get(usize::from(tag));
750 let Some(fields) = fields.filter(|f| {
751 !f.is_empty() && scan != SCAN_LARGE && usize::from(scan) == f.len()
752 }) else {
753 return malformed("not a constructor of its type");
754 };
755 if self.seen(b, t) {
756 return Ok(None);
757 }
758 write_head(&mut self.out, Head::New(u64::from(tag)));
759 return Ok(Some(frame(
760 Block::fields_ptr(b),
761 Tys::Each(fields),
762 fields.len(),
763 )));
764 }
765 _ => return malformed("a value of another kind than its type"),
766 }
767 Ok(None)
768 }
769
770 /// Whether `b` was written at type `t` already: then a back-reference
771 /// to it is written. Otherwise `b` is a new node. A unique block is
772 /// reached once: it is not recorded.
773 fn seen(&mut self, b: *mut Block, t: Ty) -> bool {
774 let n = self.count;
775 // SAFETY: `b` is live (the caller's guarantee). A shared block's
776 // count (negative) changes on other threads meanwhile: read
777 // atomically, though no change makes it 1.
778 let rc = unsafe { AtomicI32::from_ptr(&raw mut (*b).header.rc) };
779 if rc.load(Ordering::Relaxed) != 1 {
780 if let Some(&back) = self.shared.get(&Seen(b as usize, t)) {
781 write_head(&mut self.out, Head::Back(back));
782 return true;
783 }
784 self.shared.insert(Seen(b as usize, t), n);
785 }
786 self.count += 1;
787 false
788 }
789
790 /// A `String` or `Bytes` (same layout up to the NUL). One past the
791 /// payload's limit is refused before it is copied.
792 fn bytes(&mut self, b: *mut Block, t: Ty) -> Result<(), EncodeError> {
793 if self.seen(b, t) {
794 return Ok(());
795 }
796 // SAFETY: `b` is a live string or byte string.
797 let bytes = unsafe { crate::values::bytes_of(b as Value) };
798 if self.out.len() + bytes.len() > MAX_PAYLOAD as usize {
799 return Err(EncodeError::TooLarge);
800 }
801 write_head(&mut self.out, Head::New(bytes.len() as u64));
802 self.out.extend_from_slice(bytes);
803 Ok(())
804 }
805
806 /// A pid: its node's entry in the frame's list, then its serial.
807 fn pid(&mut self, pid: i64) -> Result<(), EncodeError> {
808 let (node, serial) = if is_remote(pid) {
809 let (node, serial) = parts(pid);
810 (u32::from(node), serial as u64)
811 } else if (pid as u64) < MAX_PID_SERIAL {
812 (ME, pid as u64)
813 } else {
814 return Err(EncodeError::PidSerial(pid));
815 };
816 let entry = match self.listed.iter().position(|n| *n == node) {
817 Some(i) => i,
818 None => self.list_node(node)?,
819 };
820 write_uvarint(&mut self.out, entry as u64);
821 write_uvarint(&mut self.out, serial);
822 Ok(())
823 }
824
825 /// Add `node` to the frame's node list; its entry.
826 fn list_node(&mut self, node: u32) -> Result<usize, EncodeError> {
827 let mut write = |name: &str, incarnation: u64| {
828 write_uvarint(&mut self.list, name.len() as u64);
829 self.list.extend_from_slice(name.as_bytes());
830 self.list.extend_from_slice(&incarnation.to_le_bytes());
831 };
832 if node == ME {
833 write(&self.me.name, self.me.incarnation);
834 } else {
835 let nodes = self.nodes.read().unwrap_or_else(PoisonError::into_inner);
836 let Some(n) = nodes.get(node as u16) else {
837 return Err(EncodeError::Malformed("a remote pid of no known node"));
838 };
839 write(&n.name, n.incarnation);
840 }
841 self.listed.push(node);
842 Ok(self.listed.len() - 1)
843 }
844}
845
846fn frame(fields: *mut Value, tys: Tys<'_>, len: usize) -> Frame<'_> {
847 Frame {
848 fields,
849 tys,
850 next: 0,
851 len: len as u32,
852 node: 0,
853 }
854}
855
856// ---- decoding -------------------------------------------------------------------------
857
858/// Why a frame's payload is refused: the frame is dropped and counted
859/// (ADR 0072).
860#[derive(Debug, PartialEq, Eq)]
861pub(crate) enum DecodeError {
862 /// No type is registered under the frame's hash.
863 UnknownType(u64),
864 /// The payload is malformed (`docs/wire-format.md`, *Validation*).
865 Malformed(WireError),
866 /// The frame names more new nodes than its peer may still add.
867 PeerNodes,
868 /// The node table is full (2^16 entries).
869 NodesFull,
870}
871
872impl From<WireError> for DecodeError {
873 fn from(e: WireError) -> Self {
874 DecodeError::Malformed(e)
875 }
876}
877
878impl fmt::Display for DecodeError {
879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880 match self {
881 DecodeError::UnknownType(h) => write!(f, "no wire type has the hash {h:016x}"),
882 DecodeError::Malformed(e) => write!(f, "{e}"),
883 DecodeError::PeerNodes => write!(f, "the peer names too many new nodes"),
884 DecodeError::NodesFull => write!(f, "the node table is full"),
885 }
886 }
887}
888
889/// Whose pids a node list entry names.
890#[derive(Clone, Copy)]
891enum Owner {
892 Local,
893 Remote(u16),
894}
895
896struct Decoded {
897 /// Owned by the value being built.
898 value: Value,
899 ty: Ty,
900 /// Not an ancestor of what is being read.
901 complete: bool,
902}
903
904struct Decoder<'a> {
905 types: &'a Types,
906 r: Reader<'a>,
907 owners: Vec<Owner>,
908 /// Every node read, by number.
909 nodes: Vec<Decoded>,
910 /// The nodes not complete, by number (increasing): the ancestors of
911 /// what is being read.
912 open: Vec<u64>,
913 /// A local subject no payload may name ([`decode`]).
914 reserved: Option<(i64, i64)>,
915}
916
917/// The value of a payload framed with `type_hash` (the frame's node list,
918/// then the value), owned, made outside any actor: what
919/// `dist::inbound::deliver` hands over. Every check of
920/// `docs/wire-format.md`'s *Validation* is made before allocating for the
921/// part at fault; on an error nothing is left allocated.
922///
923/// The node list's entries that name `me` make local pids; the others
924/// are entered in `nodes`. `peer_nodes` is how many new entries the
925/// sending peer may still add (start it at [`PEER_NODES`]); a frame
926/// naming more is refused before adding any, and those it adds are
927/// counted down, whether the value decodes or not.
928///
929/// `reserved` is a local subject (owner, tag) that no payload may name,
930/// the node's spawner's: only the node itself hands it a value (ADR 0072,
931/// *Spawning*). A subject naming it is malformed.
932pub(crate) fn decode(
933 registry: &Registry,
934 type_hash: u64,
935 payload: &[u8],
936 me: &Node,
937 nodes: &RwLock<Nodes>,
938 peer_nodes: &mut u32,
939 reserved: Option<(i64, i64)>,
940) -> Result<Value, DecodeError> {
941 let types = registry.read();
942 let Some(&index) = types.by_hash.get(&type_hash) else {
943 return Err(DecodeError::UnknownType(type_hash));
944 };
945 if payload.len() > MAX_PAYLOAD as usize {
946 return Err(WireError {
947 at: 0,
948 what: "payload too large",
949 }
950 .into());
951 }
952 let mut r = Reader::new(payload);
953 let owners = node_list(&mut r, me, nodes, peer_nodes)?;
954 let mut d = Decoder {
955 types: &types,
956 r,
957 owners,
958 nodes: Vec::new(),
959 open: Vec::new(),
960 reserved,
961 };
962 let mut root = UNIT;
963 // SAFETY: `root` is owned here, and holds every block the decoder
964 // makes; released whole on an error.
965 match unsafe { d.run(&raw mut root, types.entries[index as usize].ty) } {
966 Ok(()) => Ok(root),
967 Err(e) => {
968 // SAFETY: `root` is owned and well formed (unfilled fields are
969 // unit).
970 unsafe { crate::heap::drop_detached(root) };
971 Err(e.into())
972 }
973 }
974}
975
976/// The frame's node list (`docs/wire-format.md`, *Frames*): each entry's
977/// owner, new entries entered in `nodes`.
978fn node_list(
979 r: &mut Reader<'_>,
980 me: &Node,
981 nodes: &RwLock<Nodes>,
982 peer_nodes: &mut u32,
983) -> Result<Vec<Owner>, DecodeError> {
984 let fail = |r: &Reader<'_>, what| Err(DecodeError::Malformed(WireError { at: r.at(), what }));
985 let count = r.uvarint()?;
986 // An entry takes at least 10 bytes; distinct entries name this node
987 // or one of the node table's.
988 if count > (r.left() / 10) as u64 {
989 return fail(r, "count past the end of the payload");
990 }
991 if count > MAX_NODES as u64 + 1 {
992 return fail(r, "too many node list entries");
993 }
994 let mut entries: Vec<(&str, u64)> = Vec::with_capacity(count as usize);
995 let mut distinct = HashSet::with_capacity(count as usize);
996 for _ in 0..count {
997 let len = r.uvarint()?;
998 if len > MAX_NODE_NAME as u64 {
999 return fail(r, "node name too long");
1000 }
1001 let name = r.take(len)?;
1002 if !check_node_name(name) {
1003 return fail(r, "bad node name");
1004 }
1005 let name = std::str::from_utf8(name).expect("node names are ASCII");
1006 let incarnation = r.u64_le()?;
1007 if !distinct.insert((name, incarnation)) {
1008 return fail(r, "node list entry repeated");
1009 }
1010 entries.push((name, incarnation));
1011 }
1012 let is_me = |(name, incarnation): (&str, u64)| name == me.name && incarnation == me.incarnation;
1013 let mut owners = Vec::with_capacity(entries.len());
1014 let mut missing = false;
1015 {
1016 let table = nodes.read().unwrap_or_else(PoisonError::into_inner);
1017 for &e in &entries {
1018 owners.push(match table.find(e.0, e.1) {
1019 _ if is_me(e) => Owner::Local,
1020 Some(i) => Owner::Remote(i),
1021 None => {
1022 missing = true;
1023 Owner::Local
1024 }
1025 });
1026 }
1027 }
1028 if missing {
1029 let mut table = nodes.write().unwrap_or_else(PoisonError::into_inner);
1030 let new = entries
1031 .iter()
1032 .filter(|&&e| !is_me(e) && table.find(e.0, e.1).is_none())
1033 .count();
1034 if new > *peer_nodes as usize {
1035 return Err(DecodeError::PeerNodes);
1036 }
1037 for (owner, &e) in owners.iter_mut().zip(&entries) {
1038 if is_me(e) {
1039 continue;
1040 }
1041 let known = table.find(e.0, e.1);
1042 let index = known.or_else(|| table.index(e.0, e.1));
1043 *owner = Owner::Remote(index.ok_or(DecodeError::NodesFull)?);
1044 if known.is_none() {
1045 *peer_nodes -= 1;
1046 }
1047 }
1048 }
1049 Ok(owners)
1050}
1051
1052impl<'a> Decoder<'a> {
1053 fn fail<T>(&self, what: &'static str) -> Result<T, WireError> {
1054 Err(WireError {
1055 at: self.r.at(),
1056 what,
1057 })
1058 }
1059
1060 /// Read the value of type `t` into `root`.
1061 ///
1062 /// # Safety
1063 /// `root` must be owned by the caller; on an error, it holds what was
1064 /// read, well formed.
1065 unsafe fn run(&mut self, root: *mut Value, t: Ty) -> Result<(), WireError> {
1066 let mut stack: Vec<Frame<'a>> = Vec::new();
1067 let mut next = Some((root, t));
1068 while let Some((slot, t)) = next {
1069 // SAFETY: `slot` is `root` or an unfilled field of a block it
1070 // holds.
1071 let children = unsafe { self.value(slot, t)? };
1072 if children.is_none() || children.as_ref().is_some_and(|f| f.len == 0) {
1073 // Back to the nearest node with a child left: every node
1074 // read after it is complete.
1075 if let Some(top) = stack.last() {
1076 while self.open.last().is_some_and(|&n| n > top.node) {
1077 let n = self.open.pop().expect("open");
1078 self.nodes[n as usize].complete = true;
1079 }
1080 }
1081 }
1082 next = next_child(&mut stack, children).or_else(|what| self.fail(what))?;
1083 }
1084 if !self.r.is_empty() {
1085 return self.fail("bytes left after the value");
1086 }
1087 Ok(())
1088 }
1089
1090 /// A new node: its number.
1091 fn node(&mut self, value: Value, ty: Ty, children: bool) -> u64 {
1092 let n = self.nodes.len() as u64;
1093 self.nodes.push(Decoded {
1094 value,
1095 ty,
1096 complete: !children,
1097 });
1098 if children {
1099 self.open.push(n);
1100 }
1101 n
1102 }
1103
1104 /// A back-reference to node `n`, at type `t`.
1105 fn back(&self, n: u64, t: Ty) -> Result<Value, WireError> {
1106 match self.nodes.get(n as usize) {
1107 None => self.fail("back-reference to a node not read yet"),
1108 Some(d) if d.ty != t => self.fail("back-reference to a node of another type"),
1109 Some(d) if !d.complete => self.fail("back-reference to an enclosing node"),
1110 // SAFETY: a node's value is live: the value being built holds
1111 // it.
1112 Some(d) => Ok(unsafe { crate::heap::dup_value(d.value) }),
1113 }
1114 }
1115
1116 /// A pid: its node's entry in the frame's list, then its serial.
1117 fn pid(&mut self) -> Result<(i64, bool), WireError> {
1118 let entry = self.r.uvarint()?;
1119 let Some(&owner) = self.owners.get(entry as usize) else {
1120 return self.fail("pid of no node list entry");
1121 };
1122 let serial = self.r.uvarint()?;
1123 if serial >= MAX_PID_SERIAL {
1124 return self.fail("pid serial out of range");
1125 }
1126 Ok(match owner {
1127 Owner::Local => (serial as i64, true),
1128 Owner::Remote(node) => (remote(node, serial as i64).expect("serial in range"), false),
1129 })
1130 }
1131
1132 /// Read a value of type `t` into `slot`, up to its children: those to
1133 /// read next, into its fields.
1134 ///
1135 /// # Safety
1136 /// `slot` must be an unfilled (unit) slot of the value being built.
1137 unsafe fn value(&mut self, slot: *mut Value, t: Ty) -> Result<Option<Frame<'a>>, WireError> {
1138 let types = self.types;
1139 let inst = &types.insts[t as usize];
1140 let null = std::ptr::null_mut();
1141 let v = match &inst.key {
1142 Key::Unit => match self.r.byte()? {
1143 0 => UNIT,
1144 _ => return self.fail("unit is not 00"),
1145 },
1146 Key::Int => match self.r.int()? {
1147 IntHead::Small(n) => int(n),
1148 IntHead::Big(n) => {
1149 let v = crate::int::from_big(null, &n);
1150 self.node(v, t, false);
1151 v
1152 }
1153 IntHead::Back(n) => self.back(n, t)?,
1154 },
1155 Key::Float => crate::prims::tl_float_from(null, self.r.float()?),
1156 Key::U64 => crate::u64::u64_value(null, self.r.uvarint()?),
1157 Key::Dec => crate::dec::dec_value(null, self.r.dec()?),
1158 Key::Pid => int(self.pid()?.0),
1159 Key::String | Key::Bytes => match self.r.head()? {
1160 Head::Back(n) => self.back(n, t)?,
1161 Head::New(len) => {
1162 let bytes = self.r.take(len)?;
1163 let (v, raw) = if inst.key == Key::String {
1164 if std::str::from_utf8(bytes).is_err() {
1165 return self.fail("string not UTF-8");
1166 }
1167 crate::values::string_uninit(null, bytes.len())
1168 } else {
1169 crate::values::bytes_uninit(null, bytes.len())
1170 };
1171 // SAFETY: `raw` has room for `bytes.len()` bytes.
1172 unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), raw, bytes.len()) };
1173 self.node(v, t, false);
1174 v
1175 }
1176 },
1177 Key::Subject(_) => match self.r.head()? {
1178 Head::Back(n) => self.back(n, t)?,
1179 Head::New(0) => {
1180 let (owner, local) = self.pid()?;
1181 let tag = self.r.uvarint()?;
1182 if tag >= MAX_TAG {
1183 return self.fail("subject tag out of range");
1184 }
1185 if local && self.reserved == Some((owner, tag as i64)) {
1186 return self.fail("subject of the node's spawner");
1187 }
1188 // A local owner's subject is a `Subject`, never a
1189 // `Remote` (`dist`).
1190 let v = if local {
1191 crate::values::cell(null, 0, &[int(owner), int(tag as i64)])
1192 } else {
1193 debug_assert_ne!(inst.wire, NONE, "registered with its type");
1194 let wire = i64::from(inst.wire);
1195 crate::values::cell(null, 1, &[int(owner), int(tag as i64), int(wire)])
1196 };
1197 self.node(v, t, false);
1198 v
1199 }
1200 Head::New(_) => return self.fail("subject head not 0"),
1201 },
1202 Key::Array(elem) => match self.r.head()? {
1203 Head::Back(n) => self.back(n, t)?,
1204 Head::New(len) => {
1205 // Each element takes a byte at least.
1206 if len > self.r.left() as u64 {
1207 return self.fail("count past the end of the payload");
1208 }
1209 let len = len as usize;
1210 let v = crate::array::alloc(null, len, len) as Value;
1211 // SAFETY: as every store below: `slot` is unfilled.
1212 unsafe { *slot = v };
1213 let node = self.node(v, t, len > 0);
1214 let elems = crate::array::elems(v);
1215 return Ok(Some(Frame {
1216 node,
1217 ..frame(elems, Tys::All(*elem), len)
1218 }));
1219 }
1220 },
1221 Key::Tuple(cs) => match self.r.head()? {
1222 Head::Back(n) => self.back(n, t)?,
1223 // SAFETY: `slot` is unfilled (caller guarantee).
1224 Head::New(0) => return unsafe { self.block(slot, t, 0, cs) }.map(Some),
1225 Head::New(_) => return self.fail("tuple head not 0"),
1226 },
1227 Key::Adt(..) => match self.r.head()? {
1228 Head::Back(n) => self.back(n, t)?,
1229 Head::New(c) => {
1230 let Some(fields) = inst.ctors.get(c as usize) else {
1231 return self.fail("constructor out of range");
1232 };
1233 if fields.is_empty() {
1234 int(c as i64)
1235 } else {
1236 // SAFETY: `slot` is unfilled (caller guarantee).
1237 return unsafe { self.block(slot, t, c as u16, fields) }.map(Some);
1238 }
1239 }
1240 },
1241 };
1242 // SAFETY: `slot` is unfilled (caller guarantee).
1243 unsafe { *slot = v };
1244 Ok(None)
1245 }
1246
1247 /// A tuple or constructor block of `fields`, stored in `slot`, its
1248 /// fields to read next. Each takes a byte at least: checked first.
1249 ///
1250 /// # Safety
1251 /// `slot` must be an unfilled slot of the value being built.
1252 unsafe fn block(
1253 &mut self,
1254 slot: *mut Value,
1255 t: Ty,
1256 tag: u16,
1257 fields: &'a [Ty],
1258 ) -> Result<Frame<'a>, WireError> {
1259 if fields.len() > self.r.left() {
1260 return self.fail("fields past the end of the payload");
1261 }
1262 let b = crate::heap::tl_alloc(std::ptr::null_mut(), tag, fields.len() as u8, 0);
1263 // SAFETY: forwarded caller guarantee.
1264 unsafe { *slot = b as Value };
1265 let node = self.node(b as Value, t, true);
1266 Ok(Frame {
1267 node,
1268 ..frame(Block::fields_ptr(b), Tys::Each(fields), fields.len())
1269 })
1270 }
1271}
1272
1273#[cfg(test)]
1274mod tests;