troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
use std::{
    fmt,
    io::{self, Write},
    sync::{
        Arc, OnceLock,
        atomic::{AtomicUsize, Ordering},
        mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError},
    },
    thread,
    time::Duration,
};

const LOG_QUEUE_CAPACITY: usize = 128;
const LOG_RECEIVE_TIMEOUT: Duration = Duration::from_secs(1);
const LOG_WRITE_RETRY_INTERVAL: Duration = Duration::from_millis(10);
const LOG_FLUSH_TIMEOUT: Duration = Duration::from_millis(100);

#[derive(Clone)]
pub(super) struct Logger {
    lines: SyncSender<String>,
    dropped: Arc<AtomicUsize>,
}

pub(super) struct LogDrain {
    closing: Arc<OnceLock<String>>,
    finished: Receiver<()>,
}

impl Logger {
    pub(super) fn start(mut writer: impl Write + Send + 'static) -> io::Result<(Self, LogDrain)> {
        let (lines, pending) = mpsc::sync_channel::<String>(LOG_QUEUE_CAPACITY);
        let (done, finished) = mpsc::channel();
        let dropped = Arc::new(AtomicUsize::new(0));
        let closing = Arc::new(OnceLock::<String>::new());
        let worker_dropped = dropped.clone();
        let worker_closing = closing.clone();
        thread::Builder::new()
            .name("troll-serve-log".into())
            .spawn(move || -> io::Result<()> {
                loop {
                    match pending.recv_timeout(LOG_RECEIVE_TIMEOUT) {
                        Ok(line) => write_log(&mut writer, line.as_bytes())?,
                        Err(RecvTimeoutError::Timeout) => {}
                        Err(RecvTimeoutError::Disconnected) => break,
                    }
                    report_dropped(&mut writer, &worker_dropped)?;
                }
                report_dropped(&mut writer, &worker_dropped)?;
                if let Some(line) = worker_closing.get() {
                    write_log(&mut writer, line.as_bytes())?;
                }
                writer.flush()?;
                let _ = done.send(());
                Ok(())
            })?;
        Ok((Self { lines, dropped }, LogDrain { closing, finished }))
    }

    pub(super) fn line(&self, args: fmt::Arguments<'_>) {
        if let Err(TrySendError::Full(_)) = self.lines.try_send(format!("{args}\n")) {
            self.dropped.fetch_add(1, Ordering::Relaxed);
        }
    }
}

fn report_dropped(writer: &mut impl Write, dropped: &AtomicUsize) -> io::Result<()> {
    let count = dropped.swap(0, Ordering::Relaxed);
    if count != 0 {
        write_log(
            writer,
            format!("troll serve dropped {count} log lines\n").as_bytes(),
        )?;
    }
    Ok(())
}

fn write_log(writer: &mut impl Write, mut bytes: &[u8]) -> io::Result<()> {
    while !bytes.is_empty() {
        match writer.write(bytes) {
            Ok(0) => return Err(io::ErrorKind::WriteZero.into()),
            Ok(written) => bytes = &bytes[written..],
            Err(error)
                if matches!(
                    error.kind(),
                    io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
                ) =>
            {
                thread::sleep(LOG_WRITE_RETRY_INTERVAL);
            }
            Err(error) => return Err(error),
        }
    }
    Ok(())
}

impl LogDrain {
    // Closing diagnostics have a separate slot so queue pressure cannot discard them.
    pub(super) fn set_closing(&self, args: fmt::Arguments<'_>) {
        let _ = self.closing.set(format!("{args}\n"));
    }

    pub(super) fn wait(self) {
        // A blocked stderr must not keep the process alive after HTTP has stopped.
        let _ = self.finished.recv_timeout(LOG_FLUSH_TIMEOUT);
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Mutex, mpsc::Sender};

    use super::*;

    const WAIT: Duration = Duration::from_secs(5);

    struct BlockedWriter {
        gate: Option<(Sender<()>, Receiver<()>)>,
        output: Arc<Mutex<Vec<u8>>>,
    }

