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