//! Console output (`std/io`, ADR 0022): `io.println`, `io.print` and //! `io.eprintln` never block a scheduler thread. //! //! - **One writer thread** (`louise-console`) writes what actors queue, //! in the order they queued it, stdout and stderr alike, so the two //! streams interleave as the program wrote them. Each batch takes //! everything queued: consecutive stdout text goes out in one write, and //! stdout is flushed before stderr text and at the end of every batch. //! Write errors (a closed pipe) are ignored, as before: `io.println` //! cannot fail. //! - **A budget bounds what is queued** ([`BUDGET`] bytes, written or //! being written). Text that fits is queued and the call returns at //! once. Otherwise, or while other writers wait (so the order holds), //! the actor parks as in a blocking call (`Wait::Blocking`, never woken //! early) and the writer queues its text and wakes it once there is //! room. One text larger than the budget is queued when nothing else is. //! A slow console thus slows down only the actors that write to it. //! - **Where an actor cannot park** (inside a callback from C, on the //! blocking pool, or without an actor) the text is queued past the //! budget instead: these writes are rare and small, and blocking the //! thread is what this module exists to avoid. //! - **Nothing is lost at exit.** `tl_main` and `tl_main_program` wait for //! the writer once every actor stopped ([`flush`]), and so does C's //! `exit` (an `atexit` handler). The runtime's own messages (crash //! reports) are queued like `io.eprintln`, so they keep their place; a //! message printed before an abort first waits for the queue, for a //! moment at most ([`flush_before_abort`]). use std::io::Write; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock}; use std::time::{Duration, Instant}; use crate::abi::{Ctx, UNIT}; use crate::otp::Wait; use crate::sched::{park, this}; /// Bytes queued or being written before writers park: as much as a /// default Linux pipe holds. pub(crate) const BUDGET: usize = 64 * 1024; /// How long a message printed before an abort waits for queued output. const ABORT_WAIT: Duration = Duration::from_secs(1); #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Stream { Out, Err, } /// Queued text: `bytes`, cut into runs of one stream (`(stream, end)`). #[derive(Default)] struct Queue { runs: Vec<(Stream, usize)>, bytes: Vec, } impl Queue { fn push(&mut self, stream: Stream, parts: &[&[u8]]) { for part in parts { self.bytes.extend_from_slice(part); } let end = self.bytes.len(); match self.runs.last_mut() { Some((s, e)) if *s == stream => *e = end, _ => self.runs.push((stream, end)), } } fn is_empty(&self) -> bool { self.runs.is_empty() } } /// A write waiting for room: its text, its actor, and how to wake it. struct Waiter { stream: Stream, bytes: Vec, pid: i64, waker: Arc, } #[derive(Default)] struct State { queue: Queue, /// Bytes queued or being written. pending: usize, waiters: std::collections::VecDeque, /// The writer waits for work (so a write must signal it). writer_asleep: bool, } impl State { fn has_room(&self, len: usize) -> bool { self.pending == 0 || self.pending + len <= BUDGET } fn push(&mut self, stream: Stream, parts: &[&[u8]]) { self.pending += parts.iter().map(|p| p.len()).sum::(); self.queue.push(stream, parts); } /// Queue waiters, in order, while there is room; returns them, to wake. fn admit(&mut self) -> Vec { let mut admitted = Vec::new(); while let Some(w) = self.waiters.front() { if !self.has_room(w.bytes.len()) { break; } let w = self.waiters.pop_front().expect("a waiter"); self.push(w.stream, &[&w.bytes]); admitted.push(w); } admitted } } struct Console { state: Mutex, /// Signals the writer: there is work. work: Condvar, /// Signals `flush`: everything was written. idle: Condvar, } impl Console { fn lock(&self) -> MutexGuard<'_, State> { // Writing never panics with the lock held; recover anyway, so // output keeps working after an unrelated panic. self.state .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } fn signal(&self, state: &mut State) { if state.writer_asleep { state.writer_asleep = false; self.work.notify_one(); } } } static CONSOLE: OnceLock = OnceLock::new(); /// The console, starting its writer on first use. fn console() -> &'static Console { CONSOLE.get_or_init(|| { // The writer's own `console()` waits until this returns. std::thread::Builder::new() .name("louise-console".into()) .spawn(writer) .expect("louise: cannot start the console thread"); // SAFETY: `flush_at_exit` is a plain `extern "C" fn()`. unsafe { libc::atexit(flush_at_exit) }; Console { state: Mutex::new(State::default()), work: Condvar::new(), idle: Condvar::new(), } }) } /// The writer thread: write each batch, then make room for waiters. fn writer() { let console = console(); let mut batch = Queue::default(); loop { { let mut state = console.lock(); while state.queue.is_empty() { state.writer_asleep = true; state = console .work .wait(state) .unwrap_or_else(std::sync::PoisonError::into_inner); } std::mem::swap(&mut state.queue, &mut batch); } write_batch(&batch); let written = batch.bytes.len(); batch.runs.clear(); batch.bytes.clear(); // Keep the buffer for the next batch, unless one large text grew it. if batch.bytes.capacity() > 4 * BUDGET { batch.bytes = Vec::new(); } let admitted = { let mut state = console.lock(); state.pending -= written; let admitted = state.admit(); if state.pending == 0 && state.waiters.is_empty() { console.idle.notify_all(); } admitted }; for w in admitted { crate::blocking::complete(w.pid, UNIT, &w.waker); } } } fn write_batch(batch: &Queue) { let mut out = std::io::stdout().lock(); let mut start = 0; for &(stream, end) in &batch.runs { let text = &batch.bytes[start..end]; // Errors (a closed pipe, a full disk) are ignored: printing // cannot fail. match stream { Stream::Out => { let _ = out.write_all(text); } Stream::Err => { let _ = out.flush(); let _ = std::io::stderr().lock().write_all(text); } } start = end; } let _ = out.flush(); } /// Write `parts` (one text) to `stream` from the running actor: queue it, /// or park until there is room. /// /// The console lock is never held while taking a scheduler lock. /// /// # Safety /// `ctx` must be the running actor's context, or null. pub(crate) unsafe fn write(ctx: *mut Ctx, stream: Stream, parts: &[&[u8]]) { let console = console(); let len = parts.iter().map(|p| p.len()).sum::(); // SAFETY: forwarded caller guarantee. let can_park = unsafe { can_park(ctx) }; { let mut state = console.lock(); if !can_park || (state.waiters.is_empty() && state.has_room(len)) { state.push(stream, parts); console.signal(&mut state); return; } } // Park as in a blocking call: the text is queued once there is room, // then `blocking::complete` wakes the actor. Meanwhile the scheduler // counts it among the blocking calls it waits for. // SAFETY: `can_park` checked a running actor. unsafe { let (a, sched) = this(ctx); a.with_proc(|p| p.park_as(Wait::Blocking)); let waker = sched.blocking_started(); let admitted = { let mut state = console.lock(); state.waiters.push_back(Waiter { stream, bytes: parts.concat(), pid: a.pid, waker, }); // Room may have appeared since the check: the writer only // admits waiters after a batch. let admitted = state.admit(); console.signal(&mut state); admitted }; for w in admitted { crate::blocking::complete(w.pid, UNIT, &w.waker); } // Woken with unit. If the actor was killed meanwhile, its text was // still queued, and the caller unwinds. park(ctx); } } /// Whether the caller is an actor that may park. /// /// # Safety /// `ctx` must be the running actor's context, or null. pub(crate) unsafe fn can_park(ctx: *mut Ctx) -> bool { // SAFETY: forwarded caller guarantee; `rt` is null outside actors. unsafe { !ctx.is_null() && !(*ctx).rt.is_null() && !crate::callback::on_foreign_thread() && !crate::sched::in_callback(ctx) } } /// Queue a message of the runtime's own (a crash report) on stderr, /// without waiting: it keeps its place among the program's output. pub(crate) fn diagnostic(message: &str) { let console = console(); let mut state = console.lock(); state.push(Stream::Err, &[message.as_bytes(), b"\n"]); console.signal(&mut state); } /// Wait until everything queued was written, for `limit` at most. fn wait_written(limit: Option) { // Nothing was ever printed: no writer to wait for. let Some(console) = CONSOLE.get() else { return; }; let deadline = limit.map(|l| Instant::now() + l); let mut state = console.lock(); while state.pending > 0 || !state.waiters.is_empty() { state = match deadline { None => console .idle .wait(state) .unwrap_or_else(std::sync::PoisonError::into_inner), Some(d) => { let Some(left) = d.checked_duration_since(Instant::now()) else { return; }; console .idle .wait_timeout(state, left) .unwrap_or_else(std::sync::PoisonError::into_inner) .0 } }; } } /// Wait until everything queued was written. Called once every actor /// stopped, so no writer is parked and nothing else is queued meanwhile. pub(crate) fn flush() { wait_written(None); } /// Before printing a message and aborting: give queued output a moment /// to go out first, without hanging on a console nobody reads. pub(crate) fn flush_before_abort() { wait_written(Some(ABORT_WAIT)); } extern "C" fn flush_at_exit() { flush(); } #[cfg(test)] mod tests { use super::{BUDGET, State, Stream, Waiter}; use std::sync::Arc; fn waiter(waker: &Arc, pid: i64, len: usize) -> Waiter { Waiter { stream: Stream::Out, bytes: vec![b'x'; len], pid, waker: waker.clone(), } } #[test] fn runs_keep_the_streams_in_order() { let mut state = State::default(); state.push(Stream::Out, &[b"a", b"\n"]); state.push(Stream::Out, &[b"b\n"]); state.push(Stream::Err, &[b"e\n"]); state.push(Stream::Out, &[b"c"]); assert_eq!(state.queue.bytes, b"a\nb\ne\nc"); assert_eq!( state.queue.runs, [(Stream::Out, 4), (Stream::Err, 6), (Stream::Out, 7)] ); assert_eq!(state.pending, 7); } #[test] fn waiters_are_admitted_in_order_when_there_is_room() { let poll = mio::Poll::new().unwrap(); // One waker per poll: the waiters share it, as they share the // scheduler's. let waker = Arc::new(mio::Waker::new(poll.registry(), mio::Token(0)).unwrap()); let mut state = State::default(); // A text larger than the budget fits when nothing is pending. assert!(state.has_room(BUDGET * 2)); state.push(Stream::Out, &[&vec![b'x'; BUDGET - 10]]); assert!(state.has_room(10)); assert!(!state.has_room(11)); state.waiters.push_back(waiter(&waker, 1, 100)); state.waiters.push_back(waiter(&waker, 2, 5)); // The first waiter does not fit, so the second waits behind it. assert!(state.admit().is_empty()); // The writer wrote the batch: both fit now, in order. state.pending = 0; let admitted: Vec = state.admit().iter().map(|w| w.pid).collect(); assert_eq!(admitted, [1, 2]); assert_eq!(state.pending, 105); // The oversized one waits for an empty queue. state.waiters.push_back(waiter(&waker, 3, BUDGET * 2)); assert!(state.admit().is_empty()); state.pending = 0; assert_eq!(state.admit().len(), 1); } }