#![allow(dead_code)]
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::Deserialize;
use crate::model::{SiteKey, SiteStats, Unit};
use crate::profile::Profile;
#[derive(Debug, Deserialize)]
struct Pp {
mb: u64,
tbk: u64,
fs: Vec<usize>,
}
#[derive(Debug, Deserialize)]
struct DhatFile {
#[serde(rename = "dhatFileVersion")]
dhat_file_version: u32,
pps: Vec<Pp>,
ftbl: Vec<String>,
}
pub struct DhatProfile {
file: PathBuf,
workspace_root: PathBuf,
}
impl DhatProfile {
pub fn new(file: impl Into<PathBuf>, workspace_root: impl Into<PathBuf>) -> Self {
Self {
file: file.into(),
workspace_root: workspace_root.into(),
}
}
}
impl Profile for DhatProfile {
fn sites(&self) -> Result<Vec<SiteStats>> {
let raw = std::fs::read_to_string(&self.file)
.with_context(|| format!("read dhat heap file {}", self.file.display()))?;
let dump: DhatFile = serde_json::from_str(&raw)
.with_context(|| format!("parse dhat heap file {}", self.file.display()))?;
if dump.dhat_file_version != 2 {
anyhow::bail!(
"unsupported dhatFileVersion {}: only v2 is supported",
dump.dhat_file_version
);
}
aggregate_pps(&dump.pps, &dump.ftbl, &self.workspace_root)
}
}
fn aggregate_pps(pps: &[Pp], ftbl: &[String], workspace_root: &Path) -> Result<Vec<SiteStats>> {
use std::collections::HashMap;
let mut agg: HashMap<SiteKey, (u64, u64)> = HashMap::new();
for pp in pps {
let Some(key) = user_top_frame(&pp.fs, ftbl, workspace_root) else {
continue;
};
let entry = agg.entry(key).or_insert((0, 0));
entry.0 = entry.0.max(pp.mb);
entry.1 = entry.1.saturating_add(pp.tbk);
}
let mut out: Vec<SiteStats> = agg
.into_iter()
.map(|(key, (peak_bytes, count))| {
let peak = peak_bytes as usize;
SiteStats {
key,
unit: Unit::Bytes,
peak,
p50: peak, p95: peak, count,
mean: None,
p99: None,
policy: None,
}
})
.collect();
out.sort_by(|a, b| a.key.cmp(&b.key));
Ok(out)
}
fn is_std_path(path: &Path) -> bool {
let s = path.to_string_lossy();
s.contains("/rustc/")
|| s.contains("\\rustc\\")
|| s.contains("/.cargo/registry/")
|| s.contains("\\.cargo\\registry\\")
|| s.contains("/.cargo/git/")
|| s.contains("\\.cargo\\git\\")
|| (path.is_absolute() && s.contains("/library/"))
|| (path.is_absolute() && s.contains("\\library\\"))
}
fn user_top_frame(fs: &[usize], ftbl: &[String], workspace_root: &Path) -> Option<SiteKey> {
for &idx in fs {
let Some(frame) = ftbl.get(idx) else { continue };
let Some((file, line, col)) = parse_frame_location(frame) else {
continue;
};
if is_std_path(&file) {
continue;
}
if file.is_absolute() {
if file.starts_with(workspace_root) {
return Some(SiteKey { file, line, col });
}
} else {
return Some(SiteKey { file, line, col });
}
}
None
}
fn parse_frame_location(frame: &str) -> Option<(PathBuf, u32, u32)> {
let open = frame.rfind('(')?;
let close = frame.rfind(')')?;
if close <= open + 1 {
return None;
}
let inner = &frame[open + 1..close];
let mut parts = inner.rsplitn(3, ':');
let col_s = parts.next()?;
let line_s = parts.next()?;
let file_s = parts.next()?;
let col: u32 = col_s.parse().ok()?;
let line: u32 = line_s.parse().ok()?;
if file_s.is_empty() {
return None;
}
Some((PathBuf::from(file_s), line, col))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_frame_location_basic() {
let f = "0xABC: my_crate::foo (crates/my-crate/src/lib.rs:42:17)";
let (file, line, col) = parse_frame_location(f).unwrap();
assert_eq!(file, PathBuf::from("crates/my-crate/src/lib.rs"));
assert_eq!(line, 42);
assert_eq!(col, 17);
}
#[test]
fn parse_frame_location_no_parens_returns_none() {
assert!(parse_frame_location("[root]").is_none());
assert!(parse_frame_location("0xABC: weird symbol").is_none());
}
#[test]
fn parse_frame_location_windows_abs_path() {
let f = "0xABC: my_crate::bar (D:/dev/rust/myapp/src/main.rs:10:5)";
let (file, line, col) = parse_frame_location(f).unwrap();
assert_eq!(file, PathBuf::from("D:/dev/rust/myapp/src/main.rs"));
assert_eq!(line, 10);
assert_eq!(col, 5);
}
#[test]
fn parses_sample_fixture() {
let workspace_root = std::env::current_dir().unwrap();
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fixtures")
.join("dhat-heap.sample.json");
let raw = std::fs::read_to_string(&fixture).expect("fixture must exist");
let dump: DhatFile = serde_json::from_str(&raw).unwrap();
let stats = aggregate_pps(&dump.pps, &dump.ftbl, &workspace_root).unwrap();
assert_eq!(stats.len(), 1, "expected 1 aggregated site, got: {stats:?}");
let s = &stats[0];
assert_eq!(s.unit, Unit::Bytes);
assert_eq!(s.peak, 4096); assert_eq!(s.count, 30); assert_eq!(s.p50, 4096);
assert_eq!(s.p95, 4096);
assert_eq!(s.mean, None);
assert_eq!(s.p99, None);
assert_eq!(s.policy, None);
}
#[test]
fn unknown_version_errors() {
let dump = serde_json::json!({
"dhatFileVersion": 99,
"pps": [],
"ftbl": []
});
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), dump.to_string()).unwrap();
let p = DhatProfile::new(tmp.path(), std::env::current_dir().unwrap());
let err = p.sites().unwrap_err();
assert!(
err.to_string().contains("dhatFileVersion"),
"expected dhatFileVersion in error, got: {err}"
);
}
#[test]
fn std_frames_are_filtered_out() {
let pps = vec![Pp {
mb: 1024,
tbk: 5,
fs: vec![0, 1],
}];
let ftbl = vec![
"[root]".to_string(),
"0xAA: alloc::alloc::alloc (/rustc/abc/library/alloc/src/alloc.rs:97:9)".to_string(),
];
let stats = aggregate_pps(&pps, &ftbl, Path::new("/workspace")).unwrap();
assert!(stats.is_empty(), "std frames should be filtered: {stats:?}");
}
}