Skip to main content

luxid_core/
openapi.rs

1//! OpenAPI 3.1 generation.
2//!
3//! The document is assembled by walking the application's **route table** —
4//! the same explicit registration a request goes through — rather than a
5//! static registry populated by linker tricks. Routes are declared by hand, so
6//! the spec can be derived from them without discovery magic, and a route
7//! missing from the spec is a route missing from `routes`.
8//!
9//! 3.1 rather than 3.0 because 3.1 *is* JSON Schema, so schemas generated by
10//! `schemars` drop in unchanged instead of being translated into 3.0's
11//! near-miss dialect.
12//!
13//! Schemas arrive as `fn() -> Value` rather than as types, which keeps this
14//! crate free of a JSON-schema dependency: the function is generated in the
15//! application's crate, where the type actually lives.
16
17use serde_json::{Map, Value, json};
18
19use crate::router::{Method, RouteInfo};
20
21/// A schema, rendered on demand.
22pub type SchemaFn = fn() -> Value;
23
24/// Not comparable: the schema is a function pointer, and comparing those is
25/// meaningless. Compare rendered documents instead.
26#[derive(Debug, Clone, Copy)]
27pub struct ResponseSpec {
28    pub status: u16,
29    pub schema: Option<SchemaFn>,
30}
31
32/// What `#[openapi(..)]` records about one action.
33#[derive(Debug, Clone)]
34pub struct Operation {
35    pub summary: Option<&'static str>,
36    pub tag: Option<&'static str>,
37    pub body: Option<SchemaFn>,
38    pub responses: Vec<ResponseSpec>,
39}
40
41impl Operation {
42    pub fn new() -> Self {
43        Self {
44            summary: None,
45            tag: None,
46            body: None,
47            responses: Vec::new(),
48        }
49    }
50}
51
52impl Default for Operation {
53    fn default() -> Self {
54        Self::new()
55    }
56}
57
58/// Conventional descriptions, so a spec does not ship with empty strings.
59fn describe(status: u16) -> &'static str {
60    match status {
61        200 => "OK",
62        201 => "Created",
63        202 => "Accepted",
64        204 => "No content",
65        400 => "The request could not be read",
66        401 => "Unauthenticated",
67        403 => "Forbidden",
68        404 => "Not found",
69        409 => "Conflict",
70        422 => "The given data was invalid",
71        429 => "Too many requests",
72        500 => "Internal server error",
73        _ => "Response",
74    }
75}
76
77/// The RFC 7807 body every Luxid error renders, referenced by error responses
78/// so clients get the real shape rather than an untyped blob.
79fn problem_schema() -> Value {
80    json!({
81        "type": "object",
82        "title": "Problem",
83        "description": "An RFC 7807 problem document.",
84        "properties": {
85            "type": { "type": "string", "format": "uri" },
86            "title": { "type": "string" },
87            "status": { "type": "integer" },
88            "errors": {
89                "type": "object",
90                "description": "Field-keyed validation messages, present on 422 responses.",
91                "additionalProperties": { "type": "array", "items": { "type": "string" } }
92            }
93        },
94        "required": ["type", "title", "status"]
95    })
96}
97
98fn is_error(status: u16) -> bool {
99    status >= 400
100}
101
102/// Path parameters declared by the route pattern itself.
103///
104/// `/posts/{id}` needs an `id` parameter or the document is invalid; deriving
105/// it from the path means it can never disagree with the route.
106fn path_parameters(path: &str) -> Vec<Value> {
107    let mut parameters = Vec::new();
108    let mut rest = path;
109
110    while let Some(start) = rest.find('{') {
111        let Some(end) = rest[start..].find('}') else {
112            break;
113        };
114        let name = &rest[start + 1..start + end];
115
116        if !name.is_empty() {
117            parameters.push(json!({
118                "name": name,
119                "in": "path",
120                "required": true,
121                "schema": { "type": "string" }
122            }));
123        }
124
125        rest = &rest[start + end + 1..];
126    }
127
128    parameters
129}
130
131fn method_key(method: Method) -> &'static str {
132    match method {
133        Method::Get => "get",
134        Method::Post => "post",
135        Method::Put => "put",
136        Method::Patch => "patch",
137        Method::Delete => "delete",
138        Method::Options => "options",
139    }
140}
141
142/// Build an OpenAPI 3.1 document from a route table.
143///
144/// Routes with no `#[openapi(..)]` still appear — an undocumented endpoint is
145/// better represented as present-but-bare than missing entirely.
146pub fn document(title: &str, version: &str, routes: &[RouteInfo]) -> Value {
147    let mut paths: Map<String, Value> = Map::new();
148
149    for route in routes {
150        let entry = paths.entry(route.path.clone()).or_insert_with(|| json!({}));
151        let Some(entry) = entry.as_object_mut() else {
152            continue;
153        };
154
155        entry.insert(method_key(route.method).to_owned(), operation_object(route));
156    }
157
158    json!({
159        "openapi": "3.1.0",
160        "info": { "title": title, "version": version },
161        "paths": Value::Object(paths),
162        "components": { "schemas": { "Problem": problem_schema() } }
163    })
164}
165
166fn operation_object(route: &RouteInfo) -> Value {
167    let mut object = Map::new();
168
169    object.insert("operationId".to_owned(), json!(route.action));
170
171    let parameters = path_parameters(&route.path);
172    if !parameters.is_empty() {
173        object.insert("parameters".to_owned(), json!(parameters));
174    }
175
176    let Some(operation) = &route.operation else {
177        // Undocumented: say so rather than inventing responses.
178        object.insert(
179            "responses".to_owned(),
180            json!({ "default": { "description": "Undocumented" } }),
181        );
182        return Value::Object(object);
183    };
184
185    if let Some(summary) = operation.summary {
186        object.insert("summary".to_owned(), json!(summary));
187    }
188    if let Some(tag) = operation.tag {
189        object.insert("tags".to_owned(), json!([tag]));
190    }
191    if let Some(body) = operation.body {
192        object.insert(
193            "requestBody".to_owned(),
194            json!({
195                "required": true,
196                "content": { "application/json": { "schema": body() } }
197            }),
198        );
199    }
200
201    let mut responses = Map::new();
202    for response in &operation.responses {
203        let mut entry = json!({ "description": describe(response.status) });
204        let entry_object = entry.as_object_mut().expect("just built as an object");
205
206        if let Some(schema) = response.schema {
207            entry_object.insert(
208                "content".to_owned(),
209                json!({ "application/json": { "schema": schema() } }),
210            );
211        } else if is_error(response.status) {
212            entry_object.insert(
213                "content".to_owned(),
214                json!({
215                    "application/problem+json": {
216                        "schema": { "$ref": "#/components/schemas/Problem" }
217                    }
218                }),
219            );
220        }
221
222        responses.insert(response.status.to_string(), entry);
223    }
224
225    if responses.is_empty() {
226        responses.insert(
227            "default".to_owned(),
228            json!({ "description": "Undocumented" }),
229        );
230    }
231
232    object.insert("responses".to_owned(), Value::Object(responses));
233    Value::Object(object)
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    fn schema() -> Value {
241        json!({ "type": "object", "properties": { "id": { "type": "integer" } } })
242    }
243
244    fn route(method: Method, path: &str, operation: Option<Operation>) -> RouteInfo {
245        RouteInfo {
246            method,
247            path: path.to_owned(),
248            action: "PostsController::show",
249            middleware: 0,
250            operation,
251        }
252    }
253
254    #[test]
255    fn derives_path_parameters_from_the_pattern() {
256        let parameters = path_parameters("/teams/{team}/posts/{id}");
257
258        assert_eq!(parameters.len(), 2);
259        assert_eq!(parameters[0]["name"], "team");
260        assert_eq!(parameters[1]["name"], "id");
261        assert_eq!(parameters[1]["in"], "path");
262    }
263
264    #[test]
265    fn a_path_without_parameters_declares_none() {
266        assert!(path_parameters("/posts").is_empty());
267    }
268
269    #[test]
270    fn an_unclosed_brace_does_not_hang_or_panic() {
271        assert!(path_parameters("/posts/{id").is_empty());
272    }
273
274    #[test]
275    fn documents_a_described_operation() {
276        let operation = Operation {
277            summary: Some("Show a post"),
278            tag: Some("posts"),
279            body: None,
280            responses: vec![
281                ResponseSpec {
282                    status: 200,
283                    schema: Some(schema),
284                },
285                ResponseSpec {
286                    status: 404,
287                    schema: None,
288                },
289            ],
290        };
291
292        let document = document(
293            "Test",
294            "0.1.0",
295            &[route(Method::Get, "/posts/{id}", Some(operation))],
296        );
297        let get = &document["paths"]["/posts/{id}"]["get"];
298
299        assert_eq!(document["openapi"], "3.1.0");
300        assert_eq!(get["summary"], "Show a post");
301        assert_eq!(get["tags"][0], "posts");
302        assert_eq!(get["operationId"], "PostsController::show");
303        assert_eq!(
304            get["responses"]["200"]["content"]["application/json"]["schema"],
305            schema()
306        );
307
308        // Errors get the problem document, without anyone declaring it.
309        assert_eq!(get["responses"]["404"]["description"], "Not found");
310        assert_eq!(
311            get["responses"]["404"]["content"]["application/problem+json"]["schema"]["$ref"],
312            "#/components/schemas/Problem"
313        );
314    }
315
316    #[test]
317    fn a_request_body_is_marked_required() {
318        let operation = Operation {
319            body: Some(schema),
320            responses: vec![ResponseSpec {
321                status: 201,
322                schema: Some(schema),
323            }],
324            ..Operation::new()
325        };
326
327        let document = document(
328            "Test",
329            "0.1.0",
330            &[route(Method::Post, "/posts", Some(operation))],
331        );
332        let post = &document["paths"]["/posts"]["post"];
333
334        assert_eq!(post["requestBody"]["required"], true);
335        assert_eq!(
336            post["requestBody"]["content"]["application/json"]["schema"],
337            schema()
338        );
339        assert_eq!(post["responses"]["201"]["description"], "Created");
340    }
341
342    #[test]
343    fn an_undocumented_route_still_appears() {
344        let document = document("Test", "0.1.0", &[route(Method::Get, "/health", None)]);
345
346        assert_eq!(
347            document["paths"]["/health"]["get"]["responses"]["default"]["description"],
348            "Undocumented"
349        );
350    }
351
352    #[test]
353    fn methods_on_one_path_share_an_entry() {
354        let document = document(
355            "Test",
356            "0.1.0",
357            &[
358                route(Method::Get, "/posts", None),
359                route(Method::Post, "/posts", None),
360            ],
361        );
362
363        let entry = document["paths"]["/posts"].as_object().expect("object");
364        assert!(entry.contains_key("get") && entry.contains_key("post"));
365    }
366}