glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! OpenAPI: a description of the app's API, from its routes, what its
//! controllers' actions respond with and its serializers' schemas.
//! `glacier openapi` writes it.
//!
//! `#[glacier::controller]` records, for each action, the responses it
//! can give (`json … serializer: BookSerializer, status: :created`, a
//! redirect, `head`, a page), the request body when it reads
//! `params().require("book")` for a model, and the query params it reads
//! (`page`, `per_page`, `cursor`, `sort`). `routes!` hands each
//! controller's record to the router.

use serde_json::{Map, Value as Json, json};

use crate::router::Router;

/// What one action takes and gives.
#[derive(Debug, Clone)]
pub struct ActionDoc {
    pub action: &'static str,
    pub responses: Vec<ResponseDoc>,
    /// The request body: under `root` (`book`), the model's params.
    pub body: Option<BodyDoc>,
    pub query: Vec<&'static str>,
}

/// One response an action can give.
#[derive(Debug, Clone)]
pub struct ResponseDoc {
    pub status: u16,
    pub kind: ResponseKind,
}

#[derive(Debug, Clone)]
pub enum ResponseKind {
    /// JSON through a serializer: its name (for `components`), schema,
    /// whether a list, and the root key it's wrapped in.
    Serialized {
        name: String,
        schema: fn() -> Json,
        many: bool,
        root: Option<String>,
    },
    /// JSON of no known shape.
    Json,
    /// An HTML page.
    Html,
    /// A redirect.
    Redirect,
    /// No body.
    Empty,
}

/// A request body: the model's params under `root`.
#[derive(Debug, Clone)]
pub struct BodyDoc {
    pub root: &'static str,
    pub schema: fn() -> Json,
}

/// A controller whose actions are documented: `#[glacier::controller]`
/// implements it.
pub trait Documented {
    fn actions() -> Vec<ActionDoc>;
}

/// `routes!` registers a controller's docs when it has them, and passes
/// over a hand-written handler type that hasn't.
#[doc(hidden)]
pub struct DocProbe<T>(std::marker::PhantomData<fn() -> T>);

impl<T> DocProbe<T> {
    pub fn new() -> Self {
        Self(std::marker::PhantomData)
    }
}

impl<T> Default for DocProbe<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[doc(hidden)]
pub trait DocProbeDocumented {
    fn register(&self, router: &mut Router);
}

impl<T: Documented> DocProbeDocumented for &DocProbe<T> {
    fn register(&self, router: &mut Router) {
        router.document::<T>();
    }
}

#[doc(hidden)]
pub trait DocProbeAny {
    fn register(&self, router: &mut Router);
}

impl<T> DocProbeAny for DocProbe<T> {
    fn register(&self, _router: &mut Router) {}
}

/// A model's params schema, or any object for a type that isn't a model.
#[doc(hidden)]
pub struct ParamsProbe<T>(std::marker::PhantomData<fn() -> T>);

impl<T> ParamsProbe<T> {
    pub fn new() -> Self {
        Self(std::marker::PhantomData)
    }
}

impl<T> Default for ParamsProbe<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[doc(hidden)]
pub trait ParamsProbeModel {
    fn params_schema(&self) -> Json;
}

impl<T: crate::Model> ParamsProbeModel for &ParamsProbe<T> {
    fn params_schema(&self) -> Json {
        T::params_schema()
    }
}

#[doc(hidden)]
pub trait ParamsProbeAny {
    fn params_schema(&self) -> Json;
}

impl<T> ParamsProbeAny for ParamsProbe<T> {
    fn params_schema(&self) -> Json {
        json!({"type": "object"})
    }
}

