Skip to main content

capy_http/
contract.rs

1//! Explicit HTTP contracts backed by Schemars and the OpenAPI 3.1 specification.
2
3use crate::Routes;
4use capy_core::{AppError, Result};
5use schemars::{generate::SchemaSettings, JsonSchema, Schema, SchemaGenerator};
6use serde_json::{json, Map, Value};
7use std::collections::{BTreeMap, BTreeSet};
8
9/// Standard OpenAPI 3.1 document. Advanced applications can customize its JSON.
10#[derive(Clone, Debug)]
11pub struct ApiDocument(Value);
12
13impl ApiDocument {
14    /// Build a document from explicitly described routes and their mount prefixes.
15    /// Unannotated/native Axum routes are deliberately excluded.
16    pub fn from_routes<'a>(
17        title: &str,
18        version: &str,
19        routes: impl IntoIterator<Item = (&'a str, &'a Routes)>,
20    ) -> Result<Self> {
21        if title.trim().is_empty() || version.trim().is_empty() {
22            return Err(problem("API title and version must not be empty."));
23        }
24        let mut entries = Vec::new();
25        for (prefix, routes) in routes {
26            if let Some(error) = &routes.contract_error {
27                return Err(problem(error));
28            }
29            for (index, operation) in &routes.contracts {
30                let route = &routes.inventory()[*index];
31                entries.push((format!("{prefix}{}", route.path), route.method, operation));
32            }
33        }
34        entries.sort_by(|left, right| (&left.0, left.1).cmp(&(&right.0, right.1)));
35        let mut input = generator(true);
36        let mut output = generator(false);
37        let mut paths = BTreeMap::<String, BTreeMap<String, Value>>::new();
38        let mut ids = BTreeSet::new();
39        for (path, method, operation) in entries {
40            let id = operation.id.as_deref().ok_or_else(|| {
41                problem(format!("{method} {path} has contract metadata but no operation ID. Add .operation(\"stableName\") to this route."))
42            })?;
43            if !valid_identifier(id) || !ids.insert(id.to_owned()) {
44                return Err(problem(format!("Operation ID `{id}` must be unique and use an identifier such as `listPosts`. Check {method} {path}.")));
45            }
46            let (status, response) = operation.response.as_ref().ok_or_else(|| {
47                problem(format!("{method} {path} ({id}) has no success response. Add .response::<ResponseDto>(), .created::<ResponseDto>() or .no_content()."))
48            })?;
49            if !(200..300).contains(status) || (*status == 204 && response.is_some()) {
50                return Err(problem(format!("Invalid success response {status} for {method} {path}. HTTP 204 must have no body.")));
51            }
52            let mut responses = BTreeMap::new();
53            let mut success =
54                json!({"description": if *status == 204 {"No content"} else {"Success"}});
55            if let Some(schema) = response {
56                success["content"] =
57                    json!({"application/json": {"schema": (schema.generate)(&mut output)}});
58            }
59            responses.insert(status.to_string(), success);
60            for (status, error_type) in &operation.errors {
61                if !(400..600).contains(status) {
62                    return Err(problem(format!(
63                        "Invalid error status {status} for {method} {path}; use 400..599."
64                    )));
65                }
66                let schema = (error_type.generate)(&mut output);
67                responses.insert(status.to_string(), json!({
68                    "description": axum::http::StatusCode::from_u16(*status).ok().and_then(|s| s.canonical_reason()).unwrap_or("Application error"),
69                    "content": {"application/json": {"schema": schema}}
70                }));
71            }
72            let mut value = json!({"operationId": id, "responses": responses});
73            if let Some(summary) = &operation.summary {
74                value["summary"] = json!(summary);
75            }
76            if let Some(description) = &operation.description {
77                value["description"] = json!(description);
78            }
79            if !operation.tags.is_empty() {
80                value["tags"] = json!(operation.tags);
81            }
82            if let Some(body) = &operation.body {
83                value["requestBody"] = json!({"required": true, "content": {"application/json": {"schema": (body.generate)(&mut input)}}});
84            }
85            let mut parameters = Vec::new();
86            let mut declared = BTreeSet::new();
87            for (name, schema) in &operation.path {
88                if !declared.insert(name.clone()) || !path.contains(&format!("{{{name}}}")) {
89                    return Err(problem(format!(
90                        "Path parameter `{name}` is duplicate or absent from {method} {path}."
91                    )));
92                }
93                let schema = (schema.generate)(&mut input);
94                check_parameter(&schema, &input, name, id)?;
95                parameters
96                    .push(json!({"name": name, "in": "path", "required": true, "schema": schema}));
97            }
98            for segment in path.split('/') {
99                if segment.starts_with('{') && segment.ends_with('}') {
100                    let name = &segment[1..segment.len() - 1];
101                    if !declared.contains(name) {
102                        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.")));
103                    }
104                }
105            }
106            if let Some(query) = &operation.query {
107                let schema = (query.generate)(&mut input);
108                let schema = resolve(&schema, &input)?;
109                let properties = schema.get("properties").and_then(Value::as_object).ok_or_else(|| {
110                    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))
111                })?;
112                let required = schema.get("required").and_then(Value::as_array);
113                for (name, schema) in properties {
114                    check_parameter(
115                        &schema
116                            .clone()
117                            .try_into()
118                            .map_err(|_| problem("Invalid query schema"))?,
119                        &input,
120                        name,
121                        id,
122                    )?;
123                    parameters.push(json!({"name": name, "in": "query", "required": required.is_some_and(|r| r.iter().any(|v| v == name)), "schema": schema}));
124                }
125            }
126            if !parameters.is_empty() {
127                value["parameters"] = json!(parameters);
128            }
129            let duplicate = paths
130                .entry(path.clone())
131                .or_default()
132                .insert(method.to_lowercase(), value);
133            if duplicate.is_some() {
134                return Err(problem(format!("Duplicate operation for {method} {path}. Check route mount prefixes and register this path only once.")));
135            }
136        }
137        let mut document = json!({
138            "openapi": "3.1.0", "jsonSchemaDialect": "https://json-schema.org/draft/2020-12/schema",
139            "info": {"title":title, "version":version}, "paths": paths,
140            "components": {"schemas": {}}
141        });
142        let names = schema_names(input.definitions(), output.definitions())?;
143        let mut schemas = Map::new();
144        for (direction, definitions) in [
145            ("input", input.definitions()),
146            ("output", output.definitions()),
147        ] {
148            for (name, schema) in definitions {
149                let target = &names[&format!("#/x-capy-{direction}/{name}")];
150                let mut schema = schema.clone();
151                rewrite_refs(&mut schema, &names);
152                schemas.insert(target.clone(), schema);
153            }
154        }
155        rewrite_refs(&mut document, &names);
156        document["components"]["schemas"] = Value::Object(schemas);
157        Ok(Self(document))
158    }
159
160    /// Inspect the standard OpenAPI representation.
161    pub fn as_value(&self) -> &Value {
162        &self.0
163    }
164
165    /// Customize standard OpenAPI properties, including security schemes and servers.
166    /// Applications own the validity of these advanced edits.
167    pub fn as_value_mut(&mut self) -> &mut Value {
168        &mut self.0
169    }
170
171    /// Deterministic, formatted JSON with a trailing newline.
172    pub fn to_json(&self) -> Result<String> {
173        serde_json::to_string_pretty(&sorted(self.0.clone()))
174            .map(|text| text + "\n")
175            .map_err(|error| problem(format!("Could not serialize OpenAPI: {error}")))
176    }
177}
178
179/// Public metadata displayed by `capy routes --api`.
180#[derive(Clone, Debug)]
181pub struct ApiRouteInfo {
182    /// HTTP method.
183    pub method: &'static str,
184    /// Declared path before the application's mount prefix.
185    pub path: String,
186    /// Stable, application-owned operation identifier.
187    pub operation_id: Option<String>,
188    /// Success wire type, or `NoContent` for HTTP 204.
189    pub response: Option<String>,
190}
191
192#[derive(Clone)]
193pub(crate) struct SchemaType {
194    pub name: String,
195    generate: fn(&mut SchemaGenerator) -> Schema,
196}
197impl SchemaType {
198    pub fn of<T: JsonSchema>() -> Self {
199        Self {
200            name: T::schema_name().into_owned(),
201            generate: |generator| generator.subschema_for::<T>(),
202        }
203    }
204}
205
206#[derive(Clone, Default)]
207pub(crate) struct ApiOperation {
208    pub id: Option<String>,
209    pub summary: Option<String>,
210    pub description: Option<String>,
211    pub tags: BTreeSet<String>,
212    pub body: Option<SchemaType>,
213    pub query: Option<SchemaType>,
214    pub path: BTreeMap<String, SchemaType>,
215    pub response: Option<(u16, Option<SchemaType>)>,
216    pub errors: BTreeMap<u16, SchemaType>,
217}
218
219fn generator(input: bool) -> SchemaGenerator {
220    SchemaSettings::draft2020_12()
221        .with(|settings| {
222            settings.meta_schema = None;
223            settings.definitions_path = if input {
224                "/x-capy-input"
225            } else {
226                "/x-capy-output"
227            }
228            .into();
229            settings.contract = if input {
230                schemars::generate::Contract::Deserialize
231            } else {
232                schemars::generate::Contract::Serialize
233            };
234        })
235        .into_generator()
236}
237
238fn schema_names(
239    input: &Map<String, Value>,
240    output: &Map<String, Value>,
241) -> Result<BTreeMap<String, String>> {
242    let mut result = BTreeMap::new();
243    let mut used = BTreeSet::new();
244    for (direction, definitions) in [("input", input), ("output", output)] {
245        for name in definitions.keys() {
246            let target = if input.contains_key(name) && output.contains_key(name) {
247                format!(
248                    "{name}{}",
249                    if direction == "input" {
250                        "Input"
251                    } else {
252                        "Output"
253                    }
254                )
255            } else {
256                name.clone()
257            };
258            if !target
259                .chars()
260                .all(|c| c.is_ascii_alphanumeric() || "._-".contains(c))
261                || !used.insert(target.clone())
262            {
263                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.")));
264            }
265            result.insert(format!("#/x-capy-{direction}/{name}"), target);
266        }
267    }
268    Ok(result)
269}
270
271fn rewrite_refs(value: &mut Value, names: &BTreeMap<String, String>) {
272    rewrite_refs_in(value, names, true);
273}
274
275fn rewrite_refs_in(value: &mut Value, names: &BTreeMap<String, String>, keywords: bool) {
276    match value {
277        Value::Object(map) => {
278            if let Some(name) = keywords
279                .then(|| {
280                    map.get("$ref")
281                        .and_then(Value::as_str)
282                        .and_then(|r| names.get(r))
283                })
284                .flatten()
285            {
286                map.insert("$ref".into(), json!(format!("#/components/schemas/{name}")));
287            }
288            for (key, value) in map {
289                if !keywords
290                    || !matches!(
291                        key.as_str(),
292                        "example" | "examples" | "default" | "enum" | "const"
293                    )
294                {
295                    // Map keys here are application field/component names, not
296                    // JSON Schema keywords. A field named `default` still has a schema.
297                    let child_keywords = !keywords
298                        || !matches!(
299                            key.as_str(),
300                            "properties" | "patternProperties" | "$defs" | "schemas"
301                        );
302                    rewrite_refs_in(value, names, child_keywords);
303                }
304            }
305        }
306        Value::Array(array) => {
307            for value in array {
308                rewrite_refs_in(value, names, true);
309            }
310        }
311        _ => {}
312    }
313}
314
315fn resolve<'a>(schema: &'a Schema, generator: &'a SchemaGenerator) -> Result<&'a Value> {
316    let value = schema.as_value();
317    if let Some(reference) = value.get("$ref").and_then(Value::as_str) {
318        let name = reference.rsplit('/').next().unwrap_or_default();
319        generator
320            .definitions()
321            .get(name)
322            .ok_or_else(|| problem(format!("Unresolved schema {reference}")))
323    } else {
324        Ok(value)
325    }
326}
327
328fn check_parameter(
329    schema: &Schema,
330    generator: &SchemaGenerator,
331    name: &str,
332    operation: &str,
333) -> Result<()> {
334    let valid = scalar_parameter(
335        schema.as_value(),
336        generator.definitions(),
337        &mut BTreeSet::new(),
338    );
339    if !valid {
340        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.")));
341    }
342    Ok(())
343}
344
345fn scalar_parameter(
346    value: &Value,
347    definitions: &Map<String, Value>,
348    visiting: &mut BTreeSet<String>,
349) -> bool {
350    if let Some(reference) = value.get("$ref").and_then(Value::as_str) {
351        if !visiting.insert(reference.to_owned()) {
352            return false;
353        }
354        let valid = definitions
355            .get(reference.rsplit('/').next().unwrap_or_default())
356            .is_some_and(|schema| scalar_parameter(schema, definitions, visiting));
357        visiting.remove(reference);
358        return valid;
359    }
360    let scalar = |v: &Value| {
361        v.as_str()
362            .is_some_and(|s| matches!(s, "string" | "number" | "integer" | "boolean" | "null"))
363    };
364    if let Some(kind) = value.get("type") {
365        return scalar(kind)
366            || kind
367                .as_array()
368                .is_some_and(|types| !types.is_empty() && types.iter().all(scalar));
369    }
370    // Option<NamedEnum> uses anyOf(reference, null), unlike Option<String>'s
371    // simple type array. Both remain flat scalar URL parameters.
372    ["anyOf", "oneOf"].iter().any(|keyword| {
373        value
374            .get(*keyword)
375            .and_then(Value::as_array)
376            .is_some_and(|branches| {
377                !branches.is_empty()
378                    && branches
379                        .iter()
380                        .all(|branch| scalar_parameter(branch, definitions, visiting))
381            })
382    })
383}
384
385fn valid_identifier(value: &str) -> bool {
386    let mut chars = value.chars();
387    chars
388        .next()
389        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
390        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
391}
392
393fn sorted(value: Value) -> Value {
394    match value {
395        Value::Object(object) => Value::Object(
396            object
397                .into_iter()
398                .map(|(k, v)| (k, sorted(v)))
399                .collect::<BTreeMap<_, _>>()
400                .into_iter()
401                .collect(),
402        ),
403        Value::Array(array) => Value::Array(array.into_iter().map(sorted).collect()),
404        value => value,
405    }
406}
407
408fn problem(message: impl std::fmt::Display) -> AppError {
409    AppError::Configuration(format!(
410        "Capy could not generate the API contract.\n\n{message}"
411    ))
412}