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