zino_openapi/
lib.rs

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
#![doc = include_str!("../README.md")]
#![doc(html_favicon_url = "https://zino.cc/assets/zino-logo.png")]
#![doc(html_logo_url = "https://zino.cc/assets/zino-logo.svg")]
#![forbid(unsafe_code)]

use ahash::{HashMap, HashMapExt};
use convert_case::{Case, Casing};
use serde_json::json;
use std::{collections::BTreeMap, fs, io::ErrorKind, sync::OnceLock};
use toml::Table;
use utoipa::openapi::{
    content::ContentBuilder,
    external_docs::ExternalDocs,
    info::{Contact, Info, License},
    path::{PathItem, Paths, PathsBuilder},
    response::ResponseBuilder,
    schema::{
        Components, ComponentsBuilder, KnownFormat, Object, ObjectBuilder, Ref, SchemaFormat, Type,
    },
    security::SecurityRequirement,
    server::Server,
    tag::Tag,
    OpenApi, OpenApiBuilder,
};
use zino_core::{
    application::{Agent, Application},
    extension::TomlTableExt,
    LazyLock, Uuid,
};

mod model;
mod parser;

pub use model::translate_model_entry;

/// Gets the [OpenAPI](https://spec.openapis.org/oas/latest.html) document.
pub fn openapi() -> OpenApi {
    OpenApiBuilder::new()
        .paths(default_paths()) // should come first to load OpenAPI files
        .components(Some(default_components()))
        .tags(Some(default_tags()))
        .servers(Some(default_servers()))
        .security(Some(default_securities()))
        .external_docs(default_external_docs())
        .info(openapi_info(Agent::name(), Agent::version()))
        .build()
}

/// Constructs the OpenAPI `Info` object.
fn openapi_info(title: &str, version: &str) -> Info {
    let mut info = Info::new(title, version);
    if let Some(config) = OPENAPI_INFO.get() {
        if let Some(title) = config.get_str("title") {
            title.clone_into(&mut info.title);
        }
        if let Some(description) = config.get_str("description") {
            info.description = Some(description.to_owned());
        }
        if let Some(terms_of_service) = config.get_str("terms_of_service") {
            info.terms_of_service = Some(terms_of_service.to_owned());
        }
        if let Some(contact_config) = config.get_table("contact") {
            let mut contact = Contact::new();
            if let Some(contact_name) = contact_config.get_str("name") {
                contact.name = Some(contact_name.to_owned());
            }
            if let Some(contact_url) = contact_config.get_str("url") {
                contact.url = Some(contact_url.to_owned());
            }
            if let Some(contact_email) = contact_config.get_str("email") {
                contact.email = Some(contact_email.to_owned());
            }
            info.contact = Some(contact);
        }
        if let Some(license) = config.get_str("license") {
            info.license = Some(License::new(license));
        } else if let Some(license_config) = config.get_table("license") {
            let license_name = license_config.get_str("name").unwrap_or_default();
            let mut license = License::new(license_name);
            if let Some(license_url) = license_config.get_str("url") {
                license.url = Some(license_url.to_owned());
            }
            info.license = Some(license);
        }
        if let Some(version) = config.get_str("version") {
            version.clone_into(&mut info.version);
        }
    }
    info
}

/// Returns the default OpenAPI paths.
fn default_paths() -> Paths {
    let mut paths_builder = PathsBuilder::new();
    for (path, item) in OPENAPI_PATHS.iter() {
        paths_builder = paths_builder.path(path, item.clone());
    }
    paths_builder.build()
}

