about summary refs log tree commit diff
path: root/src/usage.rs
blob: 2f18613f324ae37f50ba8689ebe228fdab123c3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
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<Mutex<Vec<(&'static str, serde_json::Value)>>>);

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<T: Into<serde_json::Value>>(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"
            );
        }
    }
}