//! 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, } /// 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, } /// 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, } 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 } 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 } /// 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, }, notes: Vec::new(), next: 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!([])); } #[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"); } }