//! The signal frames of links, unlinks, monitors and exit signals across //! nodes (`docs/wire-format.md`, *Signals*): their bytes only. `node.rs` //! sends them from the hooks and applies what arrives through //! `dist::inbound`. //! //! Every one names a pid of each node of the connection, by serial: the //! sender's first, then the receiver's. An exit reason is //! `std/process.ExitReason`'s constructor in one byte, and a crash's text. use louise_rt_prims::wire::{MAX_PID_SERIAL, MAX_TAG}; use crate::sched::Exit; /// The ops of [`Tie`] frames: the signal ops `0x10` to `0x1f` are theirs. pub(super) const LINK: u8 = 0x10; pub(super) const EXIT: u8 = 0x11; pub(super) const MONITOR: u8 = 0x12; pub(super) const DOWN: u8 = 0x13; pub(super) const KILL: u8 = 0x14; pub(super) const STOP: u8 = 0x15; pub(super) const DEMONITOR: u8 = 0x16; pub(super) const UNLINK: u8 = 0x17; pub(super) const UNLINK_ACK: u8 = 0x18; /// Whether a signal frame's op is a [`Tie`]'s. pub(super) fn is_tie(op: u8) -> bool { (LINK..=0x1f).contains(&op) } /// The longest crash text a frame carries, in bytes: a longer one is cut /// at a character boundary, so every tie frame fits the smallest frame /// limit a node may announce (1 KiB). pub(super) const MAX_REASON: usize = 960; /// What a [`Tie`] frame asks of its receiver. #[derive(Clone, Debug, PartialEq)] pub(super) enum Op { /// `from` linked to `to`. Link, /// `from`, linked to `to`, exited. Exit(Exit), /// `from` monitors `to`; its `Down` is due on `tag`. Monitor { tag: u64, }, /// `from`, monitored by `to` on `tag`, exited. Down { tag: u64, reason: Exit, }, Kill, Stop, /// `from` no longer monitors `to` on `tag`. Demonitor { tag: u64, }, /// `from` unlinks `to`, as its unlink `id` (any value: the receiver /// only echoes it). Unlink { id: u64, }, /// `from` removed its half of the link that `to` unlinked as `id`, or /// had none. UnlinkAck { id: u64, }, } /// A link, monitor or exit signal frame: from the sender's actor `from` to /// the receiver's actor `to` (serials below 2^46). #[derive(Clone, Debug, PartialEq)] pub(super) struct Tie { pub(super) from: u64, pub(super) to: u64, pub(super) op: Op, } impl Tie { /// The frame's body: its op, then its fields. pub(super) fn encode(&self) -> Vec { let mut out = Vec::with_capacity(25); out.push(match self.op { Op::Link => LINK, Op::Exit(_) => EXIT, Op::Monitor { .. } => MONITOR, Op::Down { .. } => DOWN, Op::Kill => KILL, Op::Stop => STOP, Op::Demonitor { .. } => DEMONITOR, Op::Unlink { .. } => UNLINK, Op::UnlinkAck { .. } => UNLINK_ACK, }); out.extend_from_slice(&self.from.to_le_bytes()); out.extend_from_slice(&self.to.to_le_bytes()); match &self.op { Op::Link | Op::Kill | Op::Stop => {} Op::Exit(reason) => encode_reason(&mut out, reason), Op::Monitor { tag } | Op::Demonitor { tag } => { out.extend_from_slice(&tag.to_le_bytes()) } Op::Unlink { id } | Op::UnlinkAck { id } => out.extend_from_slice(&id.to_le_bytes()), Op::Down { tag, reason } => { out.extend_from_slice(&tag.to_le_bytes()); encode_reason(&mut out, reason); } } out } /// Op `op`'s frame from `body`, the bytes after the op: `None` if it is /// malformed, of another length, or out of range. pub(super) fn decode(op: u8, body: &[u8]) -> Option { let (from, rest) = word(body)?; let (to, rest) = word(rest)?; if from >= MAX_PID_SERIAL || to >= MAX_PID_SERIAL { return None; } let op = match op { LINK if rest.is_empty() => Op::Link, KILL if rest.is_empty() => Op::Kill, STOP if rest.is_empty() => Op::Stop, EXIT => Op::Exit(decode_reason(rest)?), MONITOR => Op::Monitor { tag: only_tag(rest)?, }, DEMONITOR => Op::Demonitor { tag: only_tag(rest)?, }, UNLINK => Op::Unlink { id: only_word(rest)?, }, UNLINK_ACK => Op::UnlinkAck { id: only_word(rest)?, }, DOWN => { let (tag, rest) = tag(rest)?; Op::Down { tag, reason: decode_reason(rest)?, } } _ => return None, }; Some(Tie { from, to, op }) } } /// A little-endian `u64`, and the bytes after it. fn word(bytes: &[u8]) -> Option<(u64, &[u8])> { let (w, rest) = bytes.split_first_chunk::<8>()?; Some((u64::from_le_bytes(*w), rest)) } /// A subject's tag (below 2^62), and the bytes after it. fn tag(bytes: &[u8]) -> Option<(u64, &[u8])> { word(bytes).filter(|(t, _)| *t < MAX_TAG) } /// A tag that is all of `bytes`. fn only_tag(bytes: &[u8]) -> Option { match tag(bytes)? { (tag, []) => Some(tag), _ => None, } } /// A `u64` that is all of `bytes`. fn only_word(bytes: &[u8]) -> Option { match word(bytes)? { (w, []) => Some(w), _ => None, } } /// `reason = kind (1) [, len (2), text]`: `Crashed` only has the text. fn encode_reason(out: &mut Vec, reason: &Exit) { match reason { Exit::Normal => out.push(0), Exit::Killed => out.push(1), Exit::Shutdown => out.push(3), Exit::Crashed(text) => { let mut end = text.len().min(MAX_REASON); while !text.is_char_boundary(end) { end -= 1; } out.push(2); out.extend_from_slice(&(end as u16).to_le_bytes()); out.extend_from_slice(&text.as_bytes()[..end]); } } } /// A reason that is all of `bytes`. fn decode_reason(bytes: &[u8]) -> Option { match bytes { [0] => Some(Exit::Normal), [1] => Some(Exit::Killed), [3] => Some(Exit::Shutdown), [2, l0, l1, text @ ..] if usize::from(u16::from_le_bytes([*l0, *l1])) == text.len() => { std::str::from_utf8(text) .ok() .map(|t| Exit::Crashed(t.to_owned())) } _ => None, } } #[cfg(test)] mod tests { use super::*; /// `docs/wire-format.md`'s example: actor 7, linked to actor 12 of the /// receiving node, crashed with "boom". #[test] fn an_exit_is_the_documented_bytes() { let exit = Tie { from: 7, to: 12, op: Op::Exit(Exit::Crashed("boom".into())), }; let bytes = exit.encode(); assert_eq!( bytes, [ &[0x11][..], &[7, 0, 0, 0, 0, 0, 0, 0], &[12, 0, 0, 0, 0, 0, 0, 0], &[2, 4, 0], b"boom", ] .concat() ); assert_eq!(Tie::decode(bytes[0], &bytes[1..]), Some(exit)); } /// `docs/wire-format.md`'s example: actor 7 unlinks actor 12 of the /// receiving node as its unlink 1, which that node acknowledges. #[test] fn an_unlink_and_its_acknowledgement_are_the_documented_bytes() { let unlink = Tie { from: 7, to: 12, op: Op::Unlink { id: 1 }, }; let ack = Tie { from: 12, to: 7, op: Op::UnlinkAck { id: 1 }, }; let (seven, twelve, one) = ( [7, 0, 0, 0, 0, 0, 0, 0], [12, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], ); assert_eq!( unlink.encode(), [&[0x17][..], &seven, &twelve, &one].concat() ); assert_eq!(ack.encode(), [&[0x18][..], &twelve, &seven, &one].concat()); for tie in [unlink, ack] { let bytes = tie.encode(); assert_eq!(Tie::decode(bytes[0], &bytes[1..]), Some(tie)); } } #[test] fn every_frame_round_trips() { let reasons = [ Exit::Normal, Exit::Killed, Exit::Shutdown, Exit::Crashed(String::new()), Exit::Crashed("café".into()), ]; let mut ops = vec![ Op::Link, Op::Kill, Op::Stop, Op::Monitor { tag: 40 }, Op::Demonitor { tag: 40 }, Op::Unlink { id: 1 }, Op::Unlink { id: u64::MAX }, Op::UnlinkAck { id: 0 }, Op::UnlinkAck { id: u64::MAX }, ]; for reason in reasons { ops.push(Op::Exit(reason.clone())); ops.push(Op::Down { tag: 3, reason }); } for op in ops { let tie = Tie { from: MAX_PID_SERIAL - 1, to: 0, op, }; let bytes = tie.encode(); assert!(is_tie(bytes[0])); assert_eq!(Tie::decode(bytes[0], &bytes[1..]).as_ref(), Some(&tie)); // A byte more or less is another length: refused. assert_eq!(Tie::decode(bytes[0], &bytes[1..bytes.len() - 1]), None); let mut longer = bytes.clone(); longer.push(0); assert_eq!(Tie::decode(bytes[0], &longer[1..]), None, "{tie:?}"); } } #[test] fn out_of_range_or_malformed_frames_are_refused() { let link = |from: u64, to: u64| { Tie { from, to, op: Op::Link, } .encode() }; assert_eq!(Tie::decode(LINK, &link(MAX_PID_SERIAL, 0)[1..]), None); assert_eq!(Tie::decode(LINK, &link(0, MAX_PID_SERIAL)[1..]), None); let monitor = Tie { from: 1, to: 2, op: Op::Monitor { tag: MAX_TAG }, }; assert_eq!(Tie::decode(MONITOR, &monitor.encode()[1..]), None); let demonitor = Tie { op: Op::Demonitor { tag: MAX_TAG }, ..monitor }; assert_eq!(Tie::decode(DEMONITOR, &demonitor.encode()[1..]), None); let body = &link(1, 2)[1..]; let id = [body, &[7; 8]].concat(); assert_eq!(Tie::decode(UNLINK, body), None, "no id"); assert_eq!( Tie::decode(UNLINK_ACK, &id[..id.len() - 1]), None, "7 bytes" ); assert_eq!(Tie::decode(0x19, &id), None, "no op 0x19 yet"); let exit = |reason: &[u8]| [body, reason].concat(); assert_eq!(Tie::decode(EXIT, &exit(&[4])), None, "no reason 4"); assert_eq!(Tie::decode(EXIT, &exit(&[2, 1, 0, 0xff])), None, "UTF-8"); assert_eq!(Tie::decode(EXIT, &exit(&[2, 2, 0, b'a'])), None, "length"); assert_eq!( Tie::decode(EXIT, &exit(&[2, 1, 0, b'a'])), Some(Tie { from: 1, to: 2, op: Op::Exit(Exit::Crashed("a".into())) }) ); } #[test] fn a_long_crash_text_is_cut_at_a_character_boundary() { // 'é' is 2 bytes: 481 of them end past the limit, mid-character. let text = "é".repeat(481); let down = Tie { from: 1, to: 2, op: Op::Down { tag: 3, reason: Exit::Crashed(text.clone()), }, }; let bytes = down.encode(); // The frame's kind, then this body, fit 1 KiB. assert!(bytes.len() < 1024, "{}", bytes.len()); let cut = "é".repeat(480); assert_eq!(cut.len(), MAX_REASON); assert_eq!( Tie::decode(DOWN, &bytes[1..]).map(|t| t.op), Some(Op::Down { tag: 3, reason: Exit::Crashed(cut) }) ); } }