use std::path::PathBuf;
const ROTATE_BYTES: u64 = 64 * 1024 * 1024;
pub fn resolve_path(
explicit: Option<&str>,
xdg_state: Option<&str>,
home: Option<&str>,
) -> Option<PathBuf> {
if let Some(p) = explicit {
return Some(PathBuf::from(p));
}
if let Some(x) = xdg_state {
return Some(PathBuf::from(x).join("hank").join("metrics.jsonl"));
}
home.map(|h| {
PathBuf::from(h)
.join(".local")
.join("state")
.join("hank")
.join("metrics.jsonl")
})
}
fn spool_path() -> Option<PathBuf> {
resolve_path(
std::env::var("HANK_METRICS_PATH").ok().as_deref(),
std::env::var("XDG_STATE_HOME").ok().as_deref(),
std::env::var("HOME").ok().as_deref(),
)
}
pub fn emit(kind: &str, fields: &[(&str, serde_json::Value)]) {
let Some(path) = spool_path() else { return };
emit_to(&path, kind, fields);
}
pub fn emit_to(path: &std::path::Path, kind: &str, fields: &[(&str, serde_json::Value)]) {
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut obj = serde_json::Map::new();
obj.insert("kind".into(), kind.into());
obj.insert(
"ts".into(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
.into(),
);
if let Ok(agent) = std::env::var("SHANTY_AGENT") {
obj.insert("agent".into(), agent.into());
}
if let Ok(tenant) = std::env::var("BOBBIN_ROLE") {
obj.insert("tenant".into(), tenant.into());
}
if let Some(item) = crate::plate::current() {
obj.insert("item".into(), item.into());
}
for (k, v) in fields {
obj.insert((*k).into(), v.clone());
}
let Ok(line) = serde_json::to_string(&serde_json::Value::Object(obj)) else {
return;
};
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Ok(meta) = std::fs::metadata(path) {
if meta.len() > ROTATE_BYTES {
let _ = std::fs::rename(path, path.with_extension("jsonl.old"));
}
}
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
{
let _ = writeln!(f, "{line}");
}
}));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn precedence_explicit_then_xdg_then_home() {
assert_eq!(
resolve_path(Some("/x/m.jsonl"), Some("/s"), Some("/h")).unwrap(),
PathBuf::from("/x/m.jsonl")
);
assert_eq!(
resolve_path(None, Some("/s"), Some("/h")).unwrap(),
PathBuf::from("/s/hank/metrics.jsonl")
);
assert_eq!(
resolve_path(None, None, Some("/h")).unwrap(),
PathBuf::from("/h/.local/state/hank/metrics.jsonl")
);
assert!(resolve_path(None, None, None).is_none());
}
#[test]
fn a_line_is_valid_json_with_kind_and_fields() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("m.jsonl");
emit_to(
&p,
"guard",
&[("result", "deny".into()), ("duration_ms", 12.into())],
);
let text = std::fs::read_to_string(&p).unwrap();
let v: serde_json::Value = serde_json::from_str(text.trim()).unwrap();
assert_eq!(v["kind"], "guard");
assert_eq!(v["result"], "deny");
assert_eq!(v["duration_ms"], 12);
assert!(v["ts"].as_u64().unwrap() > 0);
}
#[test]
fn lines_append_never_replace() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("m.jsonl");
emit_to(&p, "command", &[("cmd", "impact".into())]);
emit_to(&p, "command", &[("cmd", "verify".into())]);
assert_eq!(std::fs::read_to_string(&p).unwrap().lines().count(), 2);
}
#[test]
fn an_unwritable_path_is_swallowed_whole() {
let dir = tempfile::tempdir().unwrap();
emit_to(dir.path(), "guard", &[("result", "allow".into())]);
}
#[test]
fn the_spool_rotates_at_the_ceiling_instead_of_growing() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("m.jsonl");
std::fs::write(&p, vec![b'x'; (ROTATE_BYTES + 1) as usize]).unwrap();
emit_to(&p, "guard", &[("result", "allow".into())]);
assert!(
p.with_extension("jsonl.old").exists(),
"the big file rolled aside"
);
assert_eq!(
std::fs::read_to_string(&p).unwrap().lines().count(),
1,
"the fresh spool holds only the new line"
);
}
}