shors 0.12.6

Transport layer for cartridge + tarantool-module projects.
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use crate::transport::http::route::{Builder, Route};
use crate::transport::http::{Request, Response};
use crate::transport::Context;
use once_cell::sync::Lazy;
use std::collections::btree_map::Entry;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use utoipa::openapi::path::Parameter;
use utoipa::openapi::request_body::{RequestBody, RequestBodyBuilder};
use utoipa::openapi::security::SecurityScheme;
use utoipa::openapi::{
    Components, Content, Deprecated, PathItem, PathItemType, Ref, RefOr, Required, ResponseBuilder,
    Responses, Schema, SecurityRequirement, Server,
};
use utoipa::OpenApi;
use utoipa::ToSchema;
use utoipa_swagger_ui::{serve, Config};

fn append_to_components(name: impl Into<String>, schema: RefOr<Schema>) {
    let mut open_api = OPENAPI_DOC.lock().unwrap();
    if open_api.components.is_none() {
        open_api.components = Some(Components::new());
    }
    if let Some(c) = open_api.components.as_mut() {
        c.schemas.insert(name.into(), schema);
    }
}

/// OpenAPI schema builder.
///
/// Note: use [`define_schema!`] macro instead of manual creation.
pub struct SchemaDefenition {
    main_schema_name: String,
    schemas: Vec<(String, RefOr<Schema>)>,
}

impl SchemaDefenition {
    fn schema_from_type<'a, T: ToSchema<'a>>(schema_name: &str) -> (&'a str, RefOr<Schema>) {
        let aliases = T::aliases();

        if !aliases.is_empty() {
            // if schema has aliases get type name - this is an alias name
            let type_name = schema_name.split("::").last().unwrap();
            aliases
                .into_iter()
                .find_map(|(name, schema)| {
                    if name == type_name {
                        return Some((name, RefOr::T(schema)));
                    }
                    None
                })
                .unwrap_or_else(|| panic!("expect one of alias names, got {type_name}"))
        } else {
            T::schema()
        }
    }

    /// Create OpenAPI schema.
    ///
    /// Note: use [`define_schema!`] macro instead.
    ///
    /// # Arguments
    ///
    /// * `schema_name`: name of schema
    pub fn new<'a, S: ToSchema<'a>>(schema_name: &str) -> Self {
        let (schema_name, schema) = Self::schema_from_type::<S>(schema_name);
        Self {
            schemas: vec![(schema_name.to_string(), schema)],
            main_schema_name: schema_name.to_string(),
        }
    }

    /// Append component of OpenAPI schema.
    ///
    /// Note: use [`define_schema!`] instead
    ///
    /// # Arguments
    ///
    /// * `schema_name`: name of schema
    pub fn component<'a, C: ToSchema<'a>>(self, schema_name: &str) -> Self {
        let mut schemas = self.schemas;
        let (schema_name, schema) = Self::schema_from_type::<C>(schema_name);
        schemas.push((schema_name.to_string(), schema));
        Self { schemas, ..self }
    }

    fn build(self) {
        self.schemas
            .into_iter()
            .for_each(|(name, schema)| append_to_components(name, schema))
    }
}

/// Use this macro for define OpenAPI schemas.
/// Note: use `#[aliases(...)]` for define schemas for complex type with generics.
///
/// # Arguments
///
/// * `main_schema`: top-level type of the schema, must implement [`utoipa::ToSchema`] trait
/// * `component`: variadic list of inner types that using in schema. All types must implement [`utoipa::ToSchema`] trait
///
/// # Examples
///
/// Define a type with [`utoipa::ToSchema`] trait implementation, then define a schema:
///
/// ```rust
/// use utoipa::ToSchema;
/// use shors::define_schema;
///
/// #[derive(ToSchema)]
/// struct ResponsePart {
///     c: i32,
/// }
///
/// #[derive(ToSchema)]
/// struct Response {
///     a: Vec<ResponsePart>,
/// }
///
/// let defenition = define_schema!(Response, ResponsePart);
/// ```
///
/// Example with more complex type:
///
/// ```rust
/// use utoipa::ToSchema;
/// use shors::define_schema;
///
/// #[derive(serde::Serialize, ToSchema)]
/// #[aliases(ComplexResponsePartI32 = ComplexResponsePart<i32>)]
/// struct ComplexResponsePart<T> {
///     c: T,
/// }
///
/// #[derive(serde::Serialize, ToSchema)]
/// struct ComplexResponse {
///     a: Vec<ComplexResponsePartI32>,
/// }
///
/// let defenition = define_schema!(ComplexResponse, ComplexResponsePartI32);
/// ```
#[macro_export]
macro_rules! define_schema {
    ($main_schema: ty, $($component:ty),*) => {
        {
            use $crate::transport::http::openapi::SchemaDefenition;
            SchemaDefenition::new::<$main_schema>(stringify!($main_schema))
                $( .component::<$component>(stringify!($component)) )*
        }
    };
    ($main_schema: ty) => {
        define_schema!($main_schema,)
    };
}

