spikard 0.3.6 → 0.5.0

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 (113) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +21 -6
  3. data/ext/spikard_rb/Cargo.toml +2 -2
  4. data/lib/spikard/app.rb +33 -14
  5. data/lib/spikard/testing.rb +47 -12
  6. data/lib/spikard/version.rb +1 -1
  7. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
  8. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
  9. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
  10. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  11. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  12. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
  13. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
  14. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
  15. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
  16. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
  17. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
  18. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  19. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
  20. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
  21. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
  22. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
  23. data/vendor/crates/spikard-core/Cargo.toml +4 -4
  24. data/vendor/crates/spikard-core/src/debug.rs +64 -0
  25. data/vendor/crates/spikard-core/src/di/container.rs +3 -27
  26. data/vendor/crates/spikard-core/src/di/factory.rs +1 -5
  27. data/vendor/crates/spikard-core/src/di/graph.rs +8 -47
  28. data/vendor/crates/spikard-core/src/di/mod.rs +1 -1
  29. data/vendor/crates/spikard-core/src/di/resolved.rs +1 -7
  30. data/vendor/crates/spikard-core/src/di/value.rs +2 -4
  31. data/vendor/crates/spikard-core/src/errors.rs +30 -0
  32. data/vendor/crates/spikard-core/src/http.rs +262 -0
  33. data/vendor/crates/spikard-core/src/lib.rs +1 -1
  34. data/vendor/crates/spikard-core/src/lifecycle.rs +764 -0
  35. data/vendor/crates/spikard-core/src/metadata.rs +389 -0
  36. data/vendor/crates/spikard-core/src/parameters.rs +1962 -159
  37. data/vendor/crates/spikard-core/src/problem.rs +34 -0
  38. data/vendor/crates/spikard-core/src/request_data.rs +966 -1
  39. data/vendor/crates/spikard-core/src/router.rs +263 -2
  40. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +688 -0
  41. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +26 -268
  42. data/vendor/crates/spikard-http/Cargo.toml +12 -16
  43. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
  44. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
  45. data/vendor/crates/spikard-http/src/auth.rs +65 -16
  46. data/vendor/crates/spikard-http/src/background.rs +1614 -3
  47. data/vendor/crates/spikard-http/src/cors.rs +515 -0
  48. data/vendor/crates/spikard-http/src/debug.rs +65 -0
  49. data/vendor/crates/spikard-http/src/di_handler.rs +1322 -77
  50. data/vendor/crates/spikard-http/src/handler_response.rs +711 -0
  51. data/vendor/crates/spikard-http/src/handler_trait.rs +607 -5
  52. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +6 -0
  53. data/vendor/crates/spikard-http/src/lib.rs +33 -28
  54. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +81 -0
  55. data/vendor/crates/spikard-http/src/lifecycle.rs +765 -0
  56. data/vendor/crates/spikard-http/src/middleware/mod.rs +372 -117
  57. data/vendor/crates/spikard-http/src/middleware/multipart.rs +836 -10
  58. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +409 -43
  59. data/vendor/crates/spikard-http/src/middleware/validation.rs +513 -65
  60. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +345 -0
  61. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1055 -0
  62. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +473 -3
  63. data/vendor/crates/spikard-http/src/query_parser.rs +455 -31
  64. data/vendor/crates/spikard-http/src/response.rs +321 -0
  65. data/vendor/crates/spikard-http/src/server/handler.rs +1572 -9
  66. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +136 -0
  67. data/vendor/crates/spikard-http/src/server/mod.rs +875 -178
  68. data/vendor/crates/spikard-http/src/server/request_extraction.rs +674 -23
  69. data/vendor/crates/spikard-http/src/server/routing_factory.rs +599 -0
  70. data/vendor/crates/spikard-http/src/sse.rs +983 -21
  71. data/vendor/crates/spikard-http/src/testing/form.rs +38 -0
  72. data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -2
  73. data/vendor/crates/spikard-http/src/testing.rs +7 -7
  74. data/vendor/crates/spikard-http/src/websocket.rs +1055 -4
  75. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
  76. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
  77. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
  78. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
  79. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
  80. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
  81. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
  82. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
  83. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
  84. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
  85. data/vendor/crates/spikard-rb/Cargo.toml +10 -4
  86. data/vendor/crates/spikard-rb/build.rs +196 -5
  87. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  88. data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +100 -109
  89. data/vendor/crates/spikard-rb/src/conversion.rs +121 -20
  90. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
  91. data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +12 -46
  92. data/vendor/crates/spikard-rb/src/handler.rs +100 -107
  93. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  94. data/vendor/crates/spikard-rb/src/lib.rs +467 -1428
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +1 -0
  96. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  97. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +447 -0
  98. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  99. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
  100. data/vendor/crates/spikard-rb/src/server.rs +47 -22
  101. data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +187 -40
  102. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  103. data/vendor/crates/spikard-rb/src/testing/websocket.rs +635 -0
  104. data/vendor/crates/spikard-rb/src/websocket.rs +178 -37
  105. metadata +46 -13
  106. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  107. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  108. data/vendor/crates/spikard-http/src/router.rs +0 -1
  109. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  110. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  111. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  112. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
  113. /data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +0 -0
@@ -0,0 +1,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 = 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
+ }