tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

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