use crate::Routes;
use capy_core::{AppError, Result};
use schemars::{generate::SchemaSettings, JsonSchema, Schema, SchemaGenerator};
use serde_json::{json, Map, Value};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug)]
pub struct ApiDocument(Value);
impl ApiDocument {
pub fn from_routes<'a>(
title: &str,
version: &str,
routes: impl IntoIterator<Item = (&'a str, &'a Routes)>,
) -> Result<Self> {
if title.trim().is_empty() || version.trim().is_empty() {
return Err(problem("API title and version must not be empty."));
}
let mut entries = Vec::new();
for (prefix, routes) in routes {
if let Some(error) = &routes.contract_error {
return Err(problem(error));
}
for (index, operation) in &routes.contracts {
let route = &routes.inventory()[*index];
entries.push((format!("{prefix}{}", route.path), route.method, operation));
}
}
entries.sort_by(|left, right| (&left.0, left.1).cmp(&(&right.0, right.1)));
let mut input = generator(true);
let mut output = generator(false);
let mut paths = BTreeMap::<String, BTreeMap<String, Value>>::new();
let mut ids = BTreeSet::new();
let mut authentication = false;
for (path, method, operation) in entries {
let id = operation.id.as_deref().ok_or_else(|| {
problem(format!("{method} {path} has contract metadata but no operation ID. Add .operation(\"stableName\") to this route."))
})?;
if !valid_identifier(id) || !ids.insert(id.to_owned()) {
return Err(problem(format!("Operation ID `{id}` must be unique and use an identifier such as `listPosts`. Check {method} {path}.")));
}
let (status, response) = operation.response.as_ref().ok_or_else(|| {
problem(format!("{method} {path} ({id}) has no success response. Add .response::<ResponseDto>(), .created::<ResponseDto>() or .no_content()."))
})?;
if !(200..300).contains(status) || (*status == 204 && response.is_some()) {
return Err(problem(format!("Invalid success response {status} for {method} {path}. HTTP 204 must have no body.")));
}
let mut responses = BTreeMap::new();
let mut success =
json!({"description": if *status == 204 {"No content"} else {"Success"}});
if let Some(schema) = response {
success["content"] =
json!({"application/json": {"schema": (schema.generate)(&mut output)}});
}
if let Some(media_type) = &operation.binary_response {
if response.is_some() || *status == 204 {
return Err(problem(format!("{method} {path} cannot combine binary and JSON/no-content success responses.")));
}
success["content"] =
json!({media_type: {"schema": {"type": "string", "format": "binary"}}});
}
responses.insert(status.to_string(), success);
for (status, error_type) in &operation.errors {
if !(400..600).contains(status) {
return Err(problem(format!(
"Invalid error status {status} for {method} {path}; use 400..599."
)));
}
let schema = (error_type.generate)(&mut output);
responses.insert(status.to_string(), json!({
"description": axum::http::StatusCode::from_u16(*status).ok().and_then(|s| s.canonical_reason()).unwrap_or("Application error"),
"content": {"application/json": {"schema": schema}}
}));
}
let mut value = json!({"operationId": id, "responses": responses});
if operation.authenticated {
authentication = true;
value["security"] = json!([{ "session": [] }]);
}
if let Some(summary) = &operation.summary {
value["summary"] = json!(summary);
}
if let Some(description) = &operation.description {
value["description"] = json!(description);
}
if !operation.tags.is_empty() {
value["tags"] = json!(operation.tags);
}
if operation.body.is_some() && operation.binary_body.is_some() {
return Err(problem(format!(
"{method} {path} cannot declare JSON and binary bodies together."
)));
}
if let Some(body) = &operation.body {
value["requestBody"] = json!({"required": true, "content": {"application/json": {"schema": (body.generate)(&mut input)}}});
}
if let Some(media_type) = &operation.binary_body {
value["requestBody"] = json!({"required": true, "content": {media_type: {"schema": {"type": "string", "format": "binary"}}}});
}
let mut parameters = Vec::new();
let mut declared = BTreeSet::new();
for (name, schema) in &operation.path {
if !declared.insert(name.clone()) || !path.contains(&format!("{{{name}}}")) {
return Err(problem(format!(
"Path parameter `{name}` is duplicate or absent from {method} {path}."
)));
}
let schema = (schema.generate)(&mut input);
check_parameter(&schema, &input, name, id)?;
parameters
.push(json!({"name": name, "in": "path", "required": true, "schema": schema}));
}
for segment in path.split('/') {
if segment.starts_with('{') && segment.ends_with('}') {
let name = &segment[1..segment.len() - 1];
if !declared.contains(name) {
return Err(problem(format!("{method} {path} is missing schema metadata for `{name}`. Add .path::<WireType>(\"{name}\"). Catch-all paths should use native routes outside the contract.")));
}
}
}
if let Some(query) = &operation.query {
let schema = (query.generate)(&mut input);
let schema = resolve(&schema, &input)?;
let properties = schema.get("properties").and_then(Value::as_object).ok_or_else(|| {
problem(format!("Query `{}` on {id} must be a struct with flat scalar fields. Nested query objects, maps and lists need a manual OpenAPI operation.", query.name))
})?;
let required = schema.get("required").and_then(Value::as_array);
for (name, schema) in properties {
check_parameter(
&schema
.clone()
.try_into()
.map_err(|_| problem("Invalid query schema"))?,
&input,
name,
id,
)?;
parameters.push(json!({"name": name, "in": "query", "required": required.is_some_and(|r| r.iter().any(|v| v == name)), "schema": schema}));
}
}
if !parameters.is_empty() {
value["parameters"] = json!(parameters);
}
let duplicate = paths
.entry(path.clone())
.or_default()
.insert(method.to_lowercase(), value);
if duplicate.is_some() {
return Err(problem(format!("Duplicate operation for {method} {path}. Check route mount prefixes and register this path only once.")));
}
}
let mut document = json!({
"openapi": "3.1.0", "jsonSchemaDialect": "https://json-schema.org/draft/2020-12/schema",
"info": {"title":title, "version":version}, "paths": paths,
"components": {"schemas": {}}
});
if authentication {
document["components"]["securitySchemes"] =
json!({"session": {"type": "apiKey", "in": "cookie", "name": "session"}});
}
let names = schema_names(input.definitions(), output.definitions())?;
let mut schemas = Map::new();
for (direction, definitions) in [
("input", input.definitions()),
("output", output.definitions()),
] {
for (name, schema) in definitions {
let target = &names[&format!("#/x-capy-{direction}/{name}")];
let mut schema = schema.clone();
rewrite_refs(&mut schema, &names);
schemas.insert(target.clone(), schema);
}
}
rewrite_refs(&mut document, &names);
document["components"]["schemas"] = Value::Object(schemas);
Ok(Self(document))
}
pub fn as_value(&self) -> &Value {
&self.0
}
pub fn as_value_mut(&mut self) -> &mut Value {
&mut self.0
}
pub fn to_json(&self) -> Result<String> {
serde_json::to_string_pretty(&sorted(self.0.clone()))
.map(|text| text + "\n")
.map_err(|error| problem(format!("Could not serialize OpenAPI: {error}")))
}
}
#[derive(Clone, Debug)]
pub struct ApiRouteInfo {
pub method: &'static str,
pub path: String,
pub operation_id: Option<String>,
pub response: Option<String>,
}
#[derive(Clone)]
pub(crate) struct SchemaType {
pub name: String,
generate: fn(&mut SchemaGenerator) -> Schema,
}
impl SchemaType {
pub fn of<T: JsonSchema>() -> Self {
Self {
name: T::schema_name().into_owned(),
generate: |generator| generator.subschema_for::<T>(),
}
}
}
#[derive(Clone, Default)]
pub(crate) struct ApiOperation {
pub authenticated: bool,
pub id: Option<String>,
pub summary: Option<String>,
pub description: Option<String>,
pub tags: BTreeSet<String>,
pub body: Option<SchemaType>,
pub binary_body: Option<String>,
pub binary_response: Option<String>,
pub query: Option<SchemaType>,
pub path: BTreeMap<String, SchemaType>,
pub response: Option<(u16, Option<SchemaType>)>,
pub errors: BTreeMap<u16, SchemaType>,
}
fn generator(input: bool) -> SchemaGenerator {
SchemaSettings::draft2020_12()
.with(|settings| {
settings.meta_schema = None;
settings.definitions_path = if input {
"/x-capy-input"
} else {
"/x-capy-output"
}
.into();
settings.contract = if input {
schemars::generate::Contract::Deserialize
} else {
schemars::generate::Contract::Serialize
};
})
.into_generator()
}
fn schema_names(
input: &Map<String, Value>,
output: &Map<String, Value>,
) -> Result<BTreeMap<String, String>> {
let mut result = BTreeMap::new();
let mut used = BTreeSet::new();
for (direction, definitions) in [("input", input), ("output", output)] {
for name in definitions.keys() {
let target = if input.contains_key(name) && output.contains_key(name) {
format!(
"{name}{}",
if direction == "input" {
"Input"
} else {
"Output"
}
)
} else {
name.clone()
};
if !target
.chars()
.all(|c| c.is_ascii_alphanumeric() || "._-".contains(c))
|| !used.insert(target.clone())
{
return Err(problem(format!("Schema name `{target}` is invalid or ambiguous. Give the DTO a unique #[schemars(rename = \"PublicName\")] name; Input/Output suffixes are reserved for types used in both directions.")));
}
result.insert(format!("#/x-capy-{direction}/{name}"), target);
}
}
Ok(result)
}
fn rewrite_refs(value: &mut Value, names: &BTreeMap<String, String>) {
rewrite_refs_in(value, names, true);
}
fn rewrite_refs_in(value: &mut Value, names: &BTreeMap<String, String>, keywords: bool) {
match value {
Value::Object(map) => {
if let Some(name) = keywords
.then(|| {
map.get("$ref")
.and_then(Value::as_str)
.and_then(|r| names.get(r))
})
.flatten()
{
map.insert("$ref".into(), json!(format!("#/components/schemas/{name}")));
}
for (key, value) in map {
if !keywords
|| !matches!(
key.as_str(),
"example" | "examples" | "default" | "enum" | "const"
)
{
let child_keywords = !keywords
|| !matches!(
key.as_str(),
"properties" | "patternProperties" | "$defs" | "schemas"
);
rewrite_refs_in(value, names, child_keywords);
}
}
}
Value::Array(array) => {
for value in array {
rewrite_refs_in(value, names, true);
}
}
_ => {}
}
}
fn resolve<'a>(schema: &'a Schema, generator: &'a SchemaGenerator) -> Result<&'a Value> {
let value = schema.as_value();
if let Some(reference) = value.get("$ref").and_then(Value::as_str) {
let name = reference.rsplit('/').next().unwrap_or_default();
generator
.definitions()
.get(name)
.ok_or_else(|| problem(format!("Unresolved schema {reference}")))
} else {
Ok(value)
}
}
fn check_parameter(
schema: &Schema,
generator: &SchemaGenerator,
name: &str,
operation: &str,
) -> Result<()> {
let valid = scalar_parameter(
schema.as_value(),
generator.definitions(),
&mut BTreeSet::new(),
);
if !valid {
return Err(problem(format!("Parameter `{name}` on `{operation}` must have a scalar JSON schema. Use a flat query DTO or a manual OpenAPI operation for custom encodings.")));
}
Ok(())
}
fn scalar_parameter(
value: &Value,
definitions: &Map<String, Value>,
visiting: &mut BTreeSet<String>,
) -> bool {
if let Some(reference) = value.get("$ref").and_then(Value::as_str) {
if !visiting.insert(reference.to_owned()) {
return false;
}
let valid = definitions
.get(reference.rsplit('/').next().unwrap_or_default())
.is_some_and(|schema| scalar_parameter(schema, definitions, visiting));
visiting.remove(reference);
return valid;
}
let scalar = |v: &Value| {
v.as_str()
.is_some_and(|s| matches!(s, "string" | "number" | "integer" | "boolean" | "null"))
};
if let Some(kind) = value.get("type") {
return scalar(kind)
|| kind
.as_array()
.is_some_and(|types| !types.is_empty() && types.iter().all(scalar));
}
["anyOf", "oneOf"].iter().any(|keyword| {
value
.get(*keyword)
.and_then(Value::as_array)
.is_some_and(|branches| {
!branches.is_empty()
&& branches
.iter()
.all(|branch| scalar_parameter(branch, definitions, visiting))
})
})
}
fn valid_identifier(value: &str) -> bool {
let mut chars = value.chars();
chars
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn sorted(value: Value) -> Value {
match value {
Value::Object(object) => Value::Object(
object
.into_iter()
.map(|(k, v)| (k, sorted(v)))
.collect::<BTreeMap<_, _>>()
.into_iter()
.collect(),
),
Value::Array(array) => Value::Array(array.into_iter().map(sorted).collect()),
value => value,
}
}
fn problem(message: impl std::fmt::Display) -> AppError {
AppError::Configuration(format!(
"Capy could not generate the API contract.\n\n{message}"
))
}