Skip to main content

schedr_api/
docs.rs

1//! The API's description and Swagger UI over it (see archive/PROJECT.md, Web UI and CLI: Swagger
2//! UI).
3//!
4//! Both work behind a gateway that serves schedr under a path prefix and rewrites it away
5//! (Istio's `rewrite` with an `X-Forwarded-Prefix` header): Swagger UI's page refers to the
6//! description and redirects by relative URLs, and the description names the prefix as its
7//! server, so "Try it out" calls the API through the same prefix.
8
9use std::borrow::Cow;
10use std::sync::{Arc, LazyLock};
11
12use axum::Json;
13use axum::body::Bytes;
14use axum::extract::Path;
15use axum::http::{HeaderMap, StatusCode, header};
16use axum::response::{IntoResponse, Redirect, Response};
17use utoipa_swagger_ui::Config;
18
19use crate::openapi_json;
20
21#[cfg(test)]
22mod tests;
23
24/// The header a gateway names the path prefix it removed in.
25pub const FORWARDED_PREFIX_HEADER: &str = "x-forwarded-prefix";
26
27/// The description, built once.
28static DESCRIPTION: LazyLock<serde_json::Value> = LazyLock::new(openapi_json);
29
30/// Swagger UI's settings: the description relative to the page (`/api/v1/docs/`).
31static CONFIG: LazyLock<Arc<Config<'static>>> =
32    LazyLock::new(|| Arc::new(Config::new(["../openapi.json"])));
33
34/// `X-Forwarded-Prefix` when it is a plain path (`/service/schedr`), without a trailing
35/// slash; anything else is ignored, as is a prefix of `/` alone.
36#[must_use]
37pub fn forwarded_prefix(headers: &HeaderMap) -> Option<String> {
38    let prefix = headers.get(FORWARDED_PREFIX_HEADER)?.to_str().ok()?;
39    let prefix = prefix.trim_end_matches('/');
40    let plain = prefix.starts_with('/')
41        && !prefix.contains("//")
42        && prefix
43            .bytes()
44            .all(|b| b.is_ascii_alphanumeric() || b"/-._~".contains(&b));
45    plain.then(|| prefix.to_owned())
46}
47
48/// The OpenAPI description, naming the forwarded prefix as its server when there is one
49/// (`Vary`, so a cache in front keeps one per prefix).
50pub async fn description(headers: HeaderMap) -> Response {
51    let doc = match forwarded_prefix(&headers) {
52        Some(prefix) => {
53            let mut doc = DESCRIPTION.clone();
54            doc["servers"] = serde_json::json!([{ "url": prefix }]);
55            Json(doc).into_response()
56        }
57        None => Json(&*DESCRIPTION).into_response(),
58    };
59    ([(header::VARY, FORWARDED_PREFIX_HEADER)], doc).into_response()
60}
61
62/// `/api/v1/docs` to `/api/v1/docs/`, relative, so a prefix in front stays.
63pub async fn redirect() -> Redirect {
64    Redirect::to("docs/")
65}
66
67/// A file of Swagger UI (its page for `/api/v1/docs/`), cached by browsers for an hour (the
68/// files change only with schedr's version).
69pub async fn file(path: Option<Path<String>>) -> Response {
70    let tail = path.as_ref().map_or("", |Path(tail)| tail.as_str());
71    match utoipa_swagger_ui::serve(tail, CONFIG.clone()) {
72        Ok(Some(file)) => {
73            // The built-in files as they are; only the initializer is made per request.
74            let bytes = match file.bytes {
75                Cow::Borrowed(bytes) => Bytes::from_static(bytes),
76                Cow::Owned(bytes) => Bytes::from(bytes),
77            };
78            (
79                [
80                    (header::CONTENT_TYPE, file.content_type),
81                    (header::CACHE_CONTROL, "public, max-age=3600".to_owned()),
82                ],
83                bytes,
84            )
85                .into_response()
86        }
87        Ok(None) => StatusCode::NOT_FOUND.into_response(),
88        Err(error) => {
89            tracing::error!(%error, "Swagger UI's file `{tail}` couldn't be served");
90            StatusCode::INTERNAL_SERVER_ERROR.into_response()
91        }
92    }
93}