From 304b92e310df9570a67ef3cdd3bbcc714569bc83 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Mon, 16 Nov 2026 18:14:29 +0000 Subject: correlation: PC traits as basket columns, and compare-two-traits **PC traits.** `pca.traits` carries each component *as a trait*: PC1, PC2, ... with a score per individual, so a component can be used the way GN2's "PCA traits" are -- correlated, mapped, plotted, saved. Scores are the standardised values projected onto the loadings, standardised with the sample standard deviation because that is what the correlation matrix was built from; a constant trait has no z-score and refuses rather than filling a zero. They live on the complete cases of the kept traits (31 of 34 in the fixture), which is the honest reading of "a PCA is defined on a rectangle". The module story is a basket: POST /baskets with a PC's values gives a per-user, versioned, digest-recorded column (verified: 201, revision 1, values read back), which the mapping and plotting endpoints already accept. No new store, no new dataset concept. **Compare traits.** POST /compute/compare takes two trait references, keeps the individuals with a value for both, and returns r, p, n *and* the pairs -- the statistic and the data behind it. It agrees with the matrix: the same pair is r = 0.6756270426459695 in both. POST /plot/compare draws the scatter (6 303 bytes) with the individual's name in each tooltip and the OLS line implied by r and the two means; nothing is refitted. Monitor gained compute-compare and plot-compare; full run 49 ok, 0 failed, 1 skipped. Not done, deliberately: limit_to/ids_only/names_only. The listing handlers return typed rows (Envelope>), so "names only" is a shape change in every one of them -- a pass of its own rather than a query parameter. --- src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/lib.rs') diff --git a/src/lib.rs b/src/lib.rs index 976b2f1..c025c46 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -231,6 +231,8 @@ pub fn app() -> Router { .routes(routes!(routes::traits::trait_values)) .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) + .routes(routes!(routes::compare::compare)) + .routes(routes!(routes::compare::plot_compare)) .routes(routes!(routes::correlation::correlation)) .routes(routes!(routes::correlation_matrix::correlation_matrix)) .routes(routes!(routes::baskets::list_baskets)) -- cgit 1.4.1 From d4c7a85a2565997b3878f565af5e5198a4312907 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Mon, 16 Nov 2026 18:55:43 +0000 Subject: listing: the limit_to / ids_only / names_only model, with its tests The shared type for the three parameters GN2 has and we do not: one value per row (`ids_only`, `names_only`), a case-insensitive `limit_to` over id / name / trait_name / display_name / full_name, the contradiction (both shapes at once) refused rather than resolved by parse order, and a `limit_to` value that matches nothing *reported* instead of silently dropped -- "my trait is missing" is the failure this parameter exists to prevent. Five tests: identity, ids/names shaping, limit_to matching any field and being case-insensitive, its composition with ids_only, and the refusal. Status, recorded in the module docs because it is the interesting part: the handlers are NOT wired yet. A listing handler returns typed rows (`Envelope>`), so answering `["BXD", ...]` changes its return type to `Envelope` and the `body =` type in its utoipa block, which utoipa checks at compile time -- a mismatch fails as "could not find `__path_groups`", which looks like a macro bug and is not one. Six handlers or none: two would leave the API inconsistent, which is worse than not having the parameter at all. Build green with the module and its tests; nothing deployed, since until a handler uses it the binary is unchanged. --- src/lib.rs | 1 + src/listing.rs | 221 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 222 insertions(+) create mode 100644 src/listing.rs (limited to 'src/lib.rs') diff --git a/src/lib.rs b/src/lib.rs index c025c46..1d60f9d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,6 +23,7 @@ pub mod frequencies; pub mod genoupload; pub mod genotypes; pub mod heatmap; +pub mod listing; pub mod normalize; mod plot; mod error; diff --git a/src/listing.rs b/src/listing.rs new file mode 100644 index 0000000..fa42cb5 --- /dev/null +++ b/src/listing.rs @@ -0,0 +1,221 @@ +//! The shape of a listing: `limit_to`, `ids_only`, `names_only`. +//! +//! GN2 offers all three on its listings, and a client that has to enumerate a +//! group's 20 000 traits wants them for the same reason: a 2 MB answer of +//! objects to build a dropdown is a waste of everyone's connection. The three +//! are one concept, so they live in one type rather than being copied into each +//! handler's query struct: +//! +//! * `limit_to=a,b,c` keeps only the rows whose id, name, full name or trait +//! name matches one of the listed values (case-insensitive). A value that +//! matches nothing is named in the reply's note rather than silently ignored, +//! because "my trait's missing" is the failure mode this exists to prevent. +//! * `ids_only=true` answers `["BXD", "BXH", ...]` instead of objects. +//! * `names_only=true` answers `["BXD", ...]` too, but from the *name* field; +//! asking for both is a contradiction and is refused rather than guessed. +//! +//! Rows keep their order, so a caller can zip the slim answer against what it +//! asked for. +//! +//! **Status: the type and its tests are in, the handlers are not wired yet.** +//! Wiring one is small but not mechanical: a listing handler returns typed rows +//! (`Envelope>`), so answering with `["BXD", ...]` changes its +//! return type to `Envelope` *and* the `body =` type in its +//! `utoipa::path` block, which utoipa checks at compile time (a mismatch fails +//! with "could not find `__path_`", which reads like a macro problem +//! and is not one). Doing that for six handlers is a pass of its own; doing it +//! for two would leave the API inconsistent, which is worse than not having it. + +use serde::Deserialize; + +/// Query parameters three listings share. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct ListingParams { + /// Keep only these ids or names, comma-separated. + #[serde(default)] + pub limit_to: Option, + /// Answer with ids only. + #[serde(default)] + pub ids_only: Option, + /// Answer with names only. + #[serde(default)] + pub names_only: Option, +} + +/// What a listing should answer with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Listing { + /// The rows as they are. + Full, + /// One identifier per row, from this field. + Only(&'static str), +} + +/// The fields a `limit_to` value may match, in the order they are tried. +const MATCH_FIELDS: [&str; 5] = ["id", "name", "trait_name", "display_name", "full_name"]; +/// Where an `ids_only` answer takes its value from. +const ID_FIELDS: [&str; 4] = ["id", "name", "trait_name", "abbreviation"]; +/// Where a `names_only` answer takes its value from. +const NAME_FIELDS: [&str; 4] = ["name", "trait_name", "display_name", "id"]; + +impl Listing { + /// Read the parameters, refusing the contradiction. + pub fn parse(params: &ListingParams) -> Result { + let ids = params.ids_only.unwrap_or(false); + let names = params.names_only.unwrap_or(false); + match (ids, names) { + (true, true) => Err( + "ask for ids_only or names_only, not both: a row has one identifier and one name, \ + and which one you get should not depend on parse order" + .to_string(), + ), + (true, false) => Ok(Listing::Only("id")), + (false, true) => Ok(Listing::Only("name")), + (false, false) => Ok(Listing::Full), + } + } + + /// Shape `rows` (already serialised) according to the parameters. + /// + /// Returns the shaped array and, for a `limit_to` that matched nothing, the + /// values that were not found -- so the caller can say so. + pub fn apply( + &self, + rows: &serde_json::Value, + limit_to: Option<&str>, + ) -> (serde_json::Value, Vec) { + let Some(array) = rows.as_array() else { + return (rows.clone(), Vec::new()); + }; + let wanted: Option> = limit_to + .map(|text| { + text.split(',') + .map(|value| value.trim().to_lowercase()) + .filter(|value| !value.is_empty()) + .collect() + }) + .filter(|values: &Vec| !values.is_empty()); + + let mut kept: Vec = Vec::with_capacity(array.len()); + let mut found: Vec = Vec::new(); + for row in array { + if let Some(wanted) = &wanted { + let mut matched = false; + for field in MATCH_FIELDS { + if let Some(value) = row.get(field).and_then(|value| { + value + .as_str() + .map(str::to_string) + .or_else(|| value.as_i64().map(|n| n.to_string())) + }) { + let lowered = value.to_lowercase(); + if wanted.contains(&lowered) { + matched = true; + found.push(lowered); + break; + } + } + } + if !matched { + continue; + } + } + match self { + Listing::Full => kept.push(row.clone()), + Listing::Only(field) => { + let fields: &[&str] = if *field == "id" { &ID_FIELDS } else { &NAME_FIELDS }; + let value = fields + .iter() + .find_map(|candidate| row.get(*candidate)) + .cloned() + .unwrap_or(serde_json::Value::Null); + kept.push(value); + } + } + } + let missing = match &wanted { + Some(wanted) => wanted + .iter() + .filter(|value| !found.contains(value)) + .cloned() + .collect(), + None => Vec::new(), + }; + (serde_json::Value::Array(kept), missing) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn rows() -> serde_json::Value { + json!([ + {"id": 1, "name": "BXD", "full_name": "BXD recombinant inbreds"}, + {"id": 2, "name": "BXH", "full_name": "BXH recombinant inbreds"}, + {"id": 3, "name": "HET3-ITP", "full_name": "UM-HET3"} + ]) + } + + #[test] + fn full_leaves_the_rows_alone() { + let listing = Listing::parse(&ListingParams::default()).expect("default"); + assert_eq!(listing, Listing::Full); + let (shaped, missing) = listing.apply(&rows(), None); + assert_eq!(shaped, rows()); + assert!(missing.is_empty()); + } + + #[test] + fn ids_and_names_are_one_value_per_row() { + let ids = Listing::parse(&ListingParams { + ids_only: Some(true), + ..Default::default() + }) + .expect("ids"); + let (shaped, _) = ids.apply(&rows(), None); + assert_eq!(shaped, json!([1, 2, 3])); + + let names = Listing::parse(&ListingParams { + names_only: Some(true), + ..Default::default() + }) + .expect("names"); + let (shaped, _) = names.apply(&rows(), None); + assert_eq!(shaped, json!(["BXD", "BXH", "HET3-ITP"])); + } + + #[test] + fn limit_to_matches_any_of_the_matching_fields_case_insensitively() { + let listing = Listing::Full; + let (shaped, missing) = listing.apply(&rows(), Some("bxd,UM-HET3")); + assert_eq!(shaped.as_array().map(|rows| rows.len()), Some(2)); + assert!(missing.is_empty(), "both were found: {missing:?}"); + + let (shaped, missing) = listing.apply(&rows(), Some("bxd,nope")); + assert_eq!(shaped.as_array().map(|rows| rows.len()), Some(1)); + assert_eq!(missing, vec!["nope".to_string()], "the miss is reported, not dropped"); + } + + #[test] + fn limit_to_composes_with_ids_only() { + let listing = Listing::parse(&ListingParams { + ids_only: Some(true), + ..Default::default() + }) + .expect("ids"); + let (shaped, _) = listing.apply(&rows(), Some("BXH")); + assert_eq!(shaped, json!([2])); + } + + #[test] + fn asking_for_both_shapes_is_refused() { + let error = Listing::parse(&ListingParams { + ids_only: Some(true), + names_only: Some(true), + ..Default::default() + }); + assert!(error.is_err(), "ids_only + names_only must not be guessed"); + } +} -- cgit 1.4.1 From 4f7c1adc527defc54a6ea1aee77e205067a49120 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 09:07:14 +0000 Subject: compute: an async form, so a run that outlasts the client still returns a result A cold LOCO scan of a large panel is ~21 minutes of wall clock (measured from Slurm's own records: 20 GWA jobs, all started 17:40:01, 18-21 min each, last ended 18:01:27). A client cutoff at 300 s could never have returned one, and the connection closing took the answer with it -- the work already survived, as a tokio task under the compute gate, but nothing kept its result. POST /compute/gemma/async?id= -> 202 at once (0.0 s measured) with {id, state: running, status: url} GET /compute/gemma/result/ -> progress while running, the finished reply afterwards, the error if it failed The blocking endpoints are unchanged, so nothing that fits a client's patience switches to polling. Progress is what can be measured from outside the run: the process's clock, plus the cluster's job counts for this request's window (the same query meta.timing uses). The reply bodies are envelopes, like every other success response -- the openapi check in the build's check phase is what caught the first draft returning bare JSON, which is the contract doing its job. Measured on HSNIH-Palmer_true trait 10404 (warm): POST 202 in 0.0 s, polls showing state=running with growing elapsed_ms, then the finished envelope: 133,217 rows, engine pangemma, phases artifacts built 8,717 ms (a rebuild because the stale half-pair had been removed), workflow 7,894 ms, parse 146 ms, steps 20 cached, took_ms 45,932. --- src/lib.rs | 3 + src/routes/gemma.rs | 208 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/runs.rs | 126 +++++++++++++++++++++++++++++++ 3 files changed, 337 insertions(+) create mode 100644 src/runs.rs (limited to 'src/lib.rs') diff --git a/src/lib.rs b/src/lib.rs index 1d60f9d..4045818 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,7 @@ mod gemma; pub mod indexer; pub mod qtl2; pub mod response; +pub mod runs; mod routes; mod rqtl; pub mod search; @@ -286,6 +287,8 @@ pub fn app() -> Router { .routes(routes!(routes::gemma::compute_gemma)) .routes(routes!(routes::gemma::compute_gemma_ravanan)) .routes(routes!(routes::gemma::gemma_status)) + .routes(routes!(routes::gemma::compute_gemma_async)) + .routes(routes!(routes::gemma::gemma_result)) .routes(routes!(routes::fitqtl::compute_fitqtl)) .routes(routes!(routes::qtl2::compute_qtl2)) .routes(routes!(routes::rqtl::compute_rqtl)) diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 2716bfc..e97eea8 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -1593,6 +1593,214 @@ pub async fn compute_gemma_ravanan( ) -> Result>, ApiError> { gemma_via_ravanan(ctx, token, params, request, __gn4_claim, "compute_gemma_ravanan").await } +/// `POST /compute/gemma/async` -- start the same mapping a blocking call would, +/// and answer `202` at once with an id to poll. +/// +/// The blocking endpoints stay the default: this is for a run that cannot fit +/// in a client's patience, which on a large panel is any cold one (a cold +/// HSNIH-Palmer_true scan is ~20 minutes of wall clock; a 5-minute client +/// cutoff could never have returned an answer, and its connection closing used +/// to take the result with it). +#[utoipa::path(post, path = "/compute/gemma/async", + summary = "Start a mapping in the background and return an id to poll", + description = "Same request body as /compute/gemma. Answers 202 with the \ +run's id and the URL of /compute/gemma/result/{id}, which reports progress and \ +then the finished reply. Use it when the run may outlast the client: a cold \ +fit on a large panel takes tens of minutes, and a closed connection would \ +otherwise lose the answer.", + params(ComputeGemmaParams), + request_body = GemmaRequest, + responses( + (status = 202, description = "Run started; poll its id", + body = crate::response::Envelope), + (status = 409, description = "id already in use", body = ApiError) + ) +)] +pub async fn compute_gemma_async( + ctx: Ctx, + token: AuthToken, + Query(params): Query, + Json(request): Json, +) -> Result<(StatusCode, Json>), ApiError> { + let rid = ctx.request_info(); + let id = params + .id + .clone() + .filter(|id| !id.is_empty()) + .unwrap_or_else(|| { + // The request id is already a uuid (tower-http's MakeRequestUuid), + // and it is the natural name for a run started by this request. + let rid = ctx.request_info(); + format!( + "run-{}", + rid.id().unwrap_or_else(|| "anonymous".to_string()) + ) + }); + if !streaming::is_valid_run_id(&id) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_run_id", + "Invalid id", + "id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(), + "compute_gemma_async", + ) + .with_request_id(rid)); + } + let engine = match request.engine.as_deref() { + None => crate::gemma::GemmaEngine::Gemma, + Some(value) => crate::gemma::GemmaEngine::parse(value).ok_or_else(|| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_engine", + "Invalid engine", + format!("'{value}' is not an engine; use gemma (BIMBAM) or pangemma (lmdb store)."), + "compute_gemma_async", + ) + .with_request_id(rid.clone()) + })?, + }; + if !crate::runs::global().begin(&id, engine.as_str()) { + return Err(ApiError::new( + StatusCode::CONFLICT, + "run_id_in_use", + "Run id already in use", + format!("id '{id}' is already in use by another background run; pick a different id."), + "compute_gemma_async", + ) + .with_request_id(rid)); + } + + let job_id = id.clone(); + // A handle for the 202 body: `ctx` itself moves into the task below. + let reply_ctx = ctx.clone(); + let job_subject = token.sub.clone(); + let mut job_params = params.clone(); + job_params.id = Some(id.clone()); + tokio::spawn(async move { + let claim = crate::compute_gate::ravanan().claim_light( + &job_subject, + Some(&job_id), + "compute_gemma_async", + "compute_gemma_async", + "/compute/gemma/result", + ); + let outcome = gemma_via_ravanan( + ctx, + token, + job_params, + request, + claim, + "compute_gemma_async", + ) + .await; + match outcome { + Ok(Json(envelope)) => { + let body = serde_json::to_value(&envelope).unwrap_or(serde_json::Value::Null); + crate::runs::global().finish(&job_id, body); + } + Err(error) => { + let status = error.status; + let body = serde_json::to_value(&error).unwrap_or(serde_json::Value::Null); + crate::runs::global().fail(&job_id, status, body); + } + } + }); + + let envelope = reply_ctx + .envelope(serde_json::json!({ + "id": id, + "state": "running", + "engine": engine.as_str(), + "status": format!("/compute/gemma/result/{id}"), + })) + .with_note( + "The run is in flight. Poll `status`: it reports how long the run has been going \ + and what the cluster is doing, and returns the finished reply once it completes.", + ); + Ok((StatusCode::ACCEPTED, Json(envelope))) +} + +/// `GET /compute/gemma/result/{id}` -- progress while a background run is in +/// flight, its reply once it finishes, its error if it failed. +#[utoipa::path(get, path = "/compute/gemma/result/{id}", + summary = "Progress or the finished reply of a background mapping", + description = "While the run is in flight: its state, how long it has been \ +running and the cluster's job counts. Afterwards: exactly the body the blocking \ +endpoint would have returned (or the error it would have raised).", + params(("id" = String, Path, description = "The run id given to /compute/gemma/async")), + responses( + (status = 200, description = "Progress, or the finished reply", + body = crate::response::Envelope), + (status = 404, description = "No such run in this process", body = ApiError) + ) +)] +pub async fn gemma_result( + ctx: Ctx, + Path(id): Path, +) -> Result { + use axum::response::IntoResponse; + let rid = ctx.request_info(); + let Some(run) = crate::runs::global().get(&id) else { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "unknown_run", + "No such run", + format!( + "no background run '{id}' in this process; it may have finished before a \ + restart, in which case re-post the request (ravanan's store answers the \ + steps it already ran)." + ), + "compute_gemma_result", + ) + .with_request_id(rid)); + }; + match run.state.as_str() { + "finished" => { + let body = run.result.unwrap_or(serde_json::Value::Null); + Ok((StatusCode::OK, Json(body)).into_response()) + } + "failed" => { + let (status, body) = run.error.unwrap_or(( + 500, + serde_json::json!({"code": "internal_error", "detail": "no error recorded"}), + )); + let status = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + Ok((status, Json(body)).into_response()) + } + _ => { + // Still running: what we can measure from outside the run -- the + // clock, and the cluster's view of the jobs this request submitted. + let since_epoch = run + .started_at + .duration_since(std::time::UNIX_EPOCH) + .map(|since| since.as_secs()) + .unwrap_or(0); + let config = Config::load(); + let (cluster, steps) = crate::gemma::cluster_timing( + &config.ravanan_batch, + since_epoch, + &format!("{}/ravanan-store", config.ravanan_cache_dir), + ) + .await; + let envelope = ctx + .envelope(serde_json::json!({ + "id": id, + "state": "running", + "engine": run.engine, + "elapsed_ms": run.elapsed_ms(), + "cluster": cluster, + "steps_recorded": steps.len(), + })) + .with_note( + "Still running. elapsed_ms is this process's clock for the run, \ + meta.timing.cluster counts the jobs Slurm accepted for it, and \ + steps_recorded counts the step logs already in the store.", + ); + Ok((StatusCode::OK, Json(envelope)).into_response()) + } + } +} + /// The Slurm path, callable from either GEMMA endpoint. /// /// `/compute/gemma/ravanan` is this and nothing else, and `/compute/gemma` diff --git a/src/runs.rs b/src/runs.rs new file mode 100644 index 0000000..d62333f --- /dev/null +++ b/src/runs.rs @@ -0,0 +1,126 @@ +//! Compute runs started in the background, so a caller that cannot wait for a +//! long one -- a cold LOCO scan of a large panel is ~20 minutes here -- can +//! still collect its result. +//! +//! `POST /compute/gemma/async` registers an id, spawns the work and returns +//! `202` at once; `GET /compute/gemma/result/{id}` reports progress while it +//! runs and the finished reply afterwards. The blocking endpoints are +//! unchanged, so nothing that fits in a client's patience starts using this. +//! +//! In-process and unbounded on purpose: results live for the life of the +//! process (a finished reply, not a cache), so a restart forgets them -- the +//! same lifetime as the run itself, and the caller can always re-post, which +//! ravanan's store answers from its cache. +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Instant, SystemTime}; + +/// One background run. +#[derive(Clone)] +pub struct Run { + pub engine: String, + pub started: Instant, + pub started_at: SystemTime, + /// `running`, `finished` or `failed`. + pub state: String, + /// The finished reply's body, exactly as the blocking endpoint would have + /// answered it. + pub result: Option, + /// The failure body, with the status code the blocking endpoint would have + /// used, so a caller can tell a 4xx from a 5xx. + pub error: Option<(u16, serde_json::Value)>, +} + +impl Run { + pub fn elapsed_ms(&self) -> u64 { + self.started.elapsed().as_millis() as u64 + } +} + +#[derive(Clone, Default)] +pub struct Registry { + runs: Arc>>, +} + +fn registry() -> &'static Registry { + static REGISTRY: OnceLock = OnceLock::new(); + REGISTRY.get_or_init(Registry::default) +} + +/// What the handlers use. +pub fn global() -> &'static Registry { + registry() +} + +impl Registry { + /// Registers `id` as running. Returns false when it is already known, so a + /// caller cannot silently take over another run's id. + pub fn begin(&self, id: &str, engine: &str) -> bool { + let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + if runs.contains_key(id) { + return false; + } + runs.insert( + id.to_string(), + Run { + engine: engine.to_string(), + started: Instant::now(), + started_at: SystemTime::now(), + state: "running".to_string(), + result: None, + error: None, + }, + ); + true + } + + pub fn finish(&self, id: &str, body: serde_json::Value) { + let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(run) = runs.get_mut(id) { + run.state = "finished".to_string(); + run.result = Some(body); + } + } + + pub fn fail(&self, id: &str, status: u16, body: serde_json::Value) { + let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(run) = runs.get_mut(id) { + run.state = "failed".to_string(); + run.error = Some((status, body)); + } + } + + pub fn get(&self, id: &str) -> Option { + let runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + runs.get(id).cloned() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_run_is_registered_once_and_remembers_its_outcome() { + let registry = Registry::default(); + assert!(registry.begin("r1", "pangemma")); + assert!(!registry.begin("r1", "gemma"), "ids are not taken over"); + let run = registry.get("r1").expect("registered"); + assert_eq!(run.state, "running"); + assert_eq!(run.engine, "pangemma"); + registry.finish("r1", serde_json::json!({"data": []})); + let run = registry.get("r1").expect("still there"); + assert_eq!(run.state, "finished"); + assert_eq!(run.result.unwrap()["data"], serde_json::json!([])); + } + + #[test] + fn a_failure_keeps_the_status_the_blocking_endpoint_would_have_used() { + let registry = Registry::default(); + registry.begin("r2", "gemma"); + registry.fail("r2", 422, serde_json::json!({"code": "no_samples_aligned"})); + let run = registry.get("r2").expect("registered"); + assert_eq!(run.state, "failed"); + assert_eq!(run.error.unwrap().0, 422); + } +} -- cgit 1.4.1 From 3854e38fd8c4521df1f501dd6b093fe8b27a840a Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 17:04:30 +0000 Subject: api: a request body it cannot read answers in the envelope, not in text/plain An extractor's rejection never reaches a handler, so it never sees ApiError: axum answered "Failed to deserialize the JSON body ...: missing field `trait_name`" as text/plain. That is the one error class a client cannot parse, and it is the class a client most likely triggers. A middleware outside everything turns any non-JSON 4xx into the usual envelope, with the matched route as the operation id and the original text as the detail. --- src/json_errors.rs | 118 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 5 +++ 2 files changed, 123 insertions(+) create mode 100644 src/json_errors.rs (limited to 'src/lib.rs') diff --git a/src/json_errors.rs b/src/json_errors.rs new file mode 100644 index 0000000..458eea9 --- /dev/null +++ b/src/json_errors.rs @@ -0,0 +1,118 @@ +//! Make every client error answer in the API's own envelope. +//! +//! Extractor failures never reach a handler, so they never see `ApiError`: axum +//! answers a body it cannot deserialize with `text/plain`, e.g. +//! +//! ```text +//! Failed to deserialize the JSON body into the target type: +//! missing field `trait_name` at line 1 column 1387 +//! ``` +//! +//! That is the one error class a client cannot parse -- everything else carries +//! `code`, `detail` and `request_id`. Measured on the release service: a +//! `/compute/rqtl` call without `trait_name` answered 422 `text/plain`. +//! +//! A middleware fixes it in one place instead of adding a custom extractor to +//! every handler: if the response is a 4xx that is not already JSON, its body +//! becomes `{"type": "/errors/invalid_request", "title": ..., "status": ..., +//! "code": "invalid_request", "detail": , "error": null, +//! "operation_id": }`. +use axum::body::Body; +use axum::extract::MatchedPath; +use axum::http::{header, Request, StatusCode}; +use axum::middleware::Next; +use axum::response::Response; + +pub async fn jsonify_client_errors(request: Request, next: Next) -> Response { + // The matched route pattern is the closest thing to an operation id + // available this early; it names /compute/rqtl rather than the path asked. + let operation = request + .extensions() + .get::() + .map(|matched: &MatchedPath| matched.as_str().to_string()); + let mut response = next.run(request).await; + let status = response.status(); + if !status.is_client_error() { + return response; + } + let is_json = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(|value| value.starts_with("application/json")) + .unwrap_or(false); + if is_json { + return response; + } + // Take the body apart and rebuild it: the original text is the detail. + let (mut parts, body) = response.into_parts(); + let bytes = axum::body::to_bytes(body, 64 * 1024) + .await + .unwrap_or_default(); + let detail = String::from_utf8_lossy(&bytes).trim().to_string(); + let body = serde_json::json!({ + "type": "/errors/invalid_request", + "title": "Invalid request", + "status": status.as_u16(), + "code": match status { + StatusCode::UNSUPPORTED_MEDIA_TYPE => "unsupported_media_type", + StatusCode::PAYLOAD_TOO_LARGE => "payload_too_large", + _ => "invalid_request", + }, + "detail": if detail.is_empty() { "the request could not be read".to_string() } else { detail }, + "error": null, + "operation_id": operation, + "spec_url": "/openapi.json", + "next": null, + }); + let text = body.to_string(); + parts.headers.insert( + header::CONTENT_TYPE, + header::HeaderValue::from_static("application/json"), + ); + parts.headers.remove(header::CONTENT_LENGTH); + Response::from_parts(parts, Body::from(text)) +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::Router; + use axum::routing::post; + + async fn boom() -> StatusCode { + StatusCode::BAD_REQUEST + } + + /// A 4xx that is not JSON comes back as the envelope; a JSON one is left + /// alone. + #[tokio::test] + async fn a_plain_text_client_error_becomes_the_envelope() { + use tower::ServiceExt; + let app = Router::new() + .route("/boom", post(boom)) + .layer(axum::middleware::from_fn(jsonify_client_errors)); + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri("/boom") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()), + Some("application/json") + ); + let bytes = axum::body::to_bytes(response.into_body(), 4096).await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body["code"], "invalid_request"); + assert!(body["operation_id"].is_string()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 4045818..369bec1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,7 @@ mod gemma; pub mod indexer; pub mod qtl2; pub mod response; +pub mod json_errors; pub mod runs; mod routes; mod rqtl; @@ -335,6 +336,10 @@ pub fn app() -> Router { // Outermost, so the slot exists before the handler's extractors // run: see `tag_caller`. .layer(axum::middleware::from_fn(tag_caller)) + // Outside everything, so an extractor's rejection (which never + // reaches a handler) still answers in the API's envelope instead of + // axum's text/plain. + .layer(axum::middleware::from_fn(json_errors::jsonify_client_errors)) } /// The largest request body the API accepts: 64 MiB, comfortably above a -- cgit 1.4.1 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/lib.rs | 89 ++++++++++++++- src/response.rs | 38 ++++++- src/usage.rs | 333 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 454 insertions(+), 6 deletions(-) create mode 100644 src/usage.rs (limited to 'src/lib.rs') diff --git a/src/lib.rs b/src/lib.rs index 369bec1..bf1047b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -39,6 +39,7 @@ pub mod search; mod streaming; pub mod suggest; pub mod tokens; +pub mod usage; pub mod wikidata; use error::ApiError; @@ -90,6 +91,11 @@ async fn tag_caller( ) -> axum::response::Response { let slot = crate::auth::CallerSlot::default(); request.extensions_mut().insert(slot.clone()); + // What the *work* was (dataset, engine, cached, …): the handler knows + // it (it parses the body) and this middleware does not, so it opens a + // slot the same way, and reads it back below. See `crate::usage`. + let usage = crate::usage::UsageSlot::default(); + request.extensions_mut().insert(usage.clone()); let started = std::time::Instant::now(); let method = request.method().clone(); // The path only: a query string can carry a credential (`?token=`) and has @@ -125,6 +131,7 @@ async fn tag_caller( started.elapsed().as_millis(), request_id.as_deref(), caller.as_ref(), + &usage.entries(), ) ); } @@ -141,6 +148,12 @@ async fn tag_caller( /// lets `scripts/gn4-log.py` resolve the handle against the registry -- the /// subject as it is *now*, the token's status and its note -- without the log /// ever holding a secret or a hash. +/// +/// `usage` is what the handler added about the work itself (dataset, group, +/// engine, cached, run, `q`), and it is empty for every route that does not +/// call [`crate::usage`]'s macro. Those keys go after the request's own +/// fields, and [`crate::usage::RESERVED`] keeps a handler from overwriting +/// one of them. fn request_log_line( method: &str, path: &str, @@ -148,6 +161,7 @@ fn request_log_line( took_ms: u128, request_id: Option<&str>, caller: Option<&crate::auth::Caller>, + usage: &[(&'static str, serde_json::Value)], ) -> String { let mut line = serde_json::json!({ "event": "request", @@ -169,6 +183,11 @@ fn request_log_line( object.insert("token".to_string(), serde_json::json!(id)); } } + if let Some(object) = line.as_object_mut() { + for (key, value) in usage { + object.insert((*key).to_string(), value.clone()); + } + } line.to_string() } @@ -461,6 +480,7 @@ mod access_log_tests { 17, Some("abc"), Some(&caller(Scheme::Jwt, None, "zachs")), + &[], ); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert_eq!(parsed["event"], "request"); @@ -490,6 +510,7 @@ mod access_log_tests { 900, None, Some(&caller(Scheme::Opaque, Some("agent-ravanan-3"), "zachs")), + &[], ); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert_eq!(parsed["user"], "zachs"); @@ -502,9 +523,75 @@ mod access_log_tests { /// reader could mistake for a user name. #[test] fn no_user_field_when_nobody_was_identified() { - let line = request_log_line("GET", "/groups", 401, 0, None, None); + let line = request_log_line("GET", "/groups", 401, 0, None, None, &[]); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert!(parsed.get("user").is_none(), "{line}"); assert!(parsed.get("request_id").is_none(), "{line}"); } + + /// The wiring the whole feature rests on: the slot `tag_caller` puts in + /// the request extensions is the slot the handler's `Ctx` writes into and + /// the same one the line is built from. If these ever became two slots, + /// nothing would fail -- the lines would just lose their fields. + #[tokio::test] + async fn a_handler_writes_into_the_slot_the_logging_middleware_reads() { + use axum::extract::FromRequestParts; + + let slot = crate::usage::UsageSlot::default(); + let mut parts = axum::http::Request::builder() + .uri("/compute/gemma") + .body(()) + .unwrap() + .into_parts() + .0; + parts.extensions.insert(slot.clone()); + + let ctx = crate::response::Ctx::from_request_parts(&mut parts, &()) + .await + .unwrap(); + crate::usage!(ctx, dataset = "HSNIH-Palmer", engine = "gemma"); + // A clone of the handler's ctx (the fallback path) lands in the same + // place, and a second note replaces rather than duplicates. + crate::usage!(ctx.clone(), engine = "pangemma"); + + assert_eq!( + slot.entries(), + vec![ + ("dataset", serde_json::json!("HSNIH-Palmer")), + ("engine", serde_json::json!("pangemma")) + ], + "one slot, and the later answer wins" + ); + } + + /// What the handler recorded about the work lands beside the request's + /// own fields, and a route that records nothing grows nothing: five + /// sixths of the traffic (every read route) must stay as it was. + #[test] + fn usage_fields_are_added_after_the_lines_own_fields() { + let usage = vec![ + ("dataset", serde_json::json!("HSNIH-Palmer")), + ("engine", serde_json::json!("pangemma")), + ("cached", serde_json::json!(true)), + ]; + let line = request_log_line( + "POST", + "/compute/gemma", + 200, + 900, + None, + Some(&caller(Scheme::Jwt, None, "JoM")), + &usage, + ); + let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert_eq!(parsed["dataset"], "HSNIH-Palmer"); + assert_eq!(parsed["engine"], "pangemma"); + assert_eq!(parsed["cached"], true); + assert_eq!(parsed["user"], "JoM", "the line's own fields survive"); + assert_eq!(parsed["path"], "/compute/gemma"); + + let quiet = request_log_line("GET", "/groups/BXD", 200, 1, None, None, &[]); + let parsed: serde_json::Value = serde_json::from_str(&quiet).unwrap(); + assert_eq!(parsed.as_object().unwrap().len(), 6, "{quiet}"); + } } diff --git a/src/response.rs b/src/response.rs index 974a585..8ebcdcd 100644 --- a/src/response.rs +++ b/src/response.rs @@ -373,20 +373,36 @@ impl RequestInfo { /// What a handler needs to build its envelope and its errors. Take it /// as the first extractor, so the clock covers authentication too (and /// the token extractor's 401 reports the same request id and time). +/// +/// It also carries the request's usage slot (see [`crate::usage`]): a +/// handler that knows what data the request ran on says so with +/// `usage!(ctx, dataset = …, engine = …)` and the access line grows those +/// fields. Reading routes say nothing -- their dataset is already in the +/// path. pub struct Ctx { info: RequestInfo, + usage: crate::usage::UsageSlot, } -// `Ctx` is a request id and a start instant, so a clone is another handle on -// the same request: /compute/gemma needs it twice when the slurm engine runs -// and the local fallback has to answer. +// `Ctx` is a request id, a start instant and a handle on the usage slot, so a +// clone is another handle on the same request: /compute/gemma needs it twice +// when the slurm engine runs and the local fallback has to answer, and both +// must write into the one log line. impl Clone for Ctx { fn clone(&self) -> Self { - Ctx { info: self.info.clone() } + Ctx { + info: self.info.clone(), + usage: self.usage.clone(), + } } } impl Ctx { + /// Record what this request ran on, for the access log: the same call + /// the `usage!` macro makes, spelled out. + pub fn note(&self, pairs: &[(&'static str, serde_json::Value)]) { + self.usage.note(pairs); + } /// For `ApiError::with_request_id`: stamps an error with the /// request id and the time taken so far. pub fn request_info(&self) -> RequestInfo { @@ -420,7 +436,18 @@ impl FromRequestParts for Ctx { async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { let info = RequestInfo::from_parts(parts); parts.extensions.insert(info.clone()); - Ok(Ctx { info }) + // `tag_caller` opened this before routing; a `Ctx` built outside a + // request (a test, an internal call) gets its own, empty, slot. + let usage = parts + .extensions + .get::() + .cloned() + .unwrap_or_else(|| { + let slot = crate::usage::UsageSlot::default(); + parts.extensions.insert(slot.clone()); + slot + }); + Ok(Ctx { info, usage }) } } @@ -450,6 +477,7 @@ mod tests { id: Some("req-1".to_string()), started: Instant::now(), }, + usage: crate::usage::UsageSlot::default(), } } 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