tilo-rt 0.5.0

The one async runtime model for Tilo processes: an app runtime off the UI thread, bounded daemon runtimes, a CPU pool, a file-I/O pool, named threads, and the host background executors and wake routing.
Documentation
//! Which panics a process survives.
//!
//! Release builds unwind, but a Tilo process still ends on the first panic: on
//! starting a runtime or a thread through this crate, it installs a hook that aborts
//! once every earlier hook (a crash log) has run, so code keeps the abort-on-panic
//! contract it is written against and a task's panic is never swallowed by its
//! runtime.
//!
//! The one exception is a thread inside [`isolate`], where the panic unwinds to the
//! boundary and the helper's owner decides what happens next — the compositor
//! isolates its helpers this way. Debug and test builds keep unwinding everywhere;
//! under `panic = "abort"` [`isolate`] only runs its body.
//!
//! The abort writes its own backtrace, captured at the panic, rather than leaving
//! it to std's hook: that one prints only what `RUST_BACKTRACE` asks for, and its
//! short form prints no frames at all in a build without a symbol table (every
//! development build is stripped). A process that ends says where it ended,
//! whatever the environment and the symbol table are.

use std::cell::Cell;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Once;

/// Abort the process on any panic outside [`isolate`], after the hooks
/// installed before this one (which it calls first) have reported it.
/// Idempotent; a hook installed later should chain to this one.
pub fn abort_outside_boundaries() {
    static INSTALLED: Once = Once::new();
    INSTALLED.call_once(|| {
        let earlier = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            earlier(info);
            if !is_isolated() {
                // The earlier hooks may have written to a capture the abort
                // discards, as a test harness's is: say on the process's own
                // stderr what ended it, and where, so no abort goes unexplained.
                // The backtrace is captured here and printed in full: std's hook
                // answers to `RUST_BACKTRACE`, and its short form names no frame
                // at all when the symbol table is stripped, which is every
                // development build's.
                let backtrace = std::backtrace::Backtrace::force_capture();
                let _ = std::io::Write::write_fmt(
                    &mut std::io::stderr().lock(),
                    format_args!(
                        "{info}\nbacktrace:\n{backtrace:#}\n\
                         aborting: the panic above happened outside a panic boundary\n"
                    ),
                );
                std::process::abort();
            }
        }));
    });
}

pub(crate) fn abort_outside_boundaries_in_release() {
    if cfg!(all(panic = "unwind", not(debug_assertions))) {
        abort_outside_boundaries();
    }
}

thread_local! {
    static DEPTH: Cell<usize> = const { Cell::new(0) };
}

/// Run `body` as a panic boundary: a panic inside it (on this thread)
/// unwinds to here and is returned as `Err` with its payload, and
/// [`is_isolated`] answers `true` meanwhile so the process's panic hook lets
/// it unwind.
///
/// `body` must leave nothing half-updated that outlives it, or whoever
/// reads that state afterwards must tolerate it (poisoned locks read as
/// unavailable, a dropped channel as closed).
pub fn isolate<R>(body: impl FnOnce() -> R) -> std::thread::Result<R> {
    struct Entered;
    impl Drop for Entered {
        fn drop(&mut self) {
            DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
        }
    }
    DEPTH.with(|depth| depth.set(depth.get().saturating_add(1)));
    let _entered = Entered;
    catch_unwind(AssertUnwindSafe(body))
}

/// Whether the calling thread is inside [`isolate`]: a panic hook that
/// aborts the process for any other panic returns for this one.
#[must_use]
pub fn is_isolated() -> bool {
    DEPTH.with(|depth| depth.get() > 0)
}

/// The panic message in `payload`, for a log line.
#[must_use]
pub fn message(payload: &(dyn std::any::Any + Send)) -> &str {
    payload
        .downcast_ref::<&str>()
        .copied()
        .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
        .unwrap_or("<non-text panic payload>")
}

