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