diff options
Diffstat (limited to 'src/lib.rs')
| -rw-r--r-- | src/lib.rs | 100 |
1 files changed, 99 insertions, 1 deletions
diff --git a/src/lib.rs b/src/lib.rs index 976b2f1..bf1047b 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; @@ -30,12 +31,15 @@ mod gemma; pub mod indexer; pub mod qtl2; pub mod response; +pub mod json_errors; +pub mod runs; mod routes; mod rqtl; pub mod search; mod streaming; pub mod suggest; pub mod tokens; +pub mod usage; pub mod wikidata; use error::ApiError; @@ -87,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 @@ -122,6 +131,7 @@ async fn tag_caller( started.elapsed().as_millis(), request_id.as_deref(), caller.as_ref(), + &usage.entries(), ) ); } @@ -138,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, @@ -145,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", @@ -166,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() } @@ -231,6 +253,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)) @@ -283,6 +307,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)) @@ -329,6 +355,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 @@ -450,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"); @@ -479,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"); @@ -491,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}"); + } } |