#[cfg(test)]
mod tests {
    use super::*;
    use tilo_test_env::SpawnUnderEnvLock as _;

    #[test]
    fn a_panic_inside_the_boundary_returns_and_the_marker_follows_the_scope() {
        assert!(!is_isolated());
        let inner = isolate(|| {
            assert!(is_isolated());
            let nested = isolate(|| panic!("helper failed"));
            let payload = nested.expect_err("the nested panic is caught");
            assert_eq!(message(payload.as_ref()), "helper failed");
            assert!(is_isolated(), "the outer boundary still holds");
            7
        });
        assert_eq!(inner.expect("the outer body returned"), 7);
        assert!(!is_isolated());

        let formatted = isolate(|| panic!("{} failed", "broker"));
        assert_eq!(
            message(formatted.expect_err("caught").as_ref()),
            "broker failed"
        );
        assert!(!is_isolated(), "an unwound boundary is left");
    }

    const FIXTURE: &str = "TILO_RT_PANIC_BOUNDARY_FIXTURE";

    /// The step the child panics in: a function of its own, so the frame the abort prints is
    /// named with a word this test wrote rather than a closure's mangled one.
    #[inline(never)]
    fn a_step_that_ends_the_process() {
        panic!("worker failed");
    }

    #[test]
    fn panic_boundary_fixture() {
        let Ok(scenario) = std::env::var(FIXTURE) else {
            return;
        };
        // The abort is the outcome under test, not a crash to debug: it must
        // not leave a core file in the directory the tests run in.
        #[cfg(any(target_os = "linux", target_vendor = "apple"))]
        {
            let no_core = libc::rlimit {
                rlim_cur: 0,
                rlim_max: 0,
            };
            // SAFETY: `setrlimit` only reads the limit it is handed.
            assert_eq!(
                unsafe { libc::setrlimit(libc::RLIMIT_CORE, &raw const no_core) },
                0
            );
        }
        abort_outside_boundaries();
        if scenario == "isolated" {
            let helper =
                crate::spawn_thread("helper", || isolate(|| panic!("helper failed")).is_err())
                    .expect("helper thread");
            assert!(helper.join().expect("the helper thread returned"));
        } else {
            let _ = crate::spawn_thread("worker", a_step_that_ends_the_process)
                .expect("worker thread")
                .join();
        }
        println!("process survived");
    }

    #[test]
    fn only_a_panic_inside_a_boundary_leaves_the_process_running() {
        let run = |scenario: &str| {
            std::process::Command::new(std::env::current_exe().expect("test binary"))
                .args([
                    "--exact",
                    "panic_boundary::tests::panic_boundary_fixture",
                    "--nocapture",
                    "--test-threads=1",
                ])
                .env(FIXTURE, scenario)
                // The hook prints the backtrace whether or not a variable asks
                // for one: without either, std's own hook prints no frames, so
                // every frame the child says is the abort's own.
                .env_remove("RUST_BACKTRACE")
                .env_remove("RUST_LIB_BACKTRACE")
                .output_locked()
                .expect("fixture child")
        };
        let isolated = run("isolated");
        assert!(isolated.status.success(), "{isolated:?}");
        assert!(String::from_utf8_lossy(&isolated.stdout).contains("process survived"));

        let outside = run("outside");
        assert!(!outside.status.success(), "{outside:?}");
        assert!(!String::from_utf8_lossy(&outside.stdout).contains("process survived"));
        // A process that ends says where: the backtrace the hook captured names
        // the step that panicked.
        let said = String::from_utf8_lossy(&outside.stderr);
        assert!(said.contains("backtrace:"), "{said}");
        assert!(said.contains("a_step_that_ends_the_process"), "{said}");
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt as _;
            assert_eq!(outside.status.signal(), Some(libc_sigabrt()), "{outside:?}");
        }
    }

    #[cfg(unix)]
    const fn libc_sigabrt() -> i32 {
        6
    }
}