spikard 0.12.0 → 0.15.2

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 (206) hide show
  1. checksums.yaml +4 -4
  2. data/Steepfile +6 -0
  3. data/ext/spikard_rb/extconf.rb +1 -2
  4. data/ext/spikard_rb/{Cargo.lock → native/Cargo.lock} +897 -451
  5. data/ext/spikard_rb/native/Cargo.toml +24 -0
  6. data/ext/spikard_rb/src/lib.rs +5366 -3
  7. data/lib/spikard/native.rb +86 -0
  8. data/lib/spikard/version.rb +6 -1
  9. data/lib/spikard.rb +8 -45
  10. data/lib/spikard_rb.so +0 -0
  11. data/sig/types.rbs +427 -0
  12. metadata +14 -242
  13. data/LICENSE +0 -1
  14. data/README.md +0 -267
  15. data/ext/spikard_rb/Cargo.toml +0 -17
  16. data/lib/spikard/app.rb +0 -428
  17. data/lib/spikard/background.rb +0 -58
  18. data/lib/spikard/config.rb +0 -506
  19. data/lib/spikard/converters.rb +0 -13
  20. data/lib/spikard/grpc.rb +0 -182
  21. data/lib/spikard/handler_wrapper.rb +0 -113
  22. data/lib/spikard/provide.rb +0 -214
  23. data/lib/spikard/response.rb +0 -173
  24. data/lib/spikard/schema.rb +0 -243
  25. data/lib/spikard/sse.rb +0 -111
  26. data/lib/spikard/streaming_response.rb +0 -44
  27. data/lib/spikard/testing.rb +0 -432
  28. data/lib/spikard/upload_file.rb +0 -131
  29. data/lib/spikard/websocket.rb +0 -59
  30. data/sig/spikard.rbs +0 -719
  31. data/vendor/crates/spikard-bindings-shared/Cargo.toml +0 -80
  32. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +0 -132
  33. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +0 -905
  34. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +0 -210
  35. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +0 -252
  36. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +0 -404
  37. data/vendor/crates/spikard-bindings-shared/src/grpc_metadata.rs +0 -199
  38. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +0 -252
  39. data/vendor/crates/spikard-bindings-shared/src/json_conversion.rs +0 -829
  40. data/vendor/crates/spikard-bindings-shared/src/lazy_cache.rs +0 -587
  41. data/vendor/crates/spikard-bindings-shared/src/lib.rs +0 -33
  42. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +0 -298
  43. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +0 -594
  44. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +0 -743
  45. data/vendor/crates/spikard-bindings-shared/src/response_interpreter.rs +0 -944
  46. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +0 -260
  47. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +0 -369
  48. data/vendor/crates/spikard-bindings-shared/tests/config_extractor_behavior.rs +0 -192
  49. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +0 -383
  50. data/vendor/crates/spikard-bindings-shared/tests/full_coverage.rs +0 -459
  51. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +0 -280
  52. data/vendor/crates/spikard-bindings-shared/tests/integration_tests.rs +0 -669
  53. data/vendor/crates/spikard-core/Cargo.toml +0 -60
  54. data/vendor/crates/spikard-core/src/bindings/mod.rs +0 -3
  55. data/vendor/crates/spikard-core/src/bindings/response.rs +0 -130
  56. data/vendor/crates/spikard-core/src/debug.rs +0 -127
  57. data/vendor/crates/spikard-core/src/di/container.rs +0 -702
  58. data/vendor/crates/spikard-core/src/di/dependency.rs +0 -273
  59. data/vendor/crates/spikard-core/src/di/error.rs +0 -118
  60. data/vendor/crates/spikard-core/src/di/factory.rs +0 -538
  61. data/vendor/crates/spikard-core/src/di/graph.rs +0 -507
  62. data/vendor/crates/spikard-core/src/di/mod.rs +0 -192
  63. data/vendor/crates/spikard-core/src/di/resolved.rs +0 -428
  64. data/vendor/crates/spikard-core/src/di/value.rs +0 -282
  65. data/vendor/crates/spikard-core/src/errors.rs +0 -72
  66. data/vendor/crates/spikard-core/src/http.rs +0 -492
  67. data/vendor/crates/spikard-core/src/lib.rs +0 -29
  68. data/vendor/crates/spikard-core/src/lifecycle.rs +0 -1273
  69. data/vendor/crates/spikard-core/src/metadata.rs +0 -378
  70. data/vendor/crates/spikard-core/src/parameters.rs +0 -2546
  71. data/vendor/crates/spikard-core/src/problem.rs +0 -358
  72. data/vendor/crates/spikard-core/src/request_data.rs +0 -1146
  73. data/vendor/crates/spikard-core/src/router.rs +0 -530
  74. data/vendor/crates/spikard-core/src/schema_registry.rs +0 -197
  75. data/vendor/crates/spikard-core/src/type_hints.rs +0 -311
  76. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +0 -710
  77. data/vendor/crates/spikard-core/src/validation/mod.rs +0 -470
  78. data/vendor/crates/spikard-core/tests/bindings_response_tests.rs +0 -136
  79. data/vendor/crates/spikard-core/tests/di_dependency_defaults.rs +0 -37
  80. data/vendor/crates/spikard-core/tests/error_mapper.rs +0 -761
  81. data/vendor/crates/spikard-core/tests/parameters_edge_cases.rs +0 -106
  82. data/vendor/crates/spikard-core/tests/parameters_full.rs +0 -701
  83. data/vendor/crates/spikard-core/tests/parameters_schema_and_formats.rs +0 -301
  84. data/vendor/crates/spikard-core/tests/request_data_roundtrip.rs +0 -67
  85. data/vendor/crates/spikard-core/tests/validation_coverage.rs +0 -250
  86. data/vendor/crates/spikard-core/tests/validation_error_paths.rs +0 -45
  87. data/vendor/crates/spikard-http/Cargo.toml +0 -87
  88. data/vendor/crates/spikard-http/examples/sse-notifications.rs +0 -148
  89. data/vendor/crates/spikard-http/examples/websocket-chat.rs +0 -92
  90. data/vendor/crates/spikard-http/src/auth.rs +0 -301
  91. data/vendor/crates/spikard-http/src/background.rs +0 -1860
  92. data/vendor/crates/spikard-http/src/bindings/mod.rs +0 -3
  93. data/vendor/crates/spikard-http/src/bindings/response.rs +0 -1
  94. data/vendor/crates/spikard-http/src/body_metadata.rs +0 -8
  95. data/vendor/crates/spikard-http/src/cors.rs +0 -1026
  96. data/vendor/crates/spikard-http/src/debug.rs +0 -128
  97. data/vendor/crates/spikard-http/src/di_handler.rs +0 -1672
  98. data/vendor/crates/spikard-http/src/grpc/framing.rs +0 -469
  99. data/vendor/crates/spikard-http/src/grpc/handler.rs +0 -1122
  100. data/vendor/crates/spikard-http/src/grpc/mod.rs +0 -434
  101. data/vendor/crates/spikard-http/src/grpc/service.rs +0 -622
  102. data/vendor/crates/spikard-http/src/grpc/streaming.rs +0 -319
  103. data/vendor/crates/spikard-http/src/handler_response.rs +0 -901
  104. data/vendor/crates/spikard-http/src/handler_trait.rs +0 -1015
  105. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +0 -290
  106. data/vendor/crates/spikard-http/src/jsonrpc/http_handler.rs +0 -502
  107. data/vendor/crates/spikard-http/src/jsonrpc/method_registry.rs +0 -648
  108. data/vendor/crates/spikard-http/src/jsonrpc/mod.rs +0 -58
  109. data/vendor/crates/spikard-http/src/jsonrpc/protocol.rs +0 -1207
  110. data/vendor/crates/spikard-http/src/jsonrpc/router.rs +0 -2262
  111. data/vendor/crates/spikard-http/src/lib.rs +0 -548
  112. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +0 -230
  113. data/vendor/crates/spikard-http/src/lifecycle.rs +0 -1193
  114. data/vendor/crates/spikard-http/src/middleware/mod.rs +0 -560
  115. data/vendor/crates/spikard-http/src/middleware/multipart.rs +0 -912
  116. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +0 -513
  117. data/vendor/crates/spikard-http/src/middleware/validation.rs +0 -768
  118. data/vendor/crates/spikard-http/src/openapi/mod.rs +0 -309
  119. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +0 -535
  120. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +0 -1363
  121. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +0 -667
  122. data/vendor/crates/spikard-http/src/query_parser.rs +0 -793
  123. data/vendor/crates/spikard-http/src/response.rs +0 -720
  124. data/vendor/crates/spikard-http/src/server/fast_router.rs +0 -186
  125. data/vendor/crates/spikard-http/src/server/grpc_routing.rs +0 -858
  126. data/vendor/crates/spikard-http/src/server/handler.rs +0 -1661
  127. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +0 -253
  128. data/vendor/crates/spikard-http/src/server/mod.rs +0 -1649
  129. data/vendor/crates/spikard-http/src/server/request_extraction.rs +0 -871
  130. data/vendor/crates/spikard-http/src/server/routing_factory.rs +0 -618
  131. data/vendor/crates/spikard-http/src/sse.rs +0 -1409
  132. data/vendor/crates/spikard-http/src/testing/form.rs +0 -52
  133. data/vendor/crates/spikard-http/src/testing/multipart.rs +0 -64
  134. data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -787
  135. data/vendor/crates/spikard-http/src/testing.rs +0 -617
  136. data/vendor/crates/spikard-http/src/websocket.rs +0 -1477
  137. data/vendor/crates/spikard-http/tests/auth_integration.rs +0 -645
  138. data/vendor/crates/spikard-http/tests/background_behavior.rs +0 -832
  139. data/vendor/crates/spikard-http/tests/common/grpc_helpers.rs +0 -1012
  140. data/vendor/crates/spikard-http/tests/common/handlers.rs +0 -309
  141. data/vendor/crates/spikard-http/tests/common/mod.rs +0 -33
  142. data/vendor/crates/spikard-http/tests/common/test_builders.rs +0 -628
  143. data/vendor/crates/spikard-http/tests/di_handler_error_responses.rs +0 -162
  144. data/vendor/crates/spikard-http/tests/di_integration.rs +0 -192
  145. data/vendor/crates/spikard-http/tests/doc_snippets.rs +0 -5
  146. data/vendor/crates/spikard-http/tests/grpc_bidirectional_streaming.rs +0 -430
  147. data/vendor/crates/spikard-http/tests/grpc_client_streaming.rs +0 -738
  148. data/vendor/crates/spikard-http/tests/grpc_error_handling_test.rs +0 -652
  149. data/vendor/crates/spikard-http/tests/grpc_integration_test.rs +0 -334
  150. data/vendor/crates/spikard-http/tests/grpc_metadata_test.rs +0 -532
  151. data/vendor/crates/spikard-http/tests/grpc_server_integration.rs +0 -495
  152. data/vendor/crates/spikard-http/tests/grpc_server_streaming.rs +0 -974
  153. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +0 -1093
  154. data/vendor/crates/spikard-http/tests/middleware_stack_integration.rs +0 -389
  155. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +0 -656
  156. data/vendor/crates/spikard-http/tests/request_extraction_full.rs +0 -513
  157. data/vendor/crates/spikard-http/tests/server_auth_middleware_behavior.rs +0 -328
  158. data/vendor/crates/spikard-http/tests/server_config_builder.rs +0 -314
  159. data/vendor/crates/spikard-http/tests/server_configured_router_behavior.rs +0 -200
  160. data/vendor/crates/spikard-http/tests/server_cors_preflight.rs +0 -83
  161. data/vendor/crates/spikard-http/tests/server_handler_wrappers.rs +0 -464
  162. data/vendor/crates/spikard-http/tests/server_method_router_additional_behavior.rs +0 -286
  163. data/vendor/crates/spikard-http/tests/server_method_router_coverage.rs +0 -118
  164. data/vendor/crates/spikard-http/tests/server_middleware_behavior.rs +0 -99
  165. data/vendor/crates/spikard-http/tests/server_middleware_branches.rs +0 -204
  166. data/vendor/crates/spikard-http/tests/server_openapi_jsonrpc_static.rs +0 -421
  167. data/vendor/crates/spikard-http/tests/server_router_behavior.rs +0 -121
  168. data/vendor/crates/spikard-http/tests/sse_behavior.rs +0 -620
  169. data/vendor/crates/spikard-http/tests/sse_full_behavior.rs +0 -584
  170. data/vendor/crates/spikard-http/tests/sse_handler_behavior.rs +0 -130
  171. data/vendor/crates/spikard-http/tests/test_client_requests.rs +0 -167
  172. data/vendor/crates/spikard-http/tests/testing_helpers.rs +0 -87
  173. data/vendor/crates/spikard-http/tests/testing_module_coverage.rs +0 -155
  174. data/vendor/crates/spikard-http/tests/urlencoded_content_type.rs +0 -82
  175. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +0 -663
  176. data/vendor/crates/spikard-http/tests/websocket_full_behavior.rs +0 -440
  177. data/vendor/crates/spikard-http/tests/websocket_integration.rs +0 -150
  178. data/vendor/crates/spikard-rb/Cargo.toml +0 -68
  179. data/vendor/crates/spikard-rb/build.rs +0 -200
  180. data/vendor/crates/spikard-rb/src/background.rs +0 -63
  181. data/vendor/crates/spikard-rb/src/config/mod.rs +0 -5
  182. data/vendor/crates/spikard-rb/src/config/server_config.rs +0 -401
  183. data/vendor/crates/spikard-rb/src/conversion.rs +0 -688
  184. data/vendor/crates/spikard-rb/src/di/builder.rs +0 -100
  185. data/vendor/crates/spikard-rb/src/di/mod.rs +0 -375
  186. data/vendor/crates/spikard-rb/src/grpc/handler.rs +0 -834
  187. data/vendor/crates/spikard-rb/src/grpc/mod.rs +0 -13
  188. data/vendor/crates/spikard-rb/src/gvl.rs +0 -80
  189. data/vendor/crates/spikard-rb/src/handler.rs +0 -699
  190. data/vendor/crates/spikard-rb/src/integration/mod.rs +0 -3
  191. data/vendor/crates/spikard-rb/src/lib.rs +0 -2264
  192. data/vendor/crates/spikard-rb/src/lifecycle.rs +0 -303
  193. data/vendor/crates/spikard-rb/src/metadata/mod.rs +0 -5
  194. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +0 -507
  195. data/vendor/crates/spikard-rb/src/request.rs +0 -439
  196. data/vendor/crates/spikard-rb/src/runtime/mod.rs +0 -5
  197. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +0 -344
  198. data/vendor/crates/spikard-rb/src/server.rs +0 -307
  199. data/vendor/crates/spikard-rb/src/sse.rs +0 -231
  200. data/vendor/crates/spikard-rb/src/testing/client.rs +0 -698
  201. data/vendor/crates/spikard-rb/src/testing/mod.rs +0 -7
  202. data/vendor/crates/spikard-rb/src/testing/sse.rs +0 -108
  203. data/vendor/crates/spikard-rb/src/testing/websocket.rs +0 -573
  204. data/vendor/crates/spikard-rb/src/websocket.rs +0 -475
  205. data/vendor/crates/spikard-rb-macros/Cargo.toml +0 -25
  206. data/vendor/crates/spikard-rb-macros/src/lib.rs +0 -51
