tilo-actions 0.5.1

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store.
Documentation
//! Bounded observations of named scopes in the real code on this thread.
//!
//! Resource publication, the app framework and apps mark their scopes with
//! [`Phase::start`] or [`measure`]; a test wraps an interaction in
//! [`observe`] and reads every scope that ran, aggregated by name. Scopes may
//! nest, so their durations are not additive. Without an active observation a
//! scope reads no clock: one thread-local read.
//!
//! A running app observes the same scopes across one key's journey, from the
//! key to the frame answering it ([`begin_live`], [`take_live`]): the
//! window's `INPUT-FRAME` record (`ui_core::input_frame`) names the work a
//! keystroke did, in production builds.

#[cfg(not(target_arch = "wasm32"))]
pub use recorder::{Phase, Sample, begin_live, observe, take_live, unobserved};

/// A named scope; the web build records none.
#[cfg(target_arch = "wasm32")]
pub struct Phase;

#[cfg(target_arch = "wasm32")]
impl Phase {
    /// Open the scope `_name`; it closes when the value drops.
    #[inline]
    #[must_use]
    pub const fn start(_name: &'static str) -> Self {
        Self
    }

    /// Close the scope here, before the end of its block.
    #[inline]
    #[allow(
        clippy::missing_const_for_fn,
        reason = "const would stop compiling the moment this Phase gains a destructor, as the recorder's has"
    )]
    pub fn end(self) {
        let Self = self;
    }
}

/// Run `operation` without recording its scopes in an active observation:
/// work a debug build does only to verify the production path (re-running
/// what that path proved it could skip) is not the path an observation
/// measures.
#[cfg(target_arch = "wasm32")]
#[inline]
pub fn unobserved<T>(operation: impl FnOnce() -> T) -> T {
    operation()
}

/// One named scope's total over an observation; the web build records none.
#[cfg(target_arch = "wasm32")]
#[derive(Debug)]
pub struct Sample {
    /// Static operation name.
    pub phase: &'static str,
    /// Aggregate duration of the scope, nested and nonadditive.
    pub elapsed_ns: u128,
    /// Completed scopes on the observed thread.
    pub calls: usize,
}

/// Run `operation`; the web build records no scope, so what it observed is
/// empty.
#[cfg(target_arch = "wasm32")]
#[inline]
pub fn observe<T>(operation: impl FnOnce() -> T) -> (T, Vec<Sample>) {
    (operation(), Vec::new())
}

/// Start observing this thread's scopes until [`take_live`]; the web build
/// records none, so it never starts one.
#[cfg(target_arch = "wasm32")]
#[inline]
pub const fn begin_live() -> bool {
    false
}

/// What this thread's scopes did since [`begin_live`]; the web build
/// records none.
#[cfg(target_arch = "wasm32")]
#[inline]
pub fn take_live() -> Vec<Sample> {
    Vec::new()
}

/// Run `operation` as the scope `phase`.
#[inline]
pub fn measure<T>(phase: &'static str, operation: impl FnOnce() -> T) -> T {
    let _scope = Phase::start(phase);
    operation()
}

#[cfg(not(target_arch = "wasm32"))]
mod recorder {
    use std::cell::RefCell;
    use tilo_clock::time::Instant;

    thread_local! {
        static RECORDS: RefCell<Option<Capture>> = const { RefCell::new(None) };
    }

    /// Distinct scope names one observation keeps.
    pub(super) const MAX_PHASES: usize = 64;

    #[derive(Default)]
    struct Capture {
        rows: Vec<Sample>,
        overflow: bool,
    }

    /// Repeated scopes aggregate by name, with exact counts and bounded memory.
    /// These nested durations must not be added to their enclosing scope.
    #[derive(Debug, serde::Serialize)]
    pub struct Sample {
        /// Static operation name; no resource identities or document values.
        pub phase: &'static str,
        /// Aggregate duration of this actual scope, nested and nonadditive.
        pub elapsed_ns: u128,
        /// Exact number of completed scopes on the observed thread.
        pub calls: usize,
    }

