Skip to main content

yaiko_core/
openapi.rs

1//! OpenAPI 3.0 document generation for Yaiko routes.
2
3use crate::{Handler, Request, Response};
4use async_trait::async_trait;
5use hyper::Method;
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8use std::sync::Arc;
9
10#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
11pub struct OpenApiDocument {
12    pub openapi: String,
13    pub info: OpenApiInfo,
14    #[serde(default, skip_serializing_if = "Option::is_none")]
15    pub servers: Option<Vec<OpenApiServer>>,
16    pub paths: BTreeMap<String, OpenApiPathItem>,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
20pub struct OpenApiInfo {
21    pub title: String,
22    pub version: String,
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub description: Option<String>,
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
28pub struct OpenApiServer {
29    pub url: String,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub description: Option<String>,
32}
33
34#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
35pub struct OpenApiPathItem {
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub get: Option<OpenApiOperation>,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub post: Option<OpenApiOperation>,
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub put: Option<OpenApiOperation>,
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub delete: Option<OpenApiOperation>,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub patch: Option<OpenApiOperation>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub options: Option<OpenApiOperation>,
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub head: Option<OpenApiOperation>,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
53pub struct OpenApiOperation {
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub summary: Option<String>,
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub description: Option<String>,
58    #[serde(
59        rename = "operationId",
60        default,
61        skip_serializing_if = "Option::is_none"
62    )]
63    pub operation_id: Option<String>,
64    #[serde(default, skip_serializing_if = "Vec::is_empty")]
65    pub tags: Vec<String>,
66    pub responses: BTreeMap<String, OpenApiResponse>,
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
70pub struct OpenApiResponse {
71    pub description: String,
72}
73
74impl OpenApiOperation {
75    pub fn new(response_status: u16, response_description: impl Into<String>) -> Self {
76        let mut responses = BTreeMap::new();
77        responses.insert(
78            response_status.to_string(),
79            OpenApiResponse {
80                description: response_description.into(),
81            },
82        );
83        Self {
84            summary: None,
85            description: None,
86            operation_id: None,
87            tags: Vec::new(),
88            responses,
89        }
90    }
91
92    pub fn summary(mut self, value: impl Into<String>) -> Self {
93        self.summary = Some(value.into());
94        self
95    }
96
97    pub fn description(mut self, value: impl Into<String>) -> Self {
98        self.description = Some(value.into());
99        self
100    }
101
102    pub fn operation_id(mut self, value: impl Into<String>) -> Self {
103        self.operation_id = Some(value.into());
104        self
105    }
106
107    pub fn tag(mut self, value: impl Into<String>) -> Self {
108        self.tags.push(value.into());
109        self
110    }
111}
112
113impl OpenApiDocument {
114    pub fn new(title: impl Into<String>, version: impl Into<String>) -> Self {
115        Self {
116            openapi: "3.0.3".to_string(),
117            info: OpenApiInfo {
118                title: title.into(),
119                version: version.into(),
120                description: None,
121            },
122            servers: None,
123            paths: BTreeMap::new(),
124        }
125    }
126
127    pub fn description(mut self, value: impl Into<String>) -> Self {
128        self.info.description = Some(value.into());
129        self
130    }
131
132    pub fn server(mut self, url: impl Into<String>, description: Option<String>) -> Self {
133        self.servers
134            .get_or_insert_with(Vec::new)
135            .push(OpenApiServer {
136                url: url.into(),
137                description,
138            });
139        self
140    }
141
142    pub fn route(mut self, method: Method, path: &str, operation: OpenApiOperation) -> Self {
143        let path = normalize_path(path);
144        let item = self.paths.entry(path).or_default();
145        match method {
146            Method::GET => item.get = Some(operation),
147            Method::POST => item.post = Some(operation),
148            Method::PUT => item.put = Some(operation),
149            Method::DELETE => item.delete = Some(operation),
150            Method::PATCH => item.patch = Some(operation),
151            Method::OPTIONS => item.options = Some(operation),
152            Method::HEAD => item.head = Some(operation),
153            _ => {}
154        }
155        self
156    }
157
158    pub fn json(&self) -> Result<String, serde_json::Error> {
159        serde_json::to_string_pretty(self)
160    }
161
162    pub fn handler(self: Arc<Self>) -> OpenApiHandler {
163        OpenApiHandler { document: self }
164    }
165}
166
167fn normalize_path(path: &str) -> String {
168    let mut result = String::new();
169    let mut chars = path.trim_end_matches('/').chars().peekable();
170    if !path.starts_with('/') {
171        result.push('/');
172    }
173    while let Some(ch) = chars.next() {
174        if ch == ':' {
175            let mut name = String::new();
176            while let Some(next) = chars.peek().copied() {
177                if next.is_alphanumeric() || next == '_' {
178                    name.push(next);
179                    chars.next();
180                } else {
181                    break;
182                }
183            }
184            result.push('{');
185            result.push_str(&name);
186            result.push('}');
187        } else if ch == '*' {
188            result.push_str("{path}");
189        } else {
190            result.push(ch);
191        }
192    }
193    if result.is_empty() {
194        "/".to_string()
195    } else {
196        result
197    }
198}
199
200pub struct OpenApiHandler {
201    document: Arc<OpenApiDocument>,
202}
203
204#[async_trait]
205impl Handler for OpenApiHandler {
206    async fn handle(
207        &self,
208        _req: Request,
209    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
210        Ok(Response::new().json(self.document.as_ref())?)
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use hyper::Method;
218
219    #[test]
220    fn builder_serializes_framework_paths_as_openapi_paths() {
221        let document = OpenApiDocument::new("Demo", "1.0.0")
222            .description("Demo API")
223            .server("https://example.test", None)
224            .route(
225                Method::GET,
226                "/users/:id",
227                OpenApiOperation::new(200, "User returned")
228                    .summary("Get a user")
229                    .operation_id("getUser")
230                    .tag("users"),
231            );
232        let value: serde_json::Value = serde_json::from_str(&document.json().unwrap()).unwrap();
233        assert_eq!(value["openapi"], "3.0.3");
234        assert_eq!(
235            value["paths"]["/users/{id}"]["get"]["operationId"],
236            "getUser"
237        );
238        assert_eq!(
239            value["paths"]["/users/{id}"]["get"]["responses"]["200"]["description"],
240            "User returned"
241        );
242    }
243
244    #[test]
245    fn empty_and_relative_paths_are_normalized() {
246        let document = OpenApiDocument::new("Demo", "1.0.0")
247            .route(Method::GET, "", OpenApiOperation::new(200, "OK"))
248            .route(
249                Method::POST,
250                "admin/*",
251                OpenApiOperation::new(201, "Created"),
252            );
253        assert!(document.paths.contains_key("/"));
254        assert!(document.paths.contains_key("/admin/{path}"));
255    }
256}