about summary refs log tree commit diff
path: root/src/response.rs
blob: e85362a21cdd889c1f1832253d547e33716e6a14 (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
//! 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<String>,
    /// 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<Vec<String>>,
    /// How many rows `data` carries, alongside `columns` (same
    /// condition for being present).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_rows: Option<usize>,
    /// `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<usize>,
}

/// 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<T: Serialize + utoipa::ToSchema> {
    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<String>,
    pub next: Vec<NextAction>,
}

/// 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<T: Serialize + utoipa::ToSchema> Envelope<T> {
    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<String>, 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<String>,
    started: Instant,
}

impl RequestInfo {
    /// A request with this id, whose clock starts now.
    pub fn new(id: Option<String>) -> 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::<RequestInfo>() {
            return info.clone();
        }
        RequestInfo {
            id: parts
                .extensions
                .get::<RequestId>()
                .and_then(|id| id.header_value().to_str().ok())
                .map(str::to_string),
            started: Instant::now(),
        }
    }

    pub fn id(&self) -> Option<String> {
        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<T: Serialize + utoipa::ToSchema>(&self, data: T) -> Envelope<T> {
        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<S: Send + Sync> FromRequestParts<S> for Ctx {
    type Rejection = Infallible;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        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");
    }
}