spikard 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -674
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +13 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +405 -405
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -13
  11. data/lib/spikard/handler_wrapper.rb +113 -113
  12. data/lib/spikard/provide.rb +214 -214
  13. data/lib/spikard/response.rb +173 -173
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -44
  17. data/lib/spikard/testing.rb +256 -256
  18. data/lib/spikard/upload_file.rb +131 -131
  19. data/lib/spikard/version.rb +5 -5
  20. data/lib/spikard/websocket.rb +59 -59
  21. data/lib/spikard.rb +43 -43
  22. data/sig/spikard.rbs +366 -366
  23. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -63
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -132
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -752
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -194
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -246
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -401
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -238
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -24
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -292
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -616
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -305
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -248
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -351
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -454
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -383
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -280
  39. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  40. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  41. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  42. data/vendor/crates/spikard-core/src/debug.rs +127 -127
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -702
  44. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  45. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  46. data/vendor/crates/spikard-core/src/di/factory.rs +534 -534
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -506
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -405
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -281
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -69
  52. data/vendor/crates/spikard-core/src/http.rs +415 -415
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -1186
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -389
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -2525
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -344
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -1154
  59. data/vendor/crates/spikard-core/src/router.rs +510 -510
  60. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  61. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  62. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +696 -688
  63. data/vendor/crates/spikard-core/src/validation/mod.rs +457 -457
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -64
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -148
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -92
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -296
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -1860
  69. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  70. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  71. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  72. data/vendor/crates/spikard-http/src/cors.rs +1005 -1005
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -128
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -1668
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -901
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +838 -830
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -290
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -534
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -230
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -1193
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -540
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -912
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -513
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -735
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -535
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -1363
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -665
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -793
  90. data/vendor/crates/spikard-http/src/response.rs +720 -720
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -1650
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -234
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1593 -1502
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -770
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -599
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -1409
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -52
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -283
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -1375
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -832
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -309
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -26
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -192
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -5
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -1093
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -656
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -314
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -620
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -663
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -48
  113. data/vendor/crates/spikard-rb/build.rs +199 -199
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -5
  116. data/vendor/crates/spikard-rb/src/config/server_config.rs +285 -285
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -554
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -100
  119. data/vendor/crates/spikard-rb/src/di/mod.rs +375 -375
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -618
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -3
  122. data/vendor/crates/spikard-rb/src/lib.rs +1806 -1810
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -275
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -5
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -447
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -5
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -324
  128. data/vendor/crates/spikard-rb/src/server.rs +305 -308
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/testing/client.rs +538 -551
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -7
  132. data/vendor/crates/spikard-rb/src/testing/sse.rs +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -635
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -374
  135. metadata +15 -1
