From 769782d921ea1229e9a67ef173eab569f564c73f Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 27 Nov 2026 10:41:36 +0000 Subject: usage: record what a request ran on, and put it in the access line The line was built by middleware that never sees a body, so on /compute/* it named the endpoint but not the data: 706 compute requests in the week to 2026-11-27, and the dataset could only be guessed from whatever the same user had read a minute earlier (29% of them resolved to a dataset, 61% only to a group, 20% to a visit over half an hour old). So a handler that knows the answer says it. `usage!(ctx, dataset = ..., engine = ...)` writes into a per-request slot that tag_caller opens before routing and merges in after the handler -- the CallerSlot pattern, down to the Arc, which matters because compute clones its Ctx for the fallback path and both handles must land in the one line. Values are JSON, not text: hits stays a number and cached a bool, and a string is bounded at 200 characters on a boundary, because `q` on /search is caller text. RESERVED keeps a handler from overwriting the line's own fields, and TRACKED lists the handlers that must report, with a test that reads each route file so one edited later cannot silently go dark. Not every route, deliberately: a read route already carries its dataset in the path, so instrumenting it would only duplicate the path into the line. The tracked set is the compute family plus /search. --- src/usage.rs | 333 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 333 insertions(+) create mode 100644 src/usage.rs (limited to 'src/usage.rs') diff --git a/src/usage.rs b/src/usage.rs new file mode 100644 index 0000000..2f18613 --- /dev/null +++ b/src/usage.rs @@ -0,0 +1,333 @@ +//! What the *work* was, for the access log — the half a path cannot say. +//! +//! The access line (`request_log_line`, src/lib.rs) is built by middleware +//! that never sees a request body, so on its own it can say which endpoint +//! ran but not which data it ran on: `/compute/gemma` names its panel in +//! the body (`group`, `genotype_file`, `genotype_upload`), and +//! `/compute/bulklmm` names its traits there too. Measured on the week to +//! 2026-11-27, that is 706 of 2 272 requests whose dataset could only be +//! *guessed* from whatever the same user had read a minute earlier. +//! +//! So a handler that knows the answer says it, once, and the line grows +//! those fields: +//! +//! ```ignore +//! usage!(ctx, dataset = &group, engine = "pangemma", run = &run_id); +//! // {"event":"request", …, "dataset":"HSNIH-Palmer","engine":"pangemma","run":"t42"} +//! ``` +//! +//! Deliberately **not** every route: a read route already carries the +//! dataset (`/traits/{dataset}/{trait}/values`) or the group +//! (`/groups/{group}/…`) in its path, so instrumenting it would only +//! duplicate the path into the line. The tracked set is the compute +//! family, listed in [`TRACKED`], plus `/search` — whose query string the +//! line drops on purpose (a query string can carry a credential), which +//! is why `q` is recorded here instead, by the handler, sanitised. +//! +//! Two rules for a value: it is **not a secret** (never a token, a hash or +//! a file's contents), and it is **bounded** — [`MAX_VALUE`] characters, +//! truncated by `note`, because a field a caller controls must not become +//! a way to write megabytes into the log. + +use std::sync::{Arc, Mutex}; + +/// The longest value a field may carry. `q` on `/search` is caller text, +/// and a query can be long: the line stays readable and bounded. +pub const MAX_VALUE: usize = 200; + +/// Keys the line already owns. A handler must not write one of these: it +/// would overwrite the request's own record (`status`, `user`) or invent a +/// second `path`. Checked by [`tests::no_tracked_field_shadows_the_line`]. +pub const RESERVED: &[&str] = &[ + "event", + "method", + "path", + "status", + "took_ms", + "ts", + "request_id", + "user", + "scheme", + "token", +]; + +/// The handlers that must report what they ran on, and the fields each is +/// expected to add. This is documentation *and* the guard: a test walks +/// [`TRACKED`] against the source (see [`tests::every_tracked_handler_reports`]), +/// so a handler edited later without its `usage!` call fails a test rather +/// than silently going dark. +/// +/// Field meanings, shared across handlers so the log stays joinable: +/// +/// - `dataset`: a GeneNetwork dataset name (`UTHSC_BXD_Cochlea_0225`), or a +/// panel name when the request named a group. Use `group` for the second +/// case; both is best (`dataset = group` when they are the same). +/// - `group`: an `InbredSet` name (`BXD`, `HSNIH-Palmer`). +/// - `trait`: the trait id or name the request named, when it named one. +/// - `traits`: how many, for the multi-trait routes (`bulklmm`, `bnw`). +/// - `source`: where the data came from: `group`, `file`, `upload`, +/// `basket`, `values`. +/// - `engine`: `gemma` | `pangemma` | `ravanan` | `rqtl` | `qtl2` | +/// `bulklmm` | `bnw` | `native` | `gn3`. +/// - `cached`: `true` when the answer came from a cache instead of a run. +/// - `run`: the run id the caller can poll or fetch. +/// - `q`: the sanitised `/search` query. +pub const TRACKED: &[(&str, &[&str])] = &[ + ("compute_gemma", &["dataset", "group", "source", "engine", "run"]), + ("compute_gemma_ravanan", &["dataset", "group", "source", "engine", "run"]), + ("compute_gemma_async", &["dataset", "group", "source", "engine"]), + ("compute_qtl2", &["dataset", "group", "source", "trait", "engine", "run"]), + ("compute_rqtl", &["dataset", "group", "source", "trait", "engine", "run"]), + ("compute_fitqtl", &["dataset", "group", "source", "trait", "engine"]), + ("compute_bulklmm", &["group", "source", "trait", "engine"]), + ("compute_bnw", &["group", "traits", "engine"]), + ("compute_bnw_features", &["group", "traits", "engine"]), + ("search", &["q", "type", "engine", "hits"]), +]; + +/// Where a compute request's data came from: the `dataset`/`source` +/// pair every compute handler reports. +/// +/// Order matters and is the order a request may name them: a `group` is +/// the common case and names a panel (`HSNIH-Palmer`), then an upload (by +/// its handle, `Arabid.thaliana.genotypes.171126`), then a file on the +/// server -- logged by its stem, because the directory is an +/// implementation detail and `BXD.geno` says the same thing -- and last a +/// basket. `None` when the request gave only inline values, which is +/// honest: there is no dataset to name. +pub fn source<'a>( + group: Option<&'a str>, + upload: Option<&'a str>, + file: Option<&'a str>, + basket: Option<&'a str>, +) -> Option<(&'static str, String)> { + if let Some(group) = group.map(str::trim).filter(|group| !group.is_empty()) { + return Some(("group", group.to_string())); + } + if let Some(upload) = upload.map(str::trim).filter(|upload| !upload.is_empty()) { + return Some(("upload", upload.to_string())); + } + if let Some(file) = file.map(str::trim).filter(|file| !file.is_empty()) { + let stem = std::path::Path::new(file) + .file_stem() + .map(|stem| stem.to_string_lossy().to_string()) + .unwrap_or_else(|| file.to_string()); + return Some(("file", stem)); + } + if let Some(basket) = basket.map(str::trim).filter(|basket| !basket.is_empty()) { + return Some(("basket", basket.to_string())); + } + None +} + +/// The `engine` field: what the request asked for, else what the +/// deployment defaults to. Lower-cased, because the value is compared and +/// counted, not read. +pub fn engine(requested: Option<&str>, default: &str) -> String { + let engine = requested + .map(str::trim) + .filter(|engine| !engine.is_empty()) + .unwrap_or(default); + engine.to_ascii_lowercase() +} + +/// The per-request slot a handler writes its fields into. +/// +/// An `Arc` behind a mutex, exactly like [`crate::auth::CallerSlot`], for +/// the same reason: the handler is not the only holder of the request's +/// [`crate::response::Ctx`] (compute clones it for the fallback path), and +/// every handle must land in the one line. The lock is taken once per +/// note on an instrumented route and never otherwise. +#[derive(Clone, Debug, Default)] +pub struct UsageSlot(Arc>>); + +impl UsageSlot { + /// Record fields for the line. A later note with the same key replaces + /// the earlier one, so a handler can say what was asked at the top and + /// add `cached` once it knows. + pub fn note(&self, pairs: &[(&'static str, serde_json::Value)]) { + if pairs.is_empty() { + return; + } + let mut guard = match self.0.lock() { + Ok(guard) => guard, + // A poisoned slot must not fail a request: an access-log field + // is not worth a 500, and the line is still written without it. + Err(poisoned) => poisoned.into_inner(), + }; + for (key, value) in pairs { + debug_assert!( + !RESERVED.contains(key), + "{key} is a field of the line itself, not a usage field" + ); + debug_assert!( + !matches!(value, serde_json::Value::String(text) if text.len() > MAX_VALUE), + "note() should have truncated {key}" + ); + match guard.iter_mut().find(|(name, _)| name == key) { + Some(slot) => slot.1 = value.clone(), + None => guard.push((key, value.clone())), + } + } + } + + /// The fields noted so far, in the order they were first noted. + pub fn entries(&self) -> Vec<(&'static str, serde_json::Value)> { + match self.0.lock() { + Ok(guard) => guard.clone(), + Err(poisoned) => poisoned.into_inner().clone(), + } + } + + /// A value as the line will carry it: a string is bounded to + /// [`MAX_VALUE`] characters; a number or a bool stays one, so a reader + /// can count `hits` or test `cached` without parsing text back. + pub fn json>(value: T) -> serde_json::Value { + match value.into() { + serde_json::Value::String(text) => serde_json::Value::String(Self::bounded(&text)), + other => other, + } + } + + /// Truncate to [`MAX_VALUE`] characters, on a character boundary (the + /// query is caller text and may be multi-byte). + pub fn bounded(value: &str) -> String { + if value.len() <= MAX_VALUE { + return value.to_string(); + } + let mut end = MAX_VALUE; + while end > 0 && !value.is_char_boundary(end) { + end -= 1; + } + let mut truncated = value[..end].to_string(); + truncated.push('…'); + truncated + } +} + +/// Record usage fields for this request; see the module docs. Values are +/// anything `ToString` (`&str`, `String`, `bool`, numbers), so a handler +/// writes what it has without converting first. +/// +/// ```ignore +/// usage!(ctx, dataset = &group, source = "group", engine = "gemma"); +/// ``` +/// The key is `stringify!`ed, so it is written bare (`group = …`) and may be +/// a keyword (`type = …` on `/search`); it ends up a `&'static str` in the +/// line, which is what keeps a field name from being built at runtime. +#[macro_export] +macro_rules! usage { + ($ctx:expr $(, $key:tt = $value:expr )* $(,)?) => {{ + $ctx.note(&[ $( (stringify!($key), $crate::usage::UsageSlot::json($value)) ),* ]) + }}; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_note_is_read_back_in_order() { + let slot = UsageSlot::default(); + slot.note(&[ + ("dataset", "BXD".into()), + ("group", "BXD".into()), + ("cached", false.into()), + ("hits", 3.into()), + ]); + assert_eq!( + slot.entries(), + vec![ + ("dataset", serde_json::json!("BXD")), + ("group", serde_json::json!("BXD")), + ("cached", serde_json::json!(false)), + ("hits", serde_json::json!(3)), + ], + "a bool stays a bool and a number stays a number" + ); + } + + /// The handler may say what was asked at the top (`engine`) and add + /// what happened later (`cached`) without the line growing a duplicate. + #[test] + fn a_second_note_with_the_same_key_replaces_it() { + let slot = UsageSlot::default(); + slot.note(&[("cached", false.into())]); + slot.note(&[("cached", true.into())]); + assert_eq!(slot.entries(), vec![("cached", serde_json::json!(true))]); + } + + #[test] + fn an_empty_note_is_a_no_op() { + let slot = UsageSlot::default(); + slot.note(&[]); + assert!(slot.entries().is_empty()); + } + + /// `q` is caller text: bounded, and still valid UTF-8 after truncation. + #[test] + fn a_long_value_is_bounded_on_a_character_boundary() { + let long = "é".repeat(MAX_VALUE); + let bounded = UsageSlot::bounded(&long); + assert!(bounded.len() <= MAX_VALUE + '…'.len_utf8()); + assert!(bounded.ends_with('…')); + assert!(bounded.chars().all(|c| c == 'é' || c == '…')); + assert_eq!(UsageSlot::bounded("bxd"), "bxd"); + } + + /// A clone is another handle on the same line, not a second line: the + /// compute handlers clone `Ctx` for the fallback path. + #[test] + fn a_clone_writes_into_the_same_slot() { + let slot = UsageSlot::default(); + let clone = slot.clone(); + clone.note(&[("dataset", "HXB".into())]); + assert_eq!(slot.entries(), vec![("dataset", serde_json::json!("HXB"))]); + } + + #[test] + fn no_tracked_field_shadows_the_line() { + for (handler, fields) in TRACKED { + for field in *fields { + assert!( + !RESERVED.contains(field), + "{handler} would overwrite the line's own {field}" + ); + } + } + } + + /// The guard for a handler edited later without its `usage!` call: each + /// tracked handler's source must contain one. Crude on purpose — it + /// greps the file the handler lives in, so it costs nothing and cannot + /// pass by accident. + #[test] + fn every_tracked_handler_reports() { + let sources = [ + ("compute_gemma", include_str!("routes/gemma.rs")), + ("compute_gemma_ravanan", include_str!("routes/gemma.rs")), + ("compute_gemma_async", include_str!("routes/gemma.rs")), + ("compute_qtl2", include_str!("routes/qtl2.rs")), + ("compute_rqtl", include_str!("routes/rqtl.rs")), + ("compute_fitqtl", include_str!("routes/fitqtl.rs")), + ("compute_bulklmm", include_str!("routes/bulklmm.rs")), + ("compute_bnw", include_str!("routes/bnw.rs")), + ("compute_bnw_features", include_str!("routes/bnw.rs")), + ("search", include_str!("routes/search.rs")), + ]; + for (handler, source) in sources { + let start = source + .find(&format!("pub async fn {handler}(")) + .unwrap_or_else(|| panic!("{handler} is not in the source it should be")); + let rest = &source[start..]; + let end = rest.find("\npub async fn ").unwrap_or(rest.len()); + let body = &rest[..end]; + // `record_usage` is the shared helper the GEMMA handlers call; + // everything else writes the macro out. + assert!( + body.contains("usage!(") || body.contains("record_usage("), + "{handler} is in usage::TRACKED but records nothing" + ); + } + } +} -- cgit 1.4.1