use std::path::{Path, PathBuf};
use std::sync::Mutex;
use ort::session::builder::SessionBuilder;
use ort::session::Session;
const ENV_VAR: &str = "CANARY_PROFILE_DIR";
pub(crate) fn apply(
builder: SessionBuilder,
kind: &str,
) -> Result<(SessionBuilder, bool), ort::Error> {
let Some(dir) = profile_dir() else {
return Ok((builder, false));
};
let prefix: PathBuf = dir.join(format!("canary-{kind}"));
let builder = builder.with_profiling(&prefix)?;
Ok((builder, true))
}
pub(crate) fn flush(session: &Mutex<Session>, kind: &str) {
let mut guard = match session.lock() {
Ok(g) => g,
Err(_) => {
eprintln!("[canary][profile] {kind} session mutex poisoned, skipping flush");
return;
}
};
match guard.end_profiling() {
Ok(path) => eprintln!("[canary][profile] {kind} trace flushed to {path}"),
Err(e) => eprintln!("[canary][profile] {kind} end_profiling failed: {e}"),
}
}
fn profile_dir() -> Option<PathBuf> {
let raw = std::env::var(ENV_VAR).ok()?;
if raw.is_empty() {
return None;
}
Some(Path::new(&raw).to_path_buf())
}