icedwright-trace 0.0.1

The icedwright trace format: a deterministic .iwtrace archive of every step a test took, with its writer, reader and comparison
Documentation
//! What is traced, where it goes and how large it may grow.

use std::path::{Path, PathBuf};

use crate::error::TraceError;

/// When a trace file is written. Recording is the same in every mode, so the mode never
/// changes what the app does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TraceMode {
    /// Never.
    Off,
    /// Only when the test fails or panics.
    #[default]
    OnFailure,
    /// For every test.
    Always,
}

impl TraceMode {
    /// Whether a test that `passed` keeps its trace.
    #[must_use]
    pub fn writes(self, passed: bool) -> bool {
        match self {
            TraceMode::Off => false,
            TraceMode::OnFailure => !passed,
            TraceMode::Always => true,
        }
    }
}

/// Which steps keep frames. Frames are rendered the same way under every policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FramePolicy {
    /// No frames.
    None,
    /// Every step.
    #[default]
    EveryStep,
    /// Action steps only.
    ActionsOnly,
}

/// A size in bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ByteSize(u64);

impl ByteSize {
    /// `bytes` bytes.
    #[must_use]
    pub const fn bytes(bytes: u64) -> Self {
        Self(bytes)
    }

    /// `kib` kibibytes, saturating.
    #[must_use]
    pub const fn kib(kib: u64) -> Self {
        Self(kib.saturating_mul(1024))
    }

    /// `mib` mebibytes, saturating.
    #[must_use]
    pub const fn mib(mib: u64) -> Self {
        Self(mib.saturating_mul(1024 * 1024))
    }

    /// The size in bytes.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// How a harness traces. The environment overrides only the mode, output directory and size
/// cap.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceConfig {
    mode: TraceMode,
    out_dir: PathBuf,
    max_size: ByteSize,
    frames: FramePolicy,
}

impl Default for TraceConfig {
    fn default() -> Self {
        Self {
            mode: TraceMode::default(),
            out_dir: PathBuf::from("target/icedwright"),
            max_size: ByteSize::mib(64),
            frames: FramePolicy::default(),
        }
    }
}

const TRACE_VAR: &str = "ICEDWRIGHT_TRACE";
const OUT_DIR_VAR: &str = "ICEDWRIGHT_OUT_DIR";
const MAX_MB_VAR: &str = "ICEDWRIGHT_TRACE_MAX_MB";

impl TraceConfig {
    /// The defaults: [`TraceMode::OnFailure`], `target/icedwright`, 64 MiB and a frame for
    /// every step.
    pub fn new() -> Self {
        Self::default()
    }

    /// When a trace file is written.
    pub fn mode(self, mode: TraceMode) -> Self {
        Self { mode, ..self }
    }

    /// The directory everything icedwright writes goes under.
    pub fn out_dir(self, dir: impl Into<PathBuf>) -> Self {
        Self {
            out_dir: dir.into(),
            ..self
        }
    }

    /// The largest a trace file may be; frames are dropped to fit.
    pub fn max_size(self, bytes: ByteSize) -> Self {
        Self {
            max_size: bytes,
            ..self
        }
    }

    /// Which steps keep frames.
    pub fn frames(self, policy: FramePolicy) -> Self {
        Self {
            frames: policy,
            ..self
        }
    }

    /// Applies `ICEDWRIGHT_TRACE`, `ICEDWRIGHT_OUT_DIR` and `ICEDWRIGHT_TRACE_MAX_MB`, read
    /// through `env`, over this configuration.
    pub fn from_env(self, env: &impl Fn(&str) -> Option<String>) -> Result<Self, TraceError> {
        let mut config = self;
        if let Some(value) = env(TRACE_VAR) {
            config.mode = match value.as_str() {
                "off" => TraceMode::Off,
                "on-failure" => TraceMode::OnFailure,
                "always" => TraceMode::Always,
                _ => {
                    return Err(TraceError::BadEnv {
                        var: TRACE_VAR,
                        value,
                        expected: "off, on-failure or always",
                    });
                }
            };
        }
        if let Some(value) = env(OUT_DIR_VAR) {
            if value.is_empty() {
                return Err(TraceError::BadEnv {
                    var: OUT_DIR_VAR,
                    value,
                    expected: "a directory path",
                });
            }
            config.out_dir = PathBuf::from(value);
        }
        if let Some(value) = env(MAX_MB_VAR) {
            let mib = value.trim().parse::<u64>().ok().filter(|mib| *mib > 0);
            let Some(mib) = mib else {
                return Err(TraceError::BadEnv {
                    var: MAX_MB_VAR,
                    value,
                    expected: "a whole number of MiB above zero",
                });
            };
            config.max_size = ByteSize::mib(mib);
        }
        Ok(config)
    }

    /// When a trace file is written.
    #[must_use]
    pub fn trace_mode(&self) -> TraceMode {
        self.mode
    }

    /// The output directory.
    #[must_use]
    pub fn output_dir(&self) -> &Path {
        &self.out_dir
    }

