spikard 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -674
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +13 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +405 -405
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -13
  11. data/lib/spikard/handler_wrapper.rb +113 -113
  12. data/lib/spikard/provide.rb +214 -214
  13. data/lib/spikard/response.rb +173 -173
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -44
  17. data/lib/spikard/testing.rb +256 -256
  18. data/lib/spikard/upload_file.rb +131 -131
  19. data/lib/spikard/version.rb +5 -5
  20. data/lib/spikard/websocket.rb +59 -59
  21. data/lib/spikard.rb +43 -43
  22. data/sig/spikard.rbs +366 -366
  23. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -63
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -132
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -752
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -194
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -246
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -401
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -238
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -24
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -292
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -616
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -305
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -248
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -351
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -454
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -383
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -280
  39. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  40. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  41. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  42. data/vendor/crates/spikard-core/src/debug.rs +127 -127
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -702
  44. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  45. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  46. data/vendor/crates/spikard-core/src/di/factory.rs +534 -534
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -506
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -405
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -281
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -69
  52. data/vendor/crates/spikard-core/src/http.rs +415 -415
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -1186
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -389
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -2525
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -344
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -1154
  59. data/vendor/crates/spikard-core/src/router.rs +510 -510
  60. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  61. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  62. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +696 -688
  63. data/vendor/crates/spikard-core/src/validation/mod.rs +457 -457
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -64
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -148
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -92
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -296
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -1860
  69. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  70. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  71. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  72. data/vendor/crates/spikard-http/src/cors.rs +1005 -1005
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -128
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -1668
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -901
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +838 -830
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -290
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -534
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -230
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -1193
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -540
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -912
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -513
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -735
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -535
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -1363
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -665
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -793
  90. data/vendor/crates/spikard-http/src/response.rs +720 -720
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -1650
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -234
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1593 -1502
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -770
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -599
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -1409
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -52
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -283
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -1375
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -832
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -309
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -26
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -192
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -5
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -1093
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -656
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -314
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -620
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -663
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -48
  113. data/vendor/crates/spikard-rb/build.rs +199 -199
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -5
  116. data/vendor/crates/spikard-rb/src/config/server_config.rs +285 -285
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -554
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -100
  119. data/vendor/crates/spikard-rb/src/di/mod.rs +375 -375
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -618
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -3
  122. data/vendor/crates/spikard-rb/src/lib.rs +1806 -1810
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -275
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -5
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -447
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -5
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -324
  128. data/vendor/crates/spikard-rb/src/server.rs +305 -308
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/testing/client.rs +538 -551
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -7
  132. data/vendor/crates/spikard-rb/src/testing/sse.rs +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -635
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -374
  135. metadata +15 -1
