reinhardt-rest 0.1.2

REST API framework aggregator for Reinhardt
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
//! Advanced enum schema generation
//!
//! This module provides support for generating OpenAPI schemas for Rust enums
//! with various serde tagging strategies.

use super::openapi::SchemaType;
use super::{ObjectBuilder, RefOr, Schema, SchemaExt};
use utoipa::openapi::Type;

/// Enum tagging strategy
///
/// Corresponds to serde's enum representation attributes:
/// - `#[serde(tag = "type")]` - Internally tagged
/// - `#[serde(tag = "type", content = "value")]` - Adjacently tagged
/// - `#[serde(untagged)]` - Untagged
/// - No attribute - Externally tagged (default)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EnumTagging {
	/// Externally tagged (default): `{"Variant": {...}}`
	External,

	/// Internally tagged: `{"type": "Variant", ...fields}`
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use serde::Serialize;
	/// #[derive(Serialize)]
	/// #[serde(tag = "type")]
	/// enum Message {
	///     Text { content: String },
	///     Image { url: String },
	/// }
	/// ```
	Internal {
		/// The tag field name (e.g., "type")
		tag: String,
	},

	/// Adjacently tagged: `{"tag": "Variant", "content": {...}}`
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use serde::Serialize;
	/// #[derive(Serialize)]
	/// #[serde(tag = "tag", content = "content")]
	/// enum Message {
	///     Text { content: String },
	///     Image { url: String },
	/// }
	/// ```
	Adjacent {
		/// The tag field name (e.g., "tag")
		tag: String,
		/// The content field name (e.g., "content")
		content: String,
	},

	/// Untagged: no discriminator, tries each variant in order
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use serde::Serialize;
	/// #[derive(Serialize)]
	/// #[serde(untagged)]
	/// enum Value {
	///     String(String),
	///     Number(i32),
	/// }
	/// ```
	Untagged,
}

/// Builder for enum schemas
///
/// Provides a fluent API for constructing OpenAPI schemas for Rust enums
/// with different tagging strategies.
///
/// # Example
///
/// ```rust
/// use reinhardt_rest::openapi::enum_schema::{EnumSchemaBuilder, EnumTagging};
/// use reinhardt_rest::openapi::{Schema, SchemaExt};
///
/// // Internally tagged enum
/// let schema = EnumSchemaBuilder::new("Message")
///     .tagging(EnumTagging::Internal {
///         tag: "type".to_string(),
///     })
///     .variant("Text", Schema::object_with_properties(
///         vec![("content", Schema::string())],
///         vec!["content"],
///     ))
///     .variant("Image", Schema::object_with_properties(
///         vec![("url", Schema::string())],
///         vec!["url"],
///     ))
///     .build();
/// ```
pub struct EnumSchemaBuilder {
	name: String,
	tagging: EnumTagging,
	variants: Vec<(String, Schema)>,
	description: Option<String>,
}

impl EnumSchemaBuilder {
	/// Create a new enum schema builder
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_rest::openapi::enum_schema::EnumSchemaBuilder;
	///
	/// let builder = EnumSchemaBuilder::new("Status");
	/// ```
	pub fn new(name: impl Into<String>) -> Self {
		Self {
			name: name.into(),
			tagging: EnumTagging::External,
			variants: Vec::new(),
			description: None,
		}
	}

	/// Set the tagging strategy
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_rest::openapi::enum_schema::{EnumSchemaBuilder, EnumTagging};
	///
	/// let builder = EnumSchemaBuilder::new("Status")
	///     .tagging(EnumTagging::Internal {
	///         tag: "type".to_string(),
	///     });
	/// ```
	pub fn tagging(mut self, tagging: EnumTagging) -> Self {
		self.tagging = tagging;
		self
	}

	/// Add a variant to the enum
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_rest::openapi::enum_schema::EnumSchemaBuilder;
	/// use reinhardt_rest::openapi::{Schema, SchemaExt};
	///
	/// let builder = EnumSchemaBuilder::new("Status")
	///     .variant("Active", Schema::object())
	///     .variant("Inactive", Schema::object());
	/// ```
	pub fn variant(mut self, name: impl Into<String>, schema: Schema) -> Self {
		self.variants.push((name.into(), schema));
		self
	}

	/// Set the enum description
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_rest::openapi::enum_schema::EnumSchemaBuilder;
	///
	/// let builder = EnumSchemaBuilder::new("Status")
	///     .description("User status");
	/// ```
	pub fn description(mut self, description: impl Into<String>) -> Self {
		self.description = Some(description.into());
		self
	}

