use serde_json::{Map, Value as Json, json};
use crate::router::Router;
#[derive(Debug, Clone)]
pub struct ActionDoc {
pub action: &'static str,
pub responses: Vec<ResponseDoc>,
pub body: Option<BodyDoc>,
pub query: Vec<&'static str>,
}
#[derive(Debug, Clone)]
pub struct ResponseDoc {
pub status: u16,
pub kind: ResponseKind,
}
#[derive(Debug, Clone)]
pub enum ResponseKind {
Serialized {
name: String,
schema: fn() -> Json,
many: bool,
root: Option<String>,
},
Json,
Html,
Redirect,
Empty,
}
#[derive(Debug, Clone)]
pub struct BodyDoc {
pub root: &'static str,
pub schema: fn() -> Json,
}
pub trait Documented {
fn actions() -> Vec<ActionDoc>;
}
#[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) {}
}
#[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"})
}
}
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();
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)| {
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() {
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
}
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 {
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}),
}
}
#[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()
}
#[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, "/");
}
}