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.
- checksums.yaml +4 -4
- data/README.md +21 -6
- data/ext/spikard_rb/Cargo.toml +2 -2
- data/lib/spikard/app.rb +33 -14
- data/lib/spikard/testing.rb +47 -12
- data/lib/spikard/version.rb +1 -1
- data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
- data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
- data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
- data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
- data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
- data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
- data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
- data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
- data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
- data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
- data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
- data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
- data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
- data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
- data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
- data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
- data/vendor/crates/spikard-core/Cargo.toml +4 -4
- data/vendor/crates/spikard-core/src/debug.rs +64 -0
- data/vendor/crates/spikard-core/src/di/container.rs +3 -27
- data/vendor/crates/spikard-core/src/di/factory.rs +1 -5
- data/vendor/crates/spikard-core/src/di/graph.rs +8 -47
- data/vendor/crates/spikard-core/src/di/mod.rs +1 -1
- data/vendor/crates/spikard-core/src/di/resolved.rs +1 -7
- data/vendor/crates/spikard-core/src/di/value.rs +2 -4
- data/vendor/crates/spikard-core/src/errors.rs +30 -0
- data/vendor/crates/spikard-core/src/http.rs +262 -0
- data/vendor/crates/spikard-core/src/lib.rs +1 -1
- data/vendor/crates/spikard-core/src/lifecycle.rs +764 -0
- data/vendor/crates/spikard-core/src/metadata.rs +389 -0
- data/vendor/crates/spikard-core/src/parameters.rs +1962 -159
- data/vendor/crates/spikard-core/src/problem.rs +34 -0
- data/vendor/crates/spikard-core/src/request_data.rs +966 -1
- data/vendor/crates/spikard-core/src/router.rs +263 -2
- data/vendor/crates/spikard-core/src/validation/error_mapper.rs +688 -0
- data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +26 -268
- data/vendor/crates/spikard-http/Cargo.toml +12 -16
- data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
- data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
- data/vendor/crates/spikard-http/src/auth.rs +65 -16
- data/vendor/crates/spikard-http/src/background.rs +1614 -3
- data/vendor/crates/spikard-http/src/cors.rs +515 -0
- data/vendor/crates/spikard-http/src/debug.rs +65 -0
- data/vendor/crates/spikard-http/src/di_handler.rs +1322 -77
- data/vendor/crates/spikard-http/src/handler_response.rs +711 -0
- data/vendor/crates/spikard-http/src/handler_trait.rs +607 -5
- data/vendor/crates/spikard-http/src/handler_trait_tests.rs +6 -0
- data/vendor/crates/spikard-http/src/lib.rs +33 -28
- data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +81 -0
- data/vendor/crates/spikard-http/src/lifecycle.rs +765 -0
- data/vendor/crates/spikard-http/src/middleware/mod.rs +372 -117
- data/vendor/crates/spikard-http/src/middleware/multipart.rs +836 -10
- data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +409 -43
- data/vendor/crates/spikard-http/src/middleware/validation.rs +513 -65
- data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +345 -0
- data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1055 -0
- data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +473 -3
- data/vendor/crates/spikard-http/src/query_parser.rs +455 -31
- data/vendor/crates/spikard-http/src/response.rs +321 -0
- data/vendor/crates/spikard-http/src/server/handler.rs +1572 -9
- data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +136 -0
- data/vendor/crates/spikard-http/src/server/mod.rs +875 -178
- data/vendor/crates/spikard-http/src/server/request_extraction.rs +674 -23
- data/vendor/crates/spikard-http/src/server/routing_factory.rs +599 -0
- data/vendor/crates/spikard-http/src/sse.rs +983 -21
- data/vendor/crates/spikard-http/src/testing/form.rs +38 -0
- data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -2
- data/vendor/crates/spikard-http/src/testing.rs +7 -7
- data/vendor/crates/spikard-http/src/websocket.rs +1055 -4
- data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
- data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
- data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
- data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
- data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
- data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
- data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
- data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
- data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
- data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
- data/vendor/crates/spikard-rb/Cargo.toml +10 -4
- data/vendor/crates/spikard-rb/build.rs +196 -5
- data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
- data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +100 -109
- data/vendor/crates/spikard-rb/src/conversion.rs +121 -20
- data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
- data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +12 -46
- data/vendor/crates/spikard-rb/src/handler.rs +100 -107
- data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
- data/vendor/crates/spikard-rb/src/lib.rs +467 -1428
- data/vendor/crates/spikard-rb/src/lifecycle.rs +1 -0
- data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
- data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +447 -0
- data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
- data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
- data/vendor/crates/spikard-rb/src/server.rs +47 -22
- data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +187 -40
- data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
- data/vendor/crates/spikard-rb/src/testing/websocket.rs +635 -0
- data/vendor/crates/spikard-rb/src/websocket.rs +178 -37
- metadata +46 -13
- data/vendor/crates/spikard-http/src/parameters.rs +0 -1
- data/vendor/crates/spikard-http/src/problem.rs +0 -1
- data/vendor/crates/spikard-http/src/router.rs +0 -1
- data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
- data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
- data/vendor/crates/spikard-http/src/validation.rs +0 -1
- data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
- /data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +0 -0
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
//! Request/response validation using JSON Schema
|
|
2
2
|
|
|
3
|
+
pub mod error_mapper;
|
|
4
|
+
|
|
3
5
|
use crate::debug_log_module;
|
|
4
6
|
use jsonschema::Validator;
|
|
5
7
|
use serde_json::Value;
|
|
6
8
|
use std::sync::Arc;
|
|
7
9
|
|
|
10
|
+
use self::error_mapper::{ErrorCondition, ErrorMapper};
|
|
11
|
+
|
|
8
12
|
/// Schema validator that compiles and validates JSON Schema
|
|
9
13
|
#[derive(Clone)]
|
|
10
14
|
pub struct SchemaValidator {
|
|
@@ -200,280 +204,34 @@ impl SchemaValidator {
|
|
|
200
204
|
format!("/properties/{}", param_name)
|
|
201
205
|
};
|
|
202
206
|
|
|
203
|
-
let
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
"
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
)
|
|
215
|
-
} else {
|
|
216
|
-
("string_too_short".to_string(), "String is too short".to_string(), None)
|
|
217
|
-
}
|
|
218
|
-
} else if schema_path_str.contains("maxLength") {
|
|
219
|
-
if let Some(max_len) = self
|
|
220
|
-
.schema
|
|
221
|
-
.pointer(&format!("{}/maxLength", schema_prop_path))
|
|
222
|
-
.and_then(|v| v.as_u64())
|
|
223
|
-
{
|
|
224
|
-
let ctx = serde_json::json!({"max_length": max_len});
|
|
225
|
-
(
|
|
226
|
-
"string_too_long".to_string(),
|
|
227
|
-
format!("String should have at most {} characters", max_len),
|
|
228
|
-
Some(ctx),
|
|
229
|
-
)
|
|
230
|
-
} else {
|
|
231
|
-
("string_too_long".to_string(), "String is too long".to_string(), None)
|
|
232
|
-
}
|
|
233
|
-
} else if schema_path_str.contains("exclusiveMinimum")
|
|
234
|
-
|| (error_msg.contains("less than or equal to") && error_msg.contains("minimum"))
|
|
235
|
-
{
|
|
236
|
-
if let Some(min_val) = self
|
|
237
|
-
.schema
|
|
238
|
-
.pointer(&format!("{}/exclusiveMinimum", schema_prop_path))
|
|
239
|
-
.and_then(|v| v.as_i64())
|
|
240
|
-
{
|
|
241
|
-
let ctx = serde_json::json!({"gt": min_val});
|
|
242
|
-
(
|
|
243
|
-
"greater_than".to_string(),
|
|
244
|
-
format!("Input should be greater than {}", min_val),
|
|
245
|
-
Some(ctx),
|
|
246
|
-
)
|
|
247
|
-
} else {
|
|
248
|
-
(
|
|
249
|
-
"greater_than".to_string(),
|
|
250
|
-
"Input should be greater than the minimum".to_string(),
|
|
251
|
-
None,
|
|
252
|
-
)
|
|
253
|
-
}
|
|
254
|
-
} else if schema_path_str.contains("minimum") || error_msg.contains("less than the minimum") {
|
|
255
|
-
if let Some(min_val) = self
|
|
256
|
-
.schema
|
|
257
|
-
.pointer(&format!("{}/minimum", schema_prop_path))
|
|
258
|
-
.and_then(|v| v.as_i64())
|
|
259
|
-
{
|
|
260
|
-
let ctx = serde_json::json!({"ge": min_val});
|
|
261
|
-
(
|
|
262
|
-
"greater_than_equal".to_string(),
|
|
263
|
-
format!("Input should be greater than or equal to {}", min_val),
|
|
264
|
-
Some(ctx),
|
|
265
|
-
)
|
|
266
|
-
} else {
|
|
267
|
-
(
|
|
268
|
-
"greater_than_equal".to_string(),
|
|
269
|
-
"Input should be greater than or equal to the minimum".to_string(),
|
|
270
|
-
None,
|
|
271
|
-
)
|
|
272
|
-
}
|
|
273
|
-
} else if schema_path_str.contains("exclusiveMaximum")
|
|
274
|
-
|| (error_msg.contains("greater than or equal to") && error_msg.contains("maximum"))
|
|
275
|
-
{
|
|
276
|
-
if let Some(max_val) = self
|
|
277
|
-
.schema
|
|
278
|
-
.pointer(&format!("{}/exclusiveMaximum", schema_prop_path))
|
|
279
|
-
.and_then(|v| v.as_i64())
|
|
280
|
-
{
|
|
281
|
-
let ctx = serde_json::json!({"lt": max_val});
|
|
282
|
-
(
|
|
283
|
-
"less_than".to_string(),
|
|
284
|
-
format!("Input should be less than {}", max_val),
|
|
285
|
-
Some(ctx),
|
|
286
|
-
)
|
|
287
|
-
} else {
|
|
288
|
-
(
|
|
289
|
-
"less_than".to_string(),
|
|
290
|
-
"Input should be less than the maximum".to_string(),
|
|
291
|
-
None,
|
|
292
|
-
)
|
|
207
|
+
let mut error_condition = ErrorCondition::from_schema_error(schema_path_str, &error_msg);
|
|
208
|
+
|
|
209
|
+
error_condition = match error_condition {
|
|
210
|
+
ErrorCondition::TypeMismatch { .. } => {
|
|
211
|
+
let expected_type = self
|
|
212
|
+
.schema
|
|
213
|
+
.pointer(&format!("{}/type", schema_prop_path))
|
|
214
|
+
.and_then(|v| v.as_str())
|
|
215
|
+
.unwrap_or("unknown")
|
|
216
|
+
.to_string();
|
|
217
|
+
ErrorCondition::TypeMismatch { expected_type }
|
|
293
218
|
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
.pointer(&format!("{}/maximum", schema_prop_path))
|
|
298
|
-
.and_then(|v| v.as_i64())
|
|
299
|
-
{
|
|
300
|
-
let ctx = serde_json::json!({"le": max_val});
|
|
301
|
-
(
|
|
302
|
-
"less_than_equal".to_string(),
|
|
303
|
-
format!("Input should be less than or equal to {}", max_val),
|
|
304
|
-
Some(ctx),
|
|
305
|
-
)
|
|
306
|
-
} else {
|
|
307
|
-
(
|
|
308
|
-
"less_than_equal".to_string(),
|
|
309
|
-
"Input should be less than or equal to the maximum".to_string(),
|
|
310
|
-
None,
|
|
311
|
-
)
|
|
312
|
-
}
|
|
313
|
-
} else if schema_path_str.contains("enum") || error_msg.contains("is not one of") {
|
|
314
|
-
if let Some(enum_values) = self
|
|
315
|
-
.schema
|
|
316
|
-
.pointer(&format!("{}/enum", schema_prop_path))
|
|
317
|
-
.and_then(|v| v.as_array())
|
|
318
|
-
{
|
|
319
|
-
let values: Vec<String> = enum_values
|
|
320
|
-
.iter()
|
|
321
|
-
.filter_map(|v| v.as_str().map(|s| format!("'{}'", s)))
|
|
322
|
-
.collect();
|
|
323
|
-
|
|
324
|
-
let msg = if values.len() > 1 {
|
|
325
|
-
let last = values.last().unwrap();
|
|
326
|
-
let rest = &values[..values.len() - 1];
|
|
327
|
-
format!("Input should be {} or {}", rest.join(", "), last)
|
|
328
|
-
} else if !values.is_empty() {
|
|
329
|
-
format!("Input should be {}", values[0])
|
|
330
|
-
} else {
|
|
331
|
-
"Input should be one of the allowed values".to_string()
|
|
332
|
-
};
|
|
333
|
-
|
|
334
|
-
let expected_str = if values.len() > 1 {
|
|
335
|
-
let last = values.last().unwrap();
|
|
336
|
-
let rest = &values[..values.len() - 1];
|
|
337
|
-
format!("{} or {}", rest.join(", "), last)
|
|
338
|
-
} else if !values.is_empty() {
|
|
339
|
-
values[0].clone()
|
|
219
|
+
ErrorCondition::AdditionalProperties { .. } => {
|
|
220
|
+
let unexpected_field = if param_name.contains('/') {
|
|
221
|
+
param_name.split('/').next_back().unwrap_or(¶m_name).to_string()
|
|
340
222
|
} else {
|
|
341
|
-
|
|
223
|
+
param_name.clone()
|
|
342
224
|
};
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
} else {
|
|
346
|
-
(
|
|
347
|
-
"enum".to_string(),
|
|
348
|
-
"Input should be one of the allowed values".to_string(),
|
|
349
|
-
None,
|
|
350
|
-
)
|
|
351
|
-
}
|
|
352
|
-
} else if schema_path_str.contains("pattern") || error_msg.contains("does not match") {
|
|
353
|
-
if let Some(pattern) = self
|
|
354
|
-
.schema
|
|
355
|
-
.pointer(&format!("{}/pattern", schema_prop_path))
|
|
356
|
-
.and_then(|v| v.as_str())
|
|
357
|
-
{
|
|
358
|
-
let ctx = serde_json::json!({"pattern": pattern});
|
|
359
|
-
let msg = format!("String should match pattern '{}'", pattern);
|
|
360
|
-
("string_pattern_mismatch".to_string(), msg, Some(ctx))
|
|
361
|
-
} else {
|
|
362
|
-
(
|
|
363
|
-
"string_pattern_mismatch".to_string(),
|
|
364
|
-
"String does not match expected pattern".to_string(),
|
|
365
|
-
None,
|
|
366
|
-
)
|
|
367
|
-
}
|
|
368
|
-
} else if schema_path_str.contains("format") {
|
|
369
|
-
if error_msg.contains("email") {
|
|
370
|
-
let email_pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
|
|
371
|
-
let ctx = serde_json::json!({"pattern": email_pattern});
|
|
372
|
-
(
|
|
373
|
-
"string_pattern_mismatch".to_string(),
|
|
374
|
-
format!("String should match pattern '{}'", email_pattern),
|
|
375
|
-
Some(ctx),
|
|
376
|
-
)
|
|
377
|
-
} else if error_msg.contains("uuid") {
|
|
378
|
-
(
|
|
379
|
-
"uuid_parsing".to_string(),
|
|
380
|
-
"Input should be a valid UUID".to_string(),
|
|
381
|
-
None,
|
|
382
|
-
)
|
|
383
|
-
} else if error_msg.contains("date-time") {
|
|
384
|
-
(
|
|
385
|
-
"datetime_parsing".to_string(),
|
|
386
|
-
"Input should be a valid datetime".to_string(),
|
|
387
|
-
None,
|
|
388
|
-
)
|
|
389
|
-
} else if error_msg.contains("date") {
|
|
390
|
-
(
|
|
391
|
-
"date_parsing".to_string(),
|
|
392
|
-
"Input should be a valid date".to_string(),
|
|
393
|
-
None,
|
|
394
|
-
)
|
|
395
|
-
} else {
|
|
396
|
-
("format_error".to_string(), err.to_string(), None)
|
|
397
|
-
}
|
|
398
|
-
} else if schema_path_str.contains("/type") {
|
|
399
|
-
let expected_type = self
|
|
400
|
-
.schema
|
|
401
|
-
.pointer(&format!("{}/type", schema_prop_path))
|
|
402
|
-
.and_then(|v| v.as_str())
|
|
403
|
-
.unwrap_or("unknown");
|
|
404
|
-
|
|
405
|
-
let (error_type, msg) = match expected_type {
|
|
406
|
-
"integer" => (
|
|
407
|
-
"int_parsing".to_string(),
|
|
408
|
-
"Input should be a valid integer, unable to parse string as an integer".to_string(),
|
|
409
|
-
),
|
|
410
|
-
"number" => (
|
|
411
|
-
"float_parsing".to_string(),
|
|
412
|
-
"Input should be a valid number, unable to parse string as a number".to_string(),
|
|
413
|
-
),
|
|
414
|
-
"boolean" => (
|
|
415
|
-
"bool_parsing".to_string(),
|
|
416
|
-
"Input should be a valid boolean".to_string(),
|
|
417
|
-
),
|
|
418
|
-
"string" => ("string_type".to_string(), "Input should be a valid string".to_string()),
|
|
419
|
-
_ => (
|
|
420
|
-
"type_error".to_string(),
|
|
421
|
-
format!("Input should be a valid {}", expected_type),
|
|
422
|
-
),
|
|
423
|
-
};
|
|
424
|
-
(error_type, msg, None)
|
|
425
|
-
} else if schema_path_str.ends_with("/required") {
|
|
426
|
-
("missing".to_string(), "Field required".to_string(), None)
|
|
427
|
-
} else if schema_path_str.contains("/additionalProperties")
|
|
428
|
-
|| error_msg.contains("Additional properties are not allowed")
|
|
429
|
-
{
|
|
430
|
-
let unexpected_field = if param_name.contains('/') {
|
|
431
|
-
param_name.split('/').next_back().unwrap_or(¶m_name).to_string()
|
|
432
|
-
} else {
|
|
433
|
-
param_name.clone()
|
|
434
|
-
};
|
|
435
|
-
|
|
436
|
-
let ctx = serde_json::json!({
|
|
437
|
-
"additional_properties": false,
|
|
438
|
-
"unexpected_field": unexpected_field
|
|
439
|
-
});
|
|
440
|
-
(
|
|
441
|
-
"validation_error".to_string(),
|
|
442
|
-
"Additional properties are not allowed".to_string(),
|
|
443
|
-
Some(ctx),
|
|
444
|
-
)
|
|
445
|
-
} else if schema_path_str.contains("/minItems") {
|
|
446
|
-
let min_items = if let Some(start) = schema_path_str.rfind('/') {
|
|
447
|
-
if let Some(_min_idx) = schema_path_str[..start].rfind("/minItems") {
|
|
448
|
-
1
|
|
449
|
-
} else {
|
|
450
|
-
1
|
|
225
|
+
ErrorCondition::AdditionalProperties {
|
|
226
|
+
field: unexpected_field,
|
|
451
227
|
}
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
};
|
|
455
|
-
|
|
456
|
-
let ctx = serde_json::json!({
|
|
457
|
-
"min_length": min_items
|
|
458
|
-
});
|
|
459
|
-
(
|
|
460
|
-
"too_short".to_string(),
|
|
461
|
-
format!("List should have at least {} item after validation", min_items),
|
|
462
|
-
Some(ctx),
|
|
463
|
-
)
|
|
464
|
-
} else if schema_path_str.contains("/maxItems") {
|
|
465
|
-
let ctx = serde_json::json!({
|
|
466
|
-
"max_length": 1
|
|
467
|
-
});
|
|
468
|
-
(
|
|
469
|
-
"too_long".to_string(),
|
|
470
|
-
"List should have at most N items after validation".to_string(),
|
|
471
|
-
Some(ctx),
|
|
472
|
-
)
|
|
473
|
-
} else {
|
|
474
|
-
("validation_error".to_string(), err.to_string(), None)
|
|
228
|
+
}
|
|
229
|
+
other => other,
|
|
475
230
|
};
|
|
476
231
|
|
|
232
|
+
let (error_type, msg, ctx) =
|
|
233
|
+
ErrorMapper::map_error(&error_condition, &self.schema, &schema_prop_path, &error_msg);
|
|
234
|
+
|
|
477
235
|
ValidationErrorDetail {
|
|
478
236
|
error_type,
|
|
479
237
|
loc: loc_parts,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "spikard-http"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.5.0"
|
|
4
4
|
edition = "2024"
|
|
5
5
|
authors = ["Na'aman Hirschfeld <nhirschfeld@gmail.com>"]
|
|
6
6
|
license = "MIT"
|
|
@@ -13,21 +13,11 @@ documentation = "https://docs.rs/spikard-http"
|
|
|
13
13
|
readme = "README.md"
|
|
14
14
|
|
|
15
15
|
[dependencies]
|
|
16
|
-
axum = { version = "0.8", features = ["multipart", "ws"]
|
|
16
|
+
axum = { version = "0.8", features = ["multipart", "ws"] }
|
|
17
17
|
tokio = { version = "1", features = ["full"] }
|
|
18
18
|
tokio-util = "0.7"
|
|
19
19
|
tower = "0.5"
|
|
20
|
-
tower-http = { version = "0.6.
|
|
21
|
-
"trace",
|
|
22
|
-
"request-id",
|
|
23
|
-
"compression-gzip",
|
|
24
|
-
"compression-br",
|
|
25
|
-
"timeout",
|
|
26
|
-
"limit",
|
|
27
|
-
"fs",
|
|
28
|
-
"set-header",
|
|
29
|
-
"sensitive-headers",
|
|
30
|
-
] }
|
|
20
|
+
tower-http = { version = "0.6.8", features = ["trace", "request-id", "compression-gzip", "compression-br", "timeout", "limit", "fs", "set-header", "sensitive-headers"] }
|
|
31
21
|
tower_governor = "0.8"
|
|
32
22
|
jsonwebtoken = { version = "10.2", features = ["use_pem", "rust_crypto"] }
|
|
33
23
|
utoipa = { version = "5", features = ["axum_extras", "chrono", "uuid"] }
|
|
@@ -37,18 +27,20 @@ serde = { version = "1.0", features = ["derive"] }
|
|
|
37
27
|
serde_json = "1.0"
|
|
38
28
|
tracing = "0.1"
|
|
39
29
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
|
40
|
-
spikard-core = { path = "../spikard-core"
|
|
30
|
+
spikard-core = { path = "../spikard-core" }
|
|
41
31
|
futures-util = "0.3"
|
|
42
32
|
futures = "0.3"
|
|
43
33
|
jsonschema = { version = "0.37", default-features = false }
|
|
44
34
|
serde_qs = "0.15"
|
|
45
35
|
lazy_static = "1.5"
|
|
36
|
+
lru = "0.16"
|
|
46
37
|
regex = "1"
|
|
47
38
|
rustc-hash = "2.1"
|
|
48
39
|
urlencoding = "2.1"
|
|
40
|
+
url = "2.5"
|
|
49
41
|
mime = "0.3"
|
|
50
42
|
jiff = "0.2"
|
|
51
|
-
uuid = "1.
|
|
43
|
+
uuid = "1.19"
|
|
52
44
|
bytes = "1.11"
|
|
53
45
|
http-body-util = "0.1"
|
|
54
46
|
http-body = "1.0"
|
|
@@ -56,9 +48,12 @@ axum-test = { version = "18", features = ["ws"] }
|
|
|
56
48
|
anyhow = "1.0"
|
|
57
49
|
cookie = "0.18"
|
|
58
50
|
base64 = "0.22.1"
|
|
59
|
-
flate2 = "1.1"
|
|
51
|
+
flate2 = { version = "=1.1.5", default-features = false, features = ["rust_backend"] }
|
|
60
52
|
brotli = "8.0"
|
|
61
53
|
|
|
54
|
+
[lints]
|
|
55
|
+
workspace = true
|
|
56
|
+
|
|
62
57
|
[features]
|
|
63
58
|
default = []
|
|
64
59
|
di = ["spikard-core/di"]
|
|
@@ -66,3 +61,4 @@ di = ["spikard-core/di"]
|
|
|
66
61
|
[dev-dependencies]
|
|
67
62
|
chrono = "0.4"
|
|
68
63
|
doc-comment = "0.3"
|
|
64
|
+
tempfile = "3.23"
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#![allow(clippy::pedantic, clippy::nursery, clippy::all)]
|
|
2
|
+
//! SSE Notifications Server Example
|
|
3
|
+
//!
|
|
4
|
+
//! Demonstrates Server-Sent Events support in Spikard matching the AsyncAPI notifications specification.
|
|
5
|
+
|
|
6
|
+
use axum::{Router, routing::get};
|
|
7
|
+
use chrono::Utc;
|
|
8
|
+
use serde::Serialize;
|
|
9
|
+
use serde_json::json;
|
|
10
|
+
use spikard_http::{SseEvent, SseEventProducer, SseState, sse_handler};
|
|
11
|
+
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
12
|
+
use tokio::time::{Duration, sleep};
|
|
13
|
+
use tracing::info;
|
|
14
|
+
|
|
15
|
+
/// Notification event types matching AsyncAPI specification
|
|
16
|
+
#[derive(Debug, Clone, Serialize)]
|
|
17
|
+
#[serde(tag = "type")]
|
|
18
|
+
#[allow(clippy::enum_variant_names)]
|
|
19
|
+
enum Notification {
|
|
20
|
+
#[serde(rename = "system_alert")]
|
|
21
|
+
SystemAlert {
|
|
22
|
+
level: String,
|
|
23
|
+
message: String,
|
|
24
|
+
source: String,
|
|
25
|
+
timestamp: String,
|
|
26
|
+
},
|
|
27
|
+
#[serde(rename = "user_notification")]
|
|
28
|
+
UserNotification {
|
|
29
|
+
#[serde(rename = "userId")]
|
|
30
|
+
user_id: String,
|
|
31
|
+
title: String,
|
|
32
|
+
body: String,
|
|
33
|
+
priority: String,
|
|
34
|
+
timestamp: String,
|
|
35
|
+
},
|
|
36
|
+
#[serde(rename = "status_update")]
|
|
37
|
+
StatusUpdate {
|
|
38
|
+
service: String,
|
|
39
|
+
status: String,
|
|
40
|
+
message: Option<String>,
|
|
41
|
+
metadata: serde_json::Value,
|
|
42
|
+
timestamp: String,
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/// Notification producer implementing SseEventProducer trait
|
|
47
|
+
struct NotificationProducer {
|
|
48
|
+
counter: AtomicUsize,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
impl NotificationProducer {
|
|
52
|
+
fn new() -> Self {
|
|
53
|
+
Self {
|
|
54
|
+
counter: AtomicUsize::new(0),
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
fn create_notification(&self, index: usize) -> Notification {
|
|
59
|
+
let timestamp = Utc::now().to_rfc3339();
|
|
60
|
+
|
|
61
|
+
match index % 3 {
|
|
62
|
+
0 => Notification::SystemAlert {
|
|
63
|
+
level: "info".to_string(),
|
|
64
|
+
message: format!("System checkpoint {} reached", index),
|
|
65
|
+
source: "monitoring-system".to_string(),
|
|
66
|
+
timestamp,
|
|
67
|
+
},
|
|
68
|
+
1 => Notification::UserNotification {
|
|
69
|
+
user_id: format!("user_{}", index),
|
|
70
|
+
title: "New Update Available".to_string(),
|
|
71
|
+
body: format!("Version 1.{} is now available for download", index),
|
|
72
|
+
priority: "normal".to_string(),
|
|
73
|
+
timestamp,
|
|
74
|
+
},
|
|
75
|
+
_ => Notification::StatusUpdate {
|
|
76
|
+
service: "api-gateway".to_string(),
|
|
77
|
+
status: "operational".to_string(),
|
|
78
|
+
message: Some(format!("Health check {} passed", index)),
|
|
79
|
+
metadata: json!({
|
|
80
|
+
"response_time_ms": 50 + (index % 100),
|
|
81
|
+
"active_connections": 100 + (index % 50)
|
|
82
|
+
}),
|
|
83
|
+
timestamp,
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
impl SseEventProducer for NotificationProducer {
|
|
90
|
+
async fn next_event(&self) -> Option<SseEvent> {
|
|
91
|
+
sleep(Duration::from_secs(2)).await;
|
|
92
|
+
|
|
93
|
+
let count = self.counter.fetch_add(1, Ordering::Relaxed);
|
|
94
|
+
|
|
95
|
+
if count >= 10 {
|
|
96
|
+
info!("Completed sending 10 notifications");
|
|
97
|
+
return None;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
let notification = self.create_notification(count);
|
|
101
|
+
let event_type = match ¬ification {
|
|
102
|
+
Notification::SystemAlert { .. } => "system_alert",
|
|
103
|
+
Notification::UserNotification { .. } => "user_notification",
|
|
104
|
+
Notification::StatusUpdate { .. } => "status_update",
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
info!("Sending notification #{}: {}", count + 1, event_type);
|
|
108
|
+
|
|
109
|
+
let data = serde_json::to_value(notification).unwrap();
|
|
110
|
+
|
|
111
|
+
Some(
|
|
112
|
+
SseEvent::with_type(event_type, data)
|
|
113
|
+
.with_id(format!("event_{}", count))
|
|
114
|
+
.with_retry(3000),
|
|
115
|
+
)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async fn on_connect(&self) {
|
|
119
|
+
info!("Client connected to notifications stream");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async fn on_disconnect(&self) {
|
|
123
|
+
info!("Client disconnected from notifications stream");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
#[tokio::main]
|
|
128
|
+
async fn main() {
|
|
129
|
+
tracing_subscriber::fmt()
|
|
130
|
+
.with_env_filter("info,sse_notifications=debug")
|
|
131
|
+
.init();
|
|
132
|
+
|
|
133
|
+
let producer = NotificationProducer::new();
|
|
134
|
+
let sse_state = SseState::new(producer);
|
|
135
|
+
|
|
136
|
+
let app = Router::new()
|
|
137
|
+
.route("/notifications", get(sse_handler::<NotificationProducer>))
|
|
138
|
+
.with_state(sse_state);
|
|
139
|
+
|
|
140
|
+
let addr = "127.0.0.1:8000";
|
|
141
|
+
info!("SSE notifications server listening on {}", addr);
|
|
142
|
+
info!("Connect at: http://{}/notifications", addr);
|
|
143
|
+
info!("Try: curl -N http://{}/notifications", addr);
|
|
144
|
+
|
|
145
|
+
let listener = tokio::net::TcpListener::bind(addr).await.expect("Failed to bind");
|
|
146
|
+
|
|
147
|
+
axum::serve(listener, app).await.expect("Server error");
|
|
148
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#![allow(clippy::pedantic, clippy::nursery, clippy::all)]
|
|
2
|
+
//! WebSocket Chat Server Example
|
|
3
|
+
//!
|
|
4
|
+
//! Demonstrates WebSocket support in Spikard matching the AsyncAPI chat specification.
|
|
5
|
+
//! This server implements a simple chat system with three message types:
|
|
6
|
+
//! - chatMessage: User sends a chat message
|
|
7
|
+
//! - userJoined: User joins the chat
|
|
8
|
+
//! - userLeft: User leaves the chat
|
|
9
|
+
|
|
10
|
+
use axum::{Router, routing::get};
|
|
11
|
+
use serde::{Deserialize, Serialize};
|
|
12
|
+
use serde_json::Value;
|
|
13
|
+
use spikard_http::{WebSocketHandler, WebSocketState, websocket_handler};
|
|
14
|
+
use tracing::{info, warn};
|
|
15
|
+
|
|
16
|
+
/// Chat message types matching AsyncAPI specification
|
|
17
|
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
18
|
+
#[serde(tag = "type")]
|
|
19
|
+
#[allow(clippy::enum_variant_names)]
|
|
20
|
+
enum ChatMessage {
|
|
21
|
+
#[serde(rename = "message")]
|
|
22
|
+
ChatMessage {
|
|
23
|
+
user: String,
|
|
24
|
+
text: String,
|
|
25
|
+
timestamp: String,
|
|
26
|
+
},
|
|
27
|
+
#[serde(rename = "userJoined")]
|
|
28
|
+
UserJoined { user: String, timestamp: String },
|
|
29
|
+
#[serde(rename = "userLeft")]
|
|
30
|
+
UserLeft { user: String, timestamp: String },
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/// Chat handler implementing WebSocketHandler trait
|
|
34
|
+
struct ChatHandler;
|
|
35
|
+
|
|
36
|
+
impl WebSocketHandler for ChatHandler {
|
|
37
|
+
async fn handle_message(&self, message: Value) -> Option<Value> {
|
|
38
|
+
match serde_json::from_value::<ChatMessage>(message.clone()) {
|
|
39
|
+
Ok(chat_msg) => {
|
|
40
|
+
match chat_msg {
|
|
41
|
+
ChatMessage::ChatMessage { ref user, ref text, .. } => {
|
|
42
|
+
info!("Chat message from {}: {}", user, text);
|
|
43
|
+
}
|
|
44
|
+
ChatMessage::UserJoined { ref user, .. } => {
|
|
45
|
+
info!("User joined: {}", user);
|
|
46
|
+
}
|
|
47
|
+
ChatMessage::UserLeft { ref user, .. } => {
|
|
48
|
+
info!("User left: {}", user);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
Some(message)
|
|
53
|
+
}
|
|
54
|
+
Err(e) => {
|
|
55
|
+
warn!("Failed to parse chat message: {}", e);
|
|
56
|
+
Some(serde_json::json!({
|
|
57
|
+
"type": "error",
|
|
58
|
+
"message": format!("Invalid message format: {}", e)
|
|
59
|
+
}))
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async fn on_connect(&self) {
|
|
65
|
+
info!("Client connected to chat");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async fn on_disconnect(&self) {
|
|
69
|
+
info!("Client disconnected from chat");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
#[tokio::main]
|
|
74
|
+
async fn main() {
|
|
75
|
+
tracing_subscriber::fmt()
|
|
76
|
+
.with_env_filter("info,websocket_chat=debug")
|
|
77
|
+
.init();
|
|
78
|
+
|
|
79
|
+
let ws_state = WebSocketState::new(ChatHandler);
|
|
80
|
+
|
|
81
|
+
let app = Router::new()
|
|
82
|
+
.route("/chat", get(websocket_handler::<ChatHandler>))
|
|
83
|
+
.with_state(ws_state);
|
|
84
|
+
|
|
85
|
+
let addr = "127.0.0.1:8000";
|
|
86
|
+
info!("WebSocket chat server listening on {}", addr);
|
|
87
|
+
info!("Connect at: ws://{}/chat", addr);
|
|
88
|
+
|
|
89
|
+
let listener = tokio::net::TcpListener::bind(addr).await.expect("Failed to bind");
|
|
90
|
+
|
|
91
|
+
axum::serve(listener, app).await.expect("Server error");
|
|
92
|
+
}
|