roas 0.6.0

Rust OpenAPI Specification
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
//! Representing a Server.

use crate::common::helpers::{Context, PushError, ValidateWithContext, validate_required_string};
use crate::v3_1::spec::Spec;
use crate::validation::Options;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};

/// An object representing a Server.
///
/// Specification example:
///
/// ```yaml
/// servers:
/// - url: https://{username}.gigantic-server.com:{port}/{basePath}
///   description: The production API server
///   variables:
///     username:
///       # note! no enum here means it is an open value
///       default: demo
///       description: this value is assigned by the service provider, in this example `gigantic-server.com`
///     port:
///       enum:
///         - '8443'
///         - '443'
///       default: '8443'
///     basePath:
///       # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`
///       default: v2
/// ```
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)]
pub struct Server {
    /// **Required** A URL to the target host.
    /// This URL supports Server Variables and MAY be relative,
    /// to indicate that the host location is relative to the location
    /// where the OpenAPI document is being served.
    /// Variable substitutions will be made when a variable is named in {brackets}.
    pub url: String,

    /// An optional string describing the host designated by the URL.
    /// [CommonMark](https://spec.commonmark.org)  syntax MAY be used for rich text representation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// A map between a variable name and its value.
    /// The value is used for substitution in the server's URL template.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variables: Option<BTreeMap<String, ServerVariable>>,

    /// This object MAY be extended with Specification Extensions.
    /// The field name MUST begin with `x-`, for example, `x-internal-id`.
    /// The value can be null, a primitive, an array or an object.
    #[serde(flatten)]
    #[serde(with = "crate::common::extensions")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extensions: Option<BTreeMap<String, serde_json::Value>>,
}

/// An object representing a Server Variable for server URL template substitution.
///
/// Specification example:
///
/// ```yaml
/// enum:
///   - '8443'
///   - '443'
/// default: '8443'
/// description: the port to serve HTTP traffic on
/// ```
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)]
pub struct ServerVariable {
    /// An enumeration of string values to be used if the substitution options are from a limited set.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "enum")]
    enum_values: Option<Vec<String>>,

    /// **Required** The default value to use for substitution,
    /// which SHALL be sent if an alternate value is not supplied.
    /// Note this behavior is different than the Schema Object’s treatment of default values,
    /// because in those cases parameter values are optional.
    /// If the enum is defined, the value SHOULD exist in the enum’s values.
    default: String,

    /// An optional description for the server variable.
    /// [CommonMark](https://spec.commonmark.org) syntax MAY be used for rich text representation.
    description: Option<String>,

    /// This object MAY be extended with Specification Extensions.
    /// The field name MUST begin with `x-`, for example, `x-internal-id`.
    /// The value can be null, a primitive, an array or an object.
    #[serde(flatten)]
    #[serde(with = "crate::common::extensions")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extensions: Option<BTreeMap<String, serde_json::Value>>,
}

impl ValidateWithContext<Spec> for Server {
    fn validate_with_context(&self, ctx: &mut Context<Spec>, path: String) {
        validate_required_string(&self.url, ctx, format!("{path}.url"));
        let mut visited = HashSet::<String>::new();
        if let Some(variables) = &self.variables {
            for (name, variable) in variables {
                variable.validate_with_context(ctx, format!("{path}.variables[{name}]"));
                visited.insert(name.clone());
            }
        };
        let re = Regex::new(r"\{([a-zA-Z0-9.\-_]+)}").unwrap();
        for (_, [name]) in re.captures_iter(&self.url).map(|c| c.extract()) {
            if !visited.remove(name) {
                ctx.error(
                    path.clone(),
                    format_args!(".url: `{name}` is not defined in `variables`"),
                );
            }
        }
        if !ctx.is_option(Options::IgnoreUnusedServerVariables) {
            for name in visited {
                ctx.error(
                    path.clone(),
                    format_args!(".variables[{name}]: unused in `url`"),
                );
            }
        }
    }
}

