about summary refs log tree commit diff
path: root/src/response.rs
blob: 5e6fcffd861591b4d82b1745d1751ffce91f835f (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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
//! 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>,
    /// Endpoint-specific additions, flattened into `meta` so the shape stays
    /// `meta.<name>` 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<serde_json::Map<String, serde_json::Value>>,
}

/// 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>,
    /// 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<SuggestedCall>,
}

/// 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<serde_json::Value>,
}

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
    }

    /// 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<SuggestedCall>) -> 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<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
    }

    /// Adds one `meta.<key>` 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<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,
                extra: None,
            },
            notes: Vec::new(),
            next: Vec::new(),
            actions: 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!([]));
        // `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");
    }
}