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 {
if status == 404 {
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}),
}
}
pub fn typescript(document: &Json) -> String {
let mut out =
String::from("// Generated by `glacier types` from the app's serializers; don't edit.\n");
let Some(schemas) = document
.pointer("/components/schemas")
.and_then(Json::as_object)
else {
return out;
};
for (name, schema) in schemas {
out.push('\n');
match schema.get("properties") {
Some(_) => out.push_str(&format!(
"export interface {name} {}\n",
ts_object(schema, 0)
)),
None => out.push_str(&format!("export type {name} = {};\n", ts_type(schema, 0))),
}
}
out
}
fn ts_type(schema: &Json, depth: usize) -> String {
if let Some(reference) = schema.get("$ref").and_then(Json::as_str) {
return reference.rsplit('/').next().unwrap_or("unknown").to_owned();
}
if let Some(values) = schema.get("enum").and_then(Json::as_array) {
return values
.iter()
.map(Json::to_string)
.collect::<Vec<_>>()
.join(" | ");
}
let types: Vec<&str> = match schema.get("type") {
Some(Json::String(t)) => vec![t.as_str()],
Some(Json::Array(ts)) => ts.iter().filter_map(Json::as_str).collect(),
_ => return "unknown".to_owned(),
};
types
.iter()
.map(|t| match *t {
"string" => "string".to_owned(),
"integer" | "number" => "number".to_owned(),
"boolean" => "boolean".to_owned(),
"null" => "null".to_owned(),
"array" => {
let item = schema
.get("items")
.map_or("unknown".to_owned(), |i| ts_type(i, depth));
if item.contains(" | ") {
format!("({item})[]")
} else {
format!("{item}[]")
}
}
"object" if schema.get("properties").is_some() => ts_object(schema, depth),
_ => "Record<string, unknown>".to_owned(),
})
.collect::<Vec<_>>()
.join(" | ")
}
fn ts_object(schema: &Json, depth: usize) -> String {
let required: Vec<&str> = schema
.get("required")
.and_then(Json::as_array)
.map(|r| r.iter().filter_map(Json::as_str).collect())
.unwrap_or_default();
let indent = " ".repeat(depth + 1);
let mut out = String::from("{\n");
if let Some(properties) = schema.get("properties").and_then(Json::as_object) {
for (field, field_schema) in properties {
let optional = if required.contains(&field.as_str()) {
""
} else {
"?"
};
out.push_str(&format!(
"{indent}{field}{optional}: {};\n",
ts_type(field_schema, depth + 1)
));
}
}
out.push_str(&" ".repeat(depth));
out.push('}');
out
}
#[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 schemas_as_typescript() {
let document = json!({"components": {"schemas": {
"Book": {"type": "object", "properties": {
"id": {"type": "integer"},
"title": {"type": "string"},
"price": {"type": ["string", "null"]},
"tags": {"type": "array", "items": {"type": "string"}},
"status": {"type": "string", "enum": ["draft", "published"]},
"author": {"$ref": "#/components/schemas/Author"},
}, "required": ["id", "title", "price", "tags", "status", "author"]},
"Author": {"type": "object", "properties": {
"name": {"type": "string"},
"books": {"type": ["array", "null"], "items": {"$ref": "#/components/schemas/Book"}},
}, "required": ["name"]},
}}});
assert_eq!(
typescript(&document),
"// Generated by `glacier types` from the app's serializers; don't edit.\n\n\
export interface Book {\n id: number;\n title: string;\n price: string | null;\n \
tags: string[];\n status: \"draft\" | \"published\";\n author: Author;\n}\n\n\
export interface Author {\n name: string;\n books?: Book[] | null;\n}\n"
);
}
#[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, "/");
}
}