    impl Write for BlockedWriter {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            if let Some((entered, resume)) = self.gate.take() {
                entered.send(()).unwrap();
                resume.recv().unwrap();
            }
            self.output.lock().unwrap().write(bytes)
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn stalled_writer_drops_full_queue_lines_and_reports_the_count_on_recovery() {
        let (entered, writing) = mpsc::channel();
        let (resume, blocked) = mpsc::channel();
        let output = Arc::new(Mutex::new(Vec::new()));
        let (log, drain) = Logger::start(BlockedWriter {
            gate: Some((entered, blocked)),
            output: output.clone(),
        })
        .unwrap();

        log.line(format_args!("first"));
        writing.recv_timeout(WAIT).unwrap();
        let (sent, queued) = mpsc::channel();
        let producer = thread::spawn(move || {
            for i in 0..LOG_QUEUE_CAPACITY {
                log.line(format_args!("queued {i}"));
            }
            log.line(format_args!("dropped first"));
            log.line(format_args!("dropped second"));
            let _ = sent.send(());
        });
        queued
            .recv_timeout(WAIT)
            .expect("log producer blocked behind stderr");
        drain.set_closing(format_args!("closing"));
        resume.send(()).unwrap();
        producer.join().unwrap();
        drain.finished.recv_timeout(WAIT).unwrap();

        let output = output.lock().unwrap();
        let mut lines = std::str::from_utf8(&output).unwrap().lines();
        assert_eq!(lines.next(), Some("first"));
        assert_eq!(lines.next(), Some("troll serve dropped 2 log lines"));
        for i in 0..LOG_QUEUE_CAPACITY {
            assert_eq!(lines.next(), Some(format!("queued {i}").as_str()));
        }
        assert_eq!(lines.next(), Some("closing"));
        assert_eq!(lines.next(), None);
    }

    struct RecordingWriter {
        written: Sender<String>,
        first_error: Option<io::ErrorKind>,
    }

    impl Write for RecordingWriter {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            if let Some(kind) = self.first_error.take() {
                return Err(kind.into());
            }
            self.written
                .send(std::str::from_utf8(bytes).unwrap().to_owned())
                .unwrap();
            Ok(bytes.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn idle_writer_reports_a_drop_count_incremented_after_drain() {
        let (written, writes) = mpsc::channel();
        let (log, drain) = Logger::start(io::LineWriter::new(RecordingWriter {
            written,
            first_error: None,
        }))
        .unwrap();
        log.line(format_args!("last queued line"));
        assert_eq!(writes.recv_timeout(WAIT).unwrap(), "last queued line\n");

        log.dropped.fetch_add(1, Ordering::Relaxed);
        assert_eq!(
            writes.recv_timeout(WAIT).unwrap(),
            "troll serve dropped 1 log lines\n"
        );
        // The writer already reset the count before writing that report. Keep the
        // channel open and empty so a receive timeout must handle this increment.
        log.dropped.fetch_add(2, Ordering::Relaxed);
        assert_eq!(
            writes.recv_timeout(WAIT).unwrap(),
            "troll serve dropped 2 log lines\n"
        );
        drop(log);
        drain.finished.recv_timeout(WAIT).unwrap();
    }

    #[test]
    fn writer_delivers_lines_after_would_block_or_interrupted() {
        for kind in [io::ErrorKind::WouldBlock, io::ErrorKind::Interrupted] {
            let (written, writes) = mpsc::channel();
            let (log, drain) = Logger::start(RecordingWriter {
                written,
                first_error: Some(kind),
            })
            .unwrap();
            log.line(format_args!("retry this line"));
            log.line(format_args!("next line"));
            assert_eq!(writes.recv_timeout(WAIT).unwrap(), "retry this line\n");
            assert_eq!(writes.recv_timeout(WAIT).unwrap(), "next line\n");
            drop(log);
            drain.finished.recv_timeout(WAIT).unwrap();
        }
    }
}