/// Returns the default OpenAPI components.
fn default_components() -> Components {
    let mut components = OPENAPI_COMPONENTS.get_or_init(Components::new).clone();

    // Request ID
    let request_id_example = Uuid::now_v7();
    let request_id_schema = ObjectBuilder::new()
        .schema_type(Type::String)
        .format(Some(SchemaFormat::KnownFormat(KnownFormat::Uuid)))
        .build();

    // Default response
    let status_schema = ObjectBuilder::new()
        .schema_type(Type::Integer)
        .examples(Some(200))
        .build();
    let success_schema = ObjectBuilder::new()
        .schema_type(Type::Boolean)
        .examples(Some(true))
        .build();
    let message_schema = ObjectBuilder::new()
        .schema_type(Type::String)
        .examples(Some("OK"))
        .build();
    let default_response_schema = ObjectBuilder::new()
        .schema_type(Type::Object)
        .property("status", status_schema)
        .property("success", success_schema)
        .property("message", message_schema)
        .property("request_id", request_id_schema.clone())
        .property("data", Object::new())
        .required("status")
        .required("success")
        .required("message")
        .required("request_id")
        .build();
    let default_response_example = json!({
        "status": 200,
        "success": true,
        "message": "OK",
        "request_id": request_id_example,
        "data": {},
    });
    let default_response_content = ContentBuilder::new()
        .schema(Some(Ref::from_schema_name("defaultResponse")))
        .example(Some(default_response_example))
        .build();
    let default_response = ResponseBuilder::new()
        .content("application/json", default_response_content)
        .build();
    components
        .schemas
        .insert("defaultResponse".to_owned(), default_response_schema.into());
    components
        .responses
        .insert("default".to_owned(), default_response.into());

    // 4XX error response
    let model_id_example = Uuid::now_v7();
    let detail_example = format!("404 Not Found: cannot find the model `{model_id_example}`");
    let instance_example = format!("/model/{model_id_example}/view");
    let status_schema = ObjectBuilder::new()
        .schema_type(Type::Integer)
        .examples(Some(404))
        .build();
    let success_schema = ObjectBuilder::new()
        .schema_type(Type::Boolean)
        .examples(Some(false))
        .build();
    let title_schema = ObjectBuilder::new()
        .schema_type(Type::String)
        .examples(Some("NotFound"))
        .build();
    let detail_schema = ObjectBuilder::new()
        .schema_type(Type::String)
        .examples(Some(detail_example.as_str()))
        .build();
    let instance_schema = ObjectBuilder::new()
        .schema_type(Type::String)
        .examples(Some(instance_example.as_str()))
        .build();
    let error_response_schema = ObjectBuilder::new()
        .schema_type(Type::Object)
        .property("status", status_schema)
        .property("success", success_schema)
        .property("title", title_schema)
        .property("detail", detail_schema)
        .property("instance", instance_schema)
        .property("request_id", request_id_schema)
        .required("status")
        .required("success")
        .required("title")
        .required("detail")
        .required("instance")
        .required("request_id")
        .build();
    let error_response_example = json!({
        "status": 404,
        "success": false,
        "title": "NotFound",
        "detail": detail_example,
        "instance": instance_example,
        "request_id": request_id_example,
    });
    let error_response_content = ContentBuilder::new()
        .schema(Some(Ref::from_schema_name("errorResponse")))
        .example(Some(error_response_example))
        .build();
    let error_response = ResponseBuilder::new()
        .content("application/json", error_response_content)
        .build();
    components
        .schemas
        .insert("errorResponse".to_owned(), error_response_schema.into());
    components
        .responses
        .insert("4XX".to_owned(), error_response.into());

    components
}

/// Returns the default OpenAPI tags.
fn default_tags() -> Vec<Tag> {
    OPENAPI_TAGS.get_or_init(Vec::new).clone()
}

/// Returns the default OpenAPI servers.
fn default_servers() -> Vec<Server> {
    OPENAPI_SERVERS
        .get_or_init(|| vec![Server::new("/")])
        .clone()
}

/// Returns the default OpenAPI security requirements.
fn default_securities() -> Vec<SecurityRequirement> {
    OPENAPI_SECURITIES.get_or_init(Vec::new).clone()
}

/// Returns the default OpenAPI external docs.
fn default_external_docs() -> Option<ExternalDocs> {
    OPENAPI_EXTERNAL_DOCS.get().cloned()
}

