use host::file_hooks::{GuardRecord, OnRecord};
use serde_json::{Value, json};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
pub const LOKI_LOG_ENV: &str = "ULTRON_LOKI_LOG";
fn log_line(at: u64, record: &GuardRecord) -> String {
let mut line = json!({ "at": at });
if let (Value::Object(line), Value::Object(fields)) = (&mut line, record.to_json()) {
line.extend(fields);
}
format!("{line}\n")
}
fn target(value: Option<&str>) -> Option<PathBuf> {
let path = value.map(str::trim).filter(|path| !path.is_empty())?;
Some(std::path::absolute(Path::new(path)).unwrap_or_else(|_| PathBuf::from(path)))
}
static APPENDING: Mutex<()> = Mutex::new(());
fn append(target: &Path, line: &str) {
let _held = APPENDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(parent) = target.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(target) {
let _ = file.write_all(line.as_bytes());
}
}
pub fn loki_log(value: Option<&str>) -> Option<OnRecord> {
let target = target(value)?;
Some(Arc::new(move |record: &GuardRecord| {
append(&target, &log_line(jsrt::date::now_ms() as u64, record))
}))
}
pub fn setup_record(mode: &str, project_python: Option<&str>, ms: u64) -> Value {
json!({
"phase": "setup",
"outcome": "on",
"mode": mode,
"engine": "bundled",
"reports": "json",
"projectPython": project_python,
"ms": ms,
})
}
pub fn project_python(var: &dyn Fn(&str) -> Option<String>, cwd: &Path) -> Option<String> {
loki::project::find_project_python(cwd, var)
}
pub fn loki_setup(config: &crate::compose::Config) {
let started = std::time::Instant::now();
let mode = match config.loki {
host::loki_guard::LokiMode::Off => return,
host::loki_guard::LokiMode::Advise => "advise",
host::loki_guard::LokiMode::On => "on",
};
let Some(target) = target((config.var)(LOKI_LOG_ENV).as_deref()) else {
return;
};
let python = project_python(&|key| (config.var)(key), &config.cwd);
let record = setup_record(mode, python.as_deref(), started.elapsed().as_millis() as u64);
let mut line = json!({ "at": jsrt::date::now_ms() as u64 });
if let (Value::Object(line), Value::Object(fields)) = (&mut line, record) {
line.extend(fields);
}
append(&target, &format!("{line}\n"));
}