capy-http 0.10.0

Axum routing and JSON response conveniences for Capy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Explicit HTTP contracts backed by Schemars and the OpenAPI 3.1 specification.

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};

/// Standard OpenAPI 3.1 document. Advanced applications can customize its JSON.
#[derive(Clone, Debug)]
pub struct ApiDocument(Value);

impl ApiDocument {
    /// Build a document from explicitly described routes and their mount prefixes.
    /// Unannotated/native Axum routes are deliberately excluded.
    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))
    }

    /// Inspect the standard OpenAPI representation.
    pub fn as_value(&self) -> &Value {
        &self.0
    }

    /// Customize standard OpenAPI properties, including security schemes and servers.
    /// Applications own the validity of these advanced edits.
    pub fn as_value_mut(&mut self) -> &mut Value {
        &mut self.0
    }

    /// Deterministic, formatted JSON with a trailing newline.
    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}")))
    }
}

/// Public metadata displayed by `capy routes --api`.
#[derive(Clone, Debug)]
pub struct ApiRouteInfo {
    /// HTTP method.
    pub method: &'static str,
    /// Declared path before the application's mount prefix.
    pub path: String,
    /// Stable, application-owned operation identifier.
    pub operation_id: Option<String>,
    /// Success wire type, or `NoContent` for HTTP 204.
    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"
                    )
                {
                    // Map keys here are application field/component names, not
                    // JSON Schema keywords. A field named `default` still has a schema.
                    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));
    }
    // Option<NamedEnum> uses anyOf(reference, null), unlike Option<String>'s
    // simple type array. Both remain flat scalar URL parameters.
    ["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}"
    ))
}