/// OpenAPI paths.
static OPENAPI_PATHS: LazyLock<BTreeMap<String, PathItem>> = LazyLock::new(|| {
    let mut paths: BTreeMap<String, PathItem> = BTreeMap::new();
    let openapi_dir = Agent::config_dir().join("openapi");
    match fs::read_dir(openapi_dir) {
        Ok(entries) => {
            let mut openapi_tags = Vec::new();
            let mut model_definitions = HashMap::new();
            let mut components_builder = ComponentsBuilder::new();
            let files = entries
                .filter_map(|entry| entry.ok())
                .filter(|entry| entry.file_type().is_ok_and(|f| f.is_file()));
            for file in files {
                let openapi_file = file.path();
                let openapi_config = fs::read_to_string(&openapi_file)
                    .unwrap_or_else(|err| {
                        let openapi_file = openapi_file.display();
                        panic!("fail to read the OpenAPI file `{openapi_file}`: {err}");
                    })
                    .parse::<Table>()
                    .expect("fail to parse the OpenAPI file as a TOML table");
                if file.file_name() == "OPENAPI.toml" {
                    if let Some(info_config) = openapi_config.get_table("info") {
                        if OPENAPI_INFO.set(info_config.clone()).is_err() {
                            panic!("fail to set OpenAPI info");
                        }
                    }
                    if let Some(servers) = openapi_config.get_array("servers") {
                        let servers = servers
                            .iter()
                            .filter_map(|v| v.as_table())
                            .map(parser::parse_server)
                            .collect::<Vec<_>>();
                        if OPENAPI_SERVERS.set(servers).is_err() {
                            panic!("fail to set OpenAPI servers");
                        }
                    }
                    if let Some(security_schemes) = openapi_config.get_table("security_schemes") {
                        for (name, scheme) in security_schemes {
                            if let Some(scheme_config) = scheme.as_table() {
                                let scheme = parser::parse_security_scheme(scheme_config);
                                components_builder =
                                    components_builder.security_scheme(name, scheme);
                            }
                        }
                    }
                    if let Some(securities) = openapi_config.get_array("securities") {
                        let security_requirements = securities
                            .iter()
                            .filter_map(|v| v.as_table())
                            .map(parser::parse_security_requirement)
                            .collect::<Vec<_>>();
                        if OPENAPI_SECURITIES.set(security_requirements).is_err() {
                            panic!("fail to set OpenAPI security requirements");
                        }
                    }
                    if let Some(external_docs) = openapi_config.get_table("external_docs") {
                        let external_docs = parser::parse_external_docs(external_docs);
                        if OPENAPI_EXTERNAL_DOCS.set(external_docs).is_err() {
                            panic!("fail to set OpenAPI external docs");
                        }
                    }
                    continue;
                }

                let name = openapi_config
                    .get_str("name")
                    .map(|s| s.to_owned())
                    .unwrap_or_else(|| {
                        file.file_name()
                            .to_string_lossy()
                            .trim_end_matches(".toml")
                            .to_owned()
                    });
                let ignore_securities = openapi_config
                    .get_array("securities")
                    .is_some_and(|v| v.is_empty());
                if let Some(endpoints) = openapi_config.get_array("endpoints") {
                    for endpoint in endpoints.iter().filter_map(|v| v.as_table()) {
                        let path = endpoint.get_str("path").unwrap_or("/");
                        let method = endpoint
                            .get_str("method")
                            .unwrap_or_default()
                            .to_ascii_uppercase();
                        let http_method = parser::parse_http_method(&method);
                        let operation =
                            parser::parse_operation(&name, path, endpoint, ignore_securities);
                        let path_item = PathItem::new(http_method, operation);
                        if let Some(item) = paths.get_mut(path) {
                            item.merge_operations(path_item);
                        } else {
                            paths.insert(path.to_owned(), path_item);
                        }
                    }
                }
                if let Some(schemas) = openapi_config.get_table("schemas") {
                    for (key, value) in schemas.iter() {
                        if let Some(config) = value.as_table() {
                            let name = key.to_case(Case::Camel);
                            let schema = parser::parse_schema(config);
                            components_builder = components_builder.schema(name, schema);
                        }
                    }
                }
                if let Some(responses) = openapi_config.get_table("responses") {
                    for (key, value) in responses.iter() {
                        if let Some(config) = value.as_table() {
                            let name = key.to_case(Case::Camel);
                            let response = parser::parse_response(config);
                            components_builder = components_builder.response(name, response);
                        }
                    }
                }
                if let Some(models) = openapi_config.get_table("models") {
                    for (model_name, model_fields) in models {
                        if let Some(fields) = model_fields.as_table() {
                            let model_name = model_name.to_owned().leak() as &'static str;
                            model_definitions.insert(model_name, fields.to_owned());
                        }
                    }
                }
                openapi_tags.push(parser::parse_tag(&name, &openapi_config))
            }
            if OPENAPI_COMPONENTS.set(components_builder.build()).is_err() {
                panic!("fail to set OpenAPI components");
            }
            if OPENAPI_TAGS.set(openapi_tags).is_err() {
                panic!("fail to set OpenAPI tags");
            }
            if MODEL_DEFINITIONS.set(model_definitions).is_err() {
                panic!("fail to set model definitions");
            }
        }
        Err(err) => {
            if err.kind() != ErrorKind::NotFound {
                tracing::error!("{err}");
            }
        }
    }
    paths
});

/// OpenAPI info.
static OPENAPI_INFO: OnceLock<Table> = OnceLock::new();

/// OpenAPI components.
static OPENAPI_COMPONENTS: OnceLock<Components> = OnceLock::new();

/// OpenAPI tags.
static OPENAPI_TAGS: OnceLock<Vec<Tag>> = OnceLock::new();

/// OpenAPI servers.
static OPENAPI_SERVERS: OnceLock<Vec<Server>> = OnceLock::new();

/// OpenAPI securities.
static OPENAPI_SECURITIES: OnceLock<Vec<SecurityRequirement>> = OnceLock::new();

/// OpenAPI external docs.
static OPENAPI_EXTERNAL_DOCS: OnceLock<ExternalDocs> = OnceLock::new();

/// Model definitions.
static MODEL_DEFINITIONS: OnceLock<HashMap<&str, Table>> = OnceLock::new();