tracing-prof 0.3.0

Experimental library for profiling tracing spans.
Documentation
//! File backend for pprof profiles.

use std::{
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

use super::PProfBackend;

/// A backend configuration for the pprof file backend.
#[derive(Debug, Clone)]
#[must_use]
pub struct FileBackendConfig {
    /// The directory to write the profiles to.
    out_dir: PathBuf,
}

impl FileBackendConfig {
    /// Create a new configuration for the pprof file backend.
    pub fn new(out_dir: impl AsRef<Path>) -> Self {
        Self {
            out_dir: out_dir.as_ref().to_path_buf(),
        }
    }
}

/// A backend that writes pprof profiles to a files in a specified directory.
#[must_use]
pub struct FileBackend {
    config: FileBackendConfig,
}

impl FileBackend {
    /// Create a new `FileBackend` with the given output directory.
    pub fn new(config: FileBackendConfig) -> Self {
        Self { config }
    }
}

impl PProfBackend for FileBackend {
    fn save_profile(
        &self,
        kind: &str,
        _start_time: SystemTime,
        end_time: SystemTime,
        profile_data: Vec<u8>,
    ) {
        std::fs::create_dir_all(&self.config.out_dir).unwrap();

        let elapsed = end_time
            .duration_since(UNIX_EPOCH)
            .expect("start time is before end time");

        let suffix = elapsed.as_secs() * 1_000_000_000 + u64::from(elapsed.subsec_nanos());

        let filename = format!("{kind}_{suffix}.pb.gz");

        let file_path = self.config.out_dir.join(&filename);
        std::fs::write(&file_path, profile_data).unwrap();
    }
}