//! The shell-command heads the bash daemon records in the turn-stats database, //! read for the OTEL bash-command counter. use std::path::PathBuf; use rusqlite::{Connection, OpenFlags}; fn default_path() -> PathBuf { crate::paths::harness_dir().join("hyperhive-turn-stats.sqlite") } /// The shell-command heads recorded after `since` (unix seconds, exclusive), /// with how often each ran, for the OTEL bash-command counter. Reads the live /// database read-only; a missing database or `bash_commands` table (no bash /// task has run yet) is an empty list, not an error. #[must_use] pub fn bash_heads_since(since: i64) -> Vec<(String, u64)> { let Ok(conn) = Connection::open_with_flags(default_path(), OpenFlags::SQLITE_OPEN_READ_ONLY) else { return Vec::new(); }; let _ = conn.busy_timeout(std::time::Duration::from_millis(500)); read_bash_heads_since(&conn, since).unwrap_or_default() } fn read_bash_heads_since(conn: &Connection, since: i64) -> rusqlite::Result> { let mut stmt = conn.prepare("SELECT head, COUNT(*) FROM bash_commands WHERE ts > ?1 GROUP BY head")?; let rows = stmt.query_map([since], |row| { Ok(( row.get::<_, String>(0)?, u64::try_from(row.get::<_, i64>(1)?).unwrap_or(0), )) })?; rows.collect() } #[cfg(test)] mod tests { use super::*; use rusqlite::params; /// The OTEL bash-command counter reads only the heads recorded after its /// watermark, and a database without the table yields nothing. #[test] fn bash_heads_since_counts_only_newer_rows() { let conn = Connection::open_in_memory().unwrap(); assert!(read_bash_heads_since(&conn, 0).is_err(), "no table yet"); conn.execute_batch("CREATE TABLE bash_commands (ts INTEGER NOT NULL, head TEXT NOT NULL);") .unwrap(); for (ts, head) in [(10, "cargo"), (20, "cargo"), (30, "git"), (30, "cargo")] { conn.execute( "INSERT INTO bash_commands (ts, head) VALUES (?1, ?2)", params![ts, head], ) .unwrap(); } let mut got = read_bash_heads_since(&conn, 10).unwrap(); got.sort(); assert_eq!(got, vec![("cargo".to_owned(), 2), ("git".to_owned(), 1)]); assert!(read_bash_heads_since(&conn, 30).unwrap().is_empty()); } }