	/// Build the OpenAPI schema
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_rest::openapi::enum_schema::EnumSchemaBuilder;
	/// use reinhardt_rest::openapi::{Schema, SchemaExt};
	///
	/// let schema = EnumSchemaBuilder::new("Status")
	///     .variant("Active", Schema::object())
	///     .variant("Inactive", Schema::object())
	///     .build();
	/// ```
	pub fn build(self) -> Schema {
		match self.tagging.clone() {
			EnumTagging::External => self.build_external(),
			EnumTagging::Internal { tag } => self.build_internal(&tag),
			EnumTagging::Adjacent { tag, content } => self.build_adjacent(&tag, &content),
			EnumTagging::Untagged => self.build_untagged(),
		}
	}

	fn build_external(self) -> Schema {
		// External tagging: oneOf with object for each variant
		// Each variant is an object with single property (variant name)
		let variant_schemas: Vec<RefOr<Schema>> = self
			.variants
			.into_iter()
			.map(|(name, schema)| {
				RefOr::T(Schema::Object(
					ObjectBuilder::new()
						.schema_type(SchemaType::Type(Type::Object))
						.property(name, schema)
						.build(),
				))
			})
			.collect();

		let mut one_of = utoipa::openapi::schema::OneOf::new();
		one_of.items = variant_schemas;
		one_of.title = Some(self.name);

		if let Some(desc) = self.description {
			one_of.description = Some(desc);
		}

		Schema::OneOf(one_of)
	}

	fn build_internal(self, tag: &str) -> Schema {
		// Internal tagging: oneOf with discriminator
		// Each variant includes the tag field
		let variant_schemas: Vec<RefOr<Schema>> = self
			.variants
			.into_iter()
			.map(|(name, schema)| {
				let mut properties = vec![(tag.to_string(), Schema::string())];
				let mut required = vec![tag.to_string()];

				// Merge variant schema properties
				if let Schema::Object(obj) = schema {
					for (prop_name, prop_schema) in obj.properties {
						properties.push((prop_name.clone(), prop_schema.into()));
						if obj.required.contains(&prop_name) {
							required.push(prop_name);
						}
					}

					let mut builder = ObjectBuilder::new()
						.schema_type(SchemaType::Type(Type::Object))
						.property(tag, Schema::string());

					for (prop_name, prop_schema) in properties.into_iter().skip(1) {
						builder = builder.property(prop_name, prop_schema);
					}

					for req in required {
						builder = builder.required(req);
					}

					// Add const constraint for tag
					builder = builder.property(
						tag,
						Schema::Object(
							ObjectBuilder::new()
								.schema_type(SchemaType::Type(Type::String))
								.enum_values(Some(vec![serde_json::Value::String(name)]))
								.build(),
						),
					);

					RefOr::T(Schema::Object(builder.build()))
				} else {
					RefOr::T(Schema::Object(
						ObjectBuilder::new()
							.schema_type(SchemaType::Type(Type::Object))
							.property(
								tag,
								Schema::Object(
									ObjectBuilder::new()
										.schema_type(SchemaType::Type(Type::String))
										.enum_values(Some(vec![serde_json::Value::String(name)]))
										.build(),
								),
							)
							.required(tag)
							.build(),
					))
				}
			})
			.collect();

		let mut one_of = utoipa::openapi::schema::OneOf::new();
		one_of.items = variant_schemas;
		one_of.title = Some(self.name.clone());
		one_of.discriminator = Some(utoipa::openapi::schema::Discriminator::new(tag));

		if let Some(desc) = self.description {
			one_of.description = Some(desc);
		}

		Schema::OneOf(one_of)
	}

	fn build_adjacent(self, tag: &str, content: &str) -> Schema {
		// Adjacent tagging: oneOf with tag and content fields
		let variant_schemas: Vec<RefOr<Schema>> = self
			.variants
			.into_iter()
			.map(|(name, schema)| {
				RefOr::T(Schema::Object(
					ObjectBuilder::new()
						.schema_type(SchemaType::Type(Type::Object))
						.property(
							tag,
							Schema::Object(
								ObjectBuilder::new()
									.schema_type(SchemaType::Type(Type::String))
									.enum_values(Some(vec![serde_json::Value::String(name)]))
									.build(),
							),
						)
						.property(content, schema)
						.required(tag)
						.required(content)
						.build(),
				))
			})
			.collect();

		let mut one_of = utoipa::openapi::schema::OneOf::new();
		one_of.items = variant_schemas;
		one_of.title = Some(self.name);
		one_of.discriminator = Some(utoipa::openapi::schema::Discriminator::new(tag));

		if let Some(desc) = self.description {
			one_of.description = Some(desc);
		}

		Schema::OneOf(one_of)
	}