@@ -1,688 +1,696 @@
1
- //! Table-driven error mapping for JSON Schema validation failures
2
- //!
3
- //! This module provides a structured approach to mapping JSON Schema validation errors
4
- //! to consistent error codes and messages. Instead of massive if-else chains, we use
5
- //! enum variants and pattern matching for maintainability and testability.
6
-
7
- use serde_json::Value;
8
-
9
- /// Represents the different types of validation errors that can occur
10
- #[derive(Debug, Clone, PartialEq, Eq)]
11
- pub enum ErrorCondition {
12
- /// String length is below minimum
13
- StringTooShort { min_length: Option<u64> },
14
- /// String length exceeds maximum
15
- StringTooLong { max_length: Option<u64> },
16
- /// Number is not greater than exclusive minimum
17
- GreaterThan { value: Option<i64> },
18
- /// Number is not greater than or equal to minimum
19
- GreaterThanEqual { value: Option<i64> },
20
- /// Number is not less than exclusive maximum
21
- LessThan { value: Option<i64> },
22
- /// Number is not less than or equal to maximum
23
- LessThanEqual { value: Option<i64> },
24
- /// Value is not one of allowed enum values
25
- Enum { values: Option<Vec<String>> },
26
- /// String does not match pattern
27
- StringPatternMismatch { pattern: Option<String> },
28
- /// Email format validation failed
29
- EmailFormat,
30
- /// UUID format validation failed
31
- UuidFormat,
32
- /// Date-time format validation failed
33
- DatetimeFormat,
34
- /// Date format validation failed
35
- DateFormat,
36
- /// Other format validation failed
37
- FormatError,
38
- /// Type mismatch
39
- TypeMismatch { expected_type: String },
40
- /// Required field is missing
41
- Missing,
42
- /// Additional properties not allowed
43
- AdditionalProperties { field: String },
44
- /// Array has too few items
45
- TooFewItems { min_items: Option<usize> },
46
- /// Array has too many items
47
- TooManyItems,
48
- /// Fallback for unmapped errors
49
- ValidationError,
50
- }
51
-
52
- impl ErrorCondition {
53
- /// Determine the error condition from schema path and error message
54
- pub fn from_schema_error(schema_path_str: &str, error_msg: &str) -> Self {
55
- match () {
56
- _ if schema_path_str.contains("minLength") => Self::StringTooShort { min_length: None },
57
- _ if schema_path_str.contains("maxLength") => Self::StringTooLong { max_length: None },
58
- _ if schema_path_str.contains("exclusiveMinimum")
59
- || (error_msg.contains("less than or equal to") && error_msg.contains("minimum")) =>
60
- {
61
- Self::GreaterThan { value: None }
62
- }
63
- _ if schema_path_str.contains("minimum") || error_msg.contains("less than the minimum") => {
64
- Self::GreaterThanEqual { value: None }
65
- }
66
- _ if schema_path_str.contains("exclusiveMaximum")
67
- || (error_msg.contains("greater than or equal to") && error_msg.contains("maximum")) =>
68
- {
69
- Self::LessThan { value: None }
70
- }
71
- _ if schema_path_str.contains("maximum") || error_msg.contains("greater than the maximum") => {
72
- Self::LessThanEqual { value: None }
73
- }
74
- _ if schema_path_str.contains("enum") || error_msg.contains("is not one of") => Self::Enum { values: None },
75
- _ if schema_path_str.contains("pattern") || error_msg.contains("does not match") => {
76
- Self::StringPatternMismatch { pattern: None }
77
- }
78
- _ if schema_path_str.contains("format") => {
79
- if error_msg.contains("email") {
80
- Self::EmailFormat
81
- } else if error_msg.contains("uuid") {
82
- Self::UuidFormat
83
- } else if error_msg.contains("date-time") {
84
- Self::DatetimeFormat
85
- } else if error_msg.contains("date") {
86
- Self::DateFormat
87
- } else {
88
- Self::FormatError
89
- }
90
- }
91
- _ if schema_path_str.contains("/type") => Self::TypeMismatch {
92
- expected_type: "unknown".to_string(),
93
- },
94
- _ if schema_path_str.ends_with("/required") => Self::Missing,
95
- _ if schema_path_str.contains("/additionalProperties")
96
- || error_msg.contains("Additional properties are not allowed") =>
97
- {
98
- Self::AdditionalProperties { field: String::new() }
99
- }
100
- _ if schema_path_str.contains("/minItems") => Self::TooFewItems { min_items: None },
101
- _ if schema_path_str.contains("/maxItems") => Self::TooManyItems,
102
- _ => Self::ValidationError,
103
- }
104
- }
105
-
106
- /// Get the error type code for this condition
107
- pub fn error_type(&self) -> &'static str {
108
- match self {
109
- Self::StringTooShort { .. } => "string_too_short",
110
- Self::StringTooLong { .. } => "string_too_long",
111
- Self::GreaterThan { .. } => "greater_than",
112
- Self::GreaterThanEqual { .. } => "greater_than_equal",
113
- Self::LessThan { .. } => "less_than",
114
- Self::LessThanEqual { .. } => "less_than_equal",
115
- Self::Enum { .. } => "enum",
116
- Self::StringPatternMismatch { .. } => "string_pattern_mismatch",
117
- Self::EmailFormat => "string_pattern_mismatch",
118
- Self::UuidFormat => "uuid_parsing",
119
- Self::DatetimeFormat => "datetime_parsing",
120
- Self::DateFormat => "date_parsing",
121
- Self::FormatError => "format_error",
122
- Self::TypeMismatch { .. } => "type_error",
123
- Self::Missing => "missing",
124
- Self::AdditionalProperties { .. } => "validation_error",
125
- Self::TooFewItems { .. } => "too_short",
126
- Self::TooManyItems => "too_long",
127
- Self::ValidationError => "validation_error",
128
- }
129
- }
130
-
131
- /// Get default message for this error condition
132
- pub fn default_message(&self) -> &'static str {
133
- match self {
134
- Self::StringTooShort { .. } => "String is too short",
135
- Self::StringTooLong { .. } => "String is too long",
136
- Self::GreaterThan { .. } => "Input should be greater than the minimum",
137
- Self::GreaterThanEqual { .. } => "Input should be greater than or equal to the minimum",
138
- Self::LessThan { .. } => "Input should be less than the maximum",
139
- Self::LessThanEqual { .. } => "Input should be less than or equal to the maximum",
140
- Self::Enum { .. } => "Input should be one of the allowed values",
141
- Self::StringPatternMismatch { .. } => "String does not match expected pattern",
142
- Self::EmailFormat => "String should match email pattern",
143
- Self::UuidFormat => "Input should be a valid UUID",
144
- Self::DatetimeFormat => "Input should be a valid datetime",
145
- Self::DateFormat => "Input should be a valid date",
146
- Self::FormatError => "Invalid format",
147
- Self::TypeMismatch { .. } => "Invalid type",
148
- Self::Missing => "Field required",
149
- Self::AdditionalProperties { .. } => "Additional properties are not allowed",
150
- Self::TooFewItems { .. } => "List should have at least N items after validation",
151
- Self::TooManyItems => "List should have at most N items after validation",
152
- Self::ValidationError => "Validation error",
153
- }
154
- }
155
- }
156
-
157
- /// Maps validation conditions to error details with schema context
158
- pub struct ErrorMapper;
159
-
160
- impl ErrorMapper {
161
- /// Map an error condition to its type, message, and context
162
- pub fn map_error(
163
- condition: &ErrorCondition,
164
- schema: &Value,
165
- schema_prop_path: &str,
166
- generic_message: &str,
167
- ) -> (String, String, Option<Value>) {
168
- match condition {
169
- ErrorCondition::StringTooShort { .. } => {
170
- if let Some(min_len) = schema
171
- .pointer(&format!("{}/minLength", schema_prop_path))
172
- .and_then(|v| v.as_u64())
173
- {
174
- let ctx = serde_json::json!({"min_length": min_len});
175
- (
176
- "string_too_short".to_string(),
177
- format!("String should have at least {} characters", min_len),
178
- Some(ctx),
179
- )
180
- } else {
181
- ("string_too_short".to_string(), "String is too short".to_string(), None)
182
- }
183
- }
184
- ErrorCondition::StringTooLong { .. } => {
185
- if let Some(max_len) = schema
186
- .pointer(&format!("{}/maxLength", schema_prop_path))
187
- .and_then(|v| v.as_u64())
188
- {
189
- let ctx = serde_json::json!({"max_length": max_len});
190
- (
191
- "string_too_long".to_string(),
192
- format!("String should have at most {} characters", max_len),
193
- Some(ctx),
194
- )
195
- } else {
196
- ("string_too_long".to_string(), "String is too long".to_string(), None)
197
- }
198
- }
199
- ErrorCondition::GreaterThan { .. } => {
200
- if let Some(min_val) = schema
201
- .pointer(&format!("{}/exclusiveMinimum", schema_prop_path))
202
- .and_then(|v| v.as_i64())
203
- {
204
- let ctx = serde_json::json!({"gt": min_val});
205
- (
206
- "greater_than".to_string(),
207
- format!("Input should be greater than {}", min_val),
208
- Some(ctx),
209
- )
210
- } else {
211
- (
212
- "greater_than".to_string(),
213
- "Input should be greater than the minimum".to_string(),
214
- None,
215
- )
216
- }
217
- }
218
- ErrorCondition::GreaterThanEqual { .. } => {
219
- if let Some(min_val) = schema
220
- .pointer(&format!("{}/minimum", schema_prop_path))
221
- .and_then(|v| v.as_i64())
222
- {
223
- let ctx = serde_json::json!({"ge": min_val});
224
- (
225
- "greater_than_equal".to_string(),
226
- format!("Input should be greater than or equal to {}", min_val),
227
- Some(ctx),
228
- )
229
- } else {
230
- (
231
- "greater_than_equal".to_string(),
232
- "Input should be greater than or equal to the minimum".to_string(),
233
- None,
234
- )
235
- }
236
- }
237
- ErrorCondition::LessThan { .. } => {
238
- if let Some(max_val) = schema
239
- .pointer(&format!("{}/exclusiveMaximum", schema_prop_path))
240
- .and_then(|v| v.as_i64())
241
- {
242
- let ctx = serde_json::json!({"lt": max_val});
243
- (
244
- "less_than".to_string(),
245
- format!("Input should be less than {}", max_val),
246
- Some(ctx),
247
- )
248
- } else {
249
- (
250
- "less_than".to_string(),
251
- "Input should be less than the maximum".to_string(),
252
- None,
253
- )
254
- }
255
- }
256
- ErrorCondition::LessThanEqual { .. } => {
257
- if let Some(max_val) = schema
258
- .pointer(&format!("{}/maximum", schema_prop_path))
259
- .and_then(|v| v.as_i64())
260
- {
261
- let ctx = serde_json::json!({"le": max_val});
262
- (
263
- "less_than_equal".to_string(),
264
- format!("Input should be less than or equal to {}", max_val),
265
- Some(ctx),
266
- )
267
- } else {
268
- (
269
- "less_than_equal".to_string(),
270
- "Input should be less than or equal to the maximum".to_string(),
271
- None,
272
- )
273
- }
274
- }
275
- ErrorCondition::Enum { .. } => {
276
- if let Some(enum_values) = schema
277
- .pointer(&format!("{}/enum", schema_prop_path))
278
- .and_then(|v| v.as_array())
279
- {
280
- let values: Vec<String> = enum_values
281
- .iter()
282
- .filter_map(|v| v.as_str().map(|s| format!("'{}'", s)))
283
- .collect();
284
-
285
- let msg = if values.len() > 1 {
286
- let last = values.last().unwrap();
287
- let rest = &values[..values.len() - 1];
288
- format!("Input should be {} or {}", rest.join(", "), last)
289
- } else if !values.is_empty() {
290
- format!("Input should be {}", values[0])
291
- } else {
292
- "Input should be one of the allowed values".to_string()
293
- };
294
-
295
- let expected_str = if values.len() > 1 {
296
- let last = values.last().unwrap();
297
- let rest = &values[..values.len() - 1];
298
- format!("{} or {}", rest.join(", "), last)
299
- } else if !values.is_empty() {
300
- values[0].clone()
301
- } else {
302
- "allowed values".to_string()
303
- };
304
- let ctx = serde_json::json!({"expected": expected_str});
305
- ("enum".to_string(), msg, Some(ctx))
306
- } else {
307
- (
308
- "enum".to_string(),
309
- "Input should be one of the allowed values".to_string(),
310
- None,
311
- )
312
- }
313
- }
314
- ErrorCondition::StringPatternMismatch { .. } => {
315
- if let Some(pattern) = schema
316
- .pointer(&format!("{}/pattern", schema_prop_path))
317
- .and_then(|v| v.as_str())
318
- {
319
- let ctx = serde_json::json!({"pattern": pattern});
320
- let msg = format!("String should match pattern '{}'", pattern);
321
- ("string_pattern_mismatch".to_string(), msg, Some(ctx))
322
- } else {
323
- (
324
- "string_pattern_mismatch".to_string(),
325
- "String does not match expected pattern".to_string(),
326
- None,
327
- )
328
- }
329
- }
330
- ErrorCondition::EmailFormat => {
331
- let email_pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
332
- let ctx = serde_json::json!({"pattern": email_pattern});
333
- (
334
- "string_pattern_mismatch".to_string(),
335
- format!("String should match pattern '{}'", email_pattern),
336
- Some(ctx),
337
- )
338
- }
339
- ErrorCondition::UuidFormat => (
340
- "uuid_parsing".to_string(),
341
- "Input should be a valid UUID".to_string(),
342
- None,
343
- ),
344
- ErrorCondition::DatetimeFormat => (
345
- "datetime_parsing".to_string(),
346
- "Input should be a valid datetime".to_string(),
347
- None,
348
- ),
349
- ErrorCondition::DateFormat => (
350
- "date_parsing".to_string(),
351
- "Input should be a valid date".to_string(),
352
- None,
353
- ),
354
- ErrorCondition::FormatError => ("format_error".to_string(), generic_message.to_string(), None),
355
- ErrorCondition::TypeMismatch { expected_type } => {
356
- let (error_type, msg) = match expected_type.as_str() {
357
- "integer" => (
358
- "int_parsing".to_string(),
359
- "Input should be a valid integer, unable to parse string as an integer".to_string(),
360
- ),
361
- "number" => (
362
- "float_parsing".to_string(),
363
- "Input should be a valid number, unable to parse string as a number".to_string(),
364
- ),
365
- "boolean" => (
366
- "bool_parsing".to_string(),
367
- "Input should be a valid boolean".to_string(),
368
- ),
369
- "string" => ("string_type".to_string(), "Input should be a valid string".to_string()),
370
- _ => (
371
- "type_error".to_string(),
372
- format!("Input should be a valid {}", expected_type),
373
- ),
374
- };
375
- (error_type, msg, None)
376
- }
377
- ErrorCondition::Missing => ("missing".to_string(), "Field required".to_string(), None),
378
- ErrorCondition::AdditionalProperties { field } => {
379
- let ctx = serde_json::json!({
380
- "additional_properties": false,
381
- "unexpected_field": field
382
- });
383
- (
384
- "validation_error".to_string(),
385
- "Additional properties are not allowed".to_string(),
386
- Some(ctx),
387
- )
388
- }
389
- ErrorCondition::TooFewItems { min_items } => {
390
- let min = min_items.unwrap_or(1);
391
- let ctx = serde_json::json!({
392
- "min_length": min
393
- });
394
- (
395
- "too_short".to_string(),
396
- format!("List should have at least {} item after validation", min),
397
- Some(ctx),
398
- )
399
- }
400
- ErrorCondition::TooManyItems => {
401
- let ctx = serde_json::json!({
402
- "max_length": 1
403
- });
404
- (
405
- "too_long".to_string(),
406
- "List should have at most N items after validation".to_string(),
407
- Some(ctx),
408
- )
409
- }
410
- ErrorCondition::ValidationError => ("validation_error".to_string(), generic_message.to_string(), None),
411
- }
412
- }
413
- }
414
-
415
- #[cfg(test)]
416
- mod tests {
417
- use super::*;
418
- use serde_json::json;
419
-
420
- #[test]
421
- fn test_string_too_short_detection() {
422
- let condition = ErrorCondition::from_schema_error("some/path/minLength", "");
423
- assert_eq!(condition, ErrorCondition::StringTooShort { min_length: None });
424
- }
425
-
426
- #[test]
427
- fn test_string_too_long_detection() {
428
- let condition = ErrorCondition::from_schema_error("some/path/maxLength", "");
429
- assert_eq!(condition, ErrorCondition::StringTooLong { max_length: None });
430
- }
431
-
432
- #[test]
433
- fn test_minimum_detection() {
434
- let condition = ErrorCondition::from_schema_error("some/path/minimum", "");
435
- assert_eq!(condition, ErrorCondition::GreaterThanEqual { value: None });
436
- }
437
-
438
- #[test]
439
- fn test_exclusive_minimum_detection() {
440
- let condition = ErrorCondition::from_schema_error("some/path/exclusiveMinimum", "");
441
- assert_eq!(condition, ErrorCondition::GreaterThan { value: None });
442
- }
443
-
444
- #[test]
445
- fn test_maximum_detection() {
446
- let condition = ErrorCondition::from_schema_error("some/path/maximum", "");
447
- assert_eq!(condition, ErrorCondition::LessThanEqual { value: None });
448
- }
449
-
450
- #[test]
451
- fn test_exclusive_maximum_detection() {
452
- let condition = ErrorCondition::from_schema_error("some/path/exclusiveMaximum", "");
453
- assert_eq!(condition, ErrorCondition::LessThan { value: None });
454
- }
455
-
456
- #[test]
457
- fn test_enum_detection() {
458
- let condition = ErrorCondition::from_schema_error("some/path/enum", "");
459
- assert_eq!(condition, ErrorCondition::Enum { values: None });
460
- }
461
-
462
- #[test]
463
- fn test_pattern_detection() {
464
- let condition = ErrorCondition::from_schema_error("some/path/pattern", "");
465
- assert_eq!(condition, ErrorCondition::StringPatternMismatch { pattern: None });
466
- }
467
-
468
- #[test]
469
- fn test_email_format_detection() {
470
- let condition = ErrorCondition::from_schema_error("some/path/format", "email");
471
- assert_eq!(condition, ErrorCondition::EmailFormat);
472
- }
473
-
474
- #[test]
475
- fn test_uuid_format_detection() {
476
- let condition = ErrorCondition::from_schema_error("some/path/format", "uuid");
477
- assert_eq!(condition, ErrorCondition::UuidFormat);
478
- }
479
-
480
- #[test]
481
- fn test_datetime_format_detection() {
482
- let condition = ErrorCondition::from_schema_error("some/path/format", "date-time");
483
- assert_eq!(condition, ErrorCondition::DatetimeFormat);
484
- }
485
-
486
- #[test]
487
- fn test_date_format_detection() {
488
- let condition = ErrorCondition::from_schema_error("some/path/format", "date");
489
- assert_eq!(condition, ErrorCondition::DateFormat);
490
- }
491
-
492
- #[test]
493
- fn test_type_error_detection() {
494
- let condition = ErrorCondition::from_schema_error("some/path/type", "");
495
- assert!(matches!(condition, ErrorCondition::TypeMismatch { .. }));
496
- }
497
-
498
- #[test]
499
- fn test_missing_field_detection() {
500
- let condition = ErrorCondition::from_schema_error("some/path/required", "");
501
- assert_eq!(condition, ErrorCondition::Missing);
502
- }
503
-
504
- #[test]
505
- fn test_additional_properties_detection() {
506
- let condition = ErrorCondition::from_schema_error("some/path/additionalProperties", "");
507
- assert!(matches!(condition, ErrorCondition::AdditionalProperties { .. }));
508
- }
509
-
510
- #[test]
511
- fn test_min_items_detection() {
512
- let condition = ErrorCondition::from_schema_error("some/path/minItems", "");
513
- assert!(matches!(condition, ErrorCondition::TooFewItems { .. }));
514
- }
515
-
516
- #[test]
517
- fn test_max_items_detection() {
518
- let condition = ErrorCondition::from_schema_error("some/path/maxItems", "");
519
- assert_eq!(condition, ErrorCondition::TooManyItems);
520
- }
521
-
522
- #[test]
523
- fn test_error_type_codes() {
524
- assert_eq!(
525
- ErrorCondition::StringTooShort { min_length: None }.error_type(),
526
- "string_too_short"
527
- );
528
- assert_eq!(
529
- ErrorCondition::StringTooLong { max_length: None }.error_type(),
530
- "string_too_long"
531
- );
532
- assert_eq!(ErrorCondition::GreaterThan { value: None }.error_type(), "greater_than");
533
- assert_eq!(
534
- ErrorCondition::GreaterThanEqual { value: None }.error_type(),
535
- "greater_than_equal"
536
- );
537
- assert_eq!(ErrorCondition::LessThan { value: None }.error_type(), "less_than");
538
- assert_eq!(
539
- ErrorCondition::LessThanEqual { value: None }.error_type(),
540
- "less_than_equal"
541
- );
542
- assert_eq!(ErrorCondition::Enum { values: None }.error_type(), "enum");
543
- assert_eq!(
544
- ErrorCondition::StringPatternMismatch { pattern: None }.error_type(),
545
- "string_pattern_mismatch"
546
- );
547
- assert_eq!(ErrorCondition::EmailFormat.error_type(), "string_pattern_mismatch");
548
- assert_eq!(ErrorCondition::UuidFormat.error_type(), "uuid_parsing");
549
- assert_eq!(ErrorCondition::DatetimeFormat.error_type(), "datetime_parsing");
550
- assert_eq!(ErrorCondition::DateFormat.error_type(), "date_parsing");
551
- assert_eq!(ErrorCondition::FormatError.error_type(), "format_error");
552
- assert_eq!(
553
- ErrorCondition::TypeMismatch {
554
- expected_type: "integer".to_string()
555
- }
556
- .error_type(),
557
- "type_error"
558
- );
559
- assert_eq!(ErrorCondition::Missing.error_type(), "missing");
560
- assert_eq!(
561
- ErrorCondition::AdditionalProperties {
562
- field: "extra".to_string()
563
- }
564
- .error_type(),
565
- "validation_error"
566
- );
567
- assert_eq!(
568
- ErrorCondition::TooFewItems { min_items: None }.error_type(),
569
- "too_short"
570
- );
571
- assert_eq!(ErrorCondition::TooManyItems.error_type(), "too_long");
572
- }
573
-
574
- #[test]
575
- fn test_mapper_string_length_constraints() {
576
- let schema = json!({
577
- "properties": {
578
- "name": {
579
- "type": "string",
580
- "minLength": 5,
581
- "maxLength": 20
582
- }
583
- }
584
- });
585
-
586
- let condition = ErrorCondition::StringTooShort { min_length: None };
587
- let (error_type, msg, ctx_result) = ErrorMapper::map_error(&condition, &schema, "/properties/name", "");
588
- assert_eq!(error_type, "string_too_short");
589
- assert_eq!(msg, "String should have at least 5 characters");
590
- assert_eq!(ctx_result, Some(json!({"min_length": 5})));
591
- }
592
-
593
- #[test]
594
- fn test_mapper_numeric_constraints() {
595
- let schema = json!({
596
- "properties": {
597
- "age": {
598
- "type": "integer",
599
- "minimum": 0,
600
- "maximum": 150,
601
- "exclusiveMinimum": -1,
602
- "exclusiveMaximum": 151
603
- }
604
- }
605
- });
606
-
607
- let condition = ErrorCondition::GreaterThanEqual { value: None };
608
- let (error_type, msg, ctx) = ErrorMapper::map_error(&condition, &schema, "/properties/age", "");
609
- assert_eq!(error_type, "greater_than_equal");
610
- assert_eq!(msg, "Input should be greater than or equal to 0");
611
- assert_eq!(ctx, Some(json!({"ge": 0})));
612
- }
613
-
614
- #[test]
615
- fn test_mapper_enum() {
616
- let schema = json!({
617
- "properties": {
618
- "status": {
619
- "type": "string",
620
- "enum": ["active", "inactive", "pending"]
621
- }
622
- }
623
- });
624
-
625
- let condition = ErrorCondition::Enum { values: None };
626
- let (error_type, msg, _ctx) = ErrorMapper::map_error(&condition, &schema, "/properties/status", "");
627
- assert_eq!(error_type, "enum");
628
- assert!(msg.contains("'active'"));
629
- assert!(msg.contains("'inactive'"));
630
- assert!(msg.contains("'pending'"));
631
- }
632
-
633
- #[test]
634
- fn test_mapper_type_mismatch() {
635
- let schema = json!({
636
- "properties": {
637
- "count": { "type": "integer" }
638
- }
639
- });
640
-
641
- let condition = ErrorCondition::TypeMismatch {
642
- expected_type: "integer".to_string(),
643
- };
644
- let (error_type, msg, _) = ErrorMapper::map_error(&condition, &schema, "/properties/count", "");
645
- assert_eq!(error_type, "int_parsing");
646
- assert!(msg.contains("integer"));
647
- }
648
-
649
- #[test]
650
- fn test_mapper_email_format() {
651
- let schema = json!({});
652
-
653
- let condition = ErrorCondition::EmailFormat;
654
- let (error_type, msg, ctx) = ErrorMapper::map_error(&condition, &schema, "", "");
655
- assert_eq!(error_type, "string_pattern_mismatch");
656
- assert!(msg.contains("@"));
657
- assert!(ctx.is_some());
658
- }
659
-
660
- #[test]
661
- fn test_mapper_uuid_format() {
662
- let schema = json!({});
663
-
664
- let condition = ErrorCondition::UuidFormat;
665
- let (error_type, msg, _) = ErrorMapper::map_error(&condition, &schema, "", "");
666
- assert_eq!(error_type, "uuid_parsing");
667
- assert_eq!(msg, "Input should be a valid UUID");
668
- }
669
-
670
- #[test]
671
- fn test_mapper_additional_properties() {
672
- let schema = json!({});
673
-
674
- let condition = ErrorCondition::AdditionalProperties {
675
- field: "extra_field".to_string(),
676
- };
677
- let (error_type, msg, ctx) = ErrorMapper::map_error(&condition, &schema, "", "");
678
- assert_eq!(error_type, "validation_error");
679
- assert_eq!(msg, "Additional properties are not allowed");
680
- assert_eq!(
681
- ctx,
682
- Some(json!({
683
- "additional_properties": false,
684
- "unexpected_field": "extra_field"
685
- }))
686
- );
687
- }
688
- }
1
+ //! Table-driven error mapping for JSON Schema validation failures
2
+ //!
3
+ //! This module provides a structured approach to mapping JSON Schema validation errors
4
+ //! to consistent error codes and messages. Instead of massive if-else chains, we use
5
+ //! enum variants and pattern matching for maintainability and testability.
6
+
7
+ use serde_json::Value;
8
+
9
+ /// Represents the different types of validation errors that can occur
10
+ #[derive(Debug, Clone, PartialEq, Eq)]
11
+ pub enum ErrorCondition {
12
+ /// String length is below minimum
13
+ StringTooShort { min_length: Option<u64> },
14
+ /// String length exceeds maximum
15
+ StringTooLong { max_length: Option<u64> },
16
+ /// Number is not greater than exclusive minimum
17
+ GreaterThan { value: Option<i64> },
18
+ /// Number is not greater than or equal to minimum
19
+ GreaterThanEqual { value: Option<i64> },
20
+ /// Number is not less than exclusive maximum
21
+ LessThan { value: Option<i64> },
22
+ /// Number is not less than or equal to maximum
23
+ LessThanEqual { value: Option<i64> },
24
+ /// Value is not one of allowed enum values
25
+ Enum { values: Option<Vec<String>> },
26
+ /// String does not match pattern
27
+ StringPatternMismatch { pattern: Option<String> },
28
+ /// Email format validation failed
29
+ EmailFormat,
30
+ /// UUID format validation failed
31
+ UuidFormat,
32
+ /// Date-time format validation failed
33
+ DatetimeFormat,
34
+ /// Date format validation failed
35
+ DateFormat,
36
+ /// Other format validation failed
37
+ FormatError,
38
+ /// Type mismatch
39
+ TypeMismatch { expected_type: String },
40
+ /// Required field is missing
41
+ Missing,
42
+ /// Additional properties not allowed
43
+ AdditionalProperties { field: String },
44
+ /// Array has too few items
45
+ TooFewItems { min_items: Option<usize> },
46
+ /// Array has too many items
47
+ TooManyItems,
48
+ /// Fallback for unmapped errors
49
+ ValidationError,
50
+ }
51
+
52
+ impl ErrorCondition {
53
+ /// Determine the error condition from schema path and error message
54
+ pub fn from_schema_error(schema_path_str: &str, error_msg: &str) -> Self {
55
+ match () {
56
+ _ if schema_path_str.contains("minLength") => Self::StringTooShort { min_length: None },
57
+ _ if schema_path_str.contains("maxLength") => Self::StringTooLong { max_length: None },
58
+ _ if schema_path_str.contains("exclusiveMinimum")
59
+ || (error_msg.contains("less than or equal to") && error_msg.contains("minimum")) =>
60
+ {
61
+ Self::GreaterThan { value: None }
62
+ }
63
+ _ if schema_path_str.contains("minimum") || error_msg.contains("less than the minimum") => {
64
+ Self::GreaterThanEqual { value: None }
65
+ }
66
+ _ if schema_path_str.contains("exclusiveMaximum")
67
+ || (error_msg.contains("greater than or equal to") && error_msg.contains("maximum")) =>
68
+ {
69
+ Self::LessThan { value: None }
70
+ }
71
+ _ if schema_path_str.contains("maximum") || error_msg.contains("greater than the maximum") => {
72
+ Self::LessThanEqual { value: None }
73
+ }
74
+ _ if schema_path_str.contains("enum") || error_msg.contains("is not one of") => Self::Enum { values: None },
75
+ _ if schema_path_str.contains("pattern") || error_msg.contains("does not match") => {
76
+ Self::StringPatternMismatch { pattern: None }
77
+ }
78
+ _ if schema_path_str.contains("format") => {
79
+ if error_msg.contains("email") {
80
+ Self::EmailFormat
81
+ } else if error_msg.contains("uuid") {
82
+ Self::UuidFormat
83
+ } else if error_msg.contains("date-time") {
84
+ Self::DatetimeFormat
85
+ } else if error_msg.contains("date") {
86
+ Self::DateFormat
87
+ } else {
88
+ Self::FormatError
89
+ }
90
+ }
91
+ _ if schema_path_str.contains("/type") => Self::TypeMismatch {
92
+ expected_type: "unknown".to_string(),
93
+ },
94
+ _ if schema_path_str.ends_with("/required") => Self::Missing,
95
+ _ if schema_path_str.contains("/additionalProperties")
96
+ || error_msg.contains("Additional properties are not allowed") =>
97
+ {
98
+ Self::AdditionalProperties { field: String::new() }
99
+ }
100
+ _ if schema_path_str.contains("/minItems") => Self::TooFewItems { min_items: None },
101
+ _ if schema_path_str.contains("/maxItems") => Self::TooManyItems,
102
+ _ => Self::ValidationError,
103
+ }
104
+ }
105
+
106
+ /// Get the error type code for this condition
107
+ pub fn error_type(&self) -> &'static str {
108
+ match self {
109
+ Self::StringTooShort { .. } => "string_too_short",
110
+ Self::StringTooLong { .. } => "string_too_long",
111
+ Self::GreaterThan { .. } => "greater_than",
112
+ Self::GreaterThanEqual { .. } => "greater_than_equal",
113
+ Self::LessThan { .. } => "less_than",
114
+ Self::LessThanEqual { .. } => "less_than_equal",
115
+ Self::Enum { .. } => "enum",
116
+ Self::StringPatternMismatch { .. } => "string_pattern_mismatch",
117
+ Self::EmailFormat => "string_pattern_mismatch",
118
+ Self::UuidFormat => "uuid_parsing",
119
+ Self::DatetimeFormat => "datetime_parsing",
120
+ Self::DateFormat => "date_parsing",
121
+ Self::FormatError => "format_error",
122
+ Self::TypeMismatch { .. } => "type_error",
123
+ Self::Missing => "missing",
124
+ Self::AdditionalProperties { .. } => "validation_error",
125
+ Self::TooFewItems { .. } => "too_short",
126
+ Self::TooManyItems => "too_long",
127
+ Self::ValidationError => "validation_error",
128
+ }
129
+ }
130
+
131
+ /// Get default message for this error condition
132
+ pub fn default_message(&self) -> &'static str {
133
+ match self {
134
+ Self::StringTooShort { .. } => "String is too short",
135
+ Self::StringTooLong { .. } => "String is too long",
136
+ Self::GreaterThan { .. } => "Input should be greater than the minimum",
137
+ Self::GreaterThanEqual { .. } => "Input should be greater than or equal to the minimum",
138
+ Self::LessThan { .. } => "Input should be less than the maximum",
139
+ Self::LessThanEqual { .. } => "Input should be less than or equal to the maximum",
140
+ Self::Enum { .. } => "Input should be one of the allowed values",
141
+ Self::StringPatternMismatch { .. } => "String does not match expected pattern",
142
+ Self::EmailFormat => "String should match email pattern",
143
+ Self::UuidFormat => "Input should be a valid UUID",
144
+ Self::DatetimeFormat => "Input should be a valid datetime",
145
+ Self::DateFormat => "Input should be a valid date",
146
+ Self::FormatError => "Invalid format",
147
+ Self::TypeMismatch { .. } => "Invalid type",
148
+ Self::Missing => "Field required",
149
+ Self::AdditionalProperties { .. } => "Additional properties are not allowed",
150
+ Self::TooFewItems { .. } => "List should have at least N items after validation",
151
+ Self::TooManyItems => "List should have at most N items after validation",
152
+ Self::ValidationError => "Validation error",
153
+ }
154
+ }
155
+ }
156
+
157
+ /// Maps validation conditions to error details with schema context
158
+ pub struct ErrorMapper;
159
+
160
+ impl ErrorMapper {
161
+ /// Map an error condition to its type, message, and context
162
+ pub fn map_error(
163
+ condition: &ErrorCondition,
164
+ schema: &Value,
165
+ schema_prop_path: &str,
166
+ generic_message: &str,
167
+ ) -> (String, String, Option<Value>) {
168
+ match condition {
169
+ ErrorCondition::StringTooShort { .. } => {
170
+ if let Some(min_len) = schema
171
+ .pointer(&format!("{}/minLength", schema_prop_path))
172
+ .and_then(|v| v.as_u64())
173
+ {
174
+ let ctx = serde_json::json!({"min_length": min_len});
175
+ (
176
+ "string_too_short".to_string(),
177
+ format!("String should have at least {} characters", min_len),
178
+ Some(ctx),
179
+ )
180
+ } else {
181
+ ("string_too_short".to_string(), "String is too short".to_string(), None)
182
+ }
183
+ }
184
+ ErrorCondition::StringTooLong { .. } => {
185
+ if let Some(max_len) = schema
186
+ .pointer(&format!("{}/maxLength", schema_prop_path))
187
+ .and_then(|v| v.as_u64())
188
+ {
189
+ let ctx = serde_json::json!({"max_length": max_len});
190
+ (
191
+ "string_too_long".to_string(),
192
+ format!("String should have at most {} characters", max_len),
193
+ Some(ctx),
194
+ )
195
+ } else {
196
+ ("string_too_long".to_string(), "String is too long".to_string(), None)
197
+ }
198
+ }
199
+ ErrorCondition::GreaterThan { .. } => {
200
+ if let Some(min_val) = schema
201
+ .pointer(&format!("{}/exclusiveMinimum", schema_prop_path))
202
+ .and_then(|v| v.as_i64())
203
+ {
204
+ let ctx = serde_json::json!({"gt": min_val});
205
+ (
206
+ "greater_than".to_string(),
207
+ format!("Input should be greater than {}", min_val),
208
+ Some(ctx),
209
+ )
210
+ } else {
211
+ (
212
+ "greater_than".to_string(),
213
+ "Input should be greater than the minimum".to_string(),
214
+ None,
215
+ )
216
+ }
217
+ }
218
+ ErrorCondition::GreaterThanEqual { .. } => {
219
+ if let Some(min_val) = schema
220
+ .pointer(&format!("{}/minimum", schema_prop_path))
221
+ .and_then(|v| v.as_i64())
222
+ {
223
+ let ctx = serde_json::json!({"ge": min_val});
224
+ (
225
+ "greater_than_equal".to_string(),
226
+ format!("Input should be greater than or equal to {}", min_val),
227
+ Some(ctx),
228
+ )
229
+ } else {
230
+ (
231
+ "greater_than_equal".to_string(),
232
+ "Input should be greater than or equal to the minimum".to_string(),
233
+ None,
234
+ )
235
+ }
236
+ }
237
+ ErrorCondition::LessThan { .. } => {
238
+ if let Some(max_val) = schema
239
+ .pointer(&format!("{}/exclusiveMaximum", schema_prop_path))
240
+ .and_then(|v| v.as_i64())
241
+ {
242
+ let ctx = serde_json::json!({"lt": max_val});
243
+ (
244
+ "less_than".to_string(),
245
+ format!("Input should be less than {}", max_val),
246
+ Some(ctx),
247
+ )
248
+ } else {
249
+ (
250
+ "less_than".to_string(),
251
+ "Input should be less than the maximum".to_string(),
252
+ None,
253
+ )
254
+ }
255
+ }
256
+ ErrorCondition::LessThanEqual { .. } => {
257
+ if let Some(max_val) = schema
258
+ .pointer(&format!("{}/maximum", schema_prop_path))
259
+ .and_then(|v| v.as_i64())
260
+ {
261
+ let ctx = serde_json::json!({"le": max_val});
262
+ (
263
+ "less_than_equal".to_string(),
264
+ format!("Input should be less than or equal to {}", max_val),
265
+ Some(ctx),
266
+ )
267
+ } else {
268
+ (
269
+ "less_than_equal".to_string(),
270
+ "Input should be less than or equal to the maximum".to_string(),
271
+ None,
272
+ )
273
+ }
274
+ }
275
+ ErrorCondition::Enum { .. } => {
276
+ if let Some(enum_values) = schema
277
+ .pointer(&format!("{}/enum", schema_prop_path))
278
+ .and_then(|v| v.as_array())
279
+ {
280
+ let values: Vec<String> = enum_values
281
+ .iter()
282
+ .filter_map(|v| v.as_str().map(|s| format!("'{}'", s)))
283
+ .collect();
284
+
285
+ let msg = if values.len() > 1 {
286
+ let last = values.last().unwrap();
287
+ let rest = &values[..values.len() - 1];
288
+ format!("Input should be {} or {}", rest.join(", "), last)
289
+ } else if !values.is_empty() {
290
+ format!("Input should be {}", values[0])
291
+ } else {
292
+ "Input should be one of the allowed values".to_string()
293
+ };
294
+
295
+ let expected_str = if values.len() > 1 {
296
+ let last = values.last().unwrap();
297
+ let rest = &values[..values.len() - 1];
298
+ format!("{} or {}", rest.join(", "), last)
299
+ } else if !values.is_empty() {
300
+ values[0].clone()
301
+ } else {
302
+ "allowed values".to_string()
303
+ };
304
+ let ctx = serde_json::json!({"expected": expected_str});
305
+ ("enum".to_string(), msg, Some(ctx))
306
+ } else {
307
+ (
308
+ "enum".to_string(),
309
+ "Input should be one of the allowed values".to_string(),
310
+ None,
311
+ )
312
+ }
313
+ }
314
+ ErrorCondition::StringPatternMismatch { .. } => {
315
+ if let Some(pattern) = schema
316
+ .pointer(&format!("{}/pattern", schema_prop_path))
317
+ .and_then(|v| v.as_str())
318
+ {
319
+ let ctx = serde_json::json!({"pattern": pattern});
320
+ let msg = format!("String should match pattern '{}'", pattern);
321
+ ("string_pattern_mismatch".to_string(), msg, Some(ctx))
322
+ } else {
323
+ (
324
+ "string_pattern_mismatch".to_string(),
325
+ "String does not match expected pattern".to_string(),
326
+ None,
327
+ )
328
+ }
329
+ }
330
+ ErrorCondition::EmailFormat => {
331
+ let email_pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
332
+ let ctx = serde_json::json!({"pattern": email_pattern});
333
+ (
334
+ "string_pattern_mismatch".to_string(),
335
+ format!("String should match pattern '{}'", email_pattern),
336
+ Some(ctx),
337
+ )
338
+ }
339
+ ErrorCondition::UuidFormat => (
340
+ "uuid_parsing".to_string(),
341
+ "Input should be a valid UUID".to_string(),
342
+ None,
343
+ ),
344
+ ErrorCondition::DatetimeFormat => (
345
+ "datetime_parsing".to_string(),
346
+ "Input should be a valid datetime".to_string(),
347
+ None,
348
+ ),
349
+ ErrorCondition::DateFormat => (
350
+ "date_parsing".to_string(),
351
+ "Input should be a valid date".to_string(),
352
+ None,
353
+ ),
354
+ ErrorCondition::FormatError => ("format_error".to_string(), generic_message.to_string(), None),
355
+ ErrorCondition::TypeMismatch { expected_type } => {
356
+ let (error_type, msg) = match expected_type.as_str() {
357
+ "integer" => (
358
+ "int_parsing".to_string(),
359
+ "Input should be a valid integer, unable to parse string as an integer".to_string(),
360
+ ),
361
+ "number" => (
362
+ "float_parsing".to_string(),
363
+ "Input should be a valid number, unable to parse string as a number".to_string(),
364
+ ),
365
+ "boolean" => (
366
+ "bool_parsing".to_string(),
367
+ "Input should be a valid boolean".to_string(),
368
+ ),
369
+ "string" => ("string_type".to_string(), "Input should be a valid string".to_string()),
370
+ _ => (
371
+ "type_error".to_string(),
372
+ format!("Input should be a valid {}", expected_type),
373
+ ),
374
+ };
375
+ (error_type, msg, None)
376
+ }
377
+ ErrorCondition::Missing => ("missing".to_string(), "Field required".to_string(), None),
378
+ ErrorCondition::AdditionalProperties { field } => {
379
+ let ctx = serde_json::json!({
380
+ "additional_properties": false,
381
+ "unexpected_field": field
382
+ });
383
+ (
384
+ "validation_error".to_string(),
385
+ "Additional properties are not allowed".to_string(),
386
+ Some(ctx),
387
+ )
388
+ }
389
+ ErrorCondition::TooFewItems { min_items } => {
390
+ let min = schema
391
+ .pointer(&format!("{}/minItems", schema_prop_path))
392
+ .and_then(|v| v.as_u64())
393
+ .or_else(|| min_items.map(|v| v as u64))
394
+ .unwrap_or(1);
395
+ let ctx = serde_json::json!({
396
+ "min_length": min
397
+ });
398
+ (
399
+ "too_short".to_string(),
400
+ format!("List should have at least {} item after validation", min),
401
+ Some(ctx),
402
+ )
403
+ }
404
+ ErrorCondition::TooManyItems => {
405
+ let max = schema
406
+ .pointer(&format!("{}/maxItems", schema_prop_path))
407
+ .and_then(|v| v.as_u64())
408
+ .unwrap_or(1);
409
+ let ctx = serde_json::json!({
410
+ "max_length": max
411
+ });
412
+ (
413
+ "too_long".to_string(),
414
+ format!("List should have at most {} items after validation", max),
415
+ Some(ctx),
416
+ )
417
+ }
418
+ ErrorCondition::ValidationError => ("validation_error".to_string(), generic_message.to_string(), None),
419
+ }
420
+ }
421
+ }
422
+
423
+ #[cfg(test)]
424
+ mod tests {
425
+ use super::*;
426
+ use serde_json::json;
427
+
428
+ #[test]
429
+ fn test_string_too_short_detection() {
430
+ let condition = ErrorCondition::from_schema_error("some/path/minLength", "");
431
+ assert_eq!(condition, ErrorCondition::StringTooShort { min_length: None });
432
+ }
433
+
434
+ #[test]
435
+ fn test_string_too_long_detection() {
436
+ let condition = ErrorCondition::from_schema_error("some/path/maxLength", "");
437
+ assert_eq!(condition, ErrorCondition::StringTooLong { max_length: None });
438
+ }
439
+
440
+ #[test]
441
+ fn test_minimum_detection() {
442
+ let condition = ErrorCondition::from_schema_error("some/path/minimum", "");
443
+ assert_eq!(condition, ErrorCondition::GreaterThanEqual { value: None });
444
+ }
445
+
446
+ #[test]
447
+ fn test_exclusive_minimum_detection() {
448
+ let condition = ErrorCondition::from_schema_error("some/path/exclusiveMinimum", "");
449
+ assert_eq!(condition, ErrorCondition::GreaterThan { value: None });
450
+ }
451
+
452
+ #[test]
453
+ fn test_maximum_detection() {
454
+ let condition = ErrorCondition::from_schema_error("some/path/maximum", "");
455
+ assert_eq!(condition, ErrorCondition::LessThanEqual { value: None });
456
+ }
457
+
458
+ #[test]
459
+ fn test_exclusive_maximum_detection() {
460
+ let condition = ErrorCondition::from_schema_error("some/path/exclusiveMaximum", "");
461
+ assert_eq!(condition, ErrorCondition::LessThan { value: None });
462
+ }
463
+
464
+ #[test]
465
+ fn test_enum_detection() {
466
+ let condition = ErrorCondition::from_schema_error("some/path/enum", "");
467
+ assert_eq!(condition, ErrorCondition::Enum { values: None });
468
+ }
469
+
470
+ #[test]
471
+ fn test_pattern_detection() {
472
+ let condition = ErrorCondition::from_schema_error("some/path/pattern", "");
473
+ assert_eq!(condition, ErrorCondition::StringPatternMismatch { pattern: None });
474
+ }
475
+
476
+ #[test]
477
+ fn test_email_format_detection() {
478
+ let condition = ErrorCondition::from_schema_error("some/path/format", "email");
479
+ assert_eq!(condition, ErrorCondition::EmailFormat);
480
+ }
481
+
482
+ #[test]
483
+ fn test_uuid_format_detection() {
484
+ let condition = ErrorCondition::from_schema_error("some/path/format", "uuid");
485
+ assert_eq!(condition, ErrorCondition::UuidFormat);
486
+ }
487
+
488
+ #[test]
489
+ fn test_datetime_format_detection() {
490
+ let condition = ErrorCondition::from_schema_error("some/path/format", "date-time");
491
+ assert_eq!(condition, ErrorCondition::DatetimeFormat);
492
+ }
493
+
494
+ #[test]
495
+ fn test_date_format_detection() {
496
+ let condition = ErrorCondition::from_schema_error("some/path/format", "date");
497
+ assert_eq!(condition, ErrorCondition::DateFormat);
498
+ }
499
+
500
+ #[test]
501
+ fn test_type_error_detection() {
502
+ let condition = ErrorCondition::from_schema_error("some/path/type", "");
503
+ assert!(matches!(condition, ErrorCondition::TypeMismatch { .. }));
504
+ }
505
+
506
+ #[test]
507
+ fn test_missing_field_detection() {
508
+ let condition = ErrorCondition::from_schema_error("some/path/required", "");
509
+ assert_eq!(condition, ErrorCondition::Missing);
510
+ }
511
+
512
+ #[test]
513
+ fn test_additional_properties_detection() {
514
+ let condition = ErrorCondition::from_schema_error("some/path/additionalProperties", "");
515
+ assert!(matches!(condition, ErrorCondition::AdditionalProperties { .. }));
516
+ }
517
+
518
+ #[test]
519
+ fn test_min_items_detection() {
520
+ let condition = ErrorCondition::from_schema_error("some/path/minItems", "");
521
+ assert!(matches!(condition, ErrorCondition::TooFewItems { .. }));
522
+ }
523
+
524
+ #[test]
525
+ fn test_max_items_detection() {
526
+ let condition = ErrorCondition::from_schema_error("some/path/maxItems", "");
527
+ assert_eq!(condition, ErrorCondition::TooManyItems);
528
+ }
529
+
530
+ #[test]
531
+ fn test_error_type_codes() {
532
+ assert_eq!(
533
+ ErrorCondition::StringTooShort { min_length: None }.error_type(),
534
+ "string_too_short"
535
+ );
536
+ assert_eq!(
537
+ ErrorCondition::StringTooLong { max_length: None }.error_type(),
538
+ "string_too_long"
539
+ );
540
+ assert_eq!(ErrorCondition::GreaterThan { value: None }.error_type(), "greater_than");
541
+ assert_eq!(
542
+ ErrorCondition::GreaterThanEqual { value: None }.error_type(),
543
+ "greater_than_equal"
544
+ );
545
+ assert_eq!(ErrorCondition::LessThan { value: None }.error_type(), "less_than");
546
+ assert_eq!(
547
+ ErrorCondition::LessThanEqual { value: None }.error_type(),
548
+ "less_than_equal"
549
+ );
550
+ assert_eq!(ErrorCondition::Enum { values: None }.error_type(), "enum");
551
+ assert_eq!(
552
+ ErrorCondition::StringPatternMismatch { pattern: None }.error_type(),
553
+ "string_pattern_mismatch"
554
+ );
555
+ assert_eq!(ErrorCondition::EmailFormat.error_type(), "string_pattern_mismatch");
556
+ assert_eq!(ErrorCondition::UuidFormat.error_type(), "uuid_parsing");
557
+ assert_eq!(ErrorCondition::DatetimeFormat.error_type(), "datetime_parsing");
558
+ assert_eq!(ErrorCondition::DateFormat.error_type(), "date_parsing");
559
+ assert_eq!(ErrorCondition::FormatError.error_type(), "format_error");
560
+ assert_eq!(
561
+ ErrorCondition::TypeMismatch {
562
+ expected_type: "integer".to_string()
563
+ }
564
+ .error_type(),
565
+ "type_error"
566
+ );
567
+ assert_eq!(ErrorCondition::Missing.error_type(), "missing");
568
+ assert_eq!(
569
+ ErrorCondition::AdditionalProperties {
570
+ field: "extra".to_string()
571
+ }
572
+ .error_type(),
573
+ "validation_error"
574
+ );
575
+ assert_eq!(
576
+ ErrorCondition::TooFewItems { min_items: None }.error_type(),
577
+ "too_short"
578
+ );
579
+ assert_eq!(ErrorCondition::TooManyItems.error_type(), "too_long");
580
+ }
581
+
582
+ #[test]
583
+ fn test_mapper_string_length_constraints() {
584
+ let schema = json!({
585
+ "properties": {
586
+ "name": {
587
+ "type": "string",
588
+ "minLength": 5,
589
+ "maxLength": 20
590
+ }
591
+ }
592
+ });
593
+
594
+ let condition = ErrorCondition::StringTooShort { min_length: None };
595
+ let (error_type, msg, ctx_result) = ErrorMapper::map_error(&condition, &schema, "/properties/name", "");
596
+ assert_eq!(error_type, "string_too_short");
597
+ assert_eq!(msg, "String should have at least 5 characters");
598
+ assert_eq!(ctx_result, Some(json!({"min_length": 5})));
599
+ }
600
+
601
+ #[test]
602
+ fn test_mapper_numeric_constraints() {
603
+ let schema = json!({
604
+ "properties": {
605
+ "age": {
606
+ "type": "integer",
607
+ "minimum": 0,
608
+ "maximum": 150,
609
+ "exclusiveMinimum": -1,
610
+ "exclusiveMaximum": 151
611
+ }
612
+ }
613
+ });
614
+
615
+ let condition = ErrorCondition::GreaterThanEqual { value: None };
616
+ let (error_type, msg, ctx) = ErrorMapper::map_error(&condition, &schema, "/properties/age", "");
617
+ assert_eq!(error_type, "greater_than_equal");
618
+ assert_eq!(msg, "Input should be greater than or equal to 0");
619
+ assert_eq!(ctx, Some(json!({"ge": 0})));
620
+ }
621
+
622
+ #[test]
623
+ fn test_mapper_enum() {
624
+ let schema = json!({
625
+ "properties": {
626
+ "status": {
627
+ "type": "string",
628
+ "enum": ["active", "inactive", "pending"]
629
+ }
630
+ }
631
+ });
632
+
633
+ let condition = ErrorCondition::Enum { values: None };
634
+ let (error_type, msg, _ctx) = ErrorMapper::map_error(&condition, &schema, "/properties/status", "");
635
+ assert_eq!(error_type, "enum");
636
+ assert!(msg.contains("'active'"));
637
+ assert!(msg.contains("'inactive'"));
638
+ assert!(msg.contains("'pending'"));
639
+ }
640
+
641
+ #[test]
642
+ fn test_mapper_type_mismatch() {
643
+ let schema = json!({
644
+ "properties": {
645
+ "count": { "type": "integer" }
646
+ }
647
+ });
648
+
649
+ let condition = ErrorCondition::TypeMismatch {
650
+ expected_type: "integer".to_string(),
651
+ };
652
+ let (error_type, msg, _) = ErrorMapper::map_error(&condition, &schema, "/properties/count", "");
653
+ assert_eq!(error_type, "int_parsing");
654
+ assert!(msg.contains("integer"));
655
+ }
656
+
657
+ #[test]
658
+ fn test_mapper_email_format() {
659
+ let schema = json!({});
660
+
661
+ let condition = ErrorCondition::EmailFormat;
662
+ let (error_type, msg, ctx) = ErrorMapper::map_error(&condition, &schema, "", "");
663
+ assert_eq!(error_type, "string_pattern_mismatch");
664
+ assert!(msg.contains("@"));
665
+ assert!(ctx.is_some());
666
+ }
667
+
668
+ #[test]
669
+ fn test_mapper_uuid_format() {
670
+ let schema = json!({});
671
+
672
+ let condition = ErrorCondition::UuidFormat;
673
+ let (error_type, msg, _) = ErrorMapper::map_error(&condition, &schema, "", "");
674
+ assert_eq!(error_type, "uuid_parsing");
675
+ assert_eq!(msg, "Input should be a valid UUID");
676
+ }
677
+
678
+ #[test]
679
+ fn test_mapper_additional_properties() {
680
+ let schema = json!({});
681
+
682
+ let condition = ErrorCondition::AdditionalProperties {
683
+ field: "extra_field".to_string(),
684
+ };
685
+ let (error_type, msg, ctx) = ErrorMapper::map_error(&condition, &schema, "", "");
686
+ assert_eq!(error_type, "validation_error");
687
+ assert_eq!(msg, "Additional properties are not allowed");
688
+ assert_eq!(
689
+ ctx,
690
+ Some(json!({
691
+ "additional_properties": false,
692
+ "unexpected_field": "extra_field"
693
+ }))
694
+ );
695
+ }
696
+ }