Skip to main content

vcon_server/
stderr.rs

1//! The one way the binary writes to stderr: its log lines and its refusals.
2//!
3//! A reader of stderr can go away while the process runs (a `serve 2>&1 |
4//! tee` whose reader ends, a log collector restarted), and every later
5//! write then fails with EPIPE. A failed write has nowhere to be reported,
6//! so [`Quiet`] drops it and answers as if it had been written. It must not
7//! panic: `eprintln!` does, and in a request's task the panic reset the
8//! request's stream, so a server whose log pipe closed answered no request;
9//! in a command it turned the exit status into 101.
10//!
11//! A reader can also stop reading and keep its end open. The pipe then
12//! fills, and a write to it waits until the reader reads. A request's task
13//! must never wait for that, so no caller writes to stderr itself: each
14//! line is put on a bounded queue ([`CAPACITY`] bytes) that one thread of
15//! its own writes out. A line that finds the queue full is dropped and
16//! counted, and once the thread can write again it writes, where those
17//! lines would have been, a line that says how many were dropped. Nothing
18//! but the log depends on this: audit records are written with the change
19//! they describe, in the catalog.
20
21use std::collections::VecDeque;
22use std::io::{self, Write};
23use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError};
24use std::time::{Duration, Instant};
25
26/// The most bytes of log lines the queue holds while the thread waits for
27/// the reader: about seven thousand request lines.
28pub const CAPACITY: usize = 1 << 20;
29
30/// How long the binary waits at exit for its last lines to be written
31/// ([`drain`]): a reader that reads gets them, one that does not cannot
32/// hold the exit longer.
33pub const EXIT_DRAIN: Duration = Duration::from_secs(2);
34
35/// A writer that passes each write to `W` and drops any error.
36#[derive(Debug)]
37pub struct Quiet<W>(pub W);
38
39/// The process's stderr queue, started on the first line.
40static STDERR: OnceLock<Sink> = OnceLock::new();
41
42fn process() -> &'static Sink {
43    STDERR.get_or_init(|| Sink::start(Quiet(io::stderr()), CAPACITY))
44}
45
46/// stderr, behind the queue: for the log's writer and for [`line()`]. A
47/// write returns at once, whether or not the reader reads.
48#[must_use]
49pub fn stderr() -> Queued {
50    process().writer()
51}
52
53/// Writes `text` and a newline to stderr, as `eprintln!` would, as one
54/// line of the queue, dropping a failure.
55pub fn line(text: &str) {
56    line_to(&mut stderr(), text);
57}
58
59/// [`line()`] onto `out`: one write, so a queue takes or drops the line
60/// whole.
61fn line_to(out: &mut impl Write, text: &str) {
62    let _ = out.write(format!("{text}\n").as_bytes());
63}
64
65/// Waits until every line queued so far is written, at most `within`:
66/// whether they were. Called before the process exits, so its last lines
67/// reach a reader that reads, and a reader that does not cannot hold the
68/// exit.
69pub fn drain(within: Duration) -> bool {
70    STDERR.get().is_none_or(|sink| sink.drain(within))
71}
72
73impl<W: Write> Write for Quiet<W> {
74    /// The length of `buf`, whether or not `W` took it: a part it did not
75    /// take is dropped with the rest, never written again.
76    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
77        let _ = self.0.write_all(buf);
78        Ok(buf.len())
79    }
80
81    fn flush(&mut self) -> io::Result<()> {
82        let _ = self.0.flush();
83        Ok(())
84    }
85}
86
87/// The line the thread writes in place of `count` dropped lines.
88fn notice(count: u64) -> String {
89    let lines = if count == 1 { "line" } else { "lines" };
90    format!("vcon-server: {count} log {lines} dropped: standard error was full\n")
91}
92
93/// One place in the queue: a line, or the lines dropped there.
94enum Entry {
95    Line(Vec<u8>),
96    Dropped(u64),
97}
98
99/// What the queue's users and its thread share.
100struct Shared {
101    state: Mutex<State>,
102    /// Signaled when an entry is queued or the sink closes.
103    ready: Condvar,
104    /// Signaled when the thread has written everything queued.
105    idle: Condvar,
106    capacity: usize,
107    out: Mutex<Box<dyn Write + Send>>,
108}
109
110struct State {
111    entries: VecDeque<Entry>,
112    /// The bytes of the lines in `entries`.
113    bytes: usize,
114    /// Whether the thread is writing an entry it took off the queue.
115    busy: bool,
116    /// The [`Sink::drain`] calls waiting for the thread.
117    draining: usize,
118    /// Lines dropped since the sink started.
119    dropped: u64,
120    /// Whether a thread writes the queue; without one, each line is
121    /// written by its caller.
122    threaded: bool,
123    closed: bool,
124}
125
126/// How a sink starts its thread: [`std::thread::Builder::spawn`], or a
127/// stand-in for a test.
128type Spawn = fn(Box<dyn FnOnce() + Send>) -> io::Result<()>;
129
130fn spawn_thread(run: Box<dyn FnOnce() + Send>) -> io::Result<()> {
131    // The process's sink is a static that lives as long as the process,
132    // and its thread with it; the exit waits for its queue with a bound
133    // (drain), never a join, because a reader that does not read must not
134    // hold the exit, and a join would wait for it. A test's sink thread
135    // ends once its sink is dropped and its queue written; it holds only
136    // that sink's writer.
137    // thread-detached: the writer of the process's stderr, see above.
138    std::thread::Builder::new()
139        .name("stderr".to_owned())
140        .spawn(run)
141        .map(drop)
142}
143
144fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
145    mutex.lock().unwrap_or_else(PoisonError::into_inner)
146}
147
148/// A bounded queue of lines for `out`, and the thread that writes them.
149/// Dropping it ends the thread once the queue is written.
150struct Sink {
151    shared: Arc<Shared>,
152}
153
154impl Sink {
155    fn start(out: impl Write + Send + 'static, capacity: usize) -> Sink {
156        Sink::start_with(out, capacity, spawn_thread)
157    }
158
159    /// [`Sink::start`] with `spawn` to start the thread. When it cannot
160    /// start one, each line is written by its caller.
161    fn start_with(out: impl Write + Send + 'static, capacity: usize, spawn: Spawn) -> Sink {
162        let shared = Arc::new(Shared {
163            state: Mutex::new(State {
164                entries: VecDeque::new(),
165                bytes: 0,
166                busy: false,
167                draining: 0,
168                dropped: 0,
169                threaded: false,
170                closed: false,
171            }),
172            ready: Condvar::new(),
173            idle: Condvar::new(),
174            capacity,
175            out: Mutex::new(Box::new(out)),
176        });
177        let threaded = {
178            let shared = shared.clone();
179            spawn(Box::new(move || shared.write_out())).is_ok()
180        };
181        lock(&shared.state).threaded = threaded;
182        Sink { shared }
183    }
184
185    fn writer(&self) -> Queued {
186        Queued(self.shared.clone())
187    }
188
189    /// Waits until the thread has written every entry queued, at most
190    /// `within`: whether it has.
191    fn drain(&self, within: Duration) -> bool {
192        let deadline = Instant::now() + within;
193        let mut state = lock(&self.shared.state);
194        while state.busy || !state.entries.is_empty() {
195            let left = deadline.saturating_duration_since(Instant::now());
196            if left.is_zero() {
197                return false;
198            }
199            state.draining += 1;
200            state = self
201                .shared
202                .idle
203                .wait_timeout(state, left)
204                .unwrap_or_else(PoisonError::into_inner)
205                .0;
206            state.draining -= 1;
207        }
208        true
209    }
210
211    #[cfg(test)]
212    fn dropped(&self) -> u64 {
213        lock(&self.shared.state).dropped
214    }
215}
216
217impl Drop for Sink {
218    fn drop(&mut self) {
219        lock(&self.shared.state).closed = true;
220        self.shared.ready.notify_all();
221    }
222}
223
224impl Shared {
225    /// Queues `buf` as one line, or counts it dropped when the queue has
226    /// no room for it.
227    fn offer(&self, buf: &[u8]) {
228        if buf.is_empty() {
229            return;
230        }
231        let mut state = lock(&self.state);
232        if !state.threaded {
233            drop(state);
234            let _ = lock(&self.out).write_all(buf);
235            return;
236        }
237        // An empty queue takes a line of any length, so a line longer than
238        // the capacity is not always dropped.
239        if state.closed || (state.bytes > 0 && state.bytes + buf.len() > self.capacity) {
240            state.dropped += 1;
241            if let Some(Entry::Dropped(count)) = state.entries.back_mut() {
242                *count += 1;
243            } else if !state.closed {
244                state.entries.push_back(Entry::Dropped(1));
245            }
246            return;
247        }
248        state.bytes += buf.len();
249        state.entries.push_back(Entry::Line(buf.to_vec()));
250        drop(state);
251        self.ready.notify_one();
252    }
253
254    /// The thread: writes each entry as it is queued, until the sink is
255    /// dropped and the queue is written.
256    fn write_out(&self) {
257        loop {
258            let entry = {
259                let mut state = lock(&self.state);
260                loop {
261                    if let Some(entry) = state.entries.pop_front() {
262                        if let Entry::Line(line) = &entry {
263                            state.bytes -= line.len();
264                        }
265                        state.busy = true;
266                        break entry;
267                    }
268                    state.busy = false;
269                    self.idle.notify_all();
270                    if state.closed {
271                        return;
272                    }
273                    state = self
274                        .ready
275                        .wait(state)
276                        .unwrap_or_else(PoisonError::into_inner);
277                }
278            };
279            let mut out = lock(&self.out);
280            let _ = match entry {
281                Entry::Line(line) => out.write_all(&line),
282                Entry::Dropped(count) => out.write_all(notice(count).as_bytes()),
283            };
284        }
285    }
286}
287
288/// A writer onto a sink's queue: each write is one line, and returns at
289/// once.
290pub struct Queued(Arc<Shared>);
291
292impl std::fmt::Debug for Queued {
293    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294        f.write_str("Queued")
295    }
296}
297
298impl Write for Queued {
299    /// The length of `buf`: it is queued, or dropped and counted.
300    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
301        self.0.offer(buf);
302        Ok(buf.len())
303    }
304
305    /// Nothing to do: the thread writes each line as it comes.
306    fn flush(&mut self) -> io::Result<()> {
307        Ok(())
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    /// The writing end of a pipe whose reading end is closed.
316    fn closed() -> io::PipeWriter {
317        let (reader, writer) = io::pipe().expect("a pipe");
318        drop(reader);
319        writer
320    }
321
322    /// A writer that fails each write with `kind`.
323    struct Failing(io::ErrorKind);
324
325    impl Write for Failing {
326        fn write(&mut self, _: &[u8]) -> io::Result<usize> {
327            Err(io::Error::from(self.0))
328        }
329        fn flush(&mut self) -> io::Result<()> {
330            Err(io::Error::from(self.0))
331        }
332    }
333
334    /// A writer that takes at most `each` bytes per write, fails with
335    /// `then` once it holds `cap` bytes, and fails once with Interrupted
336    /// first when `interrupt`.
337    struct Short {
338        got: Vec<u8>,
339        each: usize,
340        cap: usize,
341        then: io::ErrorKind,
342        interrupt: bool,
343    }
344
345    impl Short {
346        fn new(each: usize, cap: usize) -> Short {
347            Short {
348                got: Vec::new(),
349                each,
350                cap,
351                then: io::ErrorKind::BrokenPipe,
352                interrupt: false,
353            }
354        }
355    }
356
357    impl Write for Short {
358        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
359            if std::mem::take(&mut self.interrupt) {
360                return Err(io::Error::from(io::ErrorKind::Interrupted));
361            }
362            if self.got.len() >= self.cap {
363                return Err(io::Error::from(self.then));
364            }
365            let n = buf.len().min(self.each).min(self.cap - self.got.len());
366            self.got.extend_from_slice(&buf[..n]);
367            Ok(n)
368        }
369        fn flush(&mut self) -> io::Result<()> {
370            Ok(())
371        }
372    }
373
374    // Success.
375
376    #[test]
377    fn short_writes_deliver_every_byte() {
378        let mut out = Quiet(Short::new(3, usize::MAX));
379        assert_eq!(
380            out.write(b"a log line\n").expect("no error"),
381            11,
382            "all of it"
383        );
384        assert_eq!(out.0.got, b"a log line\n", "taken three bytes at a time");
385    }
386
387    #[test]
388    fn a_write_reaches_the_writer() {
389        let mut out = Quiet(Vec::new());
390        out.write_all(b"a log line\n").expect("written");
391        assert_eq!(out.0, b"a log line\n", "the bytes as given");
392    }
393
394    #[test]
395    fn a_write_to_an_open_pipe_is_read_back() {
396        use std::io::Read;
397        let (mut reader, writer) = io::pipe().expect("a pipe");
398        let mut out = Quiet(writer);
399        out.write_all(b"serving\n").expect("written");
400        drop(out);
401        let mut read = String::new();
402        reader.read_to_string(&mut read).expect("read");
403        assert_eq!(read, "serving\n", "the reader gets the line");
404    }
405
406    #[test]
407    fn a_line_longer_than_a_pipe_reaches_the_writer_whole() {
408        let long = vec![b'x'; 70_000];
409        let mut out = Quiet(Vec::new());
410        out.write_all(&long).expect("written");
411        assert_eq!(out.0.len(), 70_000, "every byte");
412    }
413
414    #[test]
415    fn two_writes_reach_the_writer_in_order() {
416        let mut out = Quiet(Vec::new());
417        writeln!(out, "serving").expect("written");
418        writeln!(out, "stopped").expect("written");
419        assert_eq!(out.0, b"serving\nstopped\n", "in the order written");
420    }
421
422    #[test]
423    fn a_flush_reaches_the_writer() {
424        let mut out = Quiet(Vec::new());
425        out.flush().expect("flushed");
426        assert!(out.0.is_empty(), "nothing written by a flush");
427    }
428
429    // Failure.
430
431    #[test]
432    fn a_write_to_a_closed_pipe_is_dropped() {
433        let mut out = Quiet(closed());
434        assert_eq!(
435            out.write(b"a log line\n").expect("no error"),
436            11,
437            "answered as written"
438        );
439    }
440
441    #[test]
442    fn write_all_to_a_closed_pipe_is_not_an_error() {
443        let mut out = Quiet(closed());
444        assert!(
445            out.write_all(b"vcon-server: refused\n").is_ok(),
446            "no error to report"
447        );
448    }
449
450    #[test]
451    fn a_flush_of_a_failing_writer_is_not_an_error() {
452        let mut out = Quiet(Failing(io::ErrorKind::BrokenPipe));
453        assert!(out.flush().is_ok(), "no error to report");
454    }
455
456    #[test]
457    fn any_kind_of_write_error_is_dropped() {
458        for kind in [
459            io::ErrorKind::BrokenPipe,
460            io::ErrorKind::WriteZero,
461            io::ErrorKind::Other,
462        ] {
463            let mut out = Quiet(Failing(kind));
464            assert!(out.write_all(b"x").is_ok(), "{kind:?} dropped");
465        }
466    }
467
468    // Edge.
469
470    #[test]
471    fn a_write_cut_off_part_way_answers_its_whole_length() {
472        let mut out = Quiet(Short::new(4, 6));
473        assert_eq!(
474            out.write(b"serving now\n").expect("no error"),
475            12,
476            "the whole line"
477        );
478        assert_eq!(out.0.got, b"servin", "the part taken before the failure");
479        assert_eq!(
480            out.write(b"x").expect("no error"),
481            1,
482            "and the next write too"
483        );
484        assert_eq!(out.0.got, b"servin", "nothing more taken");
485    }
486
487    #[test]
488    fn an_interrupted_write_is_tried_again() {
489        let mut short = Short::new(usize::MAX, usize::MAX);
490        short.interrupt = true;
491        let mut out = Quiet(short);
492        assert_eq!(out.write(b"stopped\n").expect("no error"), 8, "written");
493        assert_eq!(out.0.got, b"stopped\n", "after the interruption");
494    }
495
496    #[test]
497    fn an_empty_write_is_zero_bytes() {
498        let mut out = Quiet(closed());
499        assert_eq!(out.write(b"").expect("no error"), 0, "nothing to write");
500    }
501
502    #[test]
503    fn writeln_to_a_closed_pipe_does_not_panic() {
504        let mut out = Quiet(closed());
505        assert!(
506            writeln!(out, "{}", "x".repeat(70_000)).is_ok(),
507            "a line past a pipe's buffer"
508        );
509    }
510
511    #[test]
512    fn line_writes_to_the_process_stderr_without_an_error() {
513        // The test harness holds stderr open; the call returns.
514        line("stderr::line test");
515    }
516
517    // ---- The queue and its thread. ----
518
519    /// How long a test waits for the thread before it fails.
520    const WAIT: Duration = Duration::from_secs(10);
521
522    /// A writer whose bytes the test reads back.
523    #[derive(Clone, Default)]
524    struct Collect(Arc<Mutex<Vec<u8>>>);
525
526    impl Collect {
527        fn text(&self) -> String {
528            String::from_utf8_lossy(&lock(&self.0)).into_owned()
529        }
530    }
531
532    impl Write for Collect {
533        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
534            lock(&self.0).extend_from_slice(buf);
535            Ok(buf.len())
536        }
537        fn flush(&mut self) -> io::Result<()> {
538            Ok(())
539        }
540    }
541
542    /// A writer that holds each write until the test opens it, and says
543    /// when a write has begun: the thread, stopped inside a write, as on a
544    /// full pipe.
545    #[derive(Clone)]
546    struct Gate {
547        got: Collect,
548        open: Arc<(Mutex<bool>, Condvar)>,
549        began: Arc<Mutex<std::sync::mpsc::Sender<()>>>,
550    }
551
552    impl Gate {
553        /// A closed gate, and the receiver that hears each write begin.
554        fn new() -> (Gate, std::sync::mpsc::Receiver<()>) {
555            let (tx, rx) = std::sync::mpsc::channel();
556            let gate = Gate {
557                got: Collect::default(),
558                open: Arc::new((Mutex::new(false), Condvar::new())),
559                began: Arc::new(Mutex::new(tx)),
560            };
561            (gate, rx)
562        }
563
564        fn set(&self, open: bool) {
565            *lock(&self.open.0) = open;
566            self.open.1.notify_all();
567        }
568    }
569
570    impl Write for Gate {
571        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
572            let _ = lock(&self.began).send(());
573            let (open, changed) = &*self.open;
574            let mut is_open = lock(open);
575            while !*is_open {
576                is_open = changed
577                    .wait(is_open)
578                    .unwrap_or_else(PoisonError::into_inner);
579            }
580            drop(is_open);
581            self.got.write(buf)
582        }
583        fn flush(&mut self) -> io::Result<()> {
584            Ok(())
585        }
586    }
587
588    /// A sink on a closed gate whose thread is inside the write of
589    /// `first`: what is offered from here on waits in the queue.
590    fn stopped_sink(capacity: usize, first: &[u8]) -> (Sink, Gate) {
591        let (gate, began) = Gate::new();
592        let sink = Sink::start(gate.clone(), capacity);
593        sink.writer().write_all(first).expect("queued");
594        began
595            .recv_timeout(WAIT)
596            .expect("the thread begins to write the first line");
597        (sink, gate)
598    }
599
600    fn offer(sink: &Sink, line: &str) {
601        let mut out = sink.writer();
602        assert_eq!(
603            out.write(line.as_bytes()).expect("never an error"),
604            line.len(),
605            "a write answers its whole length"
606        );
607    }
608
609    /// A spawn that always fails, as when the process may start no thread.
610    fn no_thread(_: Box<dyn FnOnce() + Send>) -> io::Result<()> {
611        Err(io::Error::from(io::ErrorKind::WouldBlock))
612    }
613
614    /// Runs `f` on a thread of its own and fails if it takes past `WAIT`.
615    fn within_wait(f: impl FnOnce() + Send + 'static) {
616        let (tx, rx) = std::sync::mpsc::channel();
617        let runner = std::thread::spawn(move || {
618            f();
619            let _ = tx.send(());
620        });
621        rx.recv_timeout(WAIT)
622            .expect("returns without waiting for the reader");
623        // The thread has sent, so it is at its end: wait for it, so no
624        // test leaves a thread running past its own end.
625        runner.join().expect("the thread ends");
626    }
627
628    // Success.
629
630    #[test]
631    fn a_line_offered_reaches_the_writer() {
632        let got = Collect::default();
633        let sink = Sink::start(got.clone(), CAPACITY);
634        offer(&sink, "serving\n");
635        assert!(sink.drain(WAIT), "written within the wait");
636        assert_eq!(got.text(), "serving\n", "the line as offered");
637    }
638
639    #[test]
640    fn lines_reach_the_writer_in_the_order_offered() {
641        let got = Collect::default();
642        let sink = Sink::start(got.clone(), CAPACITY);
643        let want: String = (0..100).map(|i| format!("line {i}\n")).collect();
644        for i in 0..100 {
645            offer(&sink, &format!("line {i}\n"));
646        }
647        assert!(sink.drain(WAIT), "written within the wait");
648        assert_eq!(got.text(), want, "in order, none lost");
649    }
650
651    #[test]
652    fn drain_returns_once_every_line_is_written() {
653        let got = Collect::default();
654        let sink = Sink::start(got.clone(), CAPACITY);
655        for _ in 0..1000 {
656            offer(&sink, "x\n");
657        }
658        assert!(sink.drain(WAIT), "drained");
659        assert_eq!(
660            got.text().len(),
661            2000,
662            "every line written when drain returns"
663        );
664    }
665
666    #[test]
667    fn drain_returns_when_the_writer_finishes_not_at_its_time() {
668        let (sink, gate) = stopped_sink(CAPACITY, b"first\n");
669        let sink = Arc::new(sink);
670        let (done_tx, done) = std::sync::mpsc::channel();
671        let draining = std::thread::spawn({
672            let sink = sink.clone();
673            move || {
674                let _ = done_tx.send(sink.drain(WAIT * 30));
675            }
676        });
677        // Opened only once the drain waits, so it must be woken.
678        let deadline = Instant::now() + WAIT;
679        while lock(&sink.shared.state).draining == 0 {
680            assert!(Instant::now() < deadline, "the drain begins to wait");
681            std::thread::yield_now();
682        }
683        gate.set(true);
684        assert!(
685            done.recv_timeout(WAIT)
686                .expect("drain returns once the line is written"),
687            "drained"
688        );
689        draining.join().expect("the draining thread ends");
690        assert_eq!(
691            Arc::strong_count(&sink),
692            1,
693            "the draining thread has ended and dropped its clone of the sink"
694        );
695    }
696
697    #[test]
698    fn drain_with_nothing_offered_returns_true_at_once() {
699        let sink = Sink::start(Collect::default(), CAPACITY);
700        let began = Instant::now();
701        assert!(sink.drain(WAIT), "nothing to wait for");
702        assert!(began.elapsed() < WAIT, "at once: {:?}", began.elapsed());
703    }
704
705    #[test]
706    fn lines_of_many_threads_all_arrive_whole() {
707        let got = Collect::default();
708        let sink = Arc::new(Sink::start(got.clone(), CAPACITY));
709        let threads: Vec<_> = (0..8)
710            .map(|t| {
711                let sink = sink.clone();
712                std::thread::spawn(move || {
713                    for i in 0..100 {
714                        offer(&sink, &format!("thread {t} line {i}\n"));
715                    }
716                })
717            })
718            .collect();
719        for thread in threads {
720            thread.join().expect("each thread offers its lines");
721        }
722        assert!(sink.drain(WAIT), "drained");
723        let text = got.text();
724        assert_eq!(text.lines().count(), 800, "every line");
725        for t in 0..8 {
726            let mine: Vec<&str> = text
727                .lines()
728                .filter(|l| l.starts_with(&format!("thread {t} ")))
729                .collect();
730            let want: Vec<String> = (0..100).map(|i| format!("thread {t} line {i}")).collect();
731            assert_eq!(mine, want, "thread {t}'s lines whole and in its order");
732        }
733    }
734
735    #[test]
736    fn the_count_of_dropped_lines_is_written_where_they_were_lost() {
737        let (sink, gate) = stopped_sink(8, b"first\n");
738        offer(&sink, "second\n");
739        offer(&sink, "lost 1\n");
740        offer(&sink, "lost 2\n");
741        gate.set(true);
742        assert!(sink.drain(WAIT), "drained");
743        offer(&sink, "after\n");
744        assert!(sink.drain(WAIT), "drained");
745        assert_eq!(
746            gate.got.text(),
747            format!("first\nsecond\n{}after\n", notice(2)),
748            "the count sits between the last line kept and the next"
749        );
750    }
751
752    #[test]
753    fn a_reader_that_reads_again_gets_the_lines_after_the_drops() {
754        use std::io::Read;
755        let (mut reader, writer) = io::pipe().expect("a pipe");
756        let sink = Sink::start(Quiet(writer), 4096);
757        let line = format!("{}\n", "x".repeat(99));
758        within_wait({
759            let mut out = sink.writer();
760            move || {
761                for _ in 0..5000 {
762                    let _ = out.write(line.as_bytes());
763                }
764            }
765        });
766        assert!(sink.dropped() > 0, "a pipe never read drops lines");
767        // The reader reads again, on a thread of its own, to the end.
768        let (read_tx, read_rx) = std::sync::mpsc::channel();
769        let reading = std::thread::spawn(move || {
770            let mut read = Vec::new();
771            let _ = reader.read_to_end(&mut read);
772            let _ = read_tx.send(read);
773        });
774        assert!(sink.drain(WAIT), "the queue drains once the reader reads");
775        offer(&sink, "after\n");
776        drop(sink);
777        let read = read_rx
778            .recv_timeout(WAIT)
779            .expect("the pipe ends once the sink is dropped");
780        reading.join().expect("the reading thread ends");
781        let text = String::from_utf8_lossy(&read);
782        assert!(
783            text.contains("log lines dropped"),
784            "the count is read: {}",
785            text.len()
786        );
787        assert!(text.ends_with("after\n"), "and the line after the drops");
788    }
789
790    #[test]
791    fn line_queues_the_text_and_a_newline_as_one_line() {
792        // 7 bytes of room: "refused" and then "\n" as two writes would
793        // drop the newline; "refused\n" as one is taken by the empty queue.
794        let (sink, gate) = stopped_sink(7, b"first\n");
795        line_to(&mut sink.writer(), "refused");
796        assert_eq!(sink.dropped(), 0, "the line is taken whole");
797        line_to(&mut sink.writer(), "again");
798        assert_eq!(sink.dropped(), 1, "and the next finds no room");
799        gate.set(true);
800        assert!(sink.drain(WAIT), "drained");
801        assert_eq!(
802            gate.got.text(),
803            format!("first\nrefused\n{}", notice(1)),
804            "the line and the count"
805        );
806    }
807
808    #[test]
809    fn the_queued_writer_answers_each_write_with_its_whole_length() {
810        let (sink, gate) = stopped_sink(4, b"first\n");
811        let mut out = sink.writer();
812        for line in ["fits", "dropped", ""] {
813            assert_eq!(
814                out.write(line.as_bytes()).expect("never an error"),
815                line.len(),
816                "{line:?} answered whole"
817            );
818        }
819        gate.set(true);
820    }
821
822    #[test]
823    fn a_flush_of_the_queued_writer_returns_at_once() {
824        let (sink, gate) = stopped_sink(CAPACITY, b"first\n");
825        offer(&sink, "queued\n");
826        within_wait({
827            let mut out = sink.writer();
828            move || out.flush().expect("never an error")
829        });
830        gate.set(true);
831        assert!(sink.drain(WAIT), "drained");
832        assert_eq!(gate.got.text(), "first\nqueued\n", "a flush adds nothing");
833    }
834
835    #[test]
836    fn tracing_events_reach_the_writer_as_lines() {
837        let got = Collect::default();
838        let sink = Arc::new(Sink::start(got.clone(), CAPACITY));
839        let make = {
840            let sink = sink.clone();
841            move || sink.writer()
842        };
843        let subscriber = tracing_subscriber::fmt()
844            .with_writer(make)
845            .without_time()
846            .with_target(false)
847            .log_internal_errors(false)
848            .finish();
849        tracing::subscriber::with_default(subscriber, || {
850            tracing::info!("serving");
851            tracing::warn!(count = 2, "two");
852        });
853        assert!(sink.drain(WAIT), "drained");
854        assert_eq!(
855            got.text(),
856            " INFO serving\n WARN two count=2\n",
857            "one line per event"
858        );
859    }
860
861    #[test]
862    fn the_process_queue_drains_what_line_wrote() {
863        line("stderr::drain test");
864        assert!(drain(WAIT), "the harness reads stderr, so it drains");
865    }
866
867    // Failure.
868
869    #[test]
870    fn a_write_to_a_pipe_never_read_returns_at_once() {
871        let (reader, writer) = io::pipe().expect("a pipe");
872        let sink = Sink::start(Quiet(writer), 4096);
873        let mut out = sink.writer();
874        within_wait(move || {
875            for _ in 0..10_000 {
876                let _ = out.write(b"a line of the log that nobody reads\n");
877            }
878        });
879        drop(reader);
880    }
881
882    #[test]
883    fn lines_that_find_the_queue_full_are_counted() {
884        let (sink, gate) = stopped_sink(10, b"first\n");
885        for _ in 0..12 {
886            offer(&sink, "12345\n");
887        }
888        assert_eq!(sink.dropped(), 11, "one fits in 10 bytes, 11 do not");
889        gate.set(true);
890    }
891
892    #[test]
893    fn the_queue_holds_no_more_than_its_capacity() {
894        let (sink, gate) = stopped_sink(1000, b"first\n");
895        let line = format!("{}\n", "x".repeat(99));
896        for _ in 0..50 {
897            offer(&sink, &line);
898        }
899        assert_eq!(sink.dropped(), 40, "ten 100-byte lines fit in 1000");
900        gate.set(true);
901        assert!(sink.drain(WAIT), "drained");
902        assert_eq!(
903            gate.got.text(),
904            format!("first\n{}{}", line.repeat(10), notice(40)),
905            "the ten kept and the count"
906        );
907    }
908
909    #[test]
910    fn one_dropped_line_is_named_in_the_singular() {
911        assert_eq!(
912            notice(1),
913            "vcon-server: 1 log line dropped: standard error was full\n",
914            "one line"
915        );
916    }
917
918    #[test]
919    fn more_dropped_lines_are_named_in_the_plural() {
920        assert_eq!(
921            notice(2),
922            "vcon-server: 2 log lines dropped: standard error was full\n",
923            "two lines"
924        );
925    }
926
927    #[test]
928    fn a_writer_that_fails_every_write_does_not_stop_the_queue() {
929        let sink = Sink::start(Quiet(Failing(io::ErrorKind::BrokenPipe)), 64);
930        for _ in 0..100 {
931            offer(&sink, "x\n");
932        }
933        assert!(sink.drain(WAIT), "drained though each write failed");
934    }
935
936    #[test]
937    fn a_closed_pipe_drops_each_line_and_drains() {
938        let sink = Sink::start(Quiet(closed()), CAPACITY);
939        for _ in 0..1000 {
940            offer(&sink, "a log line\n");
941        }
942        assert!(sink.drain(WAIT), "drained onto a closed pipe");
943    }
944
945    #[test]
946    fn drain_gives_up_at_its_time_while_the_writer_waits() {
947        let (sink, gate) = stopped_sink(CAPACITY, b"first\n");
948        let began = Instant::now();
949        assert!(
950            !sink.drain(Duration::from_millis(200)),
951            "not drained while the writer waits"
952        );
953        let took = began.elapsed();
954        assert!(
955            took >= Duration::from_millis(200) && took < WAIT,
956            "it waited its time and no longer: {took:?}"
957        );
958        gate.set(true);
959    }
960
961    #[test]
962    fn a_sink_whose_thread_cannot_start_writes_each_line_itself() {
963        let got = Collect::default();
964        let sink = Sink::start_with(got.clone(), CAPACITY, no_thread);
965        offer(&sink, "serving\n");
966        assert_eq!(got.text(), "serving\n", "written before the write returns");
967        assert!(sink.drain(Duration::ZERO), "nothing is left queued");
968    }
969
970    #[test]
971    fn a_sink_whose_thread_cannot_start_drops_nothing() {
972        let got = Collect::default();
973        let sink = Sink::start_with(got.clone(), 4, no_thread);
974        for _ in 0..10 {
975            offer(&sink, "longer than four\n");
976        }
977        assert_eq!(sink.dropped(), 0, "no queue to fill");
978        assert_eq!(got.text().lines().count(), 10, "each line written");
979    }
980
981    #[test]
982    fn lines_offered_after_the_sink_closed_are_dropped_and_counted() {
983        let got = Collect::default();
984        let sink = Sink::start(got.clone(), CAPACITY);
985        let mut out = sink.writer();
986        assert!(sink.drain(WAIT), "drained");
987        drop(sink);
988        assert_eq!(out.write(b"late\n").expect("never an error"), 5, "answered");
989        assert_eq!(lock(&out.0.state).dropped, 1, "counted as dropped");
990        assert!(lock(&out.0.state).entries.is_empty(), "never queued");
991    }
992
993    #[test]
994    fn a_failing_flush_does_not_stop_the_queue() {
995        struct BadFlush(Collect);
996        impl Write for BadFlush {
997            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
998                self.0.write(buf)
999            }
1000            fn flush(&mut self) -> io::Result<()> {
1001                Err(io::Error::from(io::ErrorKind::BrokenPipe))
1002            }
1003        }
1004        let got = Collect::default();
1005        let sink = Sink::start(Quiet(BadFlush(got.clone())), CAPACITY);
1006        offer(&sink, "one\n");
1007        offer(&sink, "two\n");
1008        assert!(sink.drain(WAIT), "drained");
1009        assert_eq!(got.text(), "one\ntwo\n", "both written");
1010    }
1011
1012    #[test]
1013    fn a_short_writer_gets_each_line_whole_from_the_thread() {
1014        #[derive(Clone)]
1015        struct Threes(Collect);
1016        impl Write for Threes {
1017            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1018                let n = buf.len().min(3);
1019                self.0.write(&buf[..n])
1020            }
1021            fn flush(&mut self) -> io::Result<()> {
1022                Ok(())
1023            }
1024        }
1025        let got = Collect::default();
1026        let sink = Sink::start(Quiet(Threes(got.clone())), CAPACITY);
1027        offer(&sink, "a log line\n");
1028        assert!(sink.drain(WAIT), "drained");
1029        assert_eq!(got.text(), "a log line\n", "three bytes at a time, whole");
1030    }
1031
1032    #[test]
1033    fn a_line_cut_off_by_a_failing_writer_is_not_written_again() {
1034        #[derive(Clone)]
1035        struct CutAt(Collect, usize);
1036        impl Write for CutAt {
1037            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1038                let have = lock(&(self.0).0).len();
1039                if have >= self.1 {
1040                    return Err(io::Error::from(io::ErrorKind::BrokenPipe));
1041                }
1042                let n = buf.len().min(self.1 - have);
1043                self.0.write(&buf[..n])
1044            }
1045            fn flush(&mut self) -> io::Result<()> {
1046                Ok(())
1047            }
1048        }
1049        let got = Collect::default();
1050        let sink = Sink::start(Quiet(CutAt(got.clone(), 6)), CAPACITY);
1051        offer(&sink, "serving now\n");
1052        offer(&sink, "stopped\n");
1053        assert!(sink.drain(WAIT), "drained");
1054        assert_eq!(got.text(), "servin", "the part taken, once");
1055    }
1056
1057    // Edge.
1058
1059    #[test]
1060    fn an_empty_write_is_neither_queued_nor_counted() {
1061        let (sink, gate) = stopped_sink(0, b"first\n");
1062        offer(&sink, "");
1063        assert_eq!(sink.dropped(), 0, "nothing to drop");
1064        assert!(
1065            lock(&sink.shared.state).entries.is_empty(),
1066            "nothing queued"
1067        );
1068        gate.set(true);
1069    }
1070
1071    #[test]
1072    fn a_line_of_exactly_the_free_room_is_queued() {
1073        let (sink, gate) = stopped_sink(12, b"first\n");
1074        offer(&sink, "12345\n");
1075        offer(&sink, "abcde\n");
1076        assert_eq!(sink.dropped(), 0, "6 and 6 bytes fill 12");
1077        gate.set(true);
1078    }
1079
1080    #[test]
1081    fn a_line_one_byte_past_the_free_room_is_dropped() {
1082        let (sink, gate) = stopped_sink(12, b"first\n");
1083        offer(&sink, "12345\n");
1084        offer(&sink, "abcdef\n");
1085        assert_eq!(sink.dropped(), 1, "6 and 7 bytes do not fit in 12");
1086        gate.set(true);
1087    }
1088
1089    #[test]
1090    fn a_line_longer_than_the_capacity_is_queued_when_the_queue_is_empty() {
1091        let (sink, gate) = stopped_sink(4, b"first\n");
1092        offer(&sink, "longer than four\n");
1093        assert_eq!(
1094            sink.dropped(),
1095            0,
1096            "an empty queue takes one line of any length"
1097        );
1098        offer(&sink, "x\n");
1099        assert_eq!(sink.dropped(), 1, "and then has no room");
1100        gate.set(true);
1101        assert!(sink.drain(WAIT), "drained");
1102        assert_eq!(
1103            gate.got.text(),
1104            format!("first\nlonger than four\n{}", notice(1)),
1105            "the long line whole"
1106        );
1107    }
1108
1109    #[test]
1110    fn a_zero_capacity_queues_one_line_at_a_time() {
1111        let (sink, gate) = stopped_sink(0, b"first\n");
1112        offer(&sink, "one\n");
1113        offer(&sink, "two\n");
1114        assert_eq!(sink.dropped(), 1, "only one waits");
1115        gate.set(true);
1116    }
1117
1118    #[test]
1119    fn the_capacity_is_counted_in_bytes_not_lines() {
1120        let (sink, gate) = stopped_sink(100, b"first\n");
1121        for _ in 0..50 {
1122            offer(&sink, "x\n");
1123        }
1124        assert_eq!(sink.dropped(), 0, "fifty 2-byte lines fill 100 bytes");
1125        offer(&sink, "x\n");
1126        assert_eq!(sink.dropped(), 1, "the fifty-first does not fit");
1127        gate.set(true);
1128    }
1129
1130    #[test]
1131    fn drops_in_two_runs_are_counted_twice_where_each_happened() {
1132        let (gate, began) = Gate::new();
1133        let sink = Sink::start(gate.clone(), 6);
1134        offer(&sink, "first\n");
1135        began.recv_timeout(WAIT).expect("the first write begins");
1136        offer(&sink, "kept1\n");
1137        offer(&sink, "lost\n");
1138        gate.set(true);
1139        assert!(sink.drain(WAIT), "drained");
1140        gate.set(false);
1141        while began.try_recv().is_ok() {}
1142        offer(&sink, "next\n");
1143        began.recv_timeout(WAIT).expect("the write of next begins");
1144        offer(&sink, "kept2\n");
1145        offer(&sink, "lost\n");
1146        offer(&sink, "lost\n");
1147        gate.set(true);
1148        assert!(sink.drain(WAIT), "drained");
1149        assert_eq!(
1150            gate.got.text(),
1151            format!("first\nkept1\n{}next\nkept2\n{}", notice(1), notice(2)),
1152            "each run's count where its lines were lost"
1153        );
1154        assert_eq!(sink.dropped(), 3, "every drop in the total");
1155    }
1156
1157    #[test]
1158    fn a_drain_after_drops_waits_for_the_count_to_be_written() {
1159        let (sink, gate) = stopped_sink(1, b"first\n");
1160        offer(&sink, "a\n");
1161        offer(&sink, "b\n");
1162        gate.set(true);
1163        assert!(sink.drain(WAIT), "drained");
1164        assert!(
1165            gate.got.text().ends_with(&notice(1)),
1166            "the count is written before drain returns: {:?}",
1167            gate.got.text()
1168        );
1169    }
1170
1171    #[test]
1172    fn a_line_without_a_newline_is_written_as_given() {
1173        let got = Collect::default();
1174        let sink = Sink::start(got.clone(), CAPACITY);
1175        offer(&sink, "no newline");
1176        assert!(sink.drain(WAIT), "drained");
1177        assert_eq!(got.text(), "no newline", "the bytes as given");
1178    }
1179
1180    #[test]
1181    fn bytes_that_are_not_utf8_are_written_as_given() {
1182        let got = Collect::default();
1183        let sink = Sink::start(got.clone(), CAPACITY);
1184        sink.writer()
1185            .write_all(&[0xff, 0xfe, b'\n'])
1186            .expect("queued");
1187        assert!(sink.drain(WAIT), "drained");
1188        assert_eq!(*lock(&got.0), vec![0xff, 0xfe, b'\n'], "byte for byte");
1189    }
1190
1191    #[test]
1192    fn the_count_is_one_whole_line() {
1193        for count in [1, 2, 7, 1_000_000, u64::MAX] {
1194            let text = notice(count);
1195            assert!(text.starts_with("vcon-server: "), "{count}: {text:?}");
1196            assert!(text.ends_with('\n'), "{count}: {text:?}");
1197            assert_eq!(text.matches('\n').count(), 1, "{count}: one line");
1198            assert!(
1199                text.contains(&count.to_string()),
1200                "{count}: names the count"
1201            );
1202        }
1203    }
1204
1205    #[test]
1206    fn the_thread_ends_when_the_sink_is_dropped() {
1207        struct Dropped(std::sync::mpsc::Sender<()>);
1208        impl Write for Dropped {
1209            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1210                Ok(buf.len())
1211            }
1212            fn flush(&mut self) -> io::Result<()> {
1213                Ok(())
1214            }
1215        }
1216        impl Drop for Dropped {
1217            fn drop(&mut self) {
1218                let _ = self.0.send(());
1219            }
1220        }
1221        let (tx, rx) = std::sync::mpsc::channel();
1222        let sink = Sink::start(Dropped(tx), CAPACITY);
1223        offer(&sink, "one\n");
1224        drop(sink);
1225        rx.recv_timeout(WAIT)
1226            .expect("the thread ends and the writer with it");
1227    }
1228
1229    #[test]
1230    fn drain_of_a_process_that_never_wrote_starts_no_thread() {
1231        // The process queue is shared by these tests, so this asserts only
1232        // that the call returns at once and true when nothing waits.
1233        let began = Instant::now();
1234        assert!(drain(WAIT), "nothing waits");
1235        assert!(began.elapsed() < WAIT, "at once");
1236    }
1237}