impl ValidateWithContext<Spec> for ServerVariable {
    fn validate_with_context(&self, ctx: &mut Context<Spec>, path: String) {
        validate_required_string(&self.default, ctx, format!("{path}.default"));
        if let Some(enum_values) = &self.enum_values
            && !enum_values.contains(&self.default)
        {
            ctx.error(
                path,
                format!(
                    ".default: `{}` must be in enum values: {:?}",
                    self.default, enum_values,
                ),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validation::Options;
    use enumset::EnumSet;

    #[test]
    fn test_server_variable_deserialize() {
        assert_eq!(
            serde_json::from_value::<ServerVariable>(serde_json::json!({
                "enum": [
                    "8443",
                    "443"
                ],
                "default": "8443",
                "description": "the port to serve HTTP traffic on"
            }))
            .unwrap(),
            ServerVariable {
                enum_values: Some(vec![String::from("8443"), String::from("443")]),
                default: String::from("8443"),
                description: Some(String::from("the port to serve HTTP traffic on")),
                ..Default::default()
            },
            "deserialize",
        );
    }

    #[test]
    fn test_server_variable_serialize() {
        assert_eq!(
            serde_json::to_value(ServerVariable {
                enum_values: Some(vec![String::from("8443"), String::from("443")]),
                default: String::from("8443"),
                description: Some(String::from("the port to serve HTTP traffic on")),
                ..Default::default()
            })
            .unwrap(),
            serde_json::json!({
                "enum": [
                    "8443",
                    "443"
                ],
                "default": "8443",
                "description": "the port to serve HTTP traffic on"
            }),
            "serialize",
        );
    }

    #[test]
    fn test_server_variable_validate() {
        let spec = Spec::default();
        let mut ctx = Context::new(&spec, Default::default());
        ServerVariable {
            enum_values: Some(vec![String::from("8443"), String::from("443")]),
            default: String::from("8443"),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, String::from("serverVariable"));
        assert_eq!(ctx.errors.len(), 0, "no errors: {:?}", ctx.errors);

        ServerVariable {
            enum_values: Some(vec![String::from("443")]),
            default: String::from("8443"),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, String::from("serverVariable"));
        assert_eq!(ctx.errors.len(), 1, "one error: {:?}", ctx.errors);
        assert_eq!(
            ctx.errors[0],
            "serverVariable.default: `8443` must be in enum values: [\"443\"]",
        );
    }

    #[test]
    fn test_server_serialize() {
        assert_eq!(
            serde_json::to_value(Server {
                url: String::from("https://development.gigantic-server.com/v1"),
                ..Default::default()
            })
            .unwrap(),
            serde_json::json!({
                "url": "https://development.gigantic-server.com/v1",
            }),
            "serialize with url only",
        );

        assert_eq!(
            serde_json::to_value(Server {
                url: String::from("https://development.gigantic-server.com/v1"),
                description: Some(String::from("Development server")),
                ..Default::default()
            })
            .unwrap(),
            serde_json::json!({
                "url": "https://development.gigantic-server.com/v1",
                "description": "Development server",
            }),
            "serialize with url and description",
        );

        assert_eq!(
            serde_json::to_value(Server {
                url: String::from("https://{username}.gigantic-server.com:{port}/{basePath}"),
                description: Some(String::from("Development server")),
                variables: Some({
                    let mut vars = BTreeMap::<String, ServerVariable>::new();
                    vars.insert(
                        String::from("username"),
                        ServerVariable {
                            default: String::from("demo"),
                            description: Some(String::from(
                                "this value is assigned by the service provider, in this example `gigantic-server.com`"
                            )),
                            ..Default::default()
                        },
                    );
                    vars.insert(
                        String::from("port"),
                        ServerVariable {
                            enum_values: Some(vec![String::from("8443"), String::from("443")]),
                            default: String::from("8443"),
                            description: Some(String::from("the port to serve HTTP traffic on")),
                            ..Default::default()
                        },
                    );
                    vars.insert(
                        String::from("basePath"),
                        ServerVariable {
                            default: String::from("v2"),
                            description: Some(String::from(
                                "open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`"
                            )),
                            ..Default::default()
                        },
                    );
                    vars
                }),
                ..Default::default()
            })
                .unwrap(),
            serde_json::json!({
                "url": "https://{username}.gigantic-server.com:{port}/{basePath}",
                "description": "Development server",
                "variables": {
                    "username": {
                        "default": "demo",
                        "description": "this value is assigned by the service provider, in this example `gigantic-server.com`"
                    },
                    "port": {
                        "enum": [
                            "8443",
                            "443"
                        ],
                        "default": "8443",
                        "description": "the port to serve HTTP traffic on"
                    },
                    "basePath": {
                        "default": "v2",
                        "description": "open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`"
                    }
                }
            }),
            "serialize with url, description and variables",
        );
    }

    #[test]
    fn test_server_deserialize() {
        assert_eq!(
            serde_json::from_value::<Server>(serde_json::json!({
                "url": "https://development.gigantic-server.com/v1",
            }))
            .unwrap(),
            Server {
                url: String::from("https://development.gigantic-server.com/v1"),
                ..Default::default()
            },
            "deserialize with url only",
        );

        assert_eq!(
            serde_json::from_value::<Server>(serde_json::json!({
                "url": "https://development.gigantic-server.com/v1",
                "description": "Development server",
            }))
            .unwrap(),
            Server {
                url: String::from("https://development.gigantic-server.com/v1"),
                description: Some(String::from("Development server")),
                ..Default::default()
            },
            "deserialize with url and description",
        );
        assert_eq!(
            serde_json::from_value::<Server>(serde_json::json!({
                "url": "https://{username}.gigantic-server.com:{port}/{basePath}",
                "description": "Development server",
                "variables": {
                    "username": {
                        "default": "demo",
                        "description": "this value is assigned by the service provider, in this example `gigantic-server.com`"
                    },
                    "port": {
                        "enum": [
                            "8443",
                            "443"
                        ],
                        "default": "8443",
                        "description": "the port to serve HTTP traffic on"
                    },
                    "basePath": {
                        "default": "v2",
                        "description": "open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`"
                    }
                }
            })).unwrap(),
            Server {
                url: String::from("https://{username}.gigantic-server.com:{port}/{basePath}"),
                description: Some(String::from("Development server")),
                variables: Some({
                    let mut vars = BTreeMap::<String, ServerVariable>::new();
                    vars.insert(
                        String::from("username"),
                        ServerVariable {
                            default: String::from("demo"),
                            description: Some(String::from(
                                "this value is assigned by the service provider, in this example `gigantic-server.com`"
                            )),
                            ..Default::default()
                        },
                    );
                    vars.insert(
                        String::from("port"),
                        ServerVariable {
                            enum_values: Some(vec![String::from("8443"), String::from("443")]),
                            default: String::from("8443"),
                            description: Some(String::from("the port to serve HTTP traffic on")),
                            ..Default::default()
                        },
                    );
                    vars.insert(
                        String::from("basePath"),
                        ServerVariable {
                            default: String::from("v2"),
                            description: Some(String::from(
                                "open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`"
                            )),
                            ..Default::default()
                        },
                    );
                    vars
                }),
                ..Default::default()
            },
            "deserialize with url, description and variables",
        );
    }

    #[test]
    fn test_server_validate() {
        let spec = Spec::default();
        let mut ctx = Context::new(&spec, Default::default());
        Server {
            url: String::from("https://development.gigantic-server.com/v1"),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, String::from("server"));
        assert_eq!(ctx.errors.len(), 0, "no errors: {:?}", ctx.errors);

        Server {
            url: String::from("https://{username}.gigantic-server.com:{port}/{basePath}"),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, String::from("server"));
        assert_eq!(ctx.errors.len(), 3, "3 errors: {:?}", ctx.errors);

        ctx = Context::new(&spec, Default::default());
        Server {
            url: String::from("https://{username}.gigantic-server.com:{port}/{basePath}"),
            variables: Some({
                let mut vars = BTreeMap::<String, ServerVariable>::new();
                vars.insert(
                    String::from("username"),
                    ServerVariable {
                        default: String::from("demo"),
                        ..Default::default()
                    },
                );
                vars.insert(
                    String::from("port"),
                    ServerVariable {
                        default: String::from("8443"),
                        ..Default::default()
                    },
                );
                vars.insert(
                    String::from("basePath"),
                    ServerVariable {
                        default: String::from("v2"),
                        ..Default::default()
                    },
                );
                vars
            }),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, String::from("server"));
        assert_eq!(
            ctx.errors.len(),
            0,
            "all variables are defined: {:?}",
            ctx.errors
        );

        Server {
            url: String::from("https://{username}.gigantic-server.com:{port}/{basePath}"),
            variables: Some({
                let mut vars = BTreeMap::<String, ServerVariable>::new();
                vars.insert(
                    String::from("username"),
                    ServerVariable {
                        default: String::from("demo"),
                        ..Default::default()
                    },
                );
                vars.insert(
                    String::from("port"),
                    ServerVariable {
                        default: String::from("8443"),
                        ..Default::default()
                    },
                );
                vars.insert(
                    String::from("basePath"),
                    ServerVariable {
                        default: String::from("v2"),
                        ..Default::default()
                    },
                );
                vars.insert(
                    String::from("foo"),
                    ServerVariable {
                        default: String::from("bar"),
                        ..Default::default()
                    },
                );
                vars
            }),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, String::from("server"));
        assert_eq!(ctx.errors.len(), 1, "with used variable: {:?}", ctx.errors);

        ctx = Context::new(&spec, EnumSet::only(Options::IgnoreUnusedServerVariables));
        Server {
            url: String::from("https://{username}.gigantic-server.com:{port}/{basePath}"),
            variables: Some({
                let mut vars = BTreeMap::<String, ServerVariable>::new();
                vars.insert(
                    String::from("username"),
                    ServerVariable {
                        default: String::from("demo"),
                        ..Default::default()
                    },
                );
                vars.insert(
                    String::from("port"),
                    ServerVariable {
                        default: String::from("8443"),
                        ..Default::default()
                    },
                );
                vars.insert(
                    String::from("basePath"),
                    ServerVariable {
                        default: String::from("v2"),
                        ..Default::default()
                    },
                );
                vars.insert(
                    String::from("foo"),
                    ServerVariable {
                        default: String::from("bar"),
                        ..Default::default()
                    },
                );
                vars
            }),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, String::from("server"));
        assert_eq!(
            ctx.errors.len(),
            0,
            "ignore used variable: {:?}",
            ctx.errors
        );
    }
}