1use 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
24pub const FORWARDED_PREFIX_HEADER: &str = "x-forwarded-prefix";
26
27static DESCRIPTION: LazyLock<serde_json::Value> = LazyLock::new(openapi_json);
29
30static CONFIG: LazyLock<Arc<Config<'static>>> =
32 LazyLock::new(|| Arc::new(Config::new(["../openapi.json"])));
33
34#[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
48pub 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
62pub async fn redirect() -> Redirect {
64 Redirect::to("docs/")
65}
66
67pub 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 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}