cosca 0.8.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! Minimal capturing logger: installed once per process (`log::set_logger` is
//! once-per-process); records every message so tests assert by unique marker.
//!
//! Records are append-only and never erased: each test takes a [`mark`] and scans
//! only records emitted after it via [`contains_since`], so a stale record from an
//! earlier test (e.g. a same-shape marker under OS pid reuse) can never satisfy an
//! assertion, and no test can erase another's records.

use std::sync::{Mutex, OnceLock};
use std::thread::ThreadId;

struct CaptureLog;
static RECORDS: Mutex<Vec<(log::Level, String, ThreadId)>> = Mutex::new(Vec::new());
static INSTALLED: OnceLock<()> = OnceLock::new();

impl log::Log for CaptureLog {
    fn enabled(&self, _: &log::Metadata<'_>) -> bool {
        true
    }
    fn log(&self, record: &log::Record<'_>) {
        RECORDS
            .lock()
            .unwrap()
            .push((record.level(), record.args().to_string(), std::thread::current().id()));
    }
    fn flush(&self) {}
}

pub(crate) fn install() {
    INSTALLED.get_or_init(|| {
        log::set_logger(&CaptureLog).expect("first logger in this test process");
        log::set_max_level(log::LevelFilter::Trace);
    });
}

/// Current end of the record buffer — scan from here with [`contains_since`].
pub(crate) fn mark() -> usize {
    RECORDS.lock().unwrap().len()
}

/// True if any record emitted at or after `mark` contains `marker`. Never panics:
/// records are append-only, so `mark` (a past length) is always in bounds.
pub(crate) fn contains_since(mark: usize, marker: &str) -> bool {
    RECORDS.lock().unwrap()[mark..]
        .iter()
        .any(|(_, m, _)| m.contains(marker))
}

/// The text of every record emitted at or after `mark` that contains `marker`.
pub(crate) fn records_since(mark: usize, marker: &str) -> Vec<String> {
    RECORDS.lock().unwrap()[mark..]
        .iter()
        .filter(|(_, m, _)| m.contains(marker))
        .map(|(_, m, _)| m.clone())
        .collect()
}

/// The levels of every record emitted at or after `mark` that contains `marker`.
///
/// A level is part of a log record's meaning, not decoration: it is what decides whether an
/// embedder's sink shows the message by default. Assertions about "this condition must not be
/// narrated at `warn`" are therefore assertions about the level, which [`contains_since`]
/// cannot see.
pub(crate) fn levels_since(mark: usize, marker: &str) -> Vec<log::Level> {
    RECORDS.lock().unwrap()[mark..]
        .iter()
        .filter(|(_, m, _)| m.contains(marker))
        .map(|(level, _, _)| *level)
        .collect()
}

/// Pins a test's log output: no record at `Warn` or worse may be emitted while it lives. Declare it
/// FIRST in a test, so it drops last, after the test's children have been torn down and their
/// teardown has logged. Skipped while the test is already panicking, so it never masks the real
/// failure. Mirrors `tests/common`'s `WarnWatch` (minus its `expecting`, which no test here needs),
/// which a separate compilation unit cannot share.
///
/// Reads the process-wide capture from its creation on, so it assumes one test per process (what
/// nextest runs).
#[must_use = "the watch asserts when dropped; bind it to a named `_watch`, not `_`"]
pub(crate) struct WarnWatch {
    mark: usize,
}

/// A [`WarnWatch`] over the records from now on. Installs the capture.
pub(crate) fn warn_watch() -> WarnWatch {
    install();
    WarnWatch { mark: mark() }
}

impl Drop for WarnWatch {
    fn drop(&mut self) {
        if std::thread::panicking() {
            return;
        }
        let warnings: Vec<String> = RECORDS.lock().unwrap()[self.mark..]
            .iter()
            .filter(|(level, _, _)| *level <= log::Level::Warn)
            .map(|(_, m, _)| m.clone())
            .collect();
        assert!(
            warnings.is_empty(),
            "unexpected warning(s) at Warn or above: {warnings:#?}"
        );
    }
}

/// Like [`records_since`], but only records emitted by the CALLING thread. For a marker that is
/// a constant message prefix shared by every test in the process, this is what keeps a
/// concurrently-running test's identical record from satisfying (or breaking) the assertion.
#[cfg(test)]
pub(crate) fn records_since_on_current_thread(mark: usize, marker: &str) -> Vec<(log::Level, String)> {
    let me = std::thread::current().id();
    RECORDS.lock().unwrap()[mark..]
        .iter()
        .filter(|(_, m, t)| *t == me && m.contains(marker))
        .map(|(level, m, _)| (*level, m.clone()))
        .collect()
}

/// The text of every record at `Warn` or worse that the CALLING thread logged since `mark` and
/// that contains `marker`. Pass `""` for every such record.
#[cfg(test)]
pub(crate) fn warns_since(mark: usize, marker: &str) -> Vec<String> {
    let me = std::thread::current().id();
    RECORDS.lock().unwrap()[mark..]
        .iter()
        .filter(|(level, m, t)| *t == me && *level <= log::Level::Warn && m.contains(marker))
        .map(|(_, m, _)| m.clone())
        .collect()
}

#[cfg(test)]
#[path = "log_capture_tests.rs"]
mod log_capture_tests;