Files
leleka/crates/obs/src/lib.rs
T

321 lines
12 KiB
Rust

//! Structured events for every Leleka process: one line per event, UTC millisecond timestamp, level, component, event
//! name and flat key/value fields; JSON lines when the output is a file (what the supervisor hands the children),
//! `key=value` text on a terminal. std only.
//!
//! Rules this crate enforces for every line, whoever wrote the call:
//! * text a user wrote (prompts, completions, tool arguments) and credentials never appear, see [`redact`];
//! * the volume is bounded: each event key has a token bucket ([`rate`]), values and lines are capped;
//! * a failure to write is ignored (a log consumer that went away must not take a request down).
//!
//! Environment: `LELEKA_LOG_LEVEL=debug|info|warn|error` (default info), `LELEKA_LOG_FORMAT=json|text|auto`
//! (auto: JSON unless stderr is a terminal), `LELEKA_LOG_DEBUG=1` (debug level, and the length of redacted text values
//! is logged next to the redaction marker; the text itself never is), `LELEKA_REQUEST_LOG=PATH` (the per-request
//! records go to this file instead of stderr), `LELEKA_LOG_LEGACY=1` (the lab scripts' plain lines, unsampled).
pub mod hist;
pub mod rate;
pub mod redact;
pub mod time;
pub use redact::{KeyClass, classify_key, register_secret};
pub use time::{format_utc_ms, now_ms, parse_duration_ms, parse_utc_ms};
use std::fmt::Write as _;
use std::io::{IsTerminal, Write as _};
use std::sync::{Mutex, OnceLock};
/// Longest string value in a line; longer ones are cut and end in `~`.
pub const MAX_VALUE: usize = 240;
/// Longest `msg` value (free text from a legacy call site).
pub const MAX_MSG: usize = 480;
/// Hard bound of a whole line, newline excluded.
pub const MAX_LINE: usize = 1536;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
Debug,
Info,
Warn,
Error,
}
/// A field value.
#[derive(Clone, Copy, Debug)]
pub enum V<'a> {
Str(&'a str),
Int(i64),
UInt(u64),
Float(f64),
Bool(bool),
Null,
}
pub type Field<'a> = (&'a str, V<'a>);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
Json,
Text,
}
#[derive(Clone, Copy, Debug)]
pub struct Settings {
pub min_level: Level,
pub format: Format,
/// `LELEKA_LOG_DEBUG`: debug level on, and the *length* of redacted text values is logged.
pub debug: bool,
/// `LELEKA_LOG_LEGACY=1`: the lab's unstructured lines exactly as before (no JSON, no sampling) for the scripts
/// that parse them; the secret scrub still applies.
pub legacy: bool,
}
static SETTINGS: OnceLock<Settings> = OnceLock::new();
enum Rendered {
Str(String),
Raw(String),
}
static LIMITER: std::sync::LazyLock<rate::Limiter> = std::sync::LazyLock::new(rate::Limiter::new);
/// An append-only file that takes whole lines. Opened on first use; every failure is swallowed.
pub struct FileSink {
path: std::path::PathBuf,
file: Mutex<Option<std::fs::File>>,
}
/// `warn!`-style free text through the legacy path, keyed by the call site: `obs_msg!(Level::Info, "api", "fmt {}",
/// x)`.
#[macro_export]
macro_rules! obs_msg {
($level:expr, $comp:expr, $($arg:tt)*) => {{
$crate::emit_msg($level, $comp, concat!(file!(), ":", line!()), &::std::format!($($arg)*));
}};
}
#[cfg(test)]
mod tests {
use super::*;
const JSON: Settings = Settings { min_level: Level::Info, format: Format::Json, debug: false, legacy: false };
const TEXT: Settings = Settings { min_level: Level::Info, format: Format::Text, debug: false, legacy: false };
const DEBUG: Settings = Settings { min_level: Level::Debug, format: Format::Json, debug: true, legacy: false };
#[test]
fn a_line_is_one_json_object_with_the_fixed_prefix() {
let line = format_line(
&JSON,
1_793_613_072_345,
Level::Warn,
"supervisor",
"engine_exit",
&[
("code", 137u32.into()),
("reason", "signal 9".into()),
("restart", true.into()),
("ratio", 0.5f64.into()),
("gone", V::Null),
],
0,
);
assert!(line.starts_with("{\"ts\":\"20") && line.ends_with('}') && !line.contains('\n'), "{line}");
assert!(line.contains("\"lvl\":\"warn\",\"comp\":\"supervisor\",\"ev\":\"engine_exit\""), "{line}");
assert!(
line.contains("\"code\":137,\"reason\":\"signal 9\",\"restart\":true,\"ratio\":0.5,\"gone\":null"),
"{line}"
);
}
#[test]
fn strings_are_escaped_and_non_finite_numbers_become_null() {
let line = format_line(
&JSON,
0,
Level::Info,
"api",
"x",
&[("msg", "a\"b\\c\nd\u{1}".into()), ("nan", f64::NAN.into())],
0,
);
assert!(line.contains(r#""msg":"a\"b\\c\nd\u0001""#), "{line}");
assert!(line.contains("\"nan\":null"), "{line}");
assert!(!line.contains('\n'));
}
#[test]
fn the_text_format_is_key_value() {
let line = format_line(
&TEXT,
0,
Level::Info,
"api",
"request",
&[("rid", "req-1".into()), ("msg", "two words".into()), ("n", 5u64.into())],
3,
);
assert_eq!(line, "1970-01-01T00:00:00.000Z INFO api request rid=req-1 msg=\"two words\" n=5 suppressed=3");
}
#[test]
fn prompt_and_completion_text_never_appear() {
let secret_prompt = "please refactor the payment module for customer 4417-XYZ";
let line = format_line(
&JSON,
0,
Level::Info,
"api",
"request",
&[
("prompt", secret_prompt.into()),
("completion", "sure, here is the code".into()),
("content", "hello".into()),
("output_text", "answer text".into()),
("tool_arguments", "{\"cmd\":\"rm -rf\"}".into()),
("ptok", 12u64.into()),
],
0,
);
for leaked in ["payment", "4417", "sure, here", "hello", "answer text", "rm -rf"] {
assert!(!line.contains(leaked), "{leaked} leaked: {line}");
}
assert!(line.contains("\"prompt\":\"[redacted]\"") && line.contains("\"ptok\":12"), "{line}");
assert!(!line.contains("prompt_len"), "lengths are a debug opt-in: {line}");
}
#[test]
fn the_debug_opt_in_adds_lengths_only() {
let line = format_line(&DEBUG, 0, Level::Debug, "api", "x", &[("prompt", "0123456789".into())], 0);
assert!(
line.contains("\"prompt_len\":10")
&& line.contains("\"prompt\":\"[redacted]\"")
&& !line.contains("0123456789"),
"{line}"
);
}
#[test]
fn credentials_never_appear_under_any_key() {
register_secret("sk-live-0123456789abcdefghijklmnop");
let line = format_line(
&JSON,
0,
Level::Error,
"api",
"auth",
&[
("api_key", "sk-live-0123456789abcdefghijklmnop".into()),
("authorization", "Bearer abc".into()),
("note", "header was Bearer tokentokentoken123".into()),
("msg", "loaded key sk-live-0123456789abcdefghijklmnop from file".into()),
("hf_token", "hf_whatever".into()),
],
0,
);
for leaked in ["sk-live", "abc\"", "tokentokentoken123", "hf_whatever", "0123456789abcdefghijklmnop"] {
assert!(!line.contains(leaked), "{leaked} leaked: {line}");
}
}
#[test]
fn values_and_lines_are_bounded() {
let long = "x ".repeat(2000);
let line =
format_line(&JSON, 0, Level::Info, "api", "x", &[("msg", long.as_str().into()), ("a", 1u64.into())], 0);
assert!(line.len() < MAX_LINE, "{}", line.len());
assert!(line.contains('~'));
let many: Vec<(String, u64)> = (0..400).map(|i| (format!("f{i}"), u64::MAX)).collect();
let fields: Vec<Field<'_>> = many.iter().map(|(k, v)| (k.as_str(), V::UInt(*v))).collect();
let line = format_line(&JSON, 0, Level::Info, "api", "x", &fields, 0);
assert!(line.len() <= MAX_LINE && line.contains("\"trunc\":true"), "{}", line.len());
}
#[test]
fn settings_come_from_the_environment() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| (*v).to_owned())
};
// by hand into a file: the plain lines the lab scripts read; on a terminal: key=value text, sampled
let s = Settings::from_env(env(&[]), false);
assert_eq!((s.min_level, s.format, s.debug, s.legacy), (Level::Info, Format::Text, false, true));
let s = Settings::from_env(env(&[]), true);
assert_eq!((s.format, s.legacy), (Format::Text, false));
// under `leleka run`: JSON lines, never legacy
let s = Settings::from_env(env(&[("LELEKA_LOG_FORMAT", "json"), ("LELEKA_LOG_LEVEL", "warn")]), false);
assert_eq!((s.min_level, s.format, s.legacy), (Level::Warn, Format::Json, false));
let s = Settings::from_env(env(&[("LELEKA_LOG_FORMAT", "text")]), false);
assert_eq!((s.format, s.legacy), (Format::Text, false));
let s = Settings::from_env(env(&[("LELEKA_LOG_FORMAT", "json"), ("LELEKA_LOG_LEGACY", "1")]), false);
assert!(s.legacy);
let s = Settings::from_env(env(&[("LELEKA_LOG_DEBUG", "1"), ("LELEKA_LOG_LEVEL", "error")]), false);
assert_eq!((s.min_level, s.debug), (Level::Debug, true));
}
#[test]
fn request_ids_are_unique_and_ordered() {
let a = new_request_id();
let b = new_request_id();
assert_ne!(a, b);
assert!(a.starts_with("req-") && a.len() < 24, "{a}");
}
#[test]
fn the_file_sink_appends_whole_lines_and_survives_truncation() {
let dir = std::env::temp_dir().join(format!("leleka-obs-sink-{}", std::process::id()));
let path = dir.join("requests.log");
let sink = FileSink::new(&path);
assert!(sink.write_line("{\"a\":1}") > 0);
assert!(sink.write_line("{\"a\":2}") > 0);
// the supervisor copy-truncates in place; an O_APPEND writer continues at the new end
std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len(0).unwrap();
assert!(sink.write_line("{\"a\":3}") > 0);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"a\":3}\n");
let _ = std::fs::remove_dir_all(&dir);
}
}
mod impl_level;
#[allow(unused_imports)]
use impl_level::clean_key;
#[allow(unused_imports)]
use impl_level::clean_key_dash;
#[allow(unused_imports)]
pub use impl_level::format_line;
#[allow(unused_imports)]
use impl_level::json_line;
#[allow(unused_imports)]
use impl_level::json_string;
#[allow(unused_imports)]
use impl_level::render_fields;
#[allow(unused_imports)]
pub use impl_level::settings;
#[allow(unused_imports)]
use impl_level::text_line;
mod write_stderr_fn;
#[allow(unused_imports)]
pub use write_stderr_fn::debug;
#[allow(unused_imports)]
pub use write_stderr_fn::emit;
#[allow(unused_imports)]
pub use write_stderr_fn::emit_always;
#[allow(unused_imports)]
pub use write_stderr_fn::emit_keyed;
#[allow(unused_imports)]
pub use write_stderr_fn::emit_msg;
#[allow(unused_imports)]
pub use write_stderr_fn::error;
#[allow(unused_imports)]
pub use write_stderr_fn::info;
#[allow(unused_imports)]
pub use write_stderr_fn::legacy_line;
#[allow(unused_imports)]
pub use write_stderr_fn::new_request_id;
#[allow(unused_imports)]
pub use write_stderr_fn::record;
#[allow(unused_imports)]
use write_stderr_fn::request_sink;
#[allow(unused_imports)]
pub use write_stderr_fn::trace_msg;
#[allow(unused_imports)]
pub use write_stderr_fn::warn;
#[allow(unused_imports)]
use write_stderr_fn::write_stderr;