@@ -1,87 +0,0 @@
1
- [package]
2
- name = "spikard-http"
3
- version = "0.12.0"
4
- edition = "2024"
5
- authors = ["Na'aman Hirschfeld <nhirschfeld@gmail.com>"]
6
- license = "MIT"
7
- repository = "https://github.com/Goldziher/spikard"
8
- homepage = "https://github.com/Goldziher/spikard"
9
- description = "High-performance HTTP server for Spikard with tower-http middleware stack"
10
- keywords = ["http", "server", "axum", "tower", "middleware"]
11
- categories = ["web-programming::http-server", "web-programming"]
12
- documentation = "https://docs.rs/spikard-http"
13
- readme = "README.md"
14
-
15
- [dependencies]
16
- axum = { version = "0.8", features = ["multipart", "ws"] }
17
- tokio = { version = "1", features = ["full"] }
18
- tokio-util = "0.7"
19
- tokio-stream = "0.1"
20
- tower = "0.5"
21
- tower-http = { version = "0.6.8", features = ["fs", "trace", "compression-gzip", "compression-br", "compression-deflate", "cors", "request-id", "limit", "timeout", "set-header", "sensitive-headers"] }
22
- tower_governor = "0.8"
23
- jsonwebtoken = { version = "10.2", features = ["use_pem", "rust_crypto"] }
24
- utoipa = { version = "5", features = ["axum_extras", "chrono", "uuid"] }
25
- utoipa-swagger-ui = { version = "9", features = ["axum"] }
26
- utoipa-redoc = { version = "6", features = ["axum"] }
27
- serde = { version = "1.0", features = ["derive"] }
28
- serde_json = "1.0"
29
- tracing = "0.1"
30
- tracing-subscriber = { version = "0.3", features = ["env-filter"] }
31
- spikard-core = { path = "../spikard-core" }
32
- futures-util = "0.3"
33
- futures = "0.3"
34
- jsonschema = { version = "0.37", default-features = false }
35
- serde_qs = "1.0"
36
- lazy_static = "1.5"
37
- lru = "0.16"
38
- regex = "1"
39
- rustc-hash = "2.1"
40
- urlencoding = "2.1"
41
- url = "2.5"
42
- mime = "0.3"
43
- jiff = "0.2"
44
- uuid = "1.21"
45
- ahash = "0.8"
46
- bytes = "1.11"
47
- http-body-util = "0.1"
48
- http-body = "1.0"
49
- axum-test = { version = "19", features = ["ws"] }
50
- anyhow = "1.0"
51
- cookie = "0.18"
52
- flate2 = { version = "=1.1.5", default-features = false, features = ["rust_backend"] }
53
- brotli = "8.0"
54
- tonic = { version = "0.14", features = ["transport", "codegen", "gzip"] }
55
- prost = "0.14"
56
- prost-types = "0.14"
57
- h2 = "0.4"
58
-
59
- [lints.rust]
60
- unexpected_cfgs = { level = "allow", check-cfg = ['cfg(tarpaulin_include)'] }
61
-
62
- [lints.clippy]
63
- all = { level = "deny", priority = 0 }
64
- pedantic = { level = "deny", priority = 0 }
65
- nursery = { level = "deny", priority = 0 }
66
-
67
- [features]
68
- default = []
69
- di = ["spikard-core/di"]
70
-
71
- [dev-dependencies]
72
- chrono = "0.4"
73
- doc-comment = "0.3"
74
- tempfile = "3.26"
75
-
76
- [package.metadata.cargo-machete]
77
- ignored = [
78
- "anyhow",
79
- "h2",
80
- "http-body",
81
- "jiff",
82
- "prost",
83
- "prost-types",
84
- "tokio-stream",
85
- "utoipa-redoc",
86
- "utoipa-swagger-ui",
87
- ]
@@ -1,148 +0,0 @@
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 &notification {
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
- }
@@ -1,92 +0,0 @@
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
- }
@@ -1,301 +0,0 @@
1
- //! Authentication middleware for JWT and API keys.
2
- //!
3
- //! This module provides tower middleware for authenticating requests using:
4
- //! - JWT tokens (via the Authorization header)
5
- //! - API keys (via custom headers)
6
-
7
- use axum::{
8
- body::Body,
9
- extract::Request,
10
- http::{HeaderMap, StatusCode, Uri},
11
- middleware::Next,
12
- response::{IntoResponse, Response},
13
- };
14
- use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
15
- use serde::{Deserialize, Serialize};
16
- use std::collections::HashSet;
17
-
18
- use crate::{ApiKeyConfig, JwtConfig, ProblemDetails};
19
-
20
- /// Standard type URI for authentication errors (401)
21
- const TYPE_AUTH_ERROR: &str = "https://spikard.dev/errors/unauthorized";
22
-
23
- /// Standard type URI for configuration errors (500)
24
- const TYPE_CONFIG_ERROR: &str = "https://spikard.dev/errors/configuration-error";
25
-
26
- /// Internal header key used to expose validated JWT claims to handlers.
27
- pub const INTERNAL_JWT_CLAIMS_HEADER: &str = "x-spikard-jwt-claims";
28
-
29
- /// JWT claims structure - can be extended based on needs
30
- #[derive(Debug, Clone, Serialize, Deserialize)]
31
- pub struct Claims {
32
- pub sub: String,
33
- pub exp: usize,
34
- #[serde(skip_serializing_if = "Option::is_none")]
35
- pub iat: Option<usize>,
36
- #[serde(skip_serializing_if = "Option::is_none")]
37
- pub nbf: Option<usize>,
38
- #[serde(skip_serializing_if = "Option::is_none")]
39
- pub aud: Option<Vec<String>>,
40
- #[serde(skip_serializing_if = "Option::is_none")]
41
- pub iss: Option<String>,
42
- }
43
-
44
- /// JWT authentication middleware
45
- ///
46
- /// Validates JWT tokens from the Authorization header (Bearer scheme).
47
- /// On success, the validated claims are available to downstream handlers.
48
- /// On failure, returns 401 Unauthorized with RFC 9457 Problem Details.
49
- ///
50
- /// Coverage: Tested via integration tests (`auth_integration.rs`)
51
- ///
52
- /// # Errors
53
- /// Returns an error response when the Authorization header is missing, malformed,
54
- /// the token is invalid, or configuration is incorrect.
55
- #[cfg(not(tarpaulin_include))]
56
- pub async fn jwt_auth_middleware(
57
- config: JwtConfig,
58
- headers: HeaderMap,
59
- request: Request<Body>,
60
- next: Next,
61
- ) -> Result<Response, Response> {
62
- let auth_header = headers
63
- .get("authorization")
64
- .and_then(|v| v.to_str().ok())
65
- .ok_or_else(|| {
66
- let problem = ProblemDetails::new(
67
- TYPE_AUTH_ERROR,
68
- "Missing or invalid Authorization header",
69
- StatusCode::UNAUTHORIZED,
70
- )
71
- .with_detail("Expected 'Authorization: Bearer <token>'");
72
- (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
73
- })?;
74
-
75
- let token = auth_header.strip_prefix("Bearer ").ok_or_else(|| {
76
- let problem = ProblemDetails::new(
77
- TYPE_AUTH_ERROR,
78
- "Invalid Authorization header format",
79
- StatusCode::UNAUTHORIZED,
80
- )
81
- .with_detail("Authorization header must use Bearer scheme: 'Bearer <token>'");
82
- (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
83
- })?;
84
-
85
- let parts: Vec<&str> = token.split('.').collect();
86
- if parts.len() != 3 {
87
- let problem = ProblemDetails::new(TYPE_AUTH_ERROR, "Malformed JWT token", StatusCode::UNAUTHORIZED)
88
- .with_detail(format!(
89
- "Malformed JWT token: expected 3 parts separated by dots, found {}",
90
- parts.len()
91
- ));
92
- return Err((StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response());
93
- }
94
-
95
- let algorithm = parse_algorithm(&config.algorithm).map_err(|_| {
96
- let problem = ProblemDetails::new(
97
- TYPE_CONFIG_ERROR,
98
- "Invalid JWT configuration",
99
- StatusCode::INTERNAL_SERVER_ERROR,
100
- )
101
- .with_detail(format!("Unsupported algorithm: {}", config.algorithm));
102
- (StatusCode::INTERNAL_SERVER_ERROR, axum::Json(problem)).into_response()
103
- })?;
104
-
105
- let mut validation = Validation::new(algorithm);
106
- if let Some(ref aud) = config.audience {
107
- validation.set_audience(aud);
108
- }
109
- if let Some(ref iss) = config.issuer {
110
- validation.set_issuer(std::slice::from_ref(iss));
111
- }
112
- validation.leeway = config.leeway;
113
- validation.validate_nbf = true;
114
-
115
- let decoding_key = DecodingKey::from_secret(config.secret.as_bytes());
116
- let token_data = decode::<Claims>(token, &decoding_key, &validation).map_err(|e| {
117
- let detail = match e.kind() {
118
- jsonwebtoken::errors::ErrorKind::ExpiredSignature => "Token has expired".to_string(),
119
- jsonwebtoken::errors::ErrorKind::InvalidToken => "Token is invalid".to_string(),
120
- jsonwebtoken::errors::ErrorKind::InvalidSignature | jsonwebtoken::errors::ErrorKind::Base64(_) => {
121
- "Token signature is invalid".to_string()
122
- }
123
- jsonwebtoken::errors::ErrorKind::InvalidAudience => "Token audience is invalid".to_string(),
124
- jsonwebtoken::errors::ErrorKind::InvalidIssuer => config.issuer.as_ref().map_or_else(
125
- || "Token issuer is invalid".to_string(),
126
- |expected_iss| format!("Token issuer is invalid, expected '{expected_iss}'"),
127
- ),
128
- jsonwebtoken::errors::ErrorKind::ImmatureSignature => {
129
- "JWT not valid yet, not before claim is in the future".to_string()
130
- }
131
- _ => format!("Token validation failed: {e}"),
132
- };
133
-
134
- let problem =
135
- ProblemDetails::new(TYPE_AUTH_ERROR, "JWT validation failed", StatusCode::UNAUTHORIZED).with_detail(detail);
136
- (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
137
- })?;
138
-
139
- let mut request = request;
140
- request.extensions_mut().insert(token_data.claims);
141
-
142
- Ok(next.run(request).await)
143
- }
144
-
145
- /// Parse JWT algorithm string to jsonwebtoken Algorithm enum
146
- fn parse_algorithm(alg: &str) -> Result<Algorithm, String> {
147
- match alg {
148
- "HS256" => Ok(Algorithm::HS256),
149
- "HS384" => Ok(Algorithm::HS384),
150
- "HS512" => Ok(Algorithm::HS512),
151
- "RS256" => Ok(Algorithm::RS256),
152
- "RS384" => Ok(Algorithm::RS384),
153
- "RS512" => Ok(Algorithm::RS512),
154
- "ES256" => Ok(Algorithm::ES256),
155
- "ES384" => Ok(Algorithm::ES384),
156
- "PS256" => Ok(Algorithm::PS256),
157
- "PS384" => Ok(Algorithm::PS384),
158
- "PS512" => Ok(Algorithm::PS512),
159
- _ => Err(format!("Unsupported algorithm: {alg}")),
160
- }
161
- }
162
-
163
- /// API Key authentication middleware
164
- ///
165
- /// Validates API keys from a custom header (default: X-API-Key) or query parameter.
166
- /// Checks header first, then query parameter as fallback.
167
- /// On success, the request proceeds to the next handler.
168
- /// On failure, returns 401 Unauthorized with RFC 9457 Problem Details.
169
- ///
170
- /// Coverage: Tested via integration tests (`auth_integration.rs`)
171
- ///
172
- /// # Errors
173
- /// Returns an error response when the API key is missing or invalid.
174
- #[cfg(not(tarpaulin_include))]
175
- pub async fn api_key_auth_middleware(
176
- config: ApiKeyConfig,
177
- headers: HeaderMap,
178
- request: Request<Body>,
179
- next: Next,
180
- ) -> Result<Response, Response> {
181
- let valid_keys: HashSet<String> = config.keys.into_iter().collect();
182
-
183
- let uri = request.uri().clone();
184
-
185
- let api_key_from_header = headers.get(&config.header_name).and_then(|v| v.to_str().ok());
186
-
187
- let api_key = api_key_from_header.map_or_else(|| extract_api_key_from_query(&uri), Some);
188
-
189
- let api_key = api_key.ok_or_else(|| {
190
- let problem =
191
- ProblemDetails::new(TYPE_AUTH_ERROR, "Missing API key", StatusCode::UNAUTHORIZED).with_detail(format!(
192
- "Expected '{}' header or 'api_key' query parameter with valid API key",
193
- config.header_name
194
- ));
195
- (StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response()
196
- })?;
197
-
198
- if !valid_keys.contains(api_key) {
199
- let problem = ProblemDetails::new(TYPE_AUTH_ERROR, "Invalid API key", StatusCode::UNAUTHORIZED)
200
- .with_detail("The provided API key is not valid");
201
- return Err((StatusCode::UNAUTHORIZED, axum::Json(problem)).into_response());
202
- }
203
-
204
- Ok(next.run(request).await)
205
- }
206
-
207
- /// Extract API key from query parameters
208
- ///
209
- /// Checks for common API key parameter names: api_key, apiKey, key
210
- fn extract_api_key_from_query(uri: &Uri) -> Option<&str> {
211
- let query = uri.query()?;
212
-
213
- for param in query.split('&') {
214
- if let Some((key, value)) = param.split_once('=')
215
- && (key == "api_key" || key == "apiKey" || key == "key")
216
- {
217
- return Some(value);
218
- }
219
- }
220
-
221
- None
222
- }
223
-
224
- #[cfg(test)]
225
- mod tests {
226
- use super::*;
227
-
228
- #[test]
229
- fn test_parse_algorithm() {
230
- assert!(matches!(parse_algorithm("HS256"), Ok(Algorithm::HS256)));
231
- assert!(matches!(parse_algorithm("HS384"), Ok(Algorithm::HS384)));
232
- assert!(matches!(parse_algorithm("HS512"), Ok(Algorithm::HS512)));
233
- assert!(matches!(parse_algorithm("RS256"), Ok(Algorithm::RS256)));
234
- assert!(matches!(parse_algorithm("RS384"), Ok(Algorithm::RS384)));
235
- assert!(matches!(parse_algorithm("RS512"), Ok(Algorithm::RS512)));
236
- assert!(matches!(parse_algorithm("ES256"), Ok(Algorithm::ES256)));
237
- assert!(matches!(parse_algorithm("ES384"), Ok(Algorithm::ES384)));
238
- assert!(matches!(parse_algorithm("PS256"), Ok(Algorithm::PS256)));
239
- assert!(matches!(parse_algorithm("PS384"), Ok(Algorithm::PS384)));
240
- assert!(matches!(parse_algorithm("PS512"), Ok(Algorithm::PS512)));
241
- assert!(parse_algorithm("INVALID").is_err());
242
- }
243
-
244
- #[test]
245
- fn test_claims_serialization() {
246
- let claims = Claims {
247
- sub: "user123".to_string(),
248
- exp: 1234567890,
249
- iat: Some(1234567800),
250
- nbf: None,
251
- aud: Some(vec!["https://api.example.com".to_string()]),
252
- iss: Some("https://auth.example.com".to_string()),
253
- };
254
-
255
- let json = serde_json::to_string(&claims).unwrap();
256
- assert!(json.contains("user123"));
257
- assert!(json.contains("1234567890"));
258
- }
259
-
260
- #[test]
261
- fn test_extract_api_key_from_query_api_key() {
262
- let uri: axum::http::Uri = "/api/endpoint?api_key=secret123".parse().unwrap();
263
- let result = extract_api_key_from_query(&uri);
264
- assert_eq!(result, Some("secret123"));
265
- }
266
-
267
- #[test]
268
- fn test_extract_api_key_from_query_api_key_camel_case() {
269
- let uri: axum::http::Uri = "/api/endpoint?apiKey=mykey456".parse().unwrap();
270
- let result = extract_api_key_from_query(&uri);
271
- assert_eq!(result, Some("mykey456"));
272
- }
273
-
274
- #[test]
275
- fn test_extract_api_key_from_query_key() {
276
- let uri: axum::http::Uri = "/api/endpoint?key=testkey789".parse().unwrap();
277
- let result = extract_api_key_from_query(&uri);
278
- assert_eq!(result, Some("testkey789"));
279
- }
280
-
281
- #[test]
282
- fn test_extract_api_key_from_query_no_key() {
283
- let uri: axum::http::Uri = "/api/endpoint?foo=bar&baz=qux".parse().unwrap();
284
- let result = extract_api_key_from_query(&uri);
285
- assert_eq!(result, None);
286
- }
287
-
288
- #[test]
289
- fn test_extract_api_key_from_query_empty_string() {
290
- let uri: axum::http::Uri = "/api/endpoint".parse().unwrap();
291
- let result = extract_api_key_from_query(&uri);
292
- assert_eq!(result, None);
293
- }
294
-
295
- #[test]
296
- fn test_extract_api_key_from_query_multiple_params() {
297
- let uri: axum::http::Uri = "/api/endpoint?foo=bar&api_key=found&baz=qux".parse().unwrap();
298
- let result = extract_api_key_from_query(&uri);
299
- assert_eq!(result, Some("found"));
300
- }
301
- }