#[derive(Default, Clone)]
pub struct RouteOperation {
    responses: Responses,
    request: Option<RequestBody>,
    params: Option<Vec<Parameter>>,
    tags: Option<Vec<String>>,
    summary: Option<String>,
    description: Option<String>,
    operation_id: Option<String>,
    deprecated: Option<Deprecated>,
    sec_requirements: Option<Vec<SecurityRequirement>>,
    servers: Option<Vec<Server>>,
}

impl RouteOperation {
    pub fn new() -> Self {
        Self::default()
    }

    /// Append response object to operation.
    ///
    /// Note: for define complex schemas with generic parameters use `#[aliases(...)]` macro along with `#[derive(ToSchema)]` .
    ///
    /// # Arguments
    ///
    /// * `schema`: definition of request schema, see a [`define_schema!`] macro.
    /// * `code`: http code.
    /// * `content_type`: media type, see https://spec.openapis.org/oas/v3.1.0#media-types.
    /// * `description`: a brief description of the response.
    pub fn with_response(
        self,
        schema: SchemaDefenition,
        code: impl Into<String>,
        content_type: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        let main_schema_name = schema.main_schema_name.clone();
        schema.build();

        let response_builder = ResponseBuilder::new().description(description).content(
            content_type,
            Content::new(RefOr::Ref(Ref::from_schema_name(main_schema_name))),
        );

        let mut responses = self.responses;
        responses
            .responses
            .insert(code.into(), RefOr::T(response_builder.build()));
        Self { responses, ..self }
    }

    /// Set OpenAPI requestBody.
    ///
    /// Note: for define complex schemas with generic parameters use `#[aliases(...)]` macro along with `#[derive(ToSchema)]` .
    ///
    /// # Arguments
    ///
    /// * `schema`: definition of request schema, see a [`define_schema`] macro.
    /// * `required`: determines if the request body is required in the request.
    /// * `content_type`: media type, see https://spec.openapis.org/oas/v3.1.0#media-types.
    /// * `description`: a brief description of the request body.
    pub fn with_request(
        self,
        schema: SchemaDefenition,
        required: bool,
        content_type: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        let main_schema_name = schema.main_schema_name.clone();
        schema.build();

        let mut req_builder = RequestBodyBuilder::new()
            .description(Some(description))
            .content(
                content_type,
                Content::new(RefOr::Ref(Ref::from_schema_name(main_schema_name))),
            );
        if required {
            req_builder = req_builder.required(Some(Required::True))
        }

        Self {
            request: Some(req_builder.build()),
            ..self
        }
    }

    /// Append a new [`Parameter`] to operation.
    pub fn with_param(self, param: Parameter) -> Self {
        let mut params = self.params.unwrap_or_default();
        params.push(param);
        Self {
            params: Some(params),
            ..self
        }
    }

    /// Extends current params from the given iterator of [`Parameter`].
    pub fn with_params(self, params: impl Iterator<Item = Parameter>) -> Self {
        let mut current_params = self.params.unwrap_or_default();
        current_params.extend(params);
        Self {
            params: Some(current_params),
            ..self
        }
    }

    /// Append OpenAPI tag. Tags can be used for logical grouping of operations by resources or any other qualifier.
    pub fn with_tag(self, tag: impl Into<String>) -> Self {
        let mut tags = self.tags.unwrap_or_default();
        tags.push(tag.into());
        Self {
            tags: Some(tags),
            ..self
        }
    }

    /// Append a short summary of what the operation does.
    pub fn with_summary(self, summary: impl Into<String>) -> Self {
        Self {
            summary: Some(summary.into()),
            ..self
        }
    }

    /// Append a verbose explanation of the operation behavior.
    pub fn with_description(self, descr: impl Into<String>) -> Self {
        Self {
            description: Some(descr.into()),
            ..self
        }
    }

    /// Append a verbose explanation of the operation behavior.
    pub fn with_operation_id(self, op_id: impl Into<String>) -> Self {
        Self {
            operation_id: Some(op_id.into()),
            ..self
        }
    }

    /// Declares this operation to be deprecated.
    pub fn set_deprecated(self) -> Self {
        Self {
            deprecated: Some(Deprecated::True),
            ..self
        }
    }

    /// Append [`SecurityScheme`] to operation security requirements.
    pub fn with_security(
        self,
        name: impl Into<String>,
        schema: SecurityScheme,
        scopes: &[String],
    ) -> Self {
        let mut open_api = OPENAPI_DOC.lock().unwrap();
        if open_api.components.is_none() {
            open_api.components = Some(Components::new());
        }
        let name = name.into();
        if let Some(c) = open_api.components.as_mut() {
            c.add_security_scheme(name.clone(), schema)
        }

        let req = SecurityRequirement::new(name, scopes);
        let mut sec_requirements = self.sec_requirements.unwrap_or_default();
        sec_requirements.push(req);
        Self {
            sec_requirements: Some(sec_requirements),
            ..self
        }
    }