/// The OpenAPI 3.1 document for `router`'s routes: those a request
/// naming API version `api_version` reaches, or with `None`, a request
/// naming none (unversioned routes and `default` versions).
pub fn document(router: &Router, title: &str, version: &str, api_version: Option<&str>) -> Json {
    let mut paths: Map<String, Json> = Map::new();
    let mut schemas: Map<String, Json> = Map::new();
    let mut operation_ids: Vec<String> = Vec::new();
    // For a version, its own routes come first, so that at a path both it
    // and an unversioned route answer, its route is the one described, as
    // it's the one that runs.
    let mut routes: Vec<_> = router
        .routes()
        .iter()
        .filter(|route| route.answers(api_version))
        .collect();
    if api_version.is_some() {
        routes.sort_by_key(|route| !route.is_versioned());
    }
    for route in routes {
        let method = route.method().as_str().to_ascii_lowercase();
        if method == "head" || method == "options" {
            continue;
        }
        let (path, params) = openapi_path(route.pattern());
        let label = route.label();
        let (controller, action) = label.split_once('#').unwrap_or(("", label));
        let doc = router
            .docs_for(controller)
            .into_iter()
            .find(|d| d.action == action);

        let constraints = Router::route_constraints(route);
        let mut parameters: Vec<Json> = params
            .iter()
            .map(|name| {
                let constraint = constraints
                    .iter()
                    .find(|(p, _)| p == name)
                    .map(|(p, pattern)| {
                        // Stored anchored: `^(?:\d+)$`.
                        let inner = pattern
                            .strip_prefix("^(?:")
                            .and_then(|p| p.strip_suffix(")$"))
                            .unwrap_or(pattern);
                        (*p, inner)
                    });
                let schema = match constraint {
                    Some((_, pattern)) if is_integer_pattern(pattern) => {
                        json!({"type": "integer"})
                    }
                    Some((_, pattern)) => json!({"type": "string", "pattern": pattern}),
                    None => json!({"type": "string"}),
                };
                json!({"name": name, "in": "path", "required": true, "schema": schema})
            })
            .collect();
        let mut operation = Map::new();
        if !controller.is_empty() {
            // An action routed twice (`/books/:id` and `/v1/books/:id`)
            // takes its path's first segment: `v1_books_show`.
            let base = format!("{}_{action}", glacier_inflect::snake_case(controller));
            let mut id = base.clone();
            if operation_ids.contains(&id) {
                let first = path.trim_start_matches('/').split('/').next().unwrap_or("");
                id = format!("{}_{base}", first.trim_matches(|c| c == '{' || c == '}'));
            }
            let mut n = 2;
            while operation_ids.contains(&id) {
                id = format!("{base}_{n}");
                n += 1;
            }
            operation_ids.push(id.clone());
            operation.insert("operationId".into(), json!(id));
            operation.insert("tags".into(), json!([controller]));
        }
        if let (true, Some(api_version)) = (route.is_versioned(), api_version) {
            parameters.push(json!({
                "name": "Api-Version",
                "in": "header",
                "required": true,
                "schema": {"type": "string", "enum": [api_version]},
            }));
        }
        let mut responses = Map::new();
        if let Some(doc) = &doc {
            for name in &doc.query {
                parameters.push(json!({
                    "name": name,
                    "in": "query",
                    "required": false,
                    "schema": query_schema(name),
                }));
            }
            if let Some(body) = &doc.body {
                operation.insert(
                    "requestBody".into(),
                    json!({
                        "required": true,
                        "content": {"application/json": {"schema": {
                            "type": "object",
                            "properties": {body.root: (body.schema)()},
                            "required": [body.root],
                        }}},
                    }),
                );
            }
            for response in &doc.responses {
                let key = response.status.to_string();
                if responses.contains_key(&key) {
                    continue;
                }
                responses.insert(key, response_json(response, &mut schemas));
            }
        }
        if responses.is_empty() {
            responses.insert("200".into(), json!({"description": "OK"}));
        }
        if !parameters.is_empty() {
            operation.insert("parameters".into(), Json::Array(parameters));
        }
        operation.insert("responses".into(), Json::Object(responses));
        let entry = paths.entry(path).or_insert_with(|| json!({}));
        if let Json::Object(entry) = entry {
            entry.entry(method).or_insert(Json::Object(operation));
        }
    }
    let version = api_version.unwrap_or(version);
    let mut document = json!({
        "openapi": "3.1.0",
        "info": {"title": title, "version": version},
        "paths": paths,
    });
    if !schemas.is_empty() {
        document["components"] = json!({"schemas": schemas});
    }
    document
}