    /// The size cap.
    #[must_use]
    pub fn size_cap(&self) -> ByteSize {
        self.max_size
    }

    /// Which steps keep frames.
    #[must_use]
    pub fn frame_policy(&self) -> FramePolicy {
        self.frames
    }

    /// Where the trace of a test goes: `<out>/traces/<crate>/<module path>/<test>.iwtrace`,
    /// with `module_path` as `module_path!()` prints it, crate first.
    #[must_use]
    pub fn trace_path(&self, module_path: &str, test: &str) -> PathBuf {
        let mut path = self.out_dir.join("traces");
        module_path
            .split("::")
            .filter(|part| !part.is_empty())
            .for_each(|part| path.push(part));
        path.push(format!("{test}.iwtrace"));
        path
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
        move |name| {
            vars.iter()
                .find(|(var, _)| *var == name)
                .map(|(_, value)| (*value).to_owned())
        }
    }

    #[test]
    fn defaults() {
        let config = TraceConfig::new();
        assert_eq!(config.trace_mode(), TraceMode::OnFailure);
        assert_eq!(config.output_dir(), Path::new("target/icedwright"));
        assert_eq!(config.size_cap(), ByteSize::mib(64));
        assert_eq!(config.frame_policy(), FramePolicy::EveryStep);
    }

    #[test]
    fn builder_sets_each_field() {
        let config = TraceConfig::new()
            .mode(TraceMode::Always)
            .out_dir("/tmp/out")
            .max_size(ByteSize::kib(3))
            .frames(FramePolicy::ActionsOnly);
        assert_eq!(config.trace_mode(), TraceMode::Always);
        assert_eq!(config.output_dir(), Path::new("/tmp/out"));
        assert_eq!(config.size_cap().get(), 3072);
        assert_eq!(config.frame_policy(), FramePolicy::ActionsOnly);
    }

    type Vars<'a> = &'a [(&'a str, &'a str)];

    #[test]
    fn environment_table() -> Result<(), TraceError> {
        let cases: &[(Vars<'_>, TraceMode, &str, u64)] = &[
            (&[], TraceMode::OnFailure, "target/icedwright", 64),
            (
                &[("ICEDWRIGHT_TRACE", "off")],
                TraceMode::Off,
                "target/icedwright",
                64,
            ),
            (
                &[("ICEDWRIGHT_TRACE", "always")],
                TraceMode::Always,
                "target/icedwright",
                64,
            ),
            (
                &[
                    ("ICEDWRIGHT_TRACE", "on-failure"),
                    ("ICEDWRIGHT_OUT_DIR", "out"),
                ],
                TraceMode::OnFailure,
                "out",
                64,
            ),
            (
                &[("ICEDWRIGHT_TRACE_MAX_MB", "8")],
                TraceMode::OnFailure,
                "target/icedwright",
                8,
            ),
        ];
        for (vars, mode, dir, mib) in cases {
            let config = TraceConfig::new().from_env(&env(vars))?;
            assert_eq!(config.trace_mode(), *mode, "{vars:?}");
            assert_eq!(config.output_dir(), Path::new(dir), "{vars:?}");
            assert_eq!(config.size_cap(), ByteSize::mib(*mib), "{vars:?}");
        }
        Ok(())
    }

    #[test]
    fn invalid_environment_values_name_the_variable() {
        let cases: &[(&str, &str, &str)] = &[
            (
                "ICEDWRIGHT_TRACE",
                "yes",
                "ICEDWRIGHT_TRACE=\"yes\" is not valid: off, on-failure or always",
            ),
            (
                "ICEDWRIGHT_OUT_DIR",
                "",
                "ICEDWRIGHT_OUT_DIR=\"\" is not valid: a directory path",
            ),
            (
                "ICEDWRIGHT_TRACE_MAX_MB",
                "0",
                "ICEDWRIGHT_TRACE_MAX_MB=\"0\" is not valid: a whole number of MiB above zero",
            ),
            (
                "ICEDWRIGHT_TRACE_MAX_MB",
                "1.5",
                "ICEDWRIGHT_TRACE_MAX_MB=\"1.5\" is not valid: a whole number of MiB above zero",
            ),
        ];
        for (var, value, message) in cases {
            let vars = [(*var, *value)];
            let error = TraceConfig::new().from_env(&env(&vars)).err();
            assert_eq!(error.map(|e| e.to_string()).as_deref(), Some(*message));
        }
    }

    #[test]
    fn modes_decide_what_is_written() {
        assert!(!TraceMode::Off.writes(false));
        assert!(!TraceMode::OnFailure.writes(true));
        assert!(TraceMode::OnFailure.writes(false));
        assert!(TraceMode::Always.writes(true));
    }

    #[test]
    fn trace_paths_follow_the_module_path() {
        let path = TraceConfig::new().trace_path("examples_notes::ui", "restoring_a_note");
        assert_eq!(
            path,
            Path::new("target/icedwright/traces/examples_notes/ui/restoring_a_note.iwtrace")
        );
    }
}