    /// A named scope, recorded when it drops inside an active observation.
    #[must_use]
    pub struct Phase(Option<(&'static str, Instant)>);

    impl Phase {
        /// Open the scope `name`; it closes when the value drops.
        pub fn start(name: &'static str) -> Self {
            Self(
                RECORDS
                    .with(|records| records.borrow().as_ref().map(|_| (name, tilo_clock::now()))),
            )
        }

        /// Close the scope here, before the end of its block.
        pub fn end(self) {
            drop(self);
        }
    }

    impl Drop for Phase {
        fn drop(&mut self) {
            let Some((name, start)) = self.0 else {
                return;
            };
            RECORDS.with(|records| {
                let mut records = records.borrow_mut();
                let Some(capture) = records.as_mut() else {
                    return;
                };
                let elapsed_ns = tilo_clock::now().duration_since(start).as_nanos();
                if let Some(row) = capture.rows.iter_mut().find(|row| row.phase == name) {
                    match (
                        row.elapsed_ns.checked_add(elapsed_ns),
                        row.calls.checked_add(1),
                    ) {
                        (Some(elapsed), Some(calls)) => {
                            row.elapsed_ns = elapsed;
                            row.calls = calls;
                        }
                        _ => capture.overflow = true,
                    }
                } else if capture.rows.len() < MAX_PHASES {
                    capture.rows.push(Sample {
                        phase: name,
                        elapsed_ns,
                        calls: 1,
                    });
                } else {
                    capture.overflow = true;
                }
            });
        }
    }

    struct Recording;

    impl Drop for Recording {
        fn drop(&mut self) {
            RECORDS.with(|records| *records.borrow_mut() = None);
        }
    }

    /// Run `operation` with the active observation, if any, set aside: its
    /// scopes are not recorded, and the observation resumes afterwards.
    pub fn unobserved<T>(operation: impl FnOnce() -> T) -> T {
        struct Resume(Option<Capture>);
        impl Drop for Resume {
            fn drop(&mut self) {
                let capture = self.0.take();
                RECORDS.with(|records| *records.borrow_mut() = capture);
            }
        }
        let _resume = Resume(RECORDS.with(RefCell::take));
        operation()
    }

    /// Start observing this thread's scopes, across events and frames,
    /// until [`take_live`]: a running app's record of one key's journey, or
    /// of one slow event. An observation already active (a test's, another
    /// record's) is left as it is. Answers whether this call started one,
    /// so only its starter takes it.
    pub fn begin_live() -> bool {
        RECORDS.with(|records| {
            let mut records = records.borrow_mut();
            if records.is_some() {
                return false;
            }
            *records = Some(Capture::default());
            true
        })
    }

    /// Every scope that ran since [`begin_live`], by name, ending the
    /// observation. Past [`MAX_PHASES`] names the rest are left out.
    pub fn take_live() -> Vec<Sample> {
        RECORDS
            .with(RefCell::take)
            .map(|capture| capture.rows)
            .unwrap_or_default()
    }

    /// Run the real operation and return every scope it ran, by name.
    pub fn observe<T>(operation: impl FnOnce() -> T) -> (T, Vec<Sample>) {
        RECORDS.with(|records| {
            let mut records = records.borrow_mut();
            assert!(records.is_none(), "a phase observation is already active");
            *records = Some(Capture::default());
        });
        let recording = Recording;
        let result = operation();
        let captured = RECORDS.with(RefCell::take);
        assert!(captured.is_some(), "phase observation lost its recorder");
        let capture = captured.unwrap_or_default();
        drop(recording);
        assert!(!capture.overflow, "phase observation exceeded its bound");
        (result, capture.rows)
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::recorder::MAX_PHASES;
    use super::{Phase, begin_live, measure, observe, take_live, unobserved};

    tilo_test_env::scenario! {
        fn an_observation_records_the_scopes_that_run_inside_it;

        phase recording_is_opt_in_and_aggregates_nested_scopes_by_name;
        {
            drop(Phase::start("unobserved"));
            let (value, samples) = observe(|| {
                let _outer = Phase::start("outer");
                drop(Phase::start("inner"));
                measure("inner", || 42)
            });
            assert_eq!(value, 42);
            let calls: Vec<_> = samples
                .iter()
                .map(|sample| (sample.phase, sample.calls))
                .collect();
            assert_eq!(calls, [("inner", 2), ("outer", 1)]);
            assert!(observe(|| ()).1.is_empty());
        }

        phase unobserved_scopes_are_left_out_and_the_observation_resumes;
        {
            let ((), samples) = observe(|| {
                drop(Phase::start("before"));
                unobserved(|| measure("hidden", || ()));
                drop(Phase::start("after"));
            });
            let names: Vec<_> = samples.iter().map(|sample| sample.phase).collect();
            assert_eq!(names, ["before", "after"]);
            // Outside an observation it records nothing and leaves none behind.
            unobserved(|| drop(Phase::start("alone")));
            assert!(observe(|| ()).1.is_empty());
        }

        phase a_live_observation_spans_calls_until_taken;
        {
            drop(Phase::start("before"));
            begin_live();
            drop(Phase::start("key"));
            measure("frame", || drop(Phase::start("key")));
            let calls: Vec<_> = take_live()
                .iter()
                .map(|sample| (sample.phase, sample.calls))
                .collect();
            assert_eq!(calls, [("key", 2), ("frame", 1)]);
            assert!(take_live().is_empty(), "taking it ended it");
            assert!(observe(|| ()).1.is_empty());
        }
    }

    #[test]
    fn recording_recovers_after_a_nested_observation_panics() {
        let result = std::panic::catch_unwind(|| observe(|| observe(|| ())));
        assert!(result.is_err());
        assert!(observe(|| ()).1.is_empty());
    }

    #[test]
    fn recording_refuses_incomplete_coverage_and_retires_its_recorder() {
        let result = std::panic::catch_unwind(|| {
            observe(|| {
                for index in 0..=MAX_PHASES {
                    let name: &'static str = Box::leak(format!("phase-{index}").into_boxed_str());
                    drop(Phase::start(name));
                }
            })
        });
        assert!(result.is_err());
        assert!(observe(|| ()).1.is_empty());
    }
}