	fn build_untagged(self) -> Schema {
		// Untagged: oneOf without discriminator
		let variant_schemas: Vec<RefOr<Schema>> = self
			.variants
			.into_iter()
			.map(|(_, schema)| RefOr::T(schema))
			.collect();

		let mut one_of = utoipa::openapi::schema::OneOf::new();
		one_of.items = variant_schemas;
		one_of.title = Some(self.name);

		if let Some(desc) = self.description {
			one_of.description = Some(desc);
		}

		Schema::OneOf(one_of)
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_external_tagging() {
		let schema = EnumSchemaBuilder::new("Message")
			.variant("Text", Schema::string())
			.variant("Image", Schema::string())
			.build();

		match schema {
			Schema::OneOf(one_of) => {
				assert_eq!(one_of.items.len(), 2);
			}
			_ => panic!("Expected OneOf schema"),
		}
	}

	#[test]
	fn test_internal_tagging() {
		let schema = EnumSchemaBuilder::new("Message")
			.tagging(EnumTagging::Internal {
				tag: "type".to_string(),
			})
			.variant(
				"Text",
				Schema::object_with_properties(
					vec![("content", Schema::string())],
					vec!["content"],
				),
			)
			.build();

		match schema {
			Schema::OneOf(one_of) => {
				assert!(one_of.discriminator.is_some());

				let discriminator = one_of.discriminator.unwrap();
				assert_eq!(discriminator.property_name, "type");
			}
			_ => panic!("Expected OneOf schema"),
		}
	}

	#[test]
	fn test_adjacent_tagging() {
		let schema = EnumSchemaBuilder::new("Message")
			.tagging(EnumTagging::Adjacent {
				tag: "tag".to_string(),
				content: "content".to_string(),
			})
			.variant("Text", Schema::string())
			.build();

		match schema {
			Schema::OneOf(one_of) => {
				assert!(one_of.discriminator.is_some());

				let discriminator = one_of.discriminator.unwrap();
				assert_eq!(discriminator.property_name, "tag");
			}
			_ => panic!("Expected OneOf schema"),
		}
	}

	#[test]
	fn test_untagged() {
		let schema = EnumSchemaBuilder::new("Value")
			.tagging(EnumTagging::Untagged)
			.variant("String", Schema::string())
			.variant("Number", Schema::integer())
			.build();

		match schema {
			Schema::OneOf(one_of) => {
				assert!(one_of.discriminator.is_none());
			}
			_ => panic!("Expected OneOf schema"),
		}
	}

	#[test]
	fn test_with_description() {
		let schema = EnumSchemaBuilder::new("Status")
			.description("User status")
			.variant("Active", Schema::object())
			.build();

		match schema {
			Schema::OneOf(one_of) => {
				assert_eq!(one_of.description, Some("User status".to_string()));
			}
			_ => panic!("Expected OneOf schema"),
		}
	}

	#[test]
	fn test_multiple_variants() {
		let schema = EnumSchemaBuilder::new("Color")
			.variant("Red", Schema::object())
			.variant("Green", Schema::object())
			.variant("Blue", Schema::object())
			.build();

		match schema {
			Schema::OneOf(one_of) => {
				assert_eq!(one_of.items.len(), 3);
			}
			_ => panic!("Expected OneOf schema"),
		}
	}

	#[test]
	fn test_internal_tagging_preserves_variant_properties() {
		let schema = EnumSchemaBuilder::new("Message")
			.tagging(EnumTagging::Internal {
				tag: "type".to_string(),
			})
			.variant(
				"Text",
				Schema::object_with_properties(
					vec![("content", Schema::string()), ("author", Schema::string())],
					vec!["content", "author"],
				),
			)
			.build();

		match schema {
			Schema::OneOf(one_of) => {
				assert_eq!(one_of.items.len(), 1);

				match &one_of.items[0] {
					RefOr::T(Schema::Object(variant_obj)) => {
						// Should have type, content, and author properties
						assert!(variant_obj.properties.contains_key("type"));
						assert!(variant_obj.properties.contains_key("content"));
						assert!(variant_obj.properties.contains_key("author"));

						// All should be required
						assert!(variant_obj.required.contains(&"type".to_string()));
						assert!(variant_obj.required.contains(&"content".to_string()));
						assert!(variant_obj.required.contains(&"author".to_string()));
					}
					_ => panic!("Expected T(Object) variant"),
				}
			}
			_ => panic!("Expected OneOf schema"),
		}
	}
}