//! The inbound relay: what peers send, handed to the program's [`Inbound`] //! handler on a thread of its own (`louise-dist-in`), in the order it //! arrived, so that the `louise-dist` thread only reads, frames and writes. //! //! - **Why.** The handler decodes messages, and a frame of a few MiB of //! boxed leaves (`Array`) takes hundreds of milliseconds to decode: //! on the transport's thread, every other peer's heartbeats waited for it //! (#404's security review, SEC-6). //! - **Order.** One queue for every peer and event, in the order the //! transport met them: a peer's frames after its `node_up` and before its //! `node_down`, a connection's `closed` before its `node_down`. Only //! [`Inbound::drained`] is called at once: it wakes local senders, and //! orders nothing. //! - **Back-pressure.** Each peer's frames waiting here are counted //! ([`BACKLOG`]): while they fill it, the transport stops reading that //! peer's connection, so TCP pushes back on its sender instead of this //! node buffering without bound. The relay wakes the transport once they //! are down to half. A paused connection is not judged silent: the //! transport chose not to read it. //! - **Stop.** The transport stops first, then the relay handles what is //! queued (the `node_down`s of the connections the stop closed) and its //! thread is joined. use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError}; use louise_rt_prims::wire::{HEADER_LEN, MessageHeader}; use super::{Inbound, Node, Outbox, Reason, Waiter}; /// The bytes of one peer's frames waiting for the handler past which its /// connection is not read; it is read again once they are down to half. pub(super) const BACKLOG: usize = 4 << 20; enum Event { Up(Node), Down(Node), Message(Node, MessageHeader, Vec), Signal(Node, Vec), /// The label, why, and whether the peers chose the address dialed. Closed(String, Reason, bool), } impl Event { /// The peer whose backlog it counts in, and its bytes. fn backlog(&self) -> Option<(&str, usize)> { match self { Event::Message(from, _, payload) => Some((&from.name, HEADER_LEN + payload.len())), Event::Signal(from, body) => Some((&from.name, body.len())), _ => None, } } } #[derive(Default)] struct Queue { events: VecDeque, /// Bytes of frames queued, per peer name (only those with some). backlog: HashMap, /// Peers whose connection the transport stopped reading. paused: HashSet, stopping: bool, } pub(super) struct Relay { handler: Arc, queue: Mutex, ready: Condvar, /// The transport's, to wake it when a paused peer may be read again. outbox: OnceLock>, } impl Relay { pub(super) fn new(handler: Arc) -> Relay { Relay { handler, queue: Mutex::default(), ready: Condvar::new(), outbox: OnceLock::new(), } } /// The transport to wake; set once, before any connection. pub(super) fn wakes(&self, outbox: Arc) { let _ = self.outbox.set(outbox); } fn queue(&self) -> MutexGuard<'_, Queue> { self.queue.lock().unwrap_or_else(PoisonError::into_inner) } fn push(&self, event: Event) { let mut q = self.queue(); if let Some((peer, bytes)) = event.backlog() { *q.backlog.entry(peer.to_owned()).or_default() += bytes; } q.events.push_back(event); drop(q); self.ready.notify_one(); } /// Whether `peer`'s backlog is full: then the transport stops reading /// its connection, and is woken once it is down to half. pub(super) fn full(&self, peer: &str) -> bool { let mut q = self.queue(); let full = q.backlog.get(peer).is_some_and(|b| *b >= BACKLOG); if full { q.paused.insert(peer.to_owned()); } full } /// Whether `peer`'s connection, paused, may be read again. pub(super) fn resumed(&self, peer: &str) -> bool { !self.queue().paused.contains(peer) } /// Hand the queued events to the handler until [`Relay::stop`], then /// those left: the relay thread's body. pub(super) fn run(&self) { loop { let event = { let mut q = self.queue(); loop { if let Some(event) = q.events.pop_front() { break event; } if q.stopping { return; } q = self.ready.wait(q).unwrap_or_else(PoisonError::into_inner); } }; self.handle(&event); let Some((peer, bytes)) = event.backlog() else { continue; }; let mut q = self.queue(); let left = match q.backlog.get_mut(peer) { Some(b) => { *b -= bytes; *b } None => 0, }; if left == 0 { q.backlog.remove(peer); } let resume = left <= BACKLOG / 2 && q.paused.remove(peer); drop(q); if resume && let Some(outbox) = self.outbox.get() { outbox.wake(); } } } fn handle(&self, event: &Event) { let h = &self.handler; match event { Event::Up(peer) => h.node_up(peer), Event::Down(peer) => h.node_down(peer), Event::Message(from, header, payload) => h.message(from, header, payload), Event::Signal(from, body) => h.signal(from, body), Event::Closed(peer, reason, hearsay) => h.closed(peer, reason, *hearsay), } } /// Let [`Relay::run`] return once the queue is empty. pub(super) fn stop(&self) { self.queue().stopping = true; self.ready.notify_one(); } } impl Inbound for Relay { fn node_up(&self, peer: &Node) { self.push(Event::Up(peer.clone())); } fn node_down(&self, peer: &Node) { self.push(Event::Down(peer.clone())); } fn message(&self, from: &Node, header: &MessageHeader, payload: &[u8]) { self.push(Event::Message(from.clone(), *header, payload.to_vec())); } fn signal(&self, from: &Node, body: &[u8]) { self.push(Event::Signal(from.clone(), body.to_vec())); } fn drained(&self, peer: &Node, waiters: &[Waiter]) { self.handler.drained(peer, waiters); } fn closed(&self, peer: &str, reason: &Reason, hearsay: bool) { self.push(Event::Closed(peer.to_owned(), reason.clone(), hearsay)); } }