session_core/
guard_log.rs1use host::file_hooks::{GuardRecord, OnRecord};
8use serde_json::{Value, json};
9use std::io::Write;
10use std::path::{Path, PathBuf};
11use std::sync::{Arc, Mutex};
12
13pub const LOKI_LOG_ENV: &str = "ULTRON_LOKI_LOG";
14
15fn log_line(at: u64, record: &GuardRecord) -> String {
17 let mut line = json!({ "at": at });
18 if let (Value::Object(line), Value::Object(fields)) = (&mut line, record.to_json()) {
19 line.extend(fields);
20 }
21 format!("{line}\n")
22}
23
24fn target(value: Option<&str>) -> Option<PathBuf> {
26 let path = value.map(str::trim).filter(|path| !path.is_empty())?;
27 Some(std::path::absolute(Path::new(path)).unwrap_or_else(|_| PathBuf::from(path)))
28}
29
30static APPENDING: Mutex<()> = Mutex::new(());
32
33fn append(target: &Path, line: &str) {
34 let _held = APPENDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
35 if let Some(parent) = target.parent() {
36 let _ = std::fs::create_dir_all(parent);
37 }
38 if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(target) {
39 let _ = file.write_all(line.as_bytes());
40 }
41}
42
43pub fn loki_log(value: Option<&str>) -> Option<OnRecord> {
45 let target = target(value)?;
46 Some(Arc::new(move |record: &GuardRecord| {
47 append(&target, &log_line(jsrt::date::now_ms() as u64, record))
48 }))
49}
50
51pub fn setup_record(mode: &str, project_python: Option<&str>, ms: u64) -> Value {
55 json!({
56 "phase": "setup",
57 "outcome": "on",
58 "mode": mode,
59 "engine": "bundled",
60 "reports": "json",
61 "projectPython": project_python,
62 "ms": ms,
63 })
64}
65
66pub fn project_python(var: &dyn Fn(&str) -> Option<String>, cwd: &Path) -> Option<String> {
70 loki::project::find_project_python(cwd, var)
71}
72
73pub fn loki_setup(config: &crate::compose::Config) {
76 let started = std::time::Instant::now();
77 let mode = match config.loki {
78 host::loki_guard::LokiMode::Off => return,
79 host::loki_guard::LokiMode::Advise => "advise",
80 host::loki_guard::LokiMode::On => "on",
81 };
82 let Some(target) = target((config.var)(LOKI_LOG_ENV).as_deref()) else {
83 return;
84 };
85 let python = project_python(&|key| (config.var)(key), &config.cwd);
86 let record = setup_record(mode, python.as_deref(), started.elapsed().as_millis() as u64);
87 let mut line = json!({ "at": jsrt::date::now_ms() as u64 });
88 if let (Value::Object(line), Value::Object(fields)) = (&mut line, record) {
89 line.extend(fields);
90 }
91 append(&target, &format!("{line}\n"));
92}