    /// Append a new [`Server`] to the operation servers.
    pub fn with_server(self, server: Server) -> Self {
        let mut servers = self.servers.unwrap_or_default();
        servers.push(server);
        Self {
            servers: Some(servers),
            ..self
        }
    }

    pub(crate) fn update_global_doc(self, path: &str, method: &str) {
        let it_type = match method.to_lowercase().as_str() {
            "get" => PathItemType::Get,
            "post" => PathItemType::Post,
            "put" => PathItemType::Put,
            "patch" => PathItemType::Patch,
            "delete" => PathItemType::Delete,
            _ => PathItemType::Get,
        };

        let op_builder = utoipa::openapi::path::OperationBuilder::new()
            .tags(self.tags)
            .summary(self.summary)
            .description(self.description)
            .operation_id(self.operation_id)
            .deprecated(self.deprecated)
            .securities(self.sec_requirements)
            .servers(self.servers)
            .responses(self.responses)
            .request_body(self.request)
            .parameters(self.params);

        let mut open_api = OPENAPI_DOC.lock().unwrap();

        match open_api.paths.paths.entry(path.to_string()) {
            Entry::Vacant(e) => {
                e.insert(PathItem::new(it_type, op_builder));
            }
            Entry::Occupied(mut item) => {
                item.get_mut()
                    .operations
                    .insert(it_type, op_builder.build());
            }
        }
    }
}

#[derive(OpenApi)]
#[openapi()]
pub struct ApiDoc;

static OPENAPI_DOC: Lazy<Mutex<utoipa::openapi::OpenApi>> =
    Lazy::new(|| Mutex::new(ApiDoc::openapi()));

/// Get generated instance of OpenApi document.
///
/// # Arguments
///
/// * `f`: callback to interact with OpenAPI document.
///
/// # Examples
///
/// ```
///     use utoipa::openapi::InfoBuilder;
///     use shors::transport::http::openapi::with_open_api;
///     
///     let yaml = with_open_api(|api| {
///         api.info = InfoBuilder::new()
///             .title("SHORS open api")
///             .build();
///         api.to_yaml().unwrap()
///     });
///     println!("{yaml}");
/// ```
pub fn with_open_api<T>(f: fn(&mut utoipa::openapi::OpenApi) -> T) -> T {
    let mut lock = OPENAPI_DOC.lock().unwrap();
    f(&mut lock)
}

/// Build a route to serve Swagger UI via web server.
///
/// # Arguments
///
/// * `base_path`: swagger ui base path. Full url to access a swagger ui looks like: {base path}/index.html.
/// * `config`: object used to alter Swagger UI settings. In mosts cases create config directly from url that points to the api doc json.
///
/// # Examples
///
/// Create swagger ui available at /swagger/index.html:
///
/// ```
/// use std::collections::HashMap;
/// use std::sync::Arc;
/// use utoipa_swagger_ui::Config;
/// use shors::transport::Context;
/// use shors::transport::http::openapi::{swagger_ui_route, with_open_api};
/// use shors::transport::http::{Request, Response};
/// use shors::transport::http::route::{Builder, Route};
///
/// let doc_route = Builder::new()
///         .with_method("GET")
///         .with_path("/docs/openapi.json")
///         .build(move |_ctx: &mut Context, req: Request| -> Result<_, Box<dyn std::error::Error>> {
///             let api = with_open_api(|a| a.to_json().unwrap());
///             Ok(Response {
///                 status: 200,
///                 headers: HashMap::from([("content-type".to_string(), "application/json; charset=utf8".to_string())]),
///                 body: api.as_bytes().to_vec(),
///             })
///         });
///
///     let config = Arc::new(Config::from("/docs/openapi.json"));
///     let swagger: Route<Box<dyn std::error::Error>> = swagger_ui_route("/swagger", config);
/// ```
pub fn swagger_ui_route<E>(base_path: &'static str, config: Arc<Config<'static>>) -> Route<E> {
    Builder::new()
        .with_method("GET")
        .with_path(base_path)
        .with_path("/:tail")
        .build(move |_ctx: &mut Context, req: Request| -> Result<_, E> {
            let tail = req.stash.get("tail").map(|s| s.as_str()).unwrap_or("/");

            match serve(tail, config.clone()) {
                Ok(swagger_file) => swagger_file
                    .map(|file| {
                        Ok(Response {
                            status: 200,
                            body: file.bytes.to_vec(),
                            headers: HashMap::from([(
                                "content-type".to_string(),
                                file.content_type,
                            )]),
                        })
                    })
                    .unwrap_or_else(|| {
                        Ok(Response {
                            status: 404,
                            body: "not found".as_bytes().to_vec(),
                            headers: HashMap::from([(
                                "content-type".to_string(),
                                "text/html; charset=utf-8".to_string(),
                            )]),
                        })
                    }),
                Err(error) => Ok(Response {
                    status: 500,
                    body: error.to_string().as_bytes().to_vec(),
                    headers: HashMap::from([(
                        "content-type".to_string(),
                        "text/html; charset=utf-8".to_string(),
                    )]),
                }),
            }
        })
}