stackler 0.1.0

A lightweight, always-on stack telemetry library that requires no instrumentation.
Documentation
//! An optional background thread that keeps the aggregates fresh.
//!
//! Watermarks are what make a sampler possible at all: reading one is a read of
//! the *stack itself*, so a thread other than the owner can do it. That is the
//! difference between telemetry a program has to participate in and telemetry
//! that simply happens.

use std::{
    cmp, io,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    thread::{self, JoinHandle},
    time::Duration,
};

/// How often the sampler checks whether it has been asked to stop, so that
/// shutdown does not have to wait out a whole period.
const TICK: Duration = Duration::from_millis(50);

/// A running background sampler.
///
/// Dropping the handle stops the sampler and waits for it to finish, so keeping
/// it alive for as long as the telemetry is wanted is the whole of the API.
#[derive(Debug)]
pub struct Sampler {
    stop: Arc<AtomicBool>,
    thread: Option<JoinHandle<()>>,
}

impl Sampler {
    /// Stops the sampler and waits for its thread to finish.
    pub fn stop(mut self) {
        self.shutdown();
    }

    fn shutdown(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

impl Drop for Sampler {
    fn drop(&mut self) {
        self.shutdown();
    }
}

/// Spawns a background thread that re-reads every tracked thread's watermark
/// every `period`.
///
/// The sampler does not attach, so it neither paints its own stack nor appears in
/// the registry — unless the `hook_pthread` feature is on, which attaches every
/// thread in the process and makes no exception for this one.
///
/// # Cost
///
/// One pass over the untouched part of every tracked thread's painted region,
/// every `period`. With the default paint depth and a handful of threads this is
/// negligible; with hundreds of threads and a period of milliseconds it is not,
/// and the way to make it cheap is a smaller [paint
/// depth](crate::Stackler::paint_depth) rather than a shorter period.
pub fn spawn(period: Duration) -> io::Result<Sampler> {
    let stop = Arc::new(AtomicBool::new(false));
    let flag = Arc::clone(&stop);

    let thread = thread::Builder::new()
        .name("stackler-sampler".to_owned())
        .spawn(move || {
            while !flag.load(Ordering::Relaxed) {
                let mut slept = Duration::ZERO;
                while slept < period {
                    if flag.load(Ordering::Relaxed) {
                        return;
                    }
                    let nap = cmp::min(TICK, period - slept);
                    thread::sleep(nap);
                    slept += nap;
                }

                crate::registry::poll_all();
            }
        })?;

    Ok(Sampler {
        stop,
        thread: Some(thread),
    })
}