/// `/books/:id` → `/books/{id}` and its params.
fn openapi_path(pattern: &str) -> (String, Vec<String>) {
    let mut params = Vec::new();
    let path = pattern
        .split('/')
        .map(|segment| {
            match segment
                .strip_prefix(':')
                .or_else(|| segment.strip_prefix('*'))
            {
                Some(param) => {
                    let (name, rest) = param.split_at(param.find('.').unwrap_or(param.len()));
                    params.push(name.to_owned());
                    format!("{{{name}}}{rest}")
                }
                None => segment.to_owned(),
            }
        })
        .collect::<Vec<_>>()
        .join("/");
    (if path.is_empty() { "/".into() } else { path }, params)
}

fn is_integer_pattern(pattern: &str) -> bool {
    matches!(pattern, r"\d+" | "[0-9]+" | r"^\d+$")
}

fn query_schema(name: &str) -> Json {
    match name {
        "page" | "per_page" => json!({"type": "integer", "minimum": 1}),
        "sort" => json!({
            "type": "string",
            "description": "Columns to sort by, comma-separated; `-` for descending",
        }),
        "cursor" => json!({"type": "string", "description": "From a previous page's links"}),
        _ => json!({"type": "string"}),
    }
}

fn description(status: u16) -> String {
    if status == 404 {
        // Another tenant's row answers as if it weren't there.
        return "Not Found: no such record, or not yours (another account's \
                rows answer 404, never 403)"
            .to_owned();
    }
    http::StatusCode::from_u16(status)
        .ok()
        .and_then(|s| s.canonical_reason())
        .unwrap_or("Response")
        .to_owned()
}

fn response_json(response: &ResponseDoc, schemas: &mut Map<String, Json>) -> Json {
    let description = description(response.status);
    match &response.kind {
        ResponseKind::Serialized {
            name,
            schema,
            many,
            root,
        } => {
            schemas.entry(name.clone()).or_insert_with(schema);
            let one = json!({"$ref": format!("#/components/schemas/{name}")});
            let body = if *many {
                json!({"type": "array", "items": one})
            } else {
                one
            };
            let body = match root {
                Some(root) => json!({
                    "type": "object",
                    "properties": {root: body},
                    "required": [root],
                }),
                None => body,
            };
            json!({
                "description": description,
                "content": {"application/json": {"schema": body}},
            })
        }
        ResponseKind::Json => json!({
            "description": description,
            "content": {"application/json": {"schema": {}}},
        }),
        ResponseKind::Html => json!({
            "description": description,
            "content": {"text/html": {"schema": {"type": "string"}}},
        }),
        ResponseKind::Redirect => json!({
            "description": description,
            "headers": {"Location": {"schema": {"type": "string"}}},
        }),
        ResponseKind::Empty => json!({"description": description}),
    }
}

/// The schema name for a serializer: `BookSerializer` → `Book`.
#[doc(hidden)]
pub fn schema_name<S>() -> String {
    let name = std::any::type_name::<S>();
    let name = name.rsplit("::").next().unwrap_or(name);
    name.strip_suffix("Serializer")
        .filter(|n| !n.is_empty())
        .unwrap_or(name)
        .to_owned()
}

/// A status as a number, from a name (`"created"`) or a number.
#[doc(hidden)]
pub fn status_code(status: impl crate::response::IntoStatus) -> u16 {
    status.into_status().as_u16()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn paths_use_braces() {
        assert_eq!(
            openapi_path("/books/:id/reviews/:review_id"),
            (
                "/books/{id}/reviews/{review_id}".to_owned(),
                vec!["id".to_owned(), "review_id".to_owned()]
            )
        );
        assert_eq!(openapi_path("/files/*path").0, "/files/{path}");
        assert_eq!(openapi_path("").0, "/");
    }
}