-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathschema.rs
More file actions
433 lines (397 loc) · 13.8 KB
/
schema.rs
File metadata and controls
433 lines (397 loc) · 13.8 KB
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
//! Schema-related structure definitions
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
/// Schema reference or inline schema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SchemaRef {
/// Schema reference (e.g., "#/components/schemas/User")
Ref(Reference),
/// Inline schema
Inline(Box<Schema>),
}
/// Reference definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Reference {
/// Reference path (e.g., "#/components/schemas/User")
#[serde(rename = "$ref")]
pub ref_path: String,
}
impl Reference {
/// Create a new reference
pub fn new(ref_path: String) -> Self {
Self { ref_path }
}
/// Create a component schema reference
pub fn schema(name: &str) -> Self {
Reference::new(format!("#/components/schemas/{}", name))
}
}
/// JSON Schema type
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SchemaType {
String,
Number,
Integer,
Boolean,
Array,
Object,
Null,
}
/// Number format
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NumberFormat {
Float,
Double,
Int32,
Int64,
}
/// String format
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StringFormat {
Date,
DateTime,
Password,
Byte,
Binary,
Email,
Uuid,
Uri,
Hostname,
IpV4,
IpV6,
}
/// JSON Schema definition
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Schema {
/// Schema reference ($ref) - if present, other fields are ignored
#[serde(rename = "$ref")]
#[serde(skip_serializing_if = "Option::is_none")]
pub ref_path: Option<String>,
/// Schema type
#[serde(rename = "type")]
#[serde(skip_serializing_if = "Option::is_none")]
pub schema_type: Option<SchemaType>,
/// Format (for numbers or strings)
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
/// Title
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
/// Description
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Default value
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<serde_json::Value>,
/// Example
#[serde(skip_serializing_if = "Option::is_none")]
pub example: Option<serde_json::Value>,
/// Examples
#[serde(skip_serializing_if = "Option::is_none")]
pub examples: Option<Vec<serde_json::Value>>,
// Number constraints
/// Minimum value
#[serde(skip_serializing_if = "Option::is_none")]
pub minimum: Option<f64>,
/// Maximum value
#[serde(skip_serializing_if = "Option::is_none")]
pub maximum: Option<f64>,
/// Exclusive minimum
#[serde(skip_serializing_if = "Option::is_none")]
pub exclusive_minimum: Option<bool>,
/// Exclusive maximum
#[serde(skip_serializing_if = "Option::is_none")]
pub exclusive_maximum: Option<bool>,
/// Multiple of
#[serde(skip_serializing_if = "Option::is_none")]
pub multiple_of: Option<f64>,
// String constraints
/// Minimum length
#[serde(skip_serializing_if = "Option::is_none")]
pub min_length: Option<usize>,
/// Maximum length
#[serde(skip_serializing_if = "Option::is_none")]
pub max_length: Option<usize>,
/// Pattern (regex)
#[serde(skip_serializing_if = "Option::is_none")]
pub pattern: Option<String>,
// Array constraints
/// Array item schema
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Box<SchemaRef>>,
/// Prefix items for tuple arrays (OpenAPI 3.1 / JSON Schema 2020-12)
#[serde(skip_serializing_if = "Option::is_none")]
pub prefix_items: Option<Vec<SchemaRef>>,
/// Minimum number of items
#[serde(skip_serializing_if = "Option::is_none")]
pub min_items: Option<usize>,
/// Maximum number of items
#[serde(skip_serializing_if = "Option::is_none")]
pub max_items: Option<usize>,
/// Unique items flag
#[serde(skip_serializing_if = "Option::is_none")]
pub unique_items: Option<bool>,
// Object constraints
/// Property definitions
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<BTreeMap<String, SchemaRef>>,
/// List of required properties
#[serde(skip_serializing_if = "Option::is_none")]
pub required: Option<Vec<String>>,
/// Whether additional properties are allowed (can be boolean or SchemaRef)
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_properties: Option<serde_json::Value>,
/// Minimum number of properties
#[serde(skip_serializing_if = "Option::is_none")]
pub min_properties: Option<usize>,
/// Maximum number of properties
#[serde(skip_serializing_if = "Option::is_none")]
pub max_properties: Option<usize>,
// General constraints
/// Enum values
#[serde(skip_serializing_if = "Option::is_none")]
pub r#enum: Option<Vec<serde_json::Value>>,
/// All conditions must be satisfied (AND)
#[serde(skip_serializing_if = "Option::is_none")]
pub all_of: Option<Vec<SchemaRef>>,
/// At least one condition must be satisfied (OR)
#[serde(skip_serializing_if = "Option::is_none")]
pub any_of: Option<Vec<SchemaRef>>,
/// Exactly one condition must be satisfied (XOR)
#[serde(skip_serializing_if = "Option::is_none")]
pub one_of: Option<Vec<SchemaRef>>,
/// Condition must not be satisfied (NOT)
#[serde(skip_serializing_if = "Option::is_none")]
pub not: Option<Box<SchemaRef>>,
/// Discriminator for polymorphic schemas (used with oneOf/anyOf/allOf)
#[serde(skip_serializing_if = "Option::is_none")]
pub discriminator: Option<Discriminator>,
/// Nullable flag
#[serde(skip_serializing_if = "Option::is_none")]
pub nullable: Option<bool>,
/// Read-only flag
#[serde(skip_serializing_if = "Option::is_none")]
pub read_only: Option<bool>,
/// Write-only flag
#[serde(skip_serializing_if = "Option::is_none")]
pub write_only: Option<bool>,
/// External documentation reference
#[serde(skip_serializing_if = "Option::is_none")]
pub external_docs: Option<ExternalDocumentation>,
// JSON Schema 2020-12 dynamic references
/// Definitions ($defs) - reusable schema definitions
#[serde(rename = "$defs")]
#[serde(skip_serializing_if = "Option::is_none")]
pub defs: Option<BTreeMap<String, Schema>>,
/// Dynamic anchor ($dynamicAnchor) - defines a dynamic anchor
#[serde(rename = "$dynamicAnchor")]
#[serde(skip_serializing_if = "Option::is_none")]
pub dynamic_anchor: Option<String>,
/// Dynamic reference ($dynamicRef) - references a dynamic anchor
#[serde(rename = "$dynamicRef")]
#[serde(skip_serializing_if = "Option::is_none")]
pub dynamic_ref: Option<String>,
}
impl Schema {
/// Create a new schema
pub fn new(schema_type: SchemaType) -> Self {
Self {
ref_path: None,
schema_type: Some(schema_type),
format: None,
title: None,
description: None,
default: None,
example: None,
examples: None,
minimum: None,
maximum: None,
exclusive_minimum: None,
exclusive_maximum: None,
multiple_of: None,
min_length: None,
max_length: None,
pattern: None,
items: None,
prefix_items: None,
min_items: None,
max_items: None,
unique_items: None,
properties: None,
required: None,
additional_properties: None,
min_properties: None,
max_properties: None,
r#enum: None,
all_of: None,
any_of: None,
one_of: None,
not: None,
discriminator: None,
nullable: None,
read_only: None,
write_only: None,
external_docs: None,
defs: None,
dynamic_anchor: None,
dynamic_ref: None,
}
}
/// Create a string schema
pub fn string() -> Self {
Self::new(SchemaType::String)
}
/// Create an integer schema
pub fn integer() -> Self {
Self::new(SchemaType::Integer)
}
/// Create a number schema
pub fn number() -> Self {
Self::new(SchemaType::Number)
}
/// Create a boolean schema
pub fn boolean() -> Self {
Self::new(SchemaType::Boolean)
}
/// Create an array schema
pub fn array(items: SchemaRef) -> Self {
Self {
items: Some(Box::new(items)),
..Self::new(SchemaType::Array)
}
}
/// Create an object schema
pub fn object() -> Self {
Self {
properties: Some(BTreeMap::new()),
required: Some(Vec::new()),
..Self::new(SchemaType::Object)
}
}
}
/// External documentation reference
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalDocumentation {
/// Documentation description
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Documentation URL
pub url: String,
}
/// Discriminator object for polymorphism support (OpenAPI 3.0/3.1)
///
/// Used with `oneOf`, `anyOf`, `allOf` to aid in serialization, deserialization,
/// and validation when request bodies or response payloads may be one of several types.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Discriminator {
/// The name of the property in the payload that will hold the discriminator value
pub property_name: String,
/// An object to hold mappings between payload values and schema names or references
#[serde(skip_serializing_if = "Option::is_none")]
pub mapping: Option<BTreeMap<String, String>>,
}
/// OpenAPI Components (reusable components)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Components {
/// Schema definitions
#[serde(skip_serializing_if = "Option::is_none")]
pub schemas: Option<BTreeMap<String, Schema>>,
/// Response definitions
#[serde(skip_serializing_if = "Option::is_none")]
pub responses: Option<HashMap<String, crate::route::Response>>,
/// Parameter definitions
#[serde(skip_serializing_if = "Option::is_none")]
pub parameters: Option<HashMap<String, crate::route::Parameter>>,
/// Example definitions
#[serde(skip_serializing_if = "Option::is_none")]
pub examples: Option<HashMap<String, crate::route::Example>>,
/// Request body definitions
#[serde(skip_serializing_if = "Option::is_none")]
pub request_bodies: Option<HashMap<String, crate::route::RequestBody>>,
/// Header definitions
#[serde(skip_serializing_if = "Option::is_none")]
pub headers: Option<HashMap<String, crate::route::Header>>,
/// Security scheme definitions
#[serde(skip_serializing_if = "Option::is_none")]
pub security_schemes: Option<HashMap<String, SecurityScheme>>,
}
/// Security scheme type
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SecuritySchemeType {
ApiKey,
Http,
MutualTls,
OAuth2,
OpenIdConnect,
}
/// Security scheme definition
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SecurityScheme {
/// Security scheme type
pub r#type: SecuritySchemeType,
/// Description
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Name (for API Key)
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Location (for API Key: query, header, cookie)
#[serde(skip_serializing_if = "Option::is_none")]
pub r#in: Option<String>,
/// Scheme (for HTTP: bearer, basic, etc.)
#[serde(skip_serializing_if = "Option::is_none")]
pub scheme: Option<String>,
/// Bearer format (for HTTP Bearer)
#[serde(skip_serializing_if = "Option::is_none")]
pub bearer_format: Option<String>,
}
/// Builder trait for types that can be converted to OpenAPI Schema
pub trait SchemaBuilder: Sized {
// This trait is used as a marker for derive macro
// The actual schema conversion will be implemented separately
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[rstest]
#[case(Schema::string(), SchemaType::String)]
#[case(Schema::integer(), SchemaType::Integer)]
#[case(Schema::number(), SchemaType::Number)]
#[case(Schema::boolean(), SchemaType::Boolean)]
fn primitive_helpers_set_schema_type(#[case] schema: Schema, #[case] expected: SchemaType) {
assert_eq!(schema.schema_type, Some(expected));
}
#[test]
fn array_helper_sets_type_and_items() {
let item_schema = Schema::boolean();
let schema = Schema::array(SchemaRef::Inline(Box::new(item_schema.clone())));
assert_eq!(schema.schema_type, Some(SchemaType::Array));
let items = schema.items.expect("items should be set");
match *items {
SchemaRef::Inline(inner) => {
assert_eq!(inner.schema_type, Some(SchemaType::Boolean));
}
SchemaRef::Ref(_) => panic!("array helper should set inline items"),
}
}
#[test]
fn object_helper_initializes_collections() {
let schema = Schema::object();
assert_eq!(schema.schema_type, Some(SchemaType::Object));
let props = schema.properties.expect("properties should be initialized");
assert!(props.is_empty());
let required = schema.required.expect("required should be initialized");
assert!(required.is_empty());
}
}