| @@ -0,0 +1,395 @@ |
| 1 | +//! Console output (`std/io`, ADR 0022): `io.println`, `io.print` and |
| 2 | +//! `io.eprintln` never block a scheduler thread. |
| 3 | +//! |
| 4 | +//! - **One writer thread** (`louise-console`) writes what actors queue, |
| 5 | +//! in the order they queued it, stdout and stderr alike, so the two |
| 6 | +//! streams interleave as the program wrote them. Each batch takes |
| 7 | +//! everything queued: consecutive stdout text goes out in one write, and |
| 8 | +//! stdout is flushed before stderr text and at the end of every batch. |
| 9 | +//! Write errors (a closed pipe) are ignored, as before: `io.println` |
| 10 | +//! cannot fail. |
| 11 | +//! - **A budget bounds what is queued** ([`BUDGET`] bytes, written or |
| 12 | +//! being written). Text that fits is queued and the call returns at |
| 13 | +//! once. Otherwise, or while other writers wait (so the order holds), |
| 14 | +//! the actor parks as in a blocking call (`Wait::Blocking`, never woken |
| 15 | +//! early) and the writer queues its text and wakes it once there is |
| 16 | +//! room. One text larger than the budget is queued when nothing else is. |
| 17 | +//! A slow console thus slows down only the actors that write to it. |
| 18 | +//! - **Where an actor cannot park** (inside a callback from C, on the |
| 19 | +//! blocking pool, or without an actor) the text is queued past the |
| 20 | +//! budget instead: these writes are rare and small, and blocking the |
| 21 | +//! thread is what this module exists to avoid. |
| 22 | +//! - **Nothing is lost at exit.** `tl_main` and `tl_main_program` wait for |
| 23 | +//! the writer once every actor stopped ([`flush`]), and so does C's |
| 24 | +//! `exit` (an `atexit` handler). The runtime's own messages (crash |
| 25 | +//! reports) are queued like `io.eprintln`, so they keep their place; a |
| 26 | +//! message printed before an abort first waits for the queue, for a |
| 27 | +//! moment at most ([`flush_before_abort`]). |
| 28 | + |
| 29 | +use std::io::Write; |
| 30 | +use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock}; |
| 31 | +use std::time::{Duration, Instant}; |
| 32 | + |
| 33 | +use crate::abi::{Ctx, UNIT}; |
| 34 | +use crate::sched::{Wait, park, this}; |
| 35 | + |
| 36 | +/// Bytes queued or being written before writers park: as much as a |
| 37 | +/// default Linux pipe holds. |
| 38 | +pub(crate) const BUDGET: usize = 64 * 1024; |
| 39 | + |
| 40 | +/// How long a message printed before an abort waits for queued output. |
| 41 | +const ABORT_WAIT: Duration = Duration::from_secs(1); |
| 42 | + |
| 43 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 44 | +pub(crate) enum Stream { |
| 45 | + Out, |
| 46 | + Err, |
| 47 | +} |
| 48 | + |
| 49 | +/// Queued text: `bytes`, cut into runs of one stream (`(stream, end)`). |
| 50 | +#[derive(Default)] |
| 51 | +struct Queue { |
| 52 | + runs: Vec<(Stream, usize)>, |
| 53 | + bytes: Vec<u8>, |
| 54 | +} |
| 55 | + |
| 56 | +impl Queue { |
| 57 | + fn push(&mut self, stream: Stream, parts: &[&[u8]]) { |
| 58 | + for part in parts { |
| 59 | + self.bytes.extend_from_slice(part); |
| 60 | + } |
| 61 | + let end = self.bytes.len(); |
| 62 | + match self.runs.last_mut() { |
| 63 | + Some((s, e)) if *s == stream => *e = end, |
| 64 | + _ => self.runs.push((stream, end)), |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + fn is_empty(&self) -> bool { |
| 69 | + self.runs.is_empty() |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +/// A write waiting for room: its text, its actor, and how to wake it. |
| 74 | +struct Waiter { |
| 75 | + stream: Stream, |
| 76 | + bytes: Vec<u8>, |
| 77 | + pid: i64, |
| 78 | + waker: Arc<mio::Waker>, |
| 79 | +} |
| 80 | + |
| 81 | +#[derive(Default)] |
| 82 | +struct State { |
| 83 | + queue: Queue, |
| 84 | + /// Bytes queued or being written. |
| 85 | + pending: usize, |
| 86 | + waiters: std::collections::VecDeque<Waiter>, |
| 87 | + /// The writer waits for work (so a write must signal it). |
| 88 | + writer_asleep: bool, |
| 89 | +} |
| 90 | + |
| 91 | +impl State { |
| 92 | + fn has_room(&self, len: usize) -> bool { |
| 93 | + self.pending == 0 || self.pending + len <= BUDGET |
| 94 | + } |
| 95 | + |
| 96 | + fn push(&mut self, stream: Stream, parts: &[&[u8]]) { |
| 97 | + self.pending += parts.iter().map(|p| p.len()).sum::<usize>(); |
| 98 | + self.queue.push(stream, parts); |
| 99 | + } |
| 100 | + |
| 101 | + /// Queue waiters, in order, while there is room; returns them, to wake. |
| 102 | + fn admit(&mut self) -> Vec<Waiter> { |
| 103 | + let mut admitted = Vec::new(); |
| 104 | + while let Some(w) = self.waiters.front() { |
| 105 | + if !self.has_room(w.bytes.len()) { |
| 106 | + break; |
| 107 | + } |
| 108 | + let w = self.waiters.pop_front().expect("a waiter"); |
| 109 | + self.push(w.stream, &[&w.bytes]); |
| 110 | + admitted.push(w); |
| 111 | + } |
| 112 | + admitted |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +struct Console { |
| 117 | + state: Mutex<State>, |
| 118 | + /// Signals the writer: there is work. |
| 119 | + work: Condvar, |
| 120 | + /// Signals `flush`: everything was written. |
| 121 | + idle: Condvar, |
| 122 | +} |
| 123 | + |
| 124 | +impl Console { |
| 125 | + fn lock(&self) -> MutexGuard<'_, State> { |
| 126 | + // Writing never panics with the lock held; recover anyway, so |
| 127 | + // output keeps working after an unrelated panic. |
| 128 | + self.state |
| 129 | + .lock() |
| 130 | + .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 131 | + } |
| 132 | + |
| 133 | + fn signal(&self, state: &mut State) { |
| 134 | + if state.writer_asleep { |
| 135 | + state.writer_asleep = false; |
| 136 | + self.work.notify_one(); |
| 137 | + } |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +static CONSOLE: OnceLock<Console> = OnceLock::new(); |
| 142 | + |
| 143 | +/// The console, starting its writer on first use. |
| 144 | +fn console() -> &'static Console { |
| 145 | + CONSOLE.get_or_init(|| { |
| 146 | + // The writer's own `console()` waits until this returns. |
| 147 | + std::thread::Builder::new() |
| 148 | + .name("louise-console".into()) |
| 149 | + .spawn(writer) |
| 150 | + .expect("louise: cannot start the console thread"); |
| 151 | + // SAFETY: `flush_at_exit` is a plain `extern "C" fn()`. |
| 152 | + unsafe { libc::atexit(flush_at_exit) }; |
| 153 | + Console { |
| 154 | + state: Mutex::new(State::default()), |
| 155 | + work: Condvar::new(), |
| 156 | + idle: Condvar::new(), |
| 157 | + } |
| 158 | + }) |
| 159 | +} |
| 160 | + |
| 161 | +/// The writer thread: write each batch, then make room for waiters. |
| 162 | +fn writer() { |
| 163 | + let console = console(); |
| 164 | + let mut batch = Queue::default(); |
| 165 | + loop { |
| 166 | + { |
| 167 | + let mut state = console.lock(); |
| 168 | + while state.queue.is_empty() { |
| 169 | + state.writer_asleep = true; |
| 170 | + state = console |
| 171 | + .work |
| 172 | + .wait(state) |
| 173 | + .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 174 | + } |
| 175 | + std::mem::swap(&mut state.queue, &mut batch); |
| 176 | + } |
| 177 | + write_batch(&batch); |
| 178 | + let written = batch.bytes.len(); |
| 179 | + batch.runs.clear(); |
| 180 | + batch.bytes.clear(); |
| 181 | + // Keep the buffer for the next batch, unless one large text grew it. |
| 182 | + if batch.bytes.capacity() > 4 * BUDGET { |
| 183 | + batch.bytes = Vec::new(); |
| 184 | + } |
| 185 | + let admitted = { |
| 186 | + let mut state = console.lock(); |
| 187 | + state.pending -= written; |
| 188 | + let admitted = state.admit(); |
| 189 | + if state.pending == 0 && state.waiters.is_empty() { |
| 190 | + console.idle.notify_all(); |
| 191 | + } |
| 192 | + admitted |
| 193 | + }; |
| 194 | + for w in admitted { |
| 195 | + crate::blocking::complete(w.pid, UNIT, &w.waker); |
| 196 | + } |
| 197 | + } |
| 198 | +} |
| 199 | + |
| 200 | +fn write_batch(batch: &Queue) { |
| 201 | + let mut out = std::io::stdout().lock(); |
| 202 | + let mut start = 0; |
| 203 | + for &(stream, end) in &batch.runs { |
| 204 | + let text = &batch.bytes[start..end]; |
| 205 | + // Errors (a closed pipe, a full disk) are ignored: printing |
| 206 | + // cannot fail. |
| 207 | + match stream { |
| 208 | + Stream::Out => { |
| 209 | + let _ = out.write_all(text); |
| 210 | + } |
| 211 | + Stream::Err => { |
| 212 | + let _ = out.flush(); |
| 213 | + let _ = std::io::stderr().lock().write_all(text); |
| 214 | + } |
| 215 | + } |
| 216 | + start = end; |
| 217 | + } |
| 218 | + let _ = out.flush(); |
| 219 | +} |
| 220 | + |
| 221 | +/// Write `parts` (one text) to `stream` from the running actor: queue it, |
| 222 | +/// or park until there is room. |
| 223 | +/// |
| 224 | +/// The console lock is never held while taking a scheduler lock. |
| 225 | +/// |
| 226 | +/// # Safety |
| 227 | +/// `ctx` must be the running actor's context, or null. |
| 228 | +pub(crate) unsafe fn write(ctx: *mut Ctx, stream: Stream, parts: &[&[u8]]) { |
| 229 | + let console = console(); |
| 230 | + let len = parts.iter().map(|p| p.len()).sum::<usize>(); |
| 231 | + // SAFETY: forwarded caller guarantee. |
| 232 | + let can_park = unsafe { can_park(ctx) }; |
| 233 | + { |
| 234 | + let mut state = console.lock(); |
| 235 | + if !can_park || (state.waiters.is_empty() && state.has_room(len)) { |
| 236 | + state.push(stream, parts); |
| 237 | + console.signal(&mut state); |
| 238 | + return; |
| 239 | + } |
| 240 | + } |
| 241 | + // Park as in a blocking call: the text is queued once there is room, |
| 242 | + // then `blocking::complete` wakes the actor. Meanwhile the scheduler |
| 243 | + // counts it among the blocking calls it waits for. |
| 244 | + // SAFETY: `can_park` checked a running actor. |
| 245 | + unsafe { |
| 246 | + let (a, sched) = this(ctx); |
| 247 | + sched.with_proc(a.pid, |p| p.park_as(Wait::Blocking)); |
| 248 | + let waker = sched.blocking_started(); |
| 249 | + let admitted = { |
| 250 | + let mut state = console.lock(); |
| 251 | + state.waiters.push_back(Waiter { |
| 252 | + stream, |
| 253 | + bytes: parts.concat(), |
| 254 | + pid: a.pid, |
| 255 | + waker, |
| 256 | + }); |
| 257 | + // Room may have appeared since the check: the writer only |
| 258 | + // admits waiters after a batch. |
| 259 | + let admitted = state.admit(); |
| 260 | + console.signal(&mut state); |
| 261 | + admitted |
| 262 | + }; |
| 263 | + for w in admitted { |
| 264 | + crate::blocking::complete(w.pid, UNIT, &w.waker); |
| 265 | + } |
| 266 | + // Woken with unit. If the actor was killed meanwhile, its text was |
| 267 | + // still queued, and the caller unwinds. |
| 268 | + park(ctx); |
| 269 | + } |
| 270 | +} |
| 271 | + |
| 272 | +/// Whether the caller is an actor that may park. |
| 273 | +/// |
| 274 | +/// # Safety |
| 275 | +/// `ctx` must be the running actor's context, or null. |
| 276 | +unsafe fn can_park(ctx: *mut Ctx) -> bool { |
| 277 | + // SAFETY: forwarded caller guarantee; `rt` is null outside actors. |
| 278 | + unsafe { |
| 279 | + !ctx.is_null() |
| 280 | + && !(*ctx).rt.is_null() |
| 281 | + && !crate::callback::on_foreign_thread() |
| 282 | + && !crate::sched::in_callback(ctx) |
| 283 | + } |
| 284 | +} |
| 285 | + |
| 286 | +/// Queue a message of the runtime's own (a crash report) on stderr, |
| 287 | +/// without waiting: it keeps its place among the program's output. |
| 288 | +pub(crate) fn diagnostic(message: &str) { |
| 289 | + let console = console(); |
| 290 | + let mut state = console.lock(); |
| 291 | + state.push(Stream::Err, &[message.as_bytes(), b"\n"]); |
| 292 | + console.signal(&mut state); |
| 293 | +} |
| 294 | + |
| 295 | +/// Wait until everything queued was written, for `limit` at most. |
| 296 | +fn wait_written(limit: Option<Duration>) { |
| 297 | + // Nothing was ever printed: no writer to wait for. |
| 298 | + let Some(console) = CONSOLE.get() else { |
| 299 | + return; |
| 300 | + }; |
| 301 | + let deadline = limit.map(|l| Instant::now() + l); |
| 302 | + let mut state = console.lock(); |
| 303 | + while state.pending > 0 || !state.waiters.is_empty() { |
| 304 | + state = match deadline { |
| 305 | + None => console |
| 306 | + .idle |
| 307 | + .wait(state) |
| 308 | + .unwrap_or_else(std::sync::PoisonError::into_inner), |
| 309 | + Some(d) => { |
| 310 | + let Some(left) = d.checked_duration_since(Instant::now()) else { |
| 311 | + return; |
| 312 | + }; |
| 313 | + console |
| 314 | + .idle |
| 315 | + .wait_timeout(state, left) |
| 316 | + .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 317 | + .0 |
| 318 | + } |
| 319 | + }; |
| 320 | + } |
| 321 | +} |
| 322 | + |
| 323 | +/// Wait until everything queued was written. Called once every actor |
| 324 | +/// stopped, so no writer is parked and nothing else is queued meanwhile. |
| 325 | +pub(crate) fn flush() { |
| 326 | + wait_written(None); |
| 327 | +} |
| 328 | + |
| 329 | +/// Before printing a message and aborting: give queued output a moment |
| 330 | +/// to go out first, without hanging on a console nobody reads. |
| 331 | +pub(crate) fn flush_before_abort() { |
| 332 | + wait_written(Some(ABORT_WAIT)); |
| 333 | +} |
| 334 | + |
| 335 | +extern "C" fn flush_at_exit() { |
| 336 | + flush(); |
| 337 | +} |
| 338 | + |
| 339 | +#[cfg(test)] |
| 340 | +mod tests { |
| 341 | + use super::{BUDGET, State, Stream, Waiter}; |
| 342 | + use std::sync::Arc; |
| 343 | + |
| 344 | + fn waiter(waker: &Arc<mio::Waker>, pid: i64, len: usize) -> Waiter { |
| 345 | + Waiter { |
| 346 | + stream: Stream::Out, |
| 347 | + bytes: vec![b'x'; len], |
| 348 | + pid, |
| 349 | + waker: waker.clone(), |
| 350 | + } |
| 351 | + } |
| 352 | + |
| 353 | + #[test] |
| 354 | + fn runs_keep_the_streams_in_order() { |
| 355 | + let mut state = State::default(); |
| 356 | + state.push(Stream::Out, &[b"a", b"\n"]); |
| 357 | + state.push(Stream::Out, &[b"b\n"]); |
| 358 | + state.push(Stream::Err, &[b"e\n"]); |
| 359 | + state.push(Stream::Out, &[b"c"]); |
| 360 | + assert_eq!(state.queue.bytes, b"a\nb\ne\nc"); |
| 361 | + assert_eq!( |
| 362 | + state.queue.runs, |
| 363 | + [(Stream::Out, 4), (Stream::Err, 6), (Stream::Out, 7)] |
| 364 | + ); |
| 365 | + assert_eq!(state.pending, 7); |
| 366 | + } |
| 367 | + |
| 368 | + #[test] |
| 369 | + fn waiters_are_admitted_in_order_when_there_is_room() { |
| 370 | + let poll = mio::Poll::new().unwrap(); |
| 371 | + // One waker per poll: the waiters share it, as they share the |
| 372 | + // scheduler's. |
| 373 | + let waker = Arc::new(mio::Waker::new(poll.registry(), mio::Token(0)).unwrap()); |
| 374 | + let mut state = State::default(); |
| 375 | + // A text larger than the budget fits when nothing is pending. |
| 376 | + assert!(state.has_room(BUDGET * 2)); |
| 377 | + state.push(Stream::Out, &[&vec![b'x'; BUDGET - 10]]); |
| 378 | + assert!(state.has_room(10)); |
| 379 | + assert!(!state.has_room(11)); |
| 380 | + state.waiters.push_back(waiter(&waker, 1, 100)); |
| 381 | + state.waiters.push_back(waiter(&waker, 2, 5)); |
| 382 | + // The first waiter does not fit, so the second waits behind it. |
| 383 | + assert!(state.admit().is_empty()); |
| 384 | + // The writer wrote the batch: both fit now, in order. |
| 385 | + state.pending = 0; |
| 386 | + let admitted: Vec<i64> = state.admit().iter().map(|w| w.pid).collect(); |
| 387 | + assert_eq!(admitted, [1, 2]); |
| 388 | + assert_eq!(state.pending, 105); |
| 389 | + // The oversized one waits for an empty queue. |
| 390 | + state.waiters.push_back(waiter(&waker, 3, BUDGET * 2)); |
| 391 | + assert!(state.admit().is_empty()); |
| 392 | + state.pending = 0; |
| 393 | + assert_eq!(state.admit().len(), 1); |
| 394 | + } |
| 395 | +} |