//! The one descriptive success envelope, per the foundation design //! note (topics/gn4/gn4-api-foundation.gmi): every success response //! carries its data next to a `meta` block (state, server time, request //! id), server-authored `notes` about the data, and the next actions a //! caller (human or LLM) can take. Errors use the shared RFC 7807 style //! ApiError shape in error.rs. Never ad-hoc JSON per endpoint. //! //! Handlers take a `Ctx` (which starts the clock and knows the request //! id) and build the response with `ctx.envelope(data)`. Only `/` //! (a plain-text liveness greeting) and `/openapi.json` (the OpenAPI //! document itself) are not wrapped. use axum::extract::FromRequestParts; use axum::http::request::Parts; use serde::Serialize; use std::convert::Infallible; use std::time::Instant; use tower_http::request_id::RequestId; /// Whether the response is everything that was asked for. #[derive(Serialize, utoipa::ToSchema, Clone, Copy, Debug, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum State { /// Nothing was left out or degraded. Complete, /// Usable, but something was left out or unavailable; `notes` says /// what (e.g. fields that could not be looked up, results the /// caller may not view, a ranking limited to a window). Partial, } /// Facts about this response, as opposed to its data. #[derive(Serialize, utoipa::ToSchema)] pub struct Meta { pub state: State, /// Milliseconds the server spent on the request, from when it /// started handling it (it excludes network time). pub took_ms: u64, /// The request's id, also in the `x-request-id` response header. pub request_id: Option, /// Column names for a `data` that is a list of rows, each row a /// positional array rather than a keyed object (e.g. /// `/compute/gemma`'s GEMMA `.assoc.txt` rows) -- cuts repeated key /// names out of a large response. Absent for endpoints whose `data` /// is already keyed or isn't tabular. #[serde(skip_serializing_if = "Option::is_none")] pub columns: Option>, /// How many rows `data` carries, alongside `columns` (same /// condition for being present). #[serde(skip_serializing_if = "Option::is_none")] pub num_rows: Option, /// `columns.len()`, alongside `columns`, so a caller doesn't need /// to count it itself. #[serde(skip_serializing_if = "Option::is_none")] pub num_cols: Option, /// Endpoint-specific additions, flattened into `meta` so the shape stays /// `meta.` and never a nested `meta.extra`. Used where something /// belongs beside the rows rather than around them: `/compute/qtl2`'s /// permutation null is qualifier information about the scan in `data`. #[serde(flatten, skip_serializing_if = "Option::is_none")] #[schema(inline)] pub extra: Option>, } /// A success response: the payload, facts about the response, notes on /// the data, and suggested follow-up calls. #[derive(Serialize, utoipa::ToSchema)] pub struct Envelope { pub data: T, pub meta: Meta, /// Server-authored remarks on `data` (units, caveats, what is /// missing). Never derived from database content or request input. pub notes: Vec, pub next: Vec, /// Calls the server suggests that are not plain `GET`s (see /// [`SuggestedCall`]). Present only when there is something to /// suggest, e.g. on the per-trait values endpoints, where a QTL /// mapping run is the obvious next step. #[serde(skip_serializing_if = "Vec::is_empty")] pub actions: Vec, } /// One suggested follow-up call. #[derive(Serialize, utoipa::ToSchema)] pub struct NextAction { /// Endpoint to call, relative to the API root, e.g. "/species/mouse". pub href: String, /// What this call gives you, e.g. "Drill down into one species". pub description: String, } /// A suggested call that is not a plain `GET`, so it cannot live in /// `next`: following a `next` link is a `GET` that returns 200, which is /// what makes those links safe to follow blindly (and what the test /// suite relies on). This carries the method, and a ready-to-edit body /// where the server can build one. #[derive(Serialize, utoipa::ToSchema)] pub struct SuggestedCall { /// HTTP method, e.g. "POST". pub method: String, /// Endpoint, relative to the API root, e.g. "/compute/rqtl". pub href: String, /// What this call does, and what the caller must fill in first. pub description: String, /// A body to send, with placeholders where the server cannot know /// the value (e.g. a path that has to exist on the server's own /// filesystem). #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Object)] pub body: Option, } impl Envelope { pub fn with_next(mut self, href: &str, description: &str) -> Self { self.next.push(NextAction { href: href.to_string(), description: description.to_string(), }); self } /// Adds one suggested non-`GET` call (see [`SuggestedCall`]). pub fn with_action(mut self, action: SuggestedCall) -> Self { self.actions.push(action); self } /// Adds several, e.g. everything `suggest::mapping_actions_for` /// offers for a trait's values. pub fn with_actions(mut self, actions: Vec) -> Self { self.actions.extend(actions); self } /// Adds a batch of `next` links, skipping any that duplicate a link /// already present -- a handler that adds a specific link and then a /// domain-wide batch should not list the same call twice. pub fn with_links(self, links: Vec<(String, &'static str)>) -> Self { self.with_links_except(links, "") } /// [`with_links`](Self::with_links), minus the link to the response the /// caller is already reading: a suggestion is where to go next, not here. pub fn with_links_except( mut self, links: Vec<(String, &'static str)>, current: &str, ) -> Self { let current = current.trim_end_matches('/'); for (href, description) in links { if !current.is_empty() && href.trim_end_matches('/') == current { continue; } if self.next.iter().any(|existing| existing.href == href) { continue; } self.next.push(NextAction { href, description: description.to_string(), }); } self } pub fn with_note(mut self, note: &str) -> Self { self.notes.push(note.to_string()); self } /// Sets `meta.columns`/`meta.num_cols`/`meta.num_rows` for a `data` /// of `num_rows` positional rows, each `columns.len()` long (see /// `Meta::columns`). pub fn with_columns(mut self, columns: Vec, num_rows: usize) -> Self { self.meta.num_cols = Some(columns.len()); self.meta.columns = Some(columns); self.meta.num_rows = Some(num_rows); self } /// Adds one `meta.` entry, for endpoint-specific facts that qualify /// `data` (see `Meta::extra`). pub fn with_meta(mut self, key: &str, value: serde_json::Value) -> Self { self.meta .extra .get_or_insert_with(serde_json::Map::new) .insert(key.to_string(), value); self } /// Marks the response `partial` and records why in `notes`. pub fn partial(mut self, note: &str) -> Self { self.meta.state = State::Partial; self.with_note(note) } } /// The request's id and the time the server started handling it: what /// both a success envelope (`meta`) and an error (`request_id`, /// `took_ms`) report about the request. #[derive(Clone)] pub struct RequestInfo { id: Option, started: Instant, } impl RequestInfo { /// A request with this id, whose clock starts now. pub fn new(id: Option) -> Self { RequestInfo { id, started: Instant::now(), } } /// The request's info: the one `Ctx` stored when it was extracted /// (so the clock starts there), else a fresh one starting now. pub fn from_parts(parts: &Parts) -> Self { if let Some(info) = parts.extensions.get::() { return info.clone(); } RequestInfo { id: parts .extensions .get::() .and_then(|id| id.header_value().to_str().ok()) .map(str::to_string), started: Instant::now(), } } pub fn id(&self) -> Option { self.id.clone() } /// Milliseconds since the server started handling the request. pub fn took_ms(&self) -> u64 { self.started.elapsed().as_millis() as u64 } } /// 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). pub struct Ctx { info: RequestInfo, } impl Ctx { /// For `ApiError::with_request_id`: stamps an error with the /// request id and the time taken so far. pub fn request_info(&self) -> RequestInfo { self.info.clone() } /// A `complete` envelope around `data`, with `took_ms` measured now. pub fn envelope(&self, data: T) -> Envelope { Envelope { data, meta: Meta { state: State::Complete, took_ms: self.info.took_ms(), request_id: self.info.id(), columns: None, num_rows: None, num_cols: None, extra: None, }, notes: Vec::new(), next: Vec::new(), actions: Vec::new(), } } } impl FromRequestParts for Ctx { type Rejection = Infallible; 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 }) } } /// `value` as one URL path segment: everything but unreserved /// characters is percent-encoded (e.g. the species "turquoise /// killifish" becomes `turquoise%20killifish`), for `next` hrefs. pub fn path_segment(value: &str) -> String { value .bytes() .map(|b| { if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") } }) .collect() } #[cfg(test)] mod tests { use super::*; fn ctx() -> Ctx { Ctx { info: RequestInfo { id: Some("req-1".to_string()), started: Instant::now(), }, } } #[test] fn envelope_serializes_data_meta_notes_and_next() { let envelope = ctx() .envelope(vec!["mouse", "rat"]) .with_note("two species") .with_next("/species/mouse", "Drill down into one species"); let json = serde_json::to_value(&envelope).unwrap(); assert_eq!(json["data"], serde_json::json!(["mouse", "rat"])); assert_eq!(json["meta"]["state"], "complete"); assert!(json["meta"]["took_ms"].is_u64()); assert_eq!(json["meta"]["request_id"], "req-1"); assert_eq!(json["notes"], serde_json::json!(["two species"])); assert_eq!(json["next"][0]["href"], "/species/mouse"); assert_eq!( json["next"][0]["description"], "Drill down into one species" ); } #[test] fn envelope_starts_complete_with_no_notes_or_actions() { let json = serde_json::to_value(ctx().envelope(42)).unwrap(); assert_eq!(json["meta"]["state"], "complete"); assert_eq!(json["notes"], serde_json::json!([])); assert_eq!(json["next"], serde_json::json!([])); // `actions` is omitted entirely when the server has nothing to // suggest, so most responses keep the four-member shape. assert!(json.get("actions").is_none(), "{json}"); } #[test] fn a_suggested_action_carries_its_method_and_body() { let json = serde_json::to_value( ctx().envelope(42).with_action(SuggestedCall { method: "POST".to_string(), href: "/compute/rqtl".to_string(), description: "Map it".to_string(), body: Some(serde_json::json!({"trait_name": "mytrait"})), }), ) .unwrap(); assert_eq!(json["actions"][0]["method"], "POST"); assert_eq!(json["actions"][0]["href"], "/compute/rqtl"); assert_eq!(json["actions"][0]["body"]["trait_name"], "mytrait"); // ... and `next` stays the GET-only list it was. assert_eq!(json["next"], serde_json::json!([])); } #[test] fn partial_sets_the_state_and_records_why() { let json = serde_json::to_value(ctx().envelope(1).partial("something was left out")).unwrap(); assert_eq!(json["meta"]["state"], "partial"); assert_eq!(json["notes"], serde_json::json!(["something was left out"])); } #[test] fn path_segment_encodes_all_but_unreserved_characters() { assert_eq!(path_segment("BXD-JAX_AD.1~"), "BXD-JAX_AD.1~"); assert_eq!(path_segment("turquoise killifish"), "turquoise%20killifish"); assert_eq!(path_segment("a/b?c"), "a%2Fb%3Fc"); } }