@@ -1,230 +1,230 @@
1
- //! Shared utilities for lifecycle hook implementations across language bindings.
2
- //!
3
- //! This module provides common error messages, hook registration patterns, and
4
- //! serialization utilities to eliminate duplication across Python, Node.js,
5
- //! Ruby, and WASM bindings.
6
-
7
- use crate::lifecycle::LifecycleHook;
8
- use axum::body::Body;
9
- use axum::http::{Request, Response};
10
- use std::sync::Arc;
11
-
12
- /// Standard error message formatters for lifecycle hooks.
13
- /// These are used consistently across all language bindings.
14
- pub mod error {
15
- use std::fmt::Display;
16
-
17
- /// Format error when a hook invocation fails
18
- pub fn call_failed(hook_name: &str, reason: impl Display) -> String {
19
- format!("Hook '{}' call failed: {}", hook_name, reason)
20
- }
21
-
22
- /// Format error when a task execution fails (tokio/threading)
23
- pub fn task_error(hook_name: &str, reason: impl Display) -> String {
24
- format!("Hook '{}' task error: {}", hook_name, reason)
25
- }
26
-
27
- /// Format error when a promise/future fails
28
- pub fn promise_failed(hook_name: &str, reason: impl Display) -> String {
29
- format!("Hook '{}' promise failed: {}", hook_name, reason)
30
- }
31
-
32
- /// Format error for Python-specific failures
33
- pub fn python_error(hook_name: &str, reason: impl Display) -> String {
34
- format!("Hook '{}' Python error: {}", hook_name, reason)
35
- }
36
-
37
- /// Format error when body reading fails
38
- pub fn body_read_failed(direction: &str, reason: impl Display) -> String {
39
- format!("Failed to read {} body: {}", direction, reason)
40
- }
41
-
42
- /// Format error when body writing fails
43
- pub fn body_write_failed(reason: impl Display) -> String {
44
- format!("Failed to write body: {}", reason)
45
- }
46
-
47
- /// Format error for serialization failures
48
- pub fn serialize_failed(context: &str, reason: impl Display) -> String {
49
- format!("Failed to serialize {}: {}", context, reason)
50
- }
51
-
52
- /// Format error for deserialization failures
53
- pub fn deserialize_failed(context: &str, reason: impl Display) -> String {
54
- format!("Failed to deserialize {}: {}", context, reason)
55
- }
56
-
57
- /// Format error when building HTTP objects fails
58
- pub fn build_failed(what: &str, reason: impl Display) -> String {
59
- format!("Failed to build {}: {}", what, reason)
60
- }
61
- }
62
-
63
- /// Utilities for serializing/deserializing request and response bodies
64
- pub mod serial {
65
- use super::*;
66
-
67
- /// Extract body bytes from an axum Body
68
- pub async fn extract_body(body: Body) -> Result<bytes::Bytes, String> {
69
- use axum::body::to_bytes;
70
- to_bytes(body, usize::MAX)
71
- .await
72
- .map_err(|e| error::body_read_failed("request/response", e))
73
- }
74
-
75
- /// Create a JSON-formatted response body
76
- pub fn json_response_body(json: &serde_json::Value) -> Result<Body, String> {
77
- serde_json::to_string(json)
78
- .map(Body::from)
79
- .map_err(|e| error::serialize_failed("response JSON", e))
80
- }
81
-
82
- /// Parse a JSON value from bytes
83
- pub fn parse_json(bytes: &[u8]) -> Result<serde_json::Value, String> {
84
- if bytes.is_empty() {
85
- return Ok(serde_json::Value::Null);
86
- }
87
- serde_json::from_slice(bytes)
88
- .or_else(|_| Ok(serde_json::Value::String(String::from_utf8_lossy(bytes).to_string())))
89
- }
90
- }
91
-
92
- /// Re-export of the HTTP-specific lifecycle hooks type alias
93
- pub use super::LifecycleHooks as HttpLifecycleHooks;
94
-
95
- /// Helper for registering hooks with standard naming conventions
96
- pub struct HookRegistry;
97
-
98
- impl HookRegistry {
99
- /// Extract hooks from a configuration and register them with a naming pattern
100
- /// Used by bindings to standardize hook naming (e.g., "on_request_hook_0")
101
- pub fn register_from_list<F>(
102
- hooks: &mut HttpLifecycleHooks,
103
- hook_list: Vec<Arc<dyn LifecycleHook<Request<Body>, Response<Body>>>>,
104
- _hook_type: &str,
105
- register_fn: F,
106
- ) where
107
- F: Fn(&mut HttpLifecycleHooks, Arc<dyn LifecycleHook<Request<Body>, Response<Body>>>),
108
- {
109
- for hook in hook_list {
110
- register_fn(hooks, hook);
111
- }
112
- }
113
- }
114
-
115
- #[cfg(test)]
116
- mod tests {
117
- use super::*;
118
- use crate::lifecycle::HookResult;
119
- use axum::body::Body;
120
- use axum::http::{Request, Response, StatusCode};
121
- use std::future::Future;
122
- use std::pin::Pin;
123
-
124
- #[test]
125
- fn test_error_messages() {
126
- let call_err = error::call_failed("test_hook", "test reason");
127
- assert!(call_err.contains("test_hook"));
128
- assert!(call_err.contains("test reason"));
129
-
130
- let task_err = error::task_error("task_hook", "spawn failed");
131
- assert!(task_err.contains("task_hook"));
132
-
133
- let promise_err = error::promise_failed("promise_hook", "rejected");
134
- assert!(promise_err.contains("promise_hook"));
135
- }
136
-
137
- #[test]
138
- fn test_body_error_messages() {
139
- let read_err = error::body_read_failed("request", "stream closed");
140
- assert!(read_err.contains("request"));
141
-
142
- let write_err = error::body_write_failed("allocation failed");
143
- assert!(write_err.contains("allocation"));
144
- }
145
-
146
- #[test]
147
- fn test_json_error_messages() {
148
- let ser_err = error::serialize_failed("request body", "invalid type");
149
- assert!(ser_err.contains("request body"));
150
-
151
- let deser_err = error::deserialize_failed("response", "malformed");
152
- assert!(deser_err.contains("response"));
153
- }
154
-
155
- #[tokio::test]
156
- async fn serial_extract_body_roundtrips_bytes() {
157
- let body = Body::from("hello");
158
- let bytes = serial::extract_body(body).await.expect("extract body");
159
- assert_eq!(&bytes[..], b"hello");
160
- }
161
-
162
- #[test]
163
- fn serial_parse_json_handles_empty_valid_and_invalid_json() {
164
- let empty = serial::parse_json(&[]).expect("parse empty");
165
- assert_eq!(empty, serde_json::Value::Null);
166
-
167
- let valid = serial::parse_json(br#"{"ok":true}"#).expect("parse json");
168
- assert_eq!(valid["ok"], true);
169
-
170
- let invalid = serial::parse_json(b"not-json").expect("parse fallback");
171
- assert_eq!(invalid, serde_json::Value::String("not-json".to_string()));
172
- }
173
-
174
- #[test]
175
- fn hook_registry_registers_all_hooks_via_callback() {
176
- struct NoopHook {
177
- hook_name: String,
178
- }
179
-
180
- impl LifecycleHook<Request<Body>, Response<Body>> for NoopHook {
181
- fn name(&self) -> &str {
182
- &self.hook_name
183
- }
184
-
185
- fn execute_request<'a>(
186
- &'a self,
187
- req: Request<Body>,
188
- ) -> Pin<Box<dyn Future<Output = Result<HookResult<Request<Body>, Response<Body>>, String>> + Send + 'a>>
189
- {
190
- Box::pin(async move { Ok(HookResult::Continue(req)) })
191
- }
192
-
193
- fn execute_response<'a>(
194
- &'a self,
195
- resp: Response<Body>,
196
- ) -> Pin<Box<dyn Future<Output = Result<HookResult<Response<Body>, Response<Body>>, String>> + Send + 'a>>
197
- {
198
- Box::pin(async move { Ok(HookResult::Continue(resp)) })
199
- }
200
- }
201
-
202
- let mut hooks = HttpLifecycleHooks::new();
203
- assert!(hooks.is_empty());
204
-
205
- let hook_list: Vec<Arc<dyn LifecycleHook<Request<Body>, Response<Body>>>> = vec![
206
- Arc::new(NoopHook {
207
- hook_name: "one".to_string(),
208
- }),
209
- Arc::new(NoopHook {
210
- hook_name: "two".to_string(),
211
- }),
212
- ];
213
-
214
- HookRegistry::register_from_list(&mut hooks, hook_list, "on_request", |hooks, hook| {
215
- hooks.add_on_request(hook);
216
- });
217
-
218
- let dbg = format!("{:?}", hooks);
219
- assert!(dbg.contains("on_request_count"));
220
- assert!(dbg.contains("2"));
221
-
222
- let req = Request::builder().body(Body::empty()).unwrap();
223
- let result = futures::executor::block_on(hooks.execute_on_request(req)).expect("hook run");
224
- assert!(matches!(result, HookResult::Continue(_)));
225
-
226
- let resp = Response::builder().status(StatusCode::OK).body(Body::empty()).unwrap();
227
- let resp = futures::executor::block_on(hooks.execute_on_response(resp)).expect("hook run");
228
- assert_eq!(resp.status(), StatusCode::OK);
229
- }
230
- }
1
+ //! Shared utilities for lifecycle hook implementations across language bindings.
2
+ //!
3
+ //! This module provides common error messages, hook registration patterns, and
4
+ //! serialization utilities to eliminate duplication across Python, Node.js,
5
+ //! Ruby, and WASM bindings.
6
+
7
+ use crate::lifecycle::LifecycleHook;
8
+ use axum::body::Body;
9
+ use axum::http::{Request, Response};
10
+ use std::sync::Arc;
11
+
12
+ /// Standard error message formatters for lifecycle hooks.
13
+ /// These are used consistently across all language bindings.
14
+ pub mod error {
15
+ use std::fmt::Display;
16
+
17
+ /// Format error when a hook invocation fails
18
+ pub fn call_failed(hook_name: &str, reason: impl Display) -> String {
19
+ format!("Hook '{}' call failed: {}", hook_name, reason)
20
+ }
21
+
22
+ /// Format error when a task execution fails (tokio/threading)
23
+ pub fn task_error(hook_name: &str, reason: impl Display) -> String {
24
+ format!("Hook '{}' task error: {}", hook_name, reason)
25
+ }
26
+
27
+ /// Format error when a promise/future fails
28
+ pub fn promise_failed(hook_name: &str, reason: impl Display) -> String {
29
+ format!("Hook '{}' promise failed: {}", hook_name, reason)
30
+ }
31
+
32
+ /// Format error for Python-specific failures
33
+ pub fn python_error(hook_name: &str, reason: impl Display) -> String {
34
+ format!("Hook '{}' Python error: {}", hook_name, reason)
35
+ }
36
+
37
+ /// Format error when body reading fails
38
+ pub fn body_read_failed(direction: &str, reason: impl Display) -> String {
39
+ format!("Failed to read {} body: {}", direction, reason)
40
+ }
41
+
42
+ /// Format error when body writing fails
43
+ pub fn body_write_failed(reason: impl Display) -> String {
44
+ format!("Failed to write body: {}", reason)
45
+ }
46
+
47
+ /// Format error for serialization failures
48
+ pub fn serialize_failed(context: &str, reason: impl Display) -> String {
49
+ format!("Failed to serialize {}: {}", context, reason)
50
+ }
51
+
52
+ /// Format error for deserialization failures
53
+ pub fn deserialize_failed(context: &str, reason: impl Display) -> String {
54
+ format!("Failed to deserialize {}: {}", context, reason)
55
+ }
56
+
57
+ /// Format error when building HTTP objects fails
58
+ pub fn build_failed(what: &str, reason: impl Display) -> String {
59
+ format!("Failed to build {}: {}", what, reason)
60
+ }
61
+ }
62
+
63
+ /// Utilities for serializing/deserializing request and response bodies
64
+ pub mod serial {
65
+ use super::*;
66
+
67
+ /// Extract body bytes from an axum Body
68
+ pub async fn extract_body(body: Body) -> Result<bytes::Bytes, String> {
69
+ use axum::body::to_bytes;
70
+ to_bytes(body, usize::MAX)
71
+ .await
72
+ .map_err(|e| error::body_read_failed("request/response", e))
73
+ }
74
+
75
+ /// Create a JSON-formatted response body
76
+ pub fn json_response_body(json: &serde_json::Value) -> Result<Body, String> {
77
+ serde_json::to_string(json)
78
+ .map(Body::from)
79
+ .map_err(|e| error::serialize_failed("response JSON", e))
80
+ }
81
+
82
+ /// Parse a JSON value from bytes
83
+ pub fn parse_json(bytes: &[u8]) -> Result<serde_json::Value, String> {
84
+ if bytes.is_empty() {
85
+ return Ok(serde_json::Value::Null);
86
+ }
87
+ serde_json::from_slice(bytes)
88
+ .or_else(|_| Ok(serde_json::Value::String(String::from_utf8_lossy(bytes).to_string())))
89
+ }
90
+ }
91
+
92
+ /// Re-export of the HTTP-specific lifecycle hooks type alias
93
+ pub use super::LifecycleHooks as HttpLifecycleHooks;
94
+
95
+ /// Helper for registering hooks with standard naming conventions
96
+ pub struct HookRegistry;
97
+
98
+ impl HookRegistry {
99
+ /// Extract hooks from a configuration and register them with a naming pattern
100
+ /// Used by bindings to standardize hook naming (e.g., "on_request_hook_0")
101
+ pub fn register_from_list<F>(
102
+ hooks: &mut HttpLifecycleHooks,
103
+ hook_list: Vec<Arc<dyn LifecycleHook<Request<Body>, Response<Body>>>>,
104
+ _hook_type: &str,
105
+ register_fn: F,
106
+ ) where
107
+ F: Fn(&mut HttpLifecycleHooks, Arc<dyn LifecycleHook<Request<Body>, Response<Body>>>),
108
+ {
109
+ for hook in hook_list {
110
+ register_fn(hooks, hook);
111
+ }
112
+ }
113
+ }
114
+
115
+ #[cfg(test)]
116
+ mod tests {
117
+ use super::*;
118
+ use crate::lifecycle::HookResult;
119
+ use axum::body::Body;
120
+ use axum::http::{Request, Response, StatusCode};
121
+ use std::future::Future;
122
+ use std::pin::Pin;
123
+
124
+ #[test]
125
+ fn test_error_messages() {
126
+ let call_err = error::call_failed("test_hook", "test reason");
127
+ assert!(call_err.contains("test_hook"));
128
+ assert!(call_err.contains("test reason"));
129
+
130
+ let task_err = error::task_error("task_hook", "spawn failed");
131
+ assert!(task_err.contains("task_hook"));
132
+
133
+ let promise_err = error::promise_failed("promise_hook", "rejected");
134
+ assert!(promise_err.contains("promise_hook"));
135
+ }
136
+
137
+ #[test]
138
+ fn test_body_error_messages() {
139
+ let read_err = error::body_read_failed("request", "stream closed");
140
+ assert!(read_err.contains("request"));
141
+
142
+ let write_err = error::body_write_failed("allocation failed");
143
+ assert!(write_err.contains("allocation"));
144
+ }
145
+
146
+ #[test]
147
+ fn test_json_error_messages() {
148
+ let ser_err = error::serialize_failed("request body", "invalid type");
149
+ assert!(ser_err.contains("request body"));
150
+
151
+ let deser_err = error::deserialize_failed("response", "malformed");
152
+ assert!(deser_err.contains("response"));
153
+ }
154
+
155
+ #[tokio::test]
156
+ async fn serial_extract_body_roundtrips_bytes() {
157
+ let body = Body::from("hello");
158
+ let bytes = serial::extract_body(body).await.expect("extract body");
159
+ assert_eq!(&bytes[..], b"hello");
160
+ }
161
+
162
+ #[test]
163
+ fn serial_parse_json_handles_empty_valid_and_invalid_json() {
164
+ let empty = serial::parse_json(&[]).expect("parse empty");
165
+ assert_eq!(empty, serde_json::Value::Null);
166
+
167
+ let valid = serial::parse_json(br#"{"ok":true}"#).expect("parse json");
168
+ assert_eq!(valid["ok"], true);
169
+
170
+ let invalid = serial::parse_json(b"not-json").expect("parse fallback");
171
+ assert_eq!(invalid, serde_json::Value::String("not-json".to_string()));
172
+ }
173
+
174
+ #[test]
175
+ fn hook_registry_registers_all_hooks_via_callback() {
176
+ struct NoopHook {
177
+ hook_name: String,
178
+ }
179
+
180
+ impl LifecycleHook<Request<Body>, Response<Body>> for NoopHook {
181
+ fn name(&self) -> &str {
182
+ &self.hook_name
183
+ }
184
+
185
+ fn execute_request<'a>(
186
+ &'a self,
187
+ req: Request<Body>,
188
+ ) -> Pin<Box<dyn Future<Output = Result<HookResult<Request<Body>, Response<Body>>, String>> + Send + 'a>>
189
+ {
190
+ Box::pin(async move { Ok(HookResult::Continue(req)) })
191
+ }
192
+
193
+ fn execute_response<'a>(
194
+ &'a self,
195
+ resp: Response<Body>,
196
+ ) -> Pin<Box<dyn Future<Output = Result<HookResult<Response<Body>, Response<Body>>, String>> + Send + 'a>>
197
+ {
198
+ Box::pin(async move { Ok(HookResult::Continue(resp)) })
199
+ }
200
+ }
201
+
202
+ let mut hooks = HttpLifecycleHooks::new();
203
+ assert!(hooks.is_empty());
204
+
205
+ let hook_list: Vec<Arc<dyn LifecycleHook<Request<Body>, Response<Body>>>> = vec![
206
+ Arc::new(NoopHook {
207
+ hook_name: "one".to_string(),
208
+ }),
209
+ Arc::new(NoopHook {
210
+ hook_name: "two".to_string(),
211
+ }),
212
+ ];
213
+
214
+ HookRegistry::register_from_list(&mut hooks, hook_list, "on_request", |hooks, hook| {
215
+ hooks.add_on_request(hook);
216
+ });
217
+
218
+ let dbg = format!("{:?}", hooks);
219
+ assert!(dbg.contains("on_request_count"));
220
+ assert!(dbg.contains("2"));
221
+
222
+ let req = Request::builder().body(Body::empty()).unwrap();
223
+ let result = futures::executor::block_on(hooks.execute_on_request(req)).expect("hook run");
224
+ assert!(matches!(result, HookResult::Continue(_)));
225
+
226
+ let resp = Response::builder().status(StatusCode::OK).body(Body::empty()).unwrap();
227
+ let resp = futures::executor::block_on(hooks.execute_on_response(resp)).expect("hook run");
228
+ assert_eq!(resp.status(), StatusCode::OK);
229
+ }
230
+ }