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,275 +1,275 @@
1
- //! Ruby lifecycle hooks implementation
2
- //!
3
- //! This module provides the bridge between Ruby blocks/procs and Rust's lifecycle hook system.
4
- //! Uses magnus to safely call Ruby code from Rust async tasks.
5
-
6
- use axum::{
7
- body::Body,
8
- http::{Request, Response, StatusCode},
9
- };
10
- use magnus::{RHash, Value, gc::Marker, prelude::*, value::InnerValue, value::Opaque};
11
- use serde_json::Value as JsonValue;
12
- use spikard_http::lifecycle::{HookResult, LifecycleHook};
13
- use std::future::Future;
14
- use std::pin::Pin;
15
-
16
- /// Ruby lifecycle hook wrapper
17
- ///
18
- /// Wraps a Ruby proc/block and makes it callable from Rust's lifecycle system.
19
- /// Handles conversion between Rust HTTP types and Ruby request/response objects.
20
- pub struct RubyLifecycleHook {
21
- name: String,
22
- /// Ruby proc/callable object (Opaque for Send safety)
23
- func: Opaque<Value>,
24
- }
25
-
26
- impl RubyLifecycleHook {
27
- /// Create a new Ruby lifecycle hook
28
- pub fn new(name: String, func: Value) -> Self {
29
- Self {
30
- name,
31
- func: func.into(),
32
- }
33
- }
34
-
35
- /// Mark Ruby values for GC
36
- #[allow(dead_code)]
37
- pub fn mark(&self, marker: &Marker) {
38
- if let Ok(ruby) = magnus::Ruby::get() {
39
- marker.mark(self.func.get_inner_with(&ruby));
40
- }
41
- }
42
- }
43
-
44
- impl LifecycleHook<Request<Body>, Response<Body>> for RubyLifecycleHook {
45
- fn name(&self) -> &str {
46
- &self.name
47
- }
48
-
49
- fn execute_request<'a>(
50
- &'a self,
51
- req: Request<Body>,
52
- ) -> Pin<Box<dyn Future<Output = Result<HookResult<Request<Body>, Response<Body>>, String>> + Send + 'a>> {
53
- let func = self.func;
54
- let name = self.name.clone();
55
- let name_for_error = name.clone();
56
-
57
- Box::pin(async move {
58
- let (parts, body) = req.into_parts();
59
- let body_bytes = axum::body::to_bytes(body, usize::MAX)
60
- .await
61
- .map_err(|e| format!("Failed to read request body: {}", e))?;
62
-
63
- let body_value: JsonValue = if body_bytes.is_empty() {
64
- JsonValue::Null
65
- } else {
66
- serde_json::from_slice(&body_bytes)
67
- .unwrap_or_else(|_| JsonValue::String(String::from_utf8_lossy(&body_bytes).to_string()))
68
- };
69
-
70
- let result = magnus::Ruby::get()
71
- .map_err(|e| format!("Failed to get Ruby: {}", e))
72
- .and_then(|ruby| {
73
- let request_hash = RHash::new();
74
-
75
- request_hash
76
- .aset(ruby.to_symbol("method"), ruby.str_new(parts.method.as_str()))
77
- .map_err(|e| format!("Failed to set method: {}", e))?;
78
- request_hash
79
- .aset(ruby.to_symbol("path"), ruby.str_new(parts.uri.path()))
80
- .map_err(|e| format!("Failed to set path: {}", e))?;
81
-
82
- let headers_hash = RHash::new();
83
- for (key, value) in parts.headers.iter() {
84
- headers_hash
85
- .aset(ruby.str_new(key.as_str()), ruby.str_new(value.to_str().unwrap_or("")))
86
- .map_err(|e| format!("Failed to set header: {}", e))?;
87
- }
88
- request_hash
89
- .aset(ruby.to_symbol("headers"), headers_hash)
90
- .map_err(|e| format!("Failed to set headers: {}", e))?;
91
-
92
- let body_str =
93
- serde_json::to_string(&body_value).map_err(|e| format!("Failed to serialize body: {}", e))?;
94
- request_hash
95
- .aset(ruby.to_symbol("body"), ruby.str_new(&body_str))
96
- .map_err(|e| format!("Failed to set body: {}", e))?;
97
-
98
- let func_value = ruby.get_inner(func);
99
- let result: Value = func_value
100
- .funcall("call", (request_hash,))
101
- .map_err(|e| format!("Hook '{}' call failed: {}", name, e))?;
102
-
103
- if let Some(result_hash) = RHash::from_value(result) {
104
- if let Some(status_value) = result_hash.get(ruby.to_symbol("status_code")) {
105
- let status = i64::try_convert(status_value)
106
- .map_err(|e| format!("Failed to convert status code: {}", e))?;
107
-
108
- let content = result_hash
109
- .get(ruby.to_symbol("content"))
110
- .or_else(|| result_hash.get(ruby.to_symbol("body")))
111
- .unwrap_or_else(|| ruby.qnil().as_value());
112
-
113
- let body_str = if content.is_nil() {
114
- "{}".to_string()
115
- } else {
116
- String::try_convert(content).unwrap_or_else(|_| {
117
- content
118
- .to_r_string()
119
- .map(|s| s.to_string().unwrap_or_else(|_| "{}".to_string()))
120
- .unwrap_or_else(|_| "{}".to_string())
121
- })
122
- };
123
-
124
- let response = Response::builder()
125
- .status(StatusCode::from_u16(status as u16).unwrap_or(StatusCode::OK))
126
- .header("content-type", "application/json")
127
- .body(Body::from(body_str))
128
- .map_err(|e| format!("Failed to build response: {}", e))?;
129
-
130
- return Ok(HookResult::ShortCircuit(response));
131
- }
132
-
133
- let method = result_hash
134
- .get(ruby.to_symbol("method"))
135
- .and_then(|v| String::try_convert(v).ok())
136
- .unwrap_or_else(|| "GET".to_string());
137
- let path = result_hash
138
- .get(ruby.to_symbol("path"))
139
- .and_then(|v| String::try_convert(v).ok())
140
- .unwrap_or_else(|| "/".to_string());
141
-
142
- let req_builder = Request::builder().method(method.as_str()).uri(path);
143
-
144
- let body = if let Some(body_val) = result_hash.get(ruby.to_symbol("body")) {
145
- if body_val.is_nil() {
146
- Body::empty()
147
- } else {
148
- let body_str = String::try_convert(body_val).unwrap_or_else(|_| {
149
- body_val
150
- .to_r_string()
151
- .map(|s| s.to_string().unwrap_or_default())
152
- .unwrap_or_default()
153
- });
154
- Body::from(body_str)
155
- }
156
- } else {
157
- Body::empty()
158
- };
159
-
160
- let request = req_builder
161
- .body(body)
162
- .map_err(|e| format!("Failed to build request: {}", e))?;
163
-
164
- Ok(HookResult::Continue(request))
165
- } else {
166
- Err(format!("Hook must return a Hash, got {}", unsafe {
167
- result.classname()
168
- }))
169
- }
170
- });
171
-
172
- result.map_err(|e| format!("Hook '{}' task error: {}", name_for_error, e))
173
- })
174
- }
175
-
176
- fn execute_response<'a>(
177
- &'a self,
178
- resp: Response<Body>,
179
- ) -> Pin<Box<dyn Future<Output = Result<HookResult<Response<Body>, Response<Body>>, String>> + Send + 'a>> {
180
- let func = self.func;
181
- let name = self.name.clone();
182
- let name_for_error = name.clone();
183
-
184
- Box::pin(async move {
185
- let (parts, body) = resp.into_parts();
186
- let body_bytes = axum::body::to_bytes(body, usize::MAX)
187
- .await
188
- .map_err(|e| format!("Failed to read response body: {}", e))?;
189
-
190
- let body_value: JsonValue = if body_bytes.is_empty() {
191
- JsonValue::Null
192
- } else {
193
- serde_json::from_slice(&body_bytes)
194
- .unwrap_or_else(|_| JsonValue::String(String::from_utf8_lossy(&body_bytes).to_string()))
195
- };
196
-
197
- let result = magnus::Ruby::get()
198
- .map_err(|e| format!("Failed to get Ruby: {}", e))
199
- .and_then(|ruby| {
200
- let response_hash = RHash::new();
201
-
202
- response_hash
203
- .aset(
204
- ruby.to_symbol("status_code"),
205
- ruby.integer_from_i64(parts.status.as_u16() as i64),
206
- )
207
- .map_err(|e| format!("Failed to set status_code: {}", e))?;
208
-
209
- let headers_hash = RHash::new();
210
- for (key, value) in parts.headers.iter() {
211
- headers_hash
212
- .aset(ruby.str_new(key.as_str()), ruby.str_new(value.to_str().unwrap_or("")))
213
- .map_err(|e| format!("Failed to set header: {}", e))?;
214
- }
215
- response_hash
216
- .aset(ruby.to_symbol("headers"), headers_hash)
217
- .map_err(|e| format!("Failed to set headers: {}", e))?;
218
-
219
- let body_str =
220
- serde_json::to_string(&body_value).map_err(|e| format!("Failed to serialize body: {}", e))?;
221
- response_hash
222
- .aset(ruby.to_symbol("content"), ruby.str_new(&body_str))
223
- .map_err(|e| format!("Failed to set content: {}", e))?;
224
-
225
- let func_value = ruby.get_inner(func);
226
- let result: Value = func_value
227
- .funcall("call", (response_hash,))
228
- .map_err(|e| format!("Hook '{}' call failed: {}", name, e))?;
229
-
230
- if let Some(result_hash) = RHash::from_value(result) {
231
- let status = result_hash
232
- .get(ruby.to_symbol("status_code"))
233
- .and_then(|v| i64::try_convert(v).ok())
234
- .unwrap_or(200);
235
-
236
- let content = result_hash
237
- .get(ruby.to_symbol("content"))
238
- .or_else(|| result_hash.get(ruby.to_symbol("body")))
239
- .unwrap_or_else(|| ruby.qnil().as_value());
240
-
241
- let body_str = if content.is_nil() {
242
- "{}".to_string()
243
- } else {
244
- String::try_convert(content).unwrap_or_else(|_| {
245
- content
246
- .to_r_string()
247
- .map(|s| s.to_string().unwrap_or_else(|_| "{}".to_string()))
248
- .unwrap_or_else(|_| "{}".to_string())
249
- })
250
- };
251
-
252
- let mut response_builder =
253
- Response::builder().status(StatusCode::from_u16(status as u16).unwrap_or(StatusCode::OK));
254
-
255
- response_builder = response_builder.header("content-type", "application/json");
256
-
257
- let response = response_builder
258
- .body(Body::from(body_str))
259
- .map_err(|e| format!("Failed to build response: {}", e))?;
260
-
261
- Ok(HookResult::Continue(response))
262
- } else {
263
- Err(format!("Hook must return a Hash, got {}", unsafe {
264
- result.classname()
265
- }))
266
- }
267
- });
268
-
269
- result.map_err(|e| format!("Hook '{}' task error: {}", name_for_error, e))
270
- })
271
- }
272
- }
273
-
274
- unsafe impl Send for RubyLifecycleHook {}
275
- unsafe impl Sync for RubyLifecycleHook {}
1
+ //! Ruby lifecycle hooks implementation
2
+ //!
3
+ //! This module provides the bridge between Ruby blocks/procs and Rust's lifecycle hook system.
4
+ //! Uses magnus to safely call Ruby code from Rust async tasks.
5
+
6
+ use axum::{
7
+ body::Body,
8
+ http::{Request, Response, StatusCode},
9
+ };
10
+ use magnus::{RHash, Value, gc::Marker, prelude::*, value::InnerValue, value::Opaque};
11
+ use serde_json::Value as JsonValue;
12
+ use spikard_http::lifecycle::{HookResult, LifecycleHook};
13
+ use std::future::Future;
14
+ use std::pin::Pin;
15
+
16
+ /// Ruby lifecycle hook wrapper
17
+ ///
18
+ /// Wraps a Ruby proc/block and makes it callable from Rust's lifecycle system.
19
+ /// Handles conversion between Rust HTTP types and Ruby request/response objects.
20
+ pub struct RubyLifecycleHook {
21
+ name: String,
22
+ /// Ruby proc/callable object (Opaque for Send safety)
23
+ func: Opaque<Value>,
24
+ }
25
+
26
+ impl RubyLifecycleHook {
27
+ /// Create a new Ruby lifecycle hook
28
+ pub fn new(name: String, func: Value) -> Self {
29
+ Self {
30
+ name,
31
+ func: func.into(),
32
+ }
33
+ }
34
+
35
+ /// Mark Ruby values for GC
36
+ #[allow(dead_code)]
37
+ pub fn mark(&self, marker: &Marker) {
38
+ if let Ok(ruby) = magnus::Ruby::get() {
39
+ marker.mark(self.func.get_inner_with(&ruby));
40
+ }
41
+ }
42
+ }
43
+
44
+ impl LifecycleHook<Request<Body>, Response<Body>> for RubyLifecycleHook {
45
+ fn name(&self) -> &str {
46
+ &self.name
47
+ }
48
+
49
+ fn execute_request<'a>(
50
+ &'a self,
51
+ req: Request<Body>,
52
+ ) -> Pin<Box<dyn Future<Output = Result<HookResult<Request<Body>, Response<Body>>, String>> + Send + 'a>> {
53
+ let func = self.func;
54
+ let name = self.name.clone();
55
+ let name_for_error = name.clone();
56
+
57
+ Box::pin(async move {
58
+ let (parts, body) = req.into_parts();
59
+ let body_bytes = axum::body::to_bytes(body, usize::MAX)
60
+ .await
61
+ .map_err(|e| format!("Failed to read request body: {}", e))?;
62
+
63
+ let body_value: JsonValue = if body_bytes.is_empty() {
64
+ JsonValue::Null
65
+ } else {
66
+ serde_json::from_slice(&body_bytes)
67
+ .unwrap_or_else(|_| JsonValue::String(String::from_utf8_lossy(&body_bytes).to_string()))
68
+ };
69
+
70
+ let result = magnus::Ruby::get()
71
+ .map_err(|e| format!("Failed to get Ruby: {}", e))
72
+ .and_then(|ruby| {
73
+ let request_hash = RHash::new();
74
+
75
+ request_hash
76
+ .aset(ruby.to_symbol("method"), ruby.str_new(parts.method.as_str()))
77
+ .map_err(|e| format!("Failed to set method: {}", e))?;
78
+ request_hash
79
+ .aset(ruby.to_symbol("path"), ruby.str_new(parts.uri.path()))
80
+ .map_err(|e| format!("Failed to set path: {}", e))?;
81
+
82
+ let headers_hash = RHash::new();
83
+ for (key, value) in parts.headers.iter() {
84
+ headers_hash
85
+ .aset(ruby.str_new(key.as_str()), ruby.str_new(value.to_str().unwrap_or("")))
86
+ .map_err(|e| format!("Failed to set header: {}", e))?;
87
+ }
88
+ request_hash
89
+ .aset(ruby.to_symbol("headers"), headers_hash)
90
+ .map_err(|e| format!("Failed to set headers: {}", e))?;
91
+
92
+ let body_str =
93
+ serde_json::to_string(&body_value).map_err(|e| format!("Failed to serialize body: {}", e))?;
94
+ request_hash
95
+ .aset(ruby.to_symbol("body"), ruby.str_new(&body_str))
96
+ .map_err(|e| format!("Failed to set body: {}", e))?;
97
+
98
+ let func_value = ruby.get_inner(func);
99
+ let result: Value = func_value
100
+ .funcall("call", (request_hash,))
101
+ .map_err(|e| format!("Hook '{}' call failed: {}", name, e))?;
102
+
103
+ if let Some(result_hash) = RHash::from_value(result) {
104
+ if let Some(status_value) = result_hash.get(ruby.to_symbol("status_code")) {
105
+ let status = i64::try_convert(status_value)
106
+ .map_err(|e| format!("Failed to convert status code: {}", e))?;
107
+
108
+ let content = result_hash
109
+ .get(ruby.to_symbol("content"))
110
+ .or_else(|| result_hash.get(ruby.to_symbol("body")))
111
+ .unwrap_or_else(|| ruby.qnil().as_value());
112
+
113
+ let body_str = if content.is_nil() {
114
+ "{}".to_string()
115
+ } else {
116
+ String::try_convert(content).unwrap_or_else(|_| {
117
+ content
118
+ .to_r_string()
119
+ .map(|s| s.to_string().unwrap_or_else(|_| "{}".to_string()))
120
+ .unwrap_or_else(|_| "{}".to_string())
121
+ })
122
+ };
123
+
124
+ let response = Response::builder()
125
+ .status(StatusCode::from_u16(status as u16).unwrap_or(StatusCode::OK))
126
+ .header("content-type", "application/json")
127
+ .body(Body::from(body_str))
128
+ .map_err(|e| format!("Failed to build response: {}", e))?;
129
+
130
+ return Ok(HookResult::ShortCircuit(response));
131
+ }
132
+
133
+ let method = result_hash
134
+ .get(ruby.to_symbol("method"))
135
+ .and_then(|v| String::try_convert(v).ok())
136
+ .unwrap_or_else(|| "GET".to_string());
137
+ let path = result_hash
138
+ .get(ruby.to_symbol("path"))
139
+ .and_then(|v| String::try_convert(v).ok())
140
+ .unwrap_or_else(|| "/".to_string());
141
+
142
+ let req_builder = Request::builder().method(method.as_str()).uri(path);
143
+
144
+ let body = if let Some(body_val) = result_hash.get(ruby.to_symbol("body")) {
145
+ if body_val.is_nil() {
146
+ Body::empty()
147
+ } else {
148
+ let body_str = String::try_convert(body_val).unwrap_or_else(|_| {
149
+ body_val
150
+ .to_r_string()
151
+ .map(|s| s.to_string().unwrap_or_default())
152
+ .unwrap_or_default()
153
+ });
154
+ Body::from(body_str)
155
+ }
156
+ } else {
157
+ Body::empty()
158
+ };
159
+
160
+ let request = req_builder
161
+ .body(body)
162
+ .map_err(|e| format!("Failed to build request: {}", e))?;
163
+
164
+ Ok(HookResult::Continue(request))
165
+ } else {
166
+ Err(format!("Hook must return a Hash, got {}", unsafe {
167
+ result.classname()
168
+ }))
169
+ }
170
+ });
171
+
172
+ result.map_err(|e| format!("Hook '{}' task error: {}", name_for_error, e))
173
+ })
174
+ }
175
+
176
+ fn execute_response<'a>(
177
+ &'a self,
178
+ resp: Response<Body>,
179
+ ) -> Pin<Box<dyn Future<Output = Result<HookResult<Response<Body>, Response<Body>>, String>> + Send + 'a>> {
180
+ let func = self.func;
181
+ let name = self.name.clone();
182
+ let name_for_error = name.clone();
183
+
184
+ Box::pin(async move {
185
+ let (parts, body) = resp.into_parts();
186
+ let body_bytes = axum::body::to_bytes(body, usize::MAX)
187
+ .await
188
+ .map_err(|e| format!("Failed to read response body: {}", e))?;
189
+
190
+ let body_value: JsonValue = if body_bytes.is_empty() {
191
+ JsonValue::Null
192
+ } else {
193
+ serde_json::from_slice(&body_bytes)
194
+ .unwrap_or_else(|_| JsonValue::String(String::from_utf8_lossy(&body_bytes).to_string()))
195
+ };
196
+
197
+ let result = magnus::Ruby::get()
198
+ .map_err(|e| format!("Failed to get Ruby: {}", e))
199
+ .and_then(|ruby| {
200
+ let response_hash = RHash::new();
201
+
202
+ response_hash
203
+ .aset(
204
+ ruby.to_symbol("status_code"),
205
+ ruby.integer_from_i64(parts.status.as_u16() as i64),
206
+ )
207
+ .map_err(|e| format!("Failed to set status_code: {}", e))?;
208
+
209
+ let headers_hash = RHash::new();
210
+ for (key, value) in parts.headers.iter() {
211
+ headers_hash
212
+ .aset(ruby.str_new(key.as_str()), ruby.str_new(value.to_str().unwrap_or("")))
213
+ .map_err(|e| format!("Failed to set header: {}", e))?;
214
+ }
215
+ response_hash
216
+ .aset(ruby.to_symbol("headers"), headers_hash)
217
+ .map_err(|e| format!("Failed to set headers: {}", e))?;
218
+
219
+ let body_str =
220
+ serde_json::to_string(&body_value).map_err(|e| format!("Failed to serialize body: {}", e))?;
221
+ response_hash
222
+ .aset(ruby.to_symbol("content"), ruby.str_new(&body_str))
223
+ .map_err(|e| format!("Failed to set content: {}", e))?;
224
+
225
+ let func_value = ruby.get_inner(func);
226
+ let result: Value = func_value
227
+ .funcall("call", (response_hash,))
228
+ .map_err(|e| format!("Hook '{}' call failed: {}", name, e))?;
229
+
230
+ if let Some(result_hash) = RHash::from_value(result) {
231
+ let status = result_hash
232
+ .get(ruby.to_symbol("status_code"))
233
+ .and_then(|v| i64::try_convert(v).ok())
234
+ .unwrap_or(200);
235
+
236
+ let content = result_hash
237
+ .get(ruby.to_symbol("content"))
238
+ .or_else(|| result_hash.get(ruby.to_symbol("body")))
239
+ .unwrap_or_else(|| ruby.qnil().as_value());
240
+
241
+ let body_str = if content.is_nil() {
242
+ "{}".to_string()
243
+ } else {
244
+ String::try_convert(content).unwrap_or_else(|_| {
245
+ content
246
+ .to_r_string()
247
+ .map(|s| s.to_string().unwrap_or_else(|_| "{}".to_string()))
248
+ .unwrap_or_else(|_| "{}".to_string())
249
+ })
250
+ };
251
+
252
+ let mut response_builder =
253
+ Response::builder().status(StatusCode::from_u16(status as u16).unwrap_or(StatusCode::OK));
254
+
255
+ response_builder = response_builder.header("content-type", "application/json");
256
+
257
+ let response = response_builder
258
+ .body(Body::from(body_str))
259
+ .map_err(|e| format!("Failed to build response: {}", e))?;
260
+
261
+ Ok(HookResult::Continue(response))
262
+ } else {
263
+ Err(format!("Hook must return a Hash, got {}", unsafe {
264
+ result.classname()
265
+ }))
266
+ }
267
+ });
268
+
269
+ result.map_err(|e| format!("Hook '{}' task error: {}", name_for_error, e))
270
+ })
271
+ }
272
+ }
273
+
274
+ unsafe impl Send for RubyLifecycleHook {}
275
+ unsafe impl Sync for RubyLifecycleHook {}
@@ -1,5 +1,5 @@
1
- //! Route metadata extraction and building from Ruby definitions.
2
-
3
- pub mod route_extraction;
4
-
5
- pub use route_extraction::{build_route_metadata, json_to_ruby, ruby_value_to_json};
1
+ //! Route metadata extraction and building from Ruby definitions.
2
+
3
+ pub mod route_extraction;
4
+
5
+ pub use route_extraction::{build_route_metadata, json_to_ruby, ruby_value_to_json};