Skip to main content

session_core/
guard_log.rs

1//! `ULTRON_LOKI_LOG` (loki.ts `lokiLog`): every file-hook guard outcome appended to a file as a JSON line
2//! `{"at": <ms since the epoch>, "guard", "phase", "outcome", "ms", "paths", "lane", "detail"?}`, and the session's
3//! Loki setup (`setupLoki`'s record) as `{"at", "phase": "setup", "outcome": "on", "mode", "engine", "reports",
4//! "projectPython", "ms"}`. Unset or blank writes nothing; a relative path is resolved against the process directory;
5//! write errors are ignored.
6
7use 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
15/// One log line: `JSON.stringify({ at, ...record })`.
16fn 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
24/// Where `value` (the variable's text) points; None when unset or blank.
25fn 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
30/// Lines written by one process go out one at a time.
31static 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
43/// The appender for `value` (the variable's text); None when unset or blank.
44pub 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
51/// `setupLoki`'s record of a session whose Loki guard is on: the in-process engine (`bundled`: a repository's own
52/// `.loki/loki.py` is never run, its `.loki/` policy is read), structured reports, the project interpreter named for
53/// it, and how long setting it up took.
54pub 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
66/// `findProjectPython` (loki::project): ULTRON_LOKI_PROJECT_PYTHON, else nothing when LOKI_PYTHON is set (left to
67/// the engine), else the session PATH's `python`/`python3` when it is a virtual or conda environment's, else a
68/// `.venv` or `venv` interpreter in `cwd`.
69pub fn project_python(var: &dyn Fn(&str) -> Option<String>, cwd: &Path) -> Option<String> {
70    loki::project::find_project_python(cwd, var)
71}
72
73/// The session's Loki setup, written to `ULTRON_LOKI_LOG` when the guard is on (loki.ts `options.record?.({phase:
74/// "setup", ...})`).
75pub 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}