//! Distribution's transport (ADR 0072, *Transport*): the `louise-dist` //! thread, which keeps one mutual-TLS connection per peer node and carries //! frames over it. Payloads are opaque here: the codec encodes a message //! frame before [`Transport::send`], and an [`Inbound`] handler decodes //! what arrives. The bytes on the connection are specified in //! `docs/wire-format.md`, *Handshake*. //! //! - **Only when started.** Nothing here is reachable from a program that //! does not start distribution: [`start_program`] is its only entry //! from the runtime, and the scheduler reaches [`stop_program`] only //! through the pointer it registers (`dist::shutdown`), so //! `--gc-sections` drops the transport and rustls otherwise. //! - **Its own thread and poll**, as the signals thread (ADR 0060): //! heartbeats never wait for the schedulers, so a busy node is not taken //! for a dead one. Senders queue frames and wake it ([`mio::Waker`]). //! Nor do they wait for the handler: what arrives goes to it on a second //! thread, in order (`relay`), whose backlog per peer pauses reading that //! peer's connection. //! - **mTLS both ways, no plaintext path.** Every connection presents and //! requires a certificate from the cluster's authorities (no default //! roots), TLS 1.3 only, ALPN `louise-dist`. A node name is a DNS name //! checked against the peer's certificate (`tls::has_name`) on both //! sides; the dialing side also has rustls check it as the server name. //! - **The handshake** then exchanges the protocol version, capability //! flags, the cluster, the node name, its incarnation and the schema //! hash, which must match ([`Reason`] says why one is refused). //! - **A capability flag per op family** added since stage 1 //! ([`frame::needs`]): every node sets those it implements, and a //! signal frame of such an op is queued only for a peer whose hello set //! its flag ([`SendError::Unsupported`]), so an older runtime is never //! sent one. [`Transport::lacks`] lets a sender ask first. //! - **At most `max_peers` peers**, connections past their hello: past //! that, a node that is neither a seed nor [`Transport::connect`]ed is //! refused ([`Reason::Full`]). Seeds count, and are never refused. //! - **Full-mesh discovery, opt-in** (`mesh`): peers that both set //! [`frame::FLAG_PEERS`] send each other their lists of nodes up, with //! the addresses to dial them at, and dial the nodes they did not know //! (*discovered*). An address is a hint: TLS checks the dialed name, so //! a lying peer only wastes dials, each lister's address being tried in //! turn. A discovered node is dialed again while a peer lists it, and //! forgotten once none has for `node_down_after_ms` × //! [`thread::FORGET_AFTER`]; at most `max_peers` are known, shared among //! the peers that list them (`thread`, *Discovery*). //! - **One connection per peer, one ordered stream.** Simultaneous dials //! resolve to the connection the smaller node name initiated; a new //! incarnation of a connected node replaces it (the old one is down). //! Messages and signals leave in the order they were sent. Heartbeats //! and their echoes are a control lane: written between the stream's //! frames, ahead of what is queued, so a long queue delays neither the //! peer's liveness nor the round-trip time measured from them. //! - **Back-pressure.** A peer's queue holds `max_queue` bytes of messages //! and spawn requests (or one larger one); past that a frame is given //! back ([`SendError::Full`]), and a sender that passed a [`Waiter`] is //! woken ([`Inbound::drained`]) once the thread takes the queue to write //! it, or the node is down. Other signals, small, are not capped. //! - **Down** after `node_down_after_ms` without a byte from the peer //! (heartbeats keep an idle connection alive; one the relay paused is not //! read, so not timed), or when the connection //! fails or breaks the protocol: [`Inbound::node_down`], and the //! connection is closed. A frame for a node that is not up is refused //! ([`SendError::NotConnected`]): delivery is at most once. //! - **Untrusted until the handshake.** Before it, a connection is held //! for `node_down_after_ms` at most, its frames are 1 KiB at most, and //! at most [`MAX_UNAUTHENTICATED`] accepted connections are open before //! their hello, [`MAX_UNAUTHENTICATED_PER_SOURCE`] from one address: a //! new one closes its own source's oldest, or the oldest of the source //! holding the most, so a flood from one host closes only its own. //! Their failures are logged at most every 10 s ([`Throttle`]). //! No peer input is unwrapped; every buffer is bounded by a frame limit. //! //! `tl_dist_start` (`node.rs`) starts it, with the handler that decodes //! messages and answers lookups. mod frame; mod relay; mod thread; #[cfg(test)] mod tests; use std::collections::{HashMap, VecDeque}; use std::net::SocketAddr; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock}; use std::thread::JoinHandle; use louise_rt_prims::wire::{HEADER_LEN, MAX_DELAY_MS, MAX_PEERS, MessageHeader, check_node_name}; pub(crate) use louise_rt_prims::wire::{MAX_FRAME, MIN_FRAME}; pub(crate) use crate::dist::{Node, Waiter}; use crate::sched::Shared; use frame::Entry; #[cfg(test)] pub(crate) use frame::needs; /// Accepted connections whose hello has not arrived: past this, a new one /// closes the oldest of the source that holds the most. pub(crate) const MAX_UNAUTHENTICATED: usize = 128; /// Accepted connections whose hello has not arrived, from one source (an /// IPv4 address, or an IPv6 /64): past this, a new one closes its source's /// oldest. A host flooding a node with connections then evicts only its /// own, however slow a real node's handshake (a distant one's, say). pub(crate) const MAX_UNAUTHENTICATED_PER_SOURCE: usize = 8; /// A log line at most every [`Throttle::PERIOD`], for what an /// unauthenticated host can make happen at its own rate (a connection that /// fails before its hello, an accept that fails): the first at once, then /// one per period, which says how many were held back meanwhile. #[derive(Default)] pub(crate) struct Throttle { last: Option, held: u64, } impl Throttle { pub(crate) const PERIOD: std::time::Duration = std::time::Duration::from_secs(10); /// Whether to log now: `Some(held)`, the lines held back since the /// last one; `None`, hold this one back. pub(crate) fn admit(&mut self, now: std::time::Instant) -> Option { match self.last { Some(last) if now.saturating_duration_since(last) < Self::PERIOD => { self.held += 1; None } _ => { self.last = Some(now); Some(std::mem::take(&mut self.held)) } } } /// What a line [`Throttle::admit`]ted adds about those held back. pub(crate) fn held_back(held: u64) -> String { match held { 0 => String::new(), n => format!(" ({n} more since the last such line, not logged)"), } } } /// What a node is started with: plain values, which `std/dist` reads from /// the environment and `[cluster]`. #[derive(Clone, Debug)] pub(crate) struct Config { /// This node's name: a lowercase DNS name its certificate is valid for. pub(crate) node: String, /// Nodes of other clusters are refused. A node name's syntax. pub(crate) cluster: String, pub(crate) listen: SocketAddr, /// Where peers can dial this node, which its lists of peers say /// (`mesh`): `None`, `listen` unless it is unspecified (`0.0.0.0`, /// `::`), with the port the OS chose for port 0; else nothing, a /// node only other nodes' dials do not reach. pub(crate) advertise: Option, /// Nodes to connect to at start, and again whenever their connection /// is lost. pub(crate) seeds: Vec<(String, SocketAddr)>, /// Full-mesh discovery: lists of peers are exchanged with the peers /// that also discover, and the nodes they list are dialed. Otherwise /// only seeds and `connect`ed nodes are. pub(crate) mesh: bool, /// This node's certificate chain and key (PEM), presented both as a /// server and as a client. pub(crate) cert_file: String, pub(crate) key_file: String, /// The cluster's authorities (PEM): a peer's certificate must chain to /// one. Never the system's roots. pub(crate) ca_files: Vec, /// The program's schema hash: peers must have the same (stage 1). pub(crate) schema_hash: u64, /// A heartbeat goes out to each peer this often, in the control lane; /// its echo gives the round-trip time. pub(crate) heartbeat_ms: u64, /// A peer silent for this long is down (it also bounds a handshake). pub(crate) node_down_after_ms: u64, /// The largest frame this node accepts, announced in its handshake: /// a larger one closes the connection. pub(crate) max_frame: u32, /// The message bytes (headers and payloads) queued per peer before /// [`SendError::Full`]; an empty queue takes one message of any size /// within the peer's frame limit. Signals are not counted (ADR 0072, /// *Back-pressure*). pub(crate) max_queue: usize, /// Connections past their hello kept before a peer that is neither a /// seed nor `connect`ed is refused ([`Reason::Full`]); also how many /// down nodes' statistics are kept ([`PeerStats`]). pub(crate) max_peers: usize, /// The first delay before connecting again to a known node; it doubles /// on each failure, up to 32 times. pub(crate) reconnect_ms: u64, } impl Config { /// A configuration with the defaults: heartbeats every second, down /// after 10 s, frames of 8 MiB, 64 MiB queued per peer, 256 peers. pub(crate) fn new(node: &str, cluster: &str, listen: SocketAddr) -> Config { Config { node: node.to_owned(), cluster: cluster.to_owned(), listen, advertise: None, seeds: Vec::new(), mesh: false, cert_file: String::new(), key_file: String::new(), ca_files: Vec::new(), schema_hash: 0, heartbeat_ms: 1_000, node_down_after_ms: 10_000, max_frame: 8 << 20, max_queue: 64 << 20, max_peers: 256, reconnect_ms: 1_000, } } /// Refuse what cannot work, before anything is opened. fn check(&self) -> Result<(), String> { for (what, name) in [("node", &self.node), ("cluster", &self.cluster)] .into_iter() .chain(self.seeds.iter().map(|(n, _)| ("seed", n))) { if !check_node_name(name.as_bytes()) { return Err(format!("{what} name {name:?} is not a lowercase DNS name")); } } if self.seeds.iter().any(|(n, _)| *n == self.node) { return Err(format!("{} is this node, not a seed", self.node)); } if let Some(addr) = self.advertise && !frame::dialable(addr) { return Err(format!( "cannot advertise {addr}: an address peers can dial needs a port, and is not unspecified, multicast or broadcast" )); } if self.ca_files.is_empty() { return Err("no cluster authority: give the CA files peers are signed by".into()); } if !(MIN_FRAME..=MAX_FRAME).contains(&self.max_frame) { return Err(format!( "max_frame must be between {MIN_FRAME} and {MAX_FRAME} bytes" )); } if self.heartbeat_ms == 0 || self.node_down_after_ms <= self.heartbeat_ms { return Err("node_down_after_ms must exceed heartbeat_ms, which must not be 0".into()); } if !(1..=MAX_PEERS).contains(&self.max_peers) { return Err(format!("max_peers must be between 1 and {MAX_PEERS}")); } if self.reconnect_ms == 0 { return Err("reconnect_ms must not be 0".into()); } if self.node_down_after_ms.max(self.reconnect_ms) > MAX_DELAY_MS { return Err(format!( "node_down_after_ms and reconnect_ms must be at most {MAX_DELAY_MS} (a day)" )); } Ok(()) } } /// Why a connection was refused or closed. Peer-supplied text is kept as /// sent and escaped when shown. #[derive(Clone, Debug, PartialEq)] pub(crate) enum Reason { /// TLS failed: the handshake (an unknown authority, a certificate not /// valid for the dialed name...) or a record (rustls's message). Tls(String), /// The connection did not negotiate ALPN `louise-dist`. Alpn, /// The peer speaks another protocol version. Version(u16), /// The peer is of another cluster (its name). Cluster(String), /// The peer was built with another schema (its hash). Schema(u64), /// The peer's claimed name is not valid for its certificate, not the /// name it was dialed as, or this node's own. Name(String), /// Another connection to the same node is kept: simultaneous dials, /// or one already up. Duplicate, /// A malformed or unexpected frame. Protocol(&'static str), /// A frame larger than the limit this node announced (its length). TooLarge(u32), /// Nothing from the peer for `node_down_after_ms`, or a handshake that /// took that long. Timeout, /// Closed in its handshake to make room for a newer connection: more /// than [`MAX_UNAUTHENTICATED`] were in theirs. Crowded, /// Refused at its hello: this node keeps `max_peers` connections past /// theirs, and the peer is neither a seed nor `connect`ed. Labelled by /// its address (its hello is not accepted), so `node.rs` logs it as /// sparingly as a connection that fails before its hello. Full, /// The peer ended the connection in order (TLS `close_notify`): its /// program stopped, say. PeerClosed, /// The connection failed, or ended without `close_notify`. Closed(String), /// The peer refused this node: its reason's code and text. Refused(u8, String), /// A new incarnation of the node connected. Replaced, /// This transport stops. Stopped, } impl Reason { /// The code a refusal frame carries (`docs/wire-format.md`, /// *Handshake*), for a reason this node tells its peer. fn code(&self) -> Option { Some(match self { Reason::Version(_) => 1, Reason::Cluster(_) => 2, Reason::Schema(_) => 3, Reason::Name(_) => 4, Reason::Duplicate => 5, Reason::Protocol(_) | Reason::TooLarge(_) | Reason::Alpn => 6, Reason::Replaced => 7, Reason::Full => 8, _ => return None, }) } /// Whether this is how the protocol normally goes, not worth a log: /// a peer that stops closes its connections in order. `Crowded` is /// not, but a log line for each connection of a flood would be another /// flood. pub(crate) fn routine(&self) -> bool { matches!( self, Reason::Duplicate | Reason::Refused(5, _) | Reason::Stopped | Reason::Crowded | Reason::PeerClosed ) } } impl std::fmt::Display for Reason { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Reason::Tls(e) => write!(f, "TLS: {e}"), Reason::Alpn => write!(f, "not the louise-dist protocol (ALPN)"), Reason::Version(v) => write!(f, "protocol version {v}, not {}", frame::VERSION), Reason::Cluster(c) => write!(f, "cluster {:?}", c.escape_debug().to_string()), Reason::Schema(h) => write!(f, "schema {h:016x}: built from other types"), Reason::Name(n) => write!(f, "node name {:?} refused", n.escape_debug().to_string()), Reason::Duplicate => write!(f, "already connected"), Reason::Protocol(what) => write!(f, "protocol error: {what}"), Reason::TooLarge(n) => write!(f, "frame of {n} bytes over the limit"), Reason::Timeout => write!(f, "timed out (no heartbeat, or a slow handshake)"), Reason::Crowded => write!(f, "too many connections in their handshake"), Reason::Full => write!(f, "too many peers ([cluster] max_peers)"), Reason::PeerClosed => write!(f, "connection closed: the peer closed it"), Reason::Closed(why) => write!(f, "connection closed: {why}"), Reason::Refused(code, text) => { write!(f, "refused by the peer ({code}): {}", text.escape_debug()) } Reason::Replaced => write!(f, "replaced by a new incarnation"), Reason::Stopped => write!(f, "stopped"), } } } /// What arrives from peers, called on the `louise-dist-in` thread in the /// order it arrived (per peer: the order it was sent), [`Inbound::drained`] /// excepted: on the `louise-dist` thread, at once. The real handler decodes /// and calls `dist::inbound`; it must not wait for the transport (a send is /// fine, stopping it is not). pub(crate) trait Inbound: Send + Sync { /// The handshake with `peer` completed: frames flow both ways. fn node_up(&self, peer: &Node); /// `peer`, which was up, is lost (`dist::inbound::node_down`'s /// fan-out): no more frames come from it, and frames still queued for /// it are dropped. fn node_down(&self, peer: &Node); /// A message frame from `from` for this node's incarnation, its header /// checked (`docs/wire-format.md`, *Frames*); `payload` is its /// `payload_len` bytes. fn message(&self, from: &Node, header: &MessageHeader, payload: &[u8]); /// A signal frame: a lookup or its answer, a link, monitor or exit /// signal (`docs/wire-format.md`, *Lookups* and *Signals*). fn signal(&self, from: &Node, body: &[u8]); /// Senders that found `peer`'s queue full may try again: the thread /// took the queue to write it, or the node is down (their next try /// is then refused). Each was registered once, by a refused /// [`Transport::queue`]. fn drained(&self, peer: &Node, waiters: &[Waiter]); /// A connection to `peer` (its name, or its address before the /// handshake) was refused or closed for `reason`. `hearsay`: it was a /// dial, never past its hello, to an address that only peers' lists /// gave (a discovered node that never confirmed it): the peers chose /// the name, and how often it fails. Logged by default. fn closed(&self, peer: &str, reason: &Reason, hearsay: bool) { let _ = hearsay; if !reason.routine() { eprintln!("louise: dist: {peer}: {reason}"); } } } /// A frame for a peer, already encoded. pub(crate) enum Outbound { /// A message frame: its 36-byte header, then its payload. Message(Vec), /// A signal frame that carries a payload, a spawn request: counted /// against the queue's cap as a message is. Request(Vec), /// A signal frame of a fixed small size, exempt from the queue's cap /// (not from its order). Signal(Vec), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum SendError { /// That incarnation of the node is not up: the frame is dropped. NotConnected, /// Over the peer's frame limit. TooLarge, /// The peer's queue holds `max_queue` bytes of messages: the frame is /// given back ([`Transport::queue`]). Full, /// A message frame whose header is malformed, does not match its /// length or names another incarnation: a bug in the encoder. Malformed, /// A signal frame of an op the peer's hello did not say it takes /// ([`frame::needs`]): the frame is dropped. Unsupported, } /// Where senders queue frames for the thread: per peer that is up, in /// send order. Senders hold the lock for one push; the thread takes a /// peer's whole queue once its connection has written the previous batch /// (the low-water mark: the queue is then empty, and its parked senders /// are woken), so a peer holds at most twice `max_queue` bytes of /// messages, one larger message aside. pub(super) struct Outbox { routes: Mutex>, /// Per node name, from the first time it is known: a seed, a /// connection, a message for it. Bounded: see [`PeerStats`]. stats: Mutex, commands: Mutex>, waker: mio::Waker, /// A wake is pending: senders skip theirs. woken: AtomicBool, max_queue: usize, /// Connections open, up or not. open: AtomicUsize, /// Frames received for another incarnation of this node. dropped: AtomicU64, } /// A peer that is up, as senders see it. struct Route { incarnation: u64, /// The largest frame it accepts. max_frame: u32, /// The capability flags of its hello. flags: u64, queue: VecDeque, /// Message bytes in `queue`. queued: usize, /// Senders the full queue refused, to wake when it drains. parked: Vec, stats: Arc, } /// What `std/dist.peers` reports of a node, for the whole run: counts /// across its connections, its round-trip time on the current one. pub(super) struct Stats { /// The incarnation it was last up as; 0 before. incarnation: AtomicU64, /// Microseconds from a heartbeat to its echo, the latest measured on /// the current connection; `u64::MAX` before. rtt_us: AtomicU64, /// Message frames handed to TLS for it. sent: AtomicU64, /// Message frames from it for this node's incarnation (some of which /// the handler may drop: `dropped`). received: AtomicU64, /// Messages for it not sent: it was not up, or its connection was lost /// with them queued, or their sender exited while parked. unsent: AtomicU64, /// Senders its full queue made wait (registered waiters). parked: AtomicU64, /// Frames from it dropped: for another incarnation of this node, or /// refused by the handler (undecodable, of an unknown type...). dropped: AtomicU64, } impl Stats { fn new() -> Stats { Stats { incarnation: AtomicU64::new(0), rtt_us: AtomicU64::new(u64::MAX), sent: AtomicU64::new(0), received: AtomicU64::new(0), unsent: AtomicU64::new(0), parked: AtomicU64::new(0), dropped: AtomicU64::new(0), } } pub(super) fn count(counter: &AtomicU64, n: u64) { counter.fetch_add(n, Ordering::Relaxed); } } /// Every node name this node knows, and its statistics: for the whole run /// while it is up, a seed or `connect`ed; otherwise while it is among the /// `max_down` most recently seen (`max_peers`). Names come from peers /// (a pid of a node this one never connected to, a peer that connects /// once), so a name past those forgets the least recently seen, its /// counts with it. pub(super) struct PeerStats { by_name: HashMap, /// Ticks at each touch: what "recently" means. clock: u64, max_down: usize, } struct Seen { stats: Arc, /// When it was last touched, on [`PeerStats::clock`]. at: u64, /// A connection past its hello is up with it (the thread says so). up: bool, /// A seed or `connect`ed: never forgotten. kept: bool, } impl PeerStats { pub(super) fn new(max_down: usize) -> PeerStats { PeerStats { by_name: HashMap::new(), clock: 0, max_down, } } /// `name`'s statistics, seen now. pub(super) fn stats(&mut self, name: &str) -> Arc { let new = !self.by_name.contains_key(name); let stats = self.seen(name).stats.clone(); if new { self.forget(); } stats } /// `name` is a seed or `connect`ed: kept from now on. fn keep(&mut self, name: &str) { self.seen(name).kept = true; } /// `name` is up: kept until it is down. Its statistics. pub(super) fn up(&mut self, name: &str) -> Arc { let seen = self.seen(name); seen.up = true; seen.stats.clone() } /// `name` is down: seen now, the most recent of the down nodes. pub(super) fn down(&mut self, name: &str) { self.seen(name).up = false; self.forget(); } fn seen(&mut self, name: &str) -> &mut Seen { self.clock += 1; let seen = self.by_name.entry(name.to_owned()).or_insert_with(|| Seen { stats: Arc::new(Stats::new()), at: 0, up: false, kept: false, }); seen.at = self.clock; seen } /// Forget the least recently seen of the names neither up nor kept /// while there are more than `max_down`. A scan of every name, only /// for a new name or a node down, not for each message counted. fn forget(&mut self) { loop { let mut down = 0; let mut oldest: Option<(u64, &String)> = None; for (name, seen) in &self.by_name { if seen.up || seen.kept { continue; } down += 1; if oldest.is_none_or(|(at, _)| seen.at < at) { oldest = Some((seen.at, name)); } } match oldest { Some((_, name)) if down > self.max_down => { let name = name.clone(); self.by_name.remove(&name); } _ => return, } } } /// Every name known, and its statistics. fn iter(&self) -> impl Iterator)> { self.by_name.iter().map(|(name, seen)| (name, &seen.stats)) } } /// A node as [`Transport::report`] sees it. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Report { pub(crate) node: String, /// The incarnation it is (or was last) up as; `None` if never. pub(crate) incarnation: Option, pub(crate) up: bool, /// Round-trip time in microseconds, while up and once measured. pub(crate) rtt_us: Option, /// Message bytes queued for it, not yet taken by the thread. pub(crate) queued: usize, pub(crate) sent: u64, pub(crate) received: u64, pub(crate) unsent: u64, pub(crate) parked: u64, pub(crate) dropped: u64, } /// What the handle asks of the thread. pub(super) enum Command { Connect(String, SocketAddr), Stop, } impl Outbox { fn routes(&self) -> MutexGuard<'_, HashMap> { self.routes.lock().unwrap_or_else(PoisonError::into_inner) } /// Every node name known, and its statistics. pub(super) fn peer_stats(&self) -> MutexGuard<'_, PeerStats> { self.stats.lock().unwrap_or_else(PoisonError::into_inner) } /// `name`'s statistics, seen now ([`PeerStats`]). pub(super) fn stats(&self, name: &str) -> Arc { self.peer_stats().stats(name) } fn command(&self, command: Command) { self.commands .lock() .unwrap_or_else(PoisonError::into_inner) .push(command); self.wake(); } /// Wake the thread, unless a wake is pending. pub(super) fn wake(&self) { if !self.woken.swap(true, Ordering::AcqRel) && self.waker.wake().is_err() { // The frames wait for the next event or heartbeat; the next // sender tries again. self.woken.store(false, Ordering::Release); } } } /// A running transport: its thread, and the queues senders use. pub(crate) struct Transport { outbox: Arc, thread: Option>, relay: Arc, /// The relay's thread, joined after the transport's. relayed: Option>, me: Node, local_addr: SocketAddr, } impl Transport { /// Check `config`, load its certificates, listen, and start the /// `louise-dist` thread, which dials the seeds. This node's /// incarnation is drawn at random. Touches no global state (see /// [`start_program`]). pub(crate) fn start(config: Config, inbound: Arc) -> Result { config.check()?; let mut incarnation = [0u8; 8]; rustls::crypto::ring::default_provider() .secure_random .fill(&mut incarnation) .map_err(|_| "no random incarnation".to_string())?; let me = Node { name: config.node.clone(), incarnation: u64::from_le_bytes(incarnation), }; let seeds: Vec = config.seeds.iter().map(|(n, _)| n.clone()).collect(); let relay = Arc::new(relay::Relay::new(inbound)); let thread = thread::Thread::new(config, me.clone(), relay.clone())?; let outbox = thread.outbox(); relay.wakes(outbox.clone()); for seed in &seeds { outbox.peer_stats().keep(seed); } let local_addr = thread.local_addr(); let relayed = { let relay = relay.clone(); std::thread::Builder::new() .name("louise-dist-in".into()) .spawn(move || relay.run()) .map_err(|e| format!("cannot start the louise-dist-in thread: {e}"))? }; let mut transport = Transport { outbox, thread: None, relay, relayed: Some(relayed), me, local_addr, }; // On an error, dropping the transport joins the relay. transport.thread = Some( std::thread::Builder::new() .name("louise-dist".into()) .spawn(move || thread.run()) .map_err(|e| format!("cannot start the louise-dist thread: {e}"))?, ); Ok(transport) } /// This node: its name and incarnation. pub(crate) fn me(&self) -> &Node { &self.me } /// The address it listens on (the port the OS chose, for port 0). pub(crate) fn local_addr(&self) -> SocketAddr { self.local_addr } /// Connect to `name` at `addr` (unless connected), and again whenever /// the connection is lost, as a seed: a discovered node becomes one. pub(crate) fn connect(&self, name: &str, addr: SocketAddr) { self.outbox.peer_stats().keep(name); self.outbox.command(Command::Connect(name.to_owned(), addr)); } /// Queue `frame` for `to`, behind every frame sent to it before, or /// give it back with why not. It is written by the thread; it may /// still be lost with the connection. A signal frame whose op needs a /// capability flag `to`'s hello did not set is refused /// ([`SendError::Unsupported`]), checked under the queue's lock. A message the full queue refuses /// registers `waiter`, if any, under the queue's lock, so the drain it /// waits for cannot pass unseen ([`Inbound::drained`]). From any /// thread; never waits but for the queue's lock. pub(crate) fn queue( &self, to: &Node, frame: Outbound, waiter: Option, ) -> Result<(), (SendError, Outbound)> { let counted = match &frame { Outbound::Message(body) => { let header = body .first_chunk::() .and_then(|h| MessageHeader::decode(h).ok()); let fits = header.is_some_and(|h| { h.incarnation == to.incarnation && body.len() - HEADER_LEN == h.payload_len as usize }); if !fits { return Err((SendError::Malformed, frame)); } true } Outbound::Request(_) => true, Outbound::Signal(_) => false, }; let (size, needs) = match &frame { Outbound::Message(body) => (body.len(), 0), Outbound::Request(body) | Outbound::Signal(body) => { (body.len(), body.first().map_or(0, |op| frame::needs(*op))) } }; { let mut routes = self.outbox.routes(); let Some(route) = routes .get_mut(&to.name) .filter(|r| r.incarnation == to.incarnation) else { return Err((SendError::NotConnected, frame)); }; if route.flags & needs != needs { return Err((SendError::Unsupported, frame)); } if 1 + size as u64 > u64::from(route.max_frame) { return Err((SendError::TooLarge, frame)); } if counted { // An empty queue takes any message: a queue smaller than // the peer's frame limit must not refuse one forever. if route.queued > 0 && route.queued.saturating_add(size) > self.outbox.max_queue { if let Some(waiter) = waiter { route.parked.push(waiter); Stats::count(&route.stats.parked, 1); } return Err((SendError::Full, frame)); } route.queued += size; } route.queue.push_back(match frame { Outbound::Message(body) => Entry::new(frame::MESSAGE, body), Outbound::Request(body) | Outbound::Signal(body) => Entry::new(frame::SIGNAL, body), }); } self.outbox.wake(); Ok(()) } /// Whether `to`, up as that incarnation, did not set the capability /// flag a signal frame of `op` needs ([`frame::needs`]): a frame of /// it would be refused ([`SendError::Unsupported`]). False for a node /// that is not up. pub(crate) fn lacks(&self, to: &Node, op: u8) -> bool { let needs = frame::needs(op); self.outbox .routes() .get(&to.name) .filter(|r| r.incarnation == to.incarnation) .is_some_and(|r| r.flags & needs != needs) } /// [`Transport::queue`], a refused frame dropped. pub(crate) fn send(&self, to: &Node, frame: Outbound) -> Result<(), SendError> { self.queue(to, frame, None).map_err(|(e, _)| e) } /// Forget `waiter`, registered for `to`'s queue, if the thread has not /// woken it: something else did (its actor exited). pub(crate) fn unwait(&self, to: &Node, waiter: Waiter) { if let Some(route) = self .outbox .routes() .get_mut(&to.name) .filter(|r| r.incarnation == to.incarnation) { route.parked.retain(|w| *w != waiter); } } /// A message for `name` was not sent (see [`Stats`]'s `unsent`). pub(crate) fn count_unsent(&self, name: &str) { Stats::count(&self.outbox.stats(name).unsent, 1); } /// A frame from `name` was dropped by the handler. pub(crate) fn count_dropped(&self, name: &str) { Stats::count(&self.outbox.stats(name).dropped, 1); } /// Every node known, by name: up or not, its statistics. A snapshot, /// each figure read on its own. Of the nodes neither up nor seeds, the /// `max_peers` most recently seen ([`PeerStats`]). pub(crate) fn report(&self) -> Vec { let stats: Vec<(String, Arc)> = self .outbox .peer_stats() .iter() .map(|(name, s)| (name.clone(), s.clone())) .collect(); let routes = self.outbox.routes(); let mut report: Vec = stats .into_iter() .map(|(node, s)| { let route = routes.get(&node); let load = |c: &AtomicU64| c.load(Ordering::Relaxed); let incarnation = load(&s.incarnation); Report { incarnation: route .map(|r| r.incarnation) .or((incarnation != 0).then_some(incarnation)), up: route.is_some(), rtt_us: route.map(|_| load(&s.rtt_us)).filter(|t| *t != u64::MAX), queued: route.map_or(0, |r| r.queued), sent: load(&s.sent), received: load(&s.received), unsent: load(&s.unsent), parked: load(&s.parked), dropped: load(&s.dropped), node, } }) .collect(); drop(routes); report.sort_by(|a, b| a.node.cmp(&b.node)); report } /// The peers that are up, by name. pub(crate) fn peers(&self) -> Vec { let mut peers: Vec = self .outbox .routes() .iter() .map(|(name, r)| Node { name: name.clone(), incarnation: r.incarnation, }) .collect(); peers.sort_by(|a, b| a.name.cmp(&b.name)); peers } /// Connections open, up or still in their handshake. #[cfg(test)] pub(crate) fn connections(&self) -> usize { self.outbox.open.load(Ordering::Acquire) } /// Frames received for another incarnation of this node, dropped. #[cfg(test)] pub(crate) fn dropped(&self) -> u64 { self.outbox.dropped.load(Ordering::Relaxed) } /// Close every connection (each peer that was up is down) and join /// the thread. pub(crate) fn stop(mut self) { self.join(); } /// Stop the transport's thread, then the relay's once it has handed /// over what the stop queued. fn join(&mut self) { if let Some(thread) = self.thread.take() { self.outbox.command(Command::Stop); if thread.join().is_err() { eprintln!("louise: dist: the transport thread panicked"); } } if let Some(relayed) = self.relayed.take() { self.relay.stop(); if relayed.join().is_err() { eprintln!("louise: dist: the inbound thread panicked"); } } } } impl Drop for Transport { fn drop(&mut self) { self.join(); } } // ---- the program's transport ----------------------------------------------------- /// The transport the program runs, between [`start_program`] and /// [`stop_program`]. The hooks (`dist::Hooks`) reach it here. static PROGRAM: RwLock> = RwLock::new(None); /// Start distribution for the program running on `sched` /// (`tl_dist_start`). The clock switches to real time, the scheduler's /// deadlock check counts the transport as something that can still wake /// an actor, and the scheduler stops it (joining its thread) before its /// shared state is dropped. Once per program. pub(crate) fn start_program( sched: &Shared, config: Config, inbound: Arc, ) -> Result<(), String> { let mut program = PROGRAM.write().unwrap_or_else(PoisonError::into_inner); if program.is_some() { return Err("distribution is already started".into()); } *program = Some(Transport::start(config, inbound)?); sched.switch_to_real_time(); crate::dist::transport_started(stop_program); Ok(()) } /// The program's transport, while it runs. pub(crate) fn with_program(f: impl FnOnce(&Transport) -> R) -> Option { PROGRAM .read() .unwrap_or_else(PoisonError::into_inner) .as_ref() .map(f) } /// Stop the program's transport and join its thread: remote operations act /// as on dead pids again. Outside the lock, so the handler may still reach /// [`with_program`] while the thread stops. fn stop_program() { crate::dist::uninstall(); let transport = PROGRAM .write() .unwrap_or_else(PoisonError::into_inner) .take(); if let Some(transport) = transport { transport.stop(); } crate::dist::transport_stopped(); }