spikard 0.8.1 → 0.8.3
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.
- checksums.yaml +4 -4
- data/ext/spikard_rb/Cargo.lock +6 -6
- data/ext/spikard_rb/Cargo.toml +1 -1
- data/lib/spikard/grpc.rb +5 -5
- data/lib/spikard/version.rb +1 -1
- data/vendor/crates/spikard-bindings-shared/Cargo.toml +9 -1
- data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +61 -23
- data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +16 -0
- data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +1 -1
- data/vendor/crates/spikard-bindings-shared/src/error_response.rs +22 -19
- data/vendor/crates/spikard-bindings-shared/src/grpc_metadata.rs +16 -14
- data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +15 -6
- data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +6 -0
- data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +42 -36
- data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +6 -1
- data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +18 -6
- data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +28 -10
- data/vendor/crates/spikard-core/Cargo.toml +9 -1
- data/vendor/crates/spikard-core/src/bindings/response.rs +6 -9
- data/vendor/crates/spikard-core/src/debug.rs +2 -2
- data/vendor/crates/spikard-core/src/di/container.rs +1 -1
- data/vendor/crates/spikard-core/src/di/error.rs +1 -1
- data/vendor/crates/spikard-core/src/di/factory.rs +7 -3
- data/vendor/crates/spikard-core/src/di/graph.rs +1 -0
- data/vendor/crates/spikard-core/src/di/resolved.rs +23 -0
- data/vendor/crates/spikard-core/src/di/value.rs +1 -0
- data/vendor/crates/spikard-core/src/errors.rs +3 -0
- data/vendor/crates/spikard-core/src/http.rs +19 -18
- data/vendor/crates/spikard-core/src/lifecycle.rs +42 -18
- data/vendor/crates/spikard-core/src/metadata.rs +3 -14
- data/vendor/crates/spikard-core/src/parameters.rs +61 -35
- data/vendor/crates/spikard-core/src/problem.rs +18 -4
- data/vendor/crates/spikard-core/src/request_data.rs +9 -8
- data/vendor/crates/spikard-core/src/router.rs +20 -6
- data/vendor/crates/spikard-core/src/schema_registry.rs +23 -8
- data/vendor/crates/spikard-core/src/type_hints.rs +11 -5
- data/vendor/crates/spikard-core/src/validation/error_mapper.rs +29 -15
- data/vendor/crates/spikard-core/src/validation/mod.rs +45 -32
- data/vendor/crates/spikard-http/Cargo.toml +8 -1
- data/vendor/crates/spikard-http/src/grpc/mod.rs +1 -1
- data/vendor/crates/spikard-http/src/grpc/service.rs +11 -11
- data/vendor/crates/spikard-http/src/grpc/streaming.rs +5 -1
- data/vendor/crates/spikard-http/src/server/grpc_routing.rs +59 -20
- data/vendor/crates/spikard-http/src/server/routing_factory.rs +179 -201
- data/vendor/crates/spikard-http/tests/common/grpc_helpers.rs +49 -60
- data/vendor/crates/spikard-http/tests/common/handlers.rs +5 -5
- data/vendor/crates/spikard-http/tests/common/mod.rs +7 -8
- data/vendor/crates/spikard-http/tests/common/test_builders.rs +14 -19
- data/vendor/crates/spikard-http/tests/grpc_error_handling_test.rs +68 -69
- data/vendor/crates/spikard-http/tests/grpc_integration_test.rs +1 -3
- data/vendor/crates/spikard-http/tests/grpc_metadata_test.rs +98 -84
- data/vendor/crates/spikard-http/tests/grpc_server_integration.rs +76 -57
- data/vendor/crates/spikard-rb/Cargo.toml +9 -1
- data/vendor/crates/spikard-rb/build.rs +1 -0
- data/vendor/crates/spikard-rb/src/grpc/handler.rs +30 -25
- data/vendor/crates/spikard-rb/src/lib.rs +59 -2
- data/vendor/crates/spikard-rb/src/lifecycle.rs +2 -2
- data/vendor/crates/spikard-rb-macros/Cargo.toml +9 -1
- data/vendor/crates/spikard-rb-macros/src/lib.rs +4 -5
- metadata +1 -1
|
@@ -69,6 +69,9 @@ impl ParameterValidator {
|
|
|
69
69
|
///
|
|
70
70
|
/// The schema should describe all parameters with their types and constraints.
|
|
71
71
|
/// Each property MUST have a "source" field indicating where the parameter comes from.
|
|
72
|
+
///
|
|
73
|
+
/// # Errors
|
|
74
|
+
/// Returns an error if the schema is invalid or malformed.
|
|
72
75
|
pub fn new(schema: Value) -> Result<Self, String> {
|
|
73
76
|
let parameter_defs = Self::extract_parameter_defs(&schema)?;
|
|
74
77
|
let validation_schema = Self::create_validation_schema(&schema);
|
|
@@ -88,6 +91,7 @@ impl ParameterValidator {
|
|
|
88
91
|
}
|
|
89
92
|
|
|
90
93
|
/// Whether this validator needs access to request headers.
|
|
94
|
+
#[must_use]
|
|
91
95
|
pub fn requires_headers(&self) -> bool {
|
|
92
96
|
self.inner
|
|
93
97
|
.parameter_defs
|
|
@@ -96,6 +100,7 @@ impl ParameterValidator {
|
|
|
96
100
|
}
|
|
97
101
|
|
|
98
102
|
/// Whether this validator needs access to request cookies.
|
|
103
|
+
#[must_use]
|
|
99
104
|
pub fn requires_cookies(&self) -> bool {
|
|
100
105
|
self.inner
|
|
101
106
|
.parameter_defs
|
|
@@ -104,6 +109,7 @@ impl ParameterValidator {
|
|
|
104
109
|
}
|
|
105
110
|
|
|
106
111
|
/// Whether the validator has any parameter definitions.
|
|
112
|
+
#[must_use]
|
|
107
113
|
pub fn has_params(&self) -> bool {
|
|
108
114
|
!self.inner.parameter_defs.is_empty()
|
|
109
115
|
}
|
|
@@ -125,12 +131,22 @@ impl ParameterValidator {
|
|
|
125
131
|
|
|
126
132
|
for (key, child) in obj {
|
|
127
133
|
match key.as_str() {
|
|
128
|
-
// Structural keywords we support in the coercion pass.
|
|
129
|
-
"type"
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
| "
|
|
134
|
+
// Structural keywords we support in the coercion pass, and metadata keywords.
|
|
135
|
+
"type"
|
|
136
|
+
| "format"
|
|
137
|
+
| "properties"
|
|
138
|
+
| "required"
|
|
139
|
+
| "items"
|
|
140
|
+
| "additionalProperties"
|
|
141
|
+
| "title"
|
|
142
|
+
| "description"
|
|
143
|
+
| "default"
|
|
144
|
+
| "examples"
|
|
145
|
+
| "deprecated"
|
|
146
|
+
| "readOnly"
|
|
147
|
+
| "writeOnly"
|
|
148
|
+
| "$schema"
|
|
149
|
+
| "$id" => {}
|
|
134
150
|
|
|
135
151
|
// Anything else may impose constraints we don't enforce manually.
|
|
136
152
|
_ => return true,
|
|
@@ -166,15 +182,14 @@ impl ParameterValidator {
|
|
|
166
182
|
for (name, prop) in properties {
|
|
167
183
|
let source_str = prop.get("source").and_then(|s| s.as_str()).ok_or_else(|| {
|
|
168
184
|
anyhow::anyhow!("Invalid parameter schema")
|
|
169
|
-
.context(format!("Parameter '{}' missing required 'source' field"
|
|
185
|
+
.context(format!("Parameter '{name}' missing required 'source' field"))
|
|
170
186
|
.to_string()
|
|
171
187
|
})?;
|
|
172
188
|
|
|
173
189
|
let source = ParameterSource::from_str(source_str).ok_or_else(|| {
|
|
174
190
|
anyhow::anyhow!("Invalid parameter schema")
|
|
175
191
|
.context(format!(
|
|
176
|
-
"Invalid source '{}' for parameter '{}' (expected: query, path, header, or cookie)"
|
|
177
|
-
source_str, name
|
|
192
|
+
"Invalid source '{source_str}' for parameter '{name}' (expected: query, path, header, or cookie)"
|
|
178
193
|
))
|
|
179
194
|
.to_string()
|
|
180
195
|
})?;
|
|
@@ -182,7 +197,10 @@ impl ParameterValidator {
|
|
|
182
197
|
let expected_type = prop.get("type").and_then(|t| t.as_str()).map(String::from);
|
|
183
198
|
let format = prop.get("format").and_then(|f| f.as_str()).map(String::from);
|
|
184
199
|
|
|
185
|
-
let is_optional = prop
|
|
200
|
+
let is_optional = prop
|
|
201
|
+
.get("optional")
|
|
202
|
+
.and_then(serde_json::Value::as_bool)
|
|
203
|
+
.unwrap_or(false);
|
|
186
204
|
let required = required_list.contains(&name.as_str()) && !is_optional;
|
|
187
205
|
|
|
188
206
|
let (lookup_key, error_key) = if source == ParameterSource::Header {
|
|
@@ -207,6 +225,7 @@ impl ParameterValidator {
|
|
|
207
225
|
}
|
|
208
226
|
|
|
209
227
|
/// Get the underlying JSON Schema
|
|
228
|
+
#[must_use]
|
|
210
229
|
pub fn schema(&self) -> &Value {
|
|
211
230
|
&self.inner.schema
|
|
212
231
|
}
|
|
@@ -217,6 +236,10 @@ impl ParameterValidator {
|
|
|
217
236
|
/// It performs type coercion (e.g., "123" → 123) based on the schema.
|
|
218
237
|
///
|
|
219
238
|
/// Returns the validated JSON object that can be directly converted to Python kwargs.
|
|
239
|
+
///
|
|
240
|
+
/// # Errors
|
|
241
|
+
/// Returns a validation error if parameter validation fails.
|
|
242
|
+
#[allow(clippy::too_many_lines)]
|
|
220
243
|
pub fn validate_and_extract(
|
|
221
244
|
&self,
|
|
222
245
|
query_params: &Value,
|
|
@@ -279,11 +302,11 @@ impl ParameterValidator {
|
|
|
279
302
|
"Input should be a valid boolean, unable to interpret input".to_string()
|
|
280
303
|
}
|
|
281
304
|
Some("string") => match item_format {
|
|
282
|
-
Some("uuid") => format!("Input should be a valid UUID, {}"
|
|
283
|
-
Some("date") => format!("Input should be a valid date, {}"
|
|
284
|
-
Some("date-time") => format!("Input should be a valid datetime, {}"
|
|
285
|
-
Some("time") => format!("Input should be a valid time, {}"
|
|
286
|
-
Some("duration") => format!("Input should be a valid duration, {}"
|
|
305
|
+
Some("uuid") => format!("Input should be a valid UUID, {e}"),
|
|
306
|
+
Some("date") => format!("Input should be a valid date, {e}"),
|
|
307
|
+
Some("date-time") => format!("Input should be a valid datetime, {e}"),
|
|
308
|
+
Some("time") => format!("Input should be a valid time, {e}"),
|
|
309
|
+
Some("duration") => format!("Input should be a valid duration, {e}"),
|
|
287
310
|
_ => e,
|
|
288
311
|
},
|
|
289
312
|
_ => e,
|
|
@@ -303,6 +326,7 @@ impl ParameterValidator {
|
|
|
303
326
|
};
|
|
304
327
|
let (item_type, item_format) = self.array_item_type_and_format(¶m_def.name);
|
|
305
328
|
|
|
329
|
+
#[allow(clippy::option_if_let_else)]
|
|
306
330
|
let coerced_items = match array_value.as_array() {
|
|
307
331
|
Some(items) => {
|
|
308
332
|
let mut out = Vec::with_capacity(items.len());
|
|
@@ -332,11 +356,11 @@ impl ParameterValidator {
|
|
|
332
356
|
Some("number") => "Input should be a valid number, unable to parse string as a number".to_string(),
|
|
333
357
|
Some("boolean") => "Input should be a valid boolean, unable to interpret input".to_string(),
|
|
334
358
|
Some("string") => match item_format {
|
|
335
|
-
Some("uuid") => format!("Input should be a valid UUID, {}"
|
|
336
|
-
Some("date") => format!("Input should be a valid date, {}"
|
|
337
|
-
Some("date-time") => format!("Input should be a valid datetime, {}"
|
|
338
|
-
Some("time") => format!("Input should be a valid time, {}"
|
|
339
|
-
Some("duration") => format!("Input should be a valid duration, {}"
|
|
359
|
+
Some("uuid") => format!("Input should be a valid UUID, {e}"),
|
|
360
|
+
Some("date") => format!("Input should be a valid date, {e}"),
|
|
361
|
+
Some("date-time") => format!("Input should be a valid datetime, {e}"),
|
|
362
|
+
Some("time") => format!("Input should be a valid time, {e}"),
|
|
363
|
+
Some("duration") => format!("Input should be a valid duration, {e}"),
|
|
340
364
|
_ => e.clone(),
|
|
341
365
|
},
|
|
342
366
|
_ => e.clone(),
|
|
@@ -410,19 +434,19 @@ impl ParameterValidator {
|
|
|
410
434
|
"Input should be a valid boolean, unable to interpret input".to_string(),
|
|
411
435
|
),
|
|
412
436
|
(Some("string"), Some("uuid")) => {
|
|
413
|
-
("uuid_parsing", format!("Input should be a valid UUID, {}"
|
|
437
|
+
("uuid_parsing", format!("Input should be a valid UUID, {e}"))
|
|
414
438
|
}
|
|
415
439
|
(Some("string"), Some("date")) => {
|
|
416
|
-
("date_parsing", format!("Input should be a valid date, {}"
|
|
440
|
+
("date_parsing", format!("Input should be a valid date, {e}"))
|
|
417
441
|
}
|
|
418
442
|
(Some("string"), Some("date-time")) => {
|
|
419
|
-
("datetime_parsing", format!("Input should be a valid datetime, {}"
|
|
443
|
+
("datetime_parsing", format!("Input should be a valid datetime, {e}"))
|
|
420
444
|
}
|
|
421
445
|
(Some("string"), Some("time")) => {
|
|
422
|
-
("time_parsing", format!("Input should be a valid time, {}"
|
|
446
|
+
("time_parsing", format!("Input should be a valid time, {e}"))
|
|
423
447
|
}
|
|
424
448
|
(Some("string"), Some("duration")) => {
|
|
425
|
-
("duration_parsing", format!("Input should be a valid duration, {}"
|
|
449
|
+
("duration_parsing", format!("Input should be a valid duration, {e}"))
|
|
426
450
|
}
|
|
427
451
|
_ => ("type_error", e),
|
|
428
452
|
};
|
|
@@ -445,7 +469,7 @@ impl ParameterValidator {
|
|
|
445
469
|
let params_json = Value::Object(params_map);
|
|
446
470
|
if let Some(schema_validator) = &self.inner.schema_validator {
|
|
447
471
|
match schema_validator.validate(¶ms_json) {
|
|
448
|
-
Ok(
|
|
472
|
+
Ok(()) => Ok(params_json),
|
|
449
473
|
Err(mut validation_err) => {
|
|
450
474
|
for error in &mut validation_err.errors {
|
|
451
475
|
if error.loc.len() >= 2 && error.loc[0] == "body" {
|
|
@@ -459,7 +483,7 @@ impl ParameterValidator {
|
|
|
459
483
|
};
|
|
460
484
|
error.loc[0] = source_str.to_string();
|
|
461
485
|
if param_def.source == ParameterSource::Header {
|
|
462
|
-
error.loc[1]
|
|
486
|
+
error.loc[1].clone_from(¶m_def.error_key);
|
|
463
487
|
}
|
|
464
488
|
if let Some(raw_value) =
|
|
465
489
|
self.raw_value_for_error(param_def, raw_query_params, path_params, headers, cookies)
|
|
@@ -477,6 +501,7 @@ impl ParameterValidator {
|
|
|
477
501
|
}
|
|
478
502
|
}
|
|
479
503
|
|
|
504
|
+
#[allow(clippy::unused_self)]
|
|
480
505
|
fn raw_value_for_error<'a>(
|
|
481
506
|
&self,
|
|
482
507
|
param_def: &ParameterDef,
|
|
@@ -485,6 +510,7 @@ impl ParameterValidator {
|
|
|
485
510
|
headers: &'a HashMap<String, String>,
|
|
486
511
|
cookies: &'a HashMap<String, String>,
|
|
487
512
|
) -> Option<&'a str> {
|
|
513
|
+
#[allow(clippy::too_many_arguments)]
|
|
488
514
|
match param_def.source {
|
|
489
515
|
ParameterSource::Query => raw_query_params
|
|
490
516
|
.get(¶m_def.lookup_key)
|
|
@@ -548,11 +574,11 @@ impl ParameterValidator {
|
|
|
548
574
|
Some("integer") => value
|
|
549
575
|
.parse::<i64>()
|
|
550
576
|
.map(|i| json!(i))
|
|
551
|
-
.map_err(|e| format!("Invalid integer: {}"
|
|
577
|
+
.map_err(|e| format!("Invalid integer: {e}")),
|
|
552
578
|
Some("number") => value
|
|
553
579
|
.parse::<f64>()
|
|
554
580
|
.map(|f| json!(f))
|
|
555
|
-
.map_err(|e| format!("Invalid number: {}"
|
|
581
|
+
.map_err(|e| format!("Invalid number: {e}")),
|
|
556
582
|
Some("boolean") => {
|
|
557
583
|
if value.is_empty() {
|
|
558
584
|
return Ok(json!(false));
|
|
@@ -563,7 +589,7 @@ impl ParameterValidator {
|
|
|
563
589
|
} else if value_lower == "false" || value == "0" {
|
|
564
590
|
Ok(json!(false))
|
|
565
591
|
} else {
|
|
566
|
-
Err(format!("Invalid boolean: {}"
|
|
592
|
+
Err(format!("Invalid boolean: {value}"))
|
|
567
593
|
}
|
|
568
594
|
}
|
|
569
595
|
_ => Ok(json!(value)),
|
|
@@ -574,7 +600,7 @@ impl ParameterValidator {
|
|
|
574
600
|
fn validate_date_format(value: &str) -> Result<(), String> {
|
|
575
601
|
jiff::civil::Date::strptime("%Y-%m-%d", value)
|
|
576
602
|
.map(|_| ())
|
|
577
|
-
.map_err(|e| format!("Invalid date format: {}"
|
|
603
|
+
.map_err(|e| format!("Invalid date format: {e}"))
|
|
578
604
|
}
|
|
579
605
|
|
|
580
606
|
/// Validate ISO 8601 datetime format
|
|
@@ -582,7 +608,7 @@ impl ParameterValidator {
|
|
|
582
608
|
use std::str::FromStr;
|
|
583
609
|
jiff::Timestamp::from_str(value)
|
|
584
610
|
.map(|_| ())
|
|
585
|
-
.map_err(|e| format!("Invalid datetime format: {}"
|
|
611
|
+
.map_err(|e| format!("Invalid datetime format: {e}"))
|
|
586
612
|
}
|
|
587
613
|
|
|
588
614
|
/// Validate ISO 8601 time format: HH:MM:SS or HH:MM:SS.ffffff
|
|
@@ -608,7 +634,7 @@ impl ParameterValidator {
|
|
|
608
634
|
};
|
|
609
635
|
|
|
610
636
|
let base_time = time_part.split('.').next().unwrap_or(time_part);
|
|
611
|
-
jiff::civil::Time::strptime("%H:%M:%S", base_time).map_err(|e| format!("Invalid time format: {}"
|
|
637
|
+
jiff::civil::Time::strptime("%H:%M:%S", base_time).map_err(|e| format!("Invalid time format: {e}"))?;
|
|
612
638
|
|
|
613
639
|
if let Some((_, frac)) = time_part.split_once('.')
|
|
614
640
|
&& (frac.is_empty() || frac.len() > 9 || !frac.chars().all(|c| c.is_ascii_digit()))
|
|
@@ -648,7 +674,7 @@ impl ParameterValidator {
|
|
|
648
674
|
use std::str::FromStr;
|
|
649
675
|
jiff::Span::from_str(value)
|
|
650
676
|
.map(|_| ())
|
|
651
|
-
.map_err(|e| format!("Invalid duration format: {}"
|
|
677
|
+
.map_err(|e| format!("Invalid duration format: {e}"))
|
|
652
678
|
}
|
|
653
679
|
|
|
654
680
|
/// Validate UUID format
|
|
@@ -671,7 +697,7 @@ impl ParameterValidator {
|
|
|
671
697
|
for (name, prop) in properties.iter_mut() {
|
|
672
698
|
if let Some(obj) = prop.as_object_mut() {
|
|
673
699
|
obj.remove("source");
|
|
674
|
-
if obj.get("optional").and_then(
|
|
700
|
+
if obj.get("optional").and_then(serde_json::Value::as_bool) == Some(true) {
|
|
675
701
|
optional_fields.push(name.clone());
|
|
676
702
|
}
|
|
677
703
|
obj.remove("optional");
|
|
@@ -82,7 +82,8 @@ impl ProblemDetails {
|
|
|
82
82
|
/// Standard type URI for bad request (400)
|
|
83
83
|
pub const TYPE_BAD_REQUEST: &'static str = "https://spikard.dev/errors/bad-request";
|
|
84
84
|
|
|
85
|
-
/// Create a new ProblemDetails with required fields
|
|
85
|
+
/// Create a new `ProblemDetails` with required fields
|
|
86
|
+
#[must_use]
|
|
86
87
|
pub fn new(type_uri: impl Into<String>, title: impl Into<String>, status: StatusCode) -> Self {
|
|
87
88
|
Self {
|
|
88
89
|
type_uri: type_uri.into(),
|
|
@@ -95,24 +96,29 @@ impl ProblemDetails {
|
|
|
95
96
|
}
|
|
96
97
|
|
|
97
98
|
/// Set the detail field
|
|
99
|
+
#[must_use]
|
|
98
100
|
pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
|
|
99
101
|
self.detail = Some(detail.into());
|
|
100
102
|
self
|
|
101
103
|
}
|
|
102
104
|
|
|
103
105
|
/// Set the instance field
|
|
106
|
+
#[must_use]
|
|
104
107
|
pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
|
|
105
108
|
self.instance = Some(instance.into());
|
|
106
109
|
self
|
|
107
110
|
}
|
|
108
111
|
|
|
109
112
|
/// Add an extension field
|
|
113
|
+
#[must_use]
|
|
110
114
|
pub fn with_extension(mut self, key: impl Into<String>, value: Value) -> Self {
|
|
111
115
|
self.extensions.insert(key.into(), value);
|
|
112
116
|
self
|
|
113
117
|
}
|
|
114
118
|
|
|
115
119
|
/// Add all extensions from a JSON object
|
|
120
|
+
#[must_use]
|
|
121
|
+
#[allow(clippy::needless_pass_by_value)]
|
|
116
122
|
pub fn with_extensions(mut self, extensions: Value) -> Self {
|
|
117
123
|
if let Some(obj) = extensions.as_object() {
|
|
118
124
|
for (key, value) in obj {
|
|
@@ -122,20 +128,21 @@ impl ProblemDetails {
|
|
|
122
128
|
self
|
|
123
129
|
}
|
|
124
130
|
|
|
125
|
-
/// Create a validation error Problem Details from ValidationError
|
|
131
|
+
/// Create a validation error Problem Details from `ValidationError`
|
|
126
132
|
///
|
|
127
133
|
/// This converts the FastAPI-style validation errors to RFC 9457 format:
|
|
128
|
-
/// - `type`:
|
|
134
|
+
/// - `type`: <https://spikard.dev/errors/validation-error>
|
|
129
135
|
/// - `title`: "Request Validation Failed"
|
|
130
136
|
/// - `status`: 422
|
|
131
137
|
/// - `detail`: Summary of error count
|
|
132
138
|
/// - `errors`: Array of validation error details (as extension field)
|
|
139
|
+
#[must_use]
|
|
133
140
|
pub fn from_validation_error(error: &ValidationError) -> Self {
|
|
134
141
|
let error_count = error.errors.len();
|
|
135
142
|
let detail = if error_count == 1 {
|
|
136
143
|
"1 validation error in request".to_string()
|
|
137
144
|
} else {
|
|
138
|
-
format!("{} validation errors in request"
|
|
145
|
+
format!("{error_count} validation errors in request")
|
|
139
146
|
};
|
|
140
147
|
|
|
141
148
|
let errors_json = serde_json::to_value(&error.errors).unwrap_or_else(|_| serde_json::Value::Array(vec![]));
|
|
@@ -201,16 +208,23 @@ impl ProblemDetails {
|
|
|
201
208
|
}
|
|
202
209
|
|
|
203
210
|
/// Get the HTTP status code
|
|
211
|
+
#[must_use]
|
|
204
212
|
pub fn status_code(&self) -> StatusCode {
|
|
205
213
|
StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
|
|
206
214
|
}
|
|
207
215
|
|
|
208
216
|
/// Serialize to JSON string
|
|
217
|
+
///
|
|
218
|
+
/// # Errors
|
|
219
|
+
/// Returns an error if the serialization fails.
|
|
209
220
|
pub fn to_json(&self) -> Result<String, serde_json::Error> {
|
|
210
221
|
serde_json::to_string(self)
|
|
211
222
|
}
|
|
212
223
|
|
|
213
224
|
/// Serialize to pretty JSON string
|
|
225
|
+
///
|
|
226
|
+
/// # Errors
|
|
227
|
+
/// Returns an error if the serialization fails.
|
|
214
228
|
pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
|
|
215
229
|
serde_json::to_string_pretty(self)
|
|
216
230
|
}
|
|
@@ -17,19 +17,19 @@ use bytes::Bytes;
|
|
|
17
17
|
///
|
|
18
18
|
/// This is the language-agnostic representation passed to handlers.
|
|
19
19
|
///
|
|
20
|
-
/// Uses Arc for
|
|
21
|
-
/// When RequestData is cloned, only the Arc pointers are cloned, not the underlying data.
|
|
20
|
+
/// Uses `Arc` for `HashMap`s to enable cheap cloning without duplicating data.
|
|
21
|
+
/// When `RequestData` is cloned, only the `Arc` pointers are cloned, not the underlying data.
|
|
22
22
|
///
|
|
23
|
-
/// Performance optimization: raw_body stores the unparsed request body bytes.
|
|
24
|
-
/// Language bindings should use raw_body when possible to avoid double-parsing.
|
|
25
|
-
/// The body field is lazily parsed only when needed for validation.
|
|
23
|
+
/// Performance optimization: `raw_body` stores the unparsed request body bytes.
|
|
24
|
+
/// Language bindings should use `raw_body` when possible to avoid double-parsing.
|
|
25
|
+
/// The `body` field is lazily parsed only when needed for validation.
|
|
26
26
|
#[derive(Debug, Clone)]
|
|
27
27
|
pub struct RequestData {
|
|
28
28
|
/// Path parameters extracted from the URL path
|
|
29
29
|
pub path_params: Arc<HashMap<String, String>>,
|
|
30
30
|
/// Query parameters parsed as JSON
|
|
31
31
|
pub query_params: Value,
|
|
32
|
-
/// Validated parameters produced by ParameterValidator (query/path/header/cookie combined).
|
|
32
|
+
/// Validated parameters produced by `ParameterValidator` (query/path/header/cookie combined).
|
|
33
33
|
pub validated_params: Option<Value>,
|
|
34
34
|
/// Raw query parameters as key-value pairs
|
|
35
35
|
pub raw_query_params: Arc<HashMap<String, Vec<String>>>,
|
|
@@ -66,7 +66,7 @@ impl Serialize for RequestData {
|
|
|
66
66
|
state.serialize_field("raw_query_params", &*self.raw_query_params)?;
|
|
67
67
|
state.serialize_field("body", &self.body)?;
|
|
68
68
|
#[cfg(feature = "di")]
|
|
69
|
-
state.serialize_field("raw_body", &self.raw_body.as_ref().map(
|
|
69
|
+
state.serialize_field("raw_body", &self.raw_body.as_ref().map(AsRef::as_ref))?;
|
|
70
70
|
#[cfg(not(feature = "di"))]
|
|
71
71
|
state.serialize_field("raw_body", &self.raw_body)?;
|
|
72
72
|
state.serialize_field("headers", &*self.headers)?;
|
|
@@ -78,6 +78,7 @@ impl Serialize for RequestData {
|
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
impl<'de> Deserialize<'de> for RequestData {
|
|
81
|
+
#[allow(clippy::too_many_lines)]
|
|
81
82
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
|
82
83
|
where
|
|
83
84
|
D: serde::Deserializer<'de>,
|
|
@@ -933,7 +934,7 @@ mod tests {
|
|
|
933
934
|
"float": 3.2,
|
|
934
935
|
"negative": -100,
|
|
935
936
|
"zero": 0,
|
|
936
|
-
"large":
|
|
937
|
+
"large": 9_223_372_036_854_775_807i64
|
|
937
938
|
});
|
|
938
939
|
|
|
939
940
|
let data = create_request_data(
|
|
@@ -70,8 +70,8 @@ pub struct JsonRpcMethodInfo {
|
|
|
70
70
|
|
|
71
71
|
/// Route definition with compiled validators
|
|
72
72
|
///
|
|
73
|
-
/// Validators are Arc
|
|
74
|
-
/// and to support schema deduplication via SchemaRegistry
|
|
73
|
+
/// Validators are `Arc`-wrapped to enable cheap cloning across route instances
|
|
74
|
+
/// and to support schema deduplication via `SchemaRegistry`.
|
|
75
75
|
///
|
|
76
76
|
/// The `jsonrpc_method` field is optional and has zero overhead when None,
|
|
77
77
|
/// enabling routes to optionally expose themselves as JSON-RPC methods.
|
|
@@ -102,10 +102,14 @@ impl Route {
|
|
|
102
102
|
///
|
|
103
103
|
/// Auto-generates parameter schema from type hints in the path if no explicit schema provided.
|
|
104
104
|
/// Type hints like `/items/{id:uuid}` generate appropriate JSON Schema validation.
|
|
105
|
-
/// Explicit parameter_schema overrides auto-generated schemas.
|
|
105
|
+
/// Explicit `parameter_schema` overrides auto-generated schemas.
|
|
106
|
+
///
|
|
107
|
+
/// # Errors
|
|
108
|
+
/// Returns an error if the schema compilation fails or metadata is invalid.
|
|
106
109
|
///
|
|
107
110
|
/// The schema registry ensures each unique schema is compiled only once, improving
|
|
108
111
|
/// startup performance and memory usage for applications with many routes.
|
|
112
|
+
#[allow(clippy::items_after_statements)]
|
|
109
113
|
pub fn from_metadata(metadata: RouteMetadata, registry: &SchemaRegistry) -> Result<Self, String> {
|
|
110
114
|
let method = metadata.method.parse()?;
|
|
111
115
|
|
|
@@ -135,7 +139,10 @@ impl Route {
|
|
|
135
139
|
if is_empty_schema(&explicit_schema) {
|
|
136
140
|
Some(auto_schema)
|
|
137
141
|
} else {
|
|
138
|
-
Some(crate::type_hints::merge_parameter_schemas(
|
|
142
|
+
Some(crate::type_hints::merge_parameter_schemas(
|
|
143
|
+
&auto_schema,
|
|
144
|
+
&explicit_schema,
|
|
145
|
+
))
|
|
139
146
|
}
|
|
140
147
|
}
|
|
141
148
|
(Some(auto_schema), None) => Some(auto_schema),
|
|
@@ -187,17 +194,20 @@ impl Route {
|
|
|
187
194
|
/// tags: vec!["users".to_string()],
|
|
188
195
|
/// });
|
|
189
196
|
/// ```
|
|
197
|
+
#[must_use]
|
|
190
198
|
pub fn with_jsonrpc_method(mut self, info: JsonRpcMethodInfo) -> Self {
|
|
191
199
|
self.jsonrpc_method = Some(info);
|
|
192
200
|
self
|
|
193
201
|
}
|
|
194
202
|
|
|
195
203
|
/// Check if this route has JSON-RPC metadata
|
|
196
|
-
|
|
204
|
+
#[must_use]
|
|
205
|
+
pub const fn is_jsonrpc_method(&self) -> bool {
|
|
197
206
|
self.jsonrpc_method.is_some()
|
|
198
207
|
}
|
|
199
208
|
|
|
200
209
|
/// Get the JSON-RPC method name if present
|
|
210
|
+
#[must_use]
|
|
201
211
|
pub fn jsonrpc_method_name(&self) -> Option<&str> {
|
|
202
212
|
self.jsonrpc_method.as_ref().map(|m| m.method_name.as_str())
|
|
203
213
|
}
|
|
@@ -210,6 +220,7 @@ pub struct Router {
|
|
|
210
220
|
|
|
211
221
|
impl Router {
|
|
212
222
|
/// Create a new router
|
|
223
|
+
#[must_use]
|
|
213
224
|
pub fn new() -> Self {
|
|
214
225
|
Self { routes: HashMap::new() }
|
|
215
226
|
}
|
|
@@ -221,18 +232,21 @@ impl Router {
|
|
|
221
232
|
}
|
|
222
233
|
|
|
223
234
|
/// Find a route by method and path
|
|
235
|
+
#[must_use]
|
|
224
236
|
pub fn find_route(&self, method: &Method, path: &str) -> Option<&Route> {
|
|
225
237
|
self.routes.get(path)?.get(method)
|
|
226
238
|
}
|
|
227
239
|
|
|
228
240
|
/// Get all routes
|
|
241
|
+
#[must_use]
|
|
229
242
|
pub fn routes(&self) -> Vec<&Route> {
|
|
230
243
|
self.routes.values().flat_map(|methods| methods.values()).collect()
|
|
231
244
|
}
|
|
232
245
|
|
|
233
246
|
/// Get route count
|
|
247
|
+
#[must_use]
|
|
234
248
|
pub fn route_count(&self) -> usize {
|
|
235
|
-
self.routes.values().map(
|
|
249
|
+
self.routes.values().map(std::collections::HashMap::len).sum()
|
|
236
250
|
}
|
|
237
251
|
}
|
|
238
252
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
//! Schema registry for deduplication and OpenAPI generation
|
|
1
|
+
//! Schema registry for deduplication and `OpenAPI` generation
|
|
2
2
|
//!
|
|
3
3
|
//! This module provides a global registry that compiles JSON schemas once at application
|
|
4
4
|
//! startup and reuses them across all routes. This enables:
|
|
5
5
|
//! - Schema deduplication (same schema used by multiple routes)
|
|
6
|
-
//! - OpenAPI spec generation (access to all schemas)
|
|
6
|
+
//! - `OpenAPI` spec generation (access to all schemas)
|
|
7
7
|
//! - Memory efficiency (one compiled validator per unique schema)
|
|
8
8
|
|
|
9
9
|
use crate::validation::SchemaValidator;
|
|
@@ -14,7 +14,7 @@ use std::sync::{Arc, RwLock};
|
|
|
14
14
|
/// Global schema registry for compiled validators
|
|
15
15
|
///
|
|
16
16
|
/// Thread-safe registry that ensures each unique schema is compiled exactly once.
|
|
17
|
-
/// Uses RwLock for concurrent read access with occasional writes during startup.
|
|
17
|
+
/// Uses `RwLock` for concurrent read access with occasional writes during startup.
|
|
18
18
|
pub struct SchemaRegistry {
|
|
19
19
|
/// Map from schema JSON string to compiled validator
|
|
20
20
|
schemas: RwLock<HashMap<String, Arc<SchemaValidator>>>,
|
|
@@ -22,13 +22,14 @@ pub struct SchemaRegistry {
|
|
|
22
22
|
|
|
23
23
|
impl SchemaRegistry {
|
|
24
24
|
/// Create a new empty schema registry
|
|
25
|
+
#[must_use]
|
|
25
26
|
pub fn new() -> Self {
|
|
26
27
|
Self {
|
|
27
28
|
schemas: RwLock::new(HashMap::new()),
|
|
28
29
|
}
|
|
29
30
|
}
|
|
30
31
|
|
|
31
|
-
/// Get or compile a schema, returning Arc to the compiled validator
|
|
32
|
+
/// Get or compile a schema, returning `Arc` to the compiled validator
|
|
32
33
|
///
|
|
33
34
|
/// This method is thread-safe and uses a double-check pattern:
|
|
34
35
|
/// 1. Fast path: Read lock to check if schema exists
|
|
@@ -38,9 +39,15 @@ impl SchemaRegistry {
|
|
|
38
39
|
/// * `schema` - The JSON schema to compile
|
|
39
40
|
///
|
|
40
41
|
/// # Returns
|
|
41
|
-
/// Arc
|
|
42
|
+
/// `Arc`-wrapped compiled validator that can be cheaply cloned
|
|
43
|
+
///
|
|
44
|
+
/// # Errors
|
|
45
|
+
/// Returns an error if schema serialization or compilation fails.
|
|
46
|
+
///
|
|
47
|
+
/// # Panics
|
|
48
|
+
/// Panics if the read or write lock is poisoned.
|
|
42
49
|
pub fn get_or_compile(&self, schema: &Value) -> Result<Arc<SchemaValidator>, String> {
|
|
43
|
-
let key = serde_json::to_string(schema).map_err(|e| format!("Failed to serialize schema: {}"
|
|
50
|
+
let key = serde_json::to_string(schema).map_err(|e| format!("Failed to serialize schema: {e}"))?;
|
|
44
51
|
|
|
45
52
|
{
|
|
46
53
|
let schemas = self.schemas.read().unwrap();
|
|
@@ -62,10 +69,14 @@ impl SchemaRegistry {
|
|
|
62
69
|
Ok(validator)
|
|
63
70
|
}
|
|
64
71
|
|
|
65
|
-
/// Get all registered schemas (for OpenAPI generation)
|
|
72
|
+
/// Get all registered schemas (for `OpenAPI` generation)
|
|
66
73
|
///
|
|
67
74
|
/// Returns a snapshot of all compiled validators.
|
|
68
|
-
/// Useful for generating OpenAPI specifications from runtime schema information.
|
|
75
|
+
/// Useful for generating `OpenAPI` specifications from runtime schema information.
|
|
76
|
+
///
|
|
77
|
+
/// # Panics
|
|
78
|
+
/// Panics if the read lock is poisoned.
|
|
79
|
+
#[must_use]
|
|
69
80
|
pub fn all_schemas(&self) -> Vec<Arc<SchemaValidator>> {
|
|
70
81
|
let schemas = self.schemas.read().unwrap();
|
|
71
82
|
schemas.values().cloned().collect()
|
|
@@ -74,6 +85,10 @@ impl SchemaRegistry {
|
|
|
74
85
|
/// Get the number of unique schemas registered
|
|
75
86
|
///
|
|
76
87
|
/// Useful for diagnostics and understanding schema deduplication effectiveness.
|
|
88
|
+
///
|
|
89
|
+
/// # Panics
|
|
90
|
+
/// Panics if the read lock is poisoned.
|
|
91
|
+
#[must_use]
|
|
77
92
|
pub fn schema_count(&self) -> usize {
|
|
78
93
|
let schemas = self.schemas.read().unwrap();
|
|
79
94
|
schemas.len()
|
|
@@ -39,6 +39,10 @@ fn path_type_regex() -> &'static Regex {
|
|
|
39
39
|
/// assert_eq!(hints.get("id"), Some(&"uuid".to_string()));
|
|
40
40
|
/// assert_eq!(hints.get("tag_id"), Some(&"int".to_string()));
|
|
41
41
|
/// ```
|
|
42
|
+
///
|
|
43
|
+
/// # Panics
|
|
44
|
+
/// Panics if regex capture groups don't contain expected indices.
|
|
45
|
+
#[must_use]
|
|
42
46
|
pub fn parse_type_hints(route_path: &str) -> HashMap<String, String> {
|
|
43
47
|
let mut hints = HashMap::new();
|
|
44
48
|
let re = type_hint_regex();
|
|
@@ -66,6 +70,7 @@ pub fn parse_type_hints(route_path: &str) -> HashMap<String, String> {
|
|
|
66
70
|
/// assert_eq!(strip_type_hints("/items/{id:uuid}"), "/items/{id}");
|
|
67
71
|
/// assert_eq!(strip_type_hints("/files/{path:path}"), "/files/{*path}");
|
|
68
72
|
/// ```
|
|
73
|
+
#[must_use]
|
|
69
74
|
pub fn strip_type_hints(route_path: &str) -> String {
|
|
70
75
|
let path_re = path_type_regex();
|
|
71
76
|
let route_path = path_re.replace_all(route_path, "{*$1}");
|
|
@@ -86,6 +91,8 @@ pub fn strip_type_hints(route_path: &str) -> String {
|
|
|
86
91
|
/// - `date` → `{"type": "string", "format": "date"}`
|
|
87
92
|
/// - `datetime` → `{"type": "string", "format": "date-time"}`
|
|
88
93
|
/// - `path` → `{"type": "string"}` (wildcard capture)
|
|
94
|
+
#[must_use]
|
|
95
|
+
#[allow(clippy::match_same_arms)]
|
|
89
96
|
pub fn type_hint_to_schema(type_hint: &str) -> Value {
|
|
90
97
|
match type_hint {
|
|
91
98
|
"uuid" => json!({
|
|
@@ -95,7 +102,7 @@ pub fn type_hint_to_schema(type_hint: &str) -> Value {
|
|
|
95
102
|
"int" | "integer" => json!({
|
|
96
103
|
"type": "integer"
|
|
97
104
|
}),
|
|
98
|
-
"str" | "string" => json!({
|
|
105
|
+
"str" | "string" | "path" => json!({
|
|
99
106
|
"type": "string"
|
|
100
107
|
}),
|
|
101
108
|
"float" | "number" => json!({
|
|
@@ -112,9 +119,6 @@ pub fn type_hint_to_schema(type_hint: &str) -> Value {
|
|
|
112
119
|
"type": "string",
|
|
113
120
|
"format": "date-time"
|
|
114
121
|
}),
|
|
115
|
-
"path" => json!({
|
|
116
|
-
"type": "string"
|
|
117
|
-
}),
|
|
118
122
|
_ => json!({
|
|
119
123
|
"type": "string"
|
|
120
124
|
}),
|
|
@@ -145,6 +149,7 @@ pub fn type_hint_to_schema(type_hint: &str) -> Value {
|
|
|
145
149
|
/// "required": ["id"]
|
|
146
150
|
/// })));
|
|
147
151
|
/// ```
|
|
152
|
+
#[must_use]
|
|
148
153
|
pub fn auto_generate_parameter_schema(route_path: &str) -> Option<Value> {
|
|
149
154
|
let type_hints = parse_type_hints(route_path);
|
|
150
155
|
|
|
@@ -204,7 +209,8 @@ pub fn auto_generate_parameter_schema(route_path: &str) -> Option<Value> {
|
|
|
204
209
|
/// let merged = merge_parameter_schemas(auto_schema, explicit_schema);
|
|
205
210
|
/// // Result: auto-generated id + explicit count with constraints
|
|
206
211
|
/// ```
|
|
207
|
-
|
|
212
|
+
#[must_use]
|
|
213
|
+
pub fn merge_parameter_schemas(auto_schema: &Value, explicit_schema: &Value) -> Value {
|
|
208
214
|
let mut result = auto_schema.clone();
|
|
209
215
|
|
|
210
216
|
let auto_props = result.get_mut("properties").and_then(|v| v.as_object_mut());
|