spikard 0.3.6 → 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 (142) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -659
  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 -386
  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 -221
  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 -0
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
  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 -63
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -726
  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 -538
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -545
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -411
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -283
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -39
  52. data/vendor/crates/spikard-core/src/http.rs +415 -153
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -422
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -0
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -722
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -310
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -189
  59. data/vendor/crates/spikard-core/src/router.rs +510 -249
  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 -0
  63. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +457 -699
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -68
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -247
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -249
  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 -490
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -63
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -423
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -190
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +838 -228
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -284
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -529
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -149
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -428
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -285
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -86
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -147
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -287
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -190
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -308
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -195
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -369
  90. data/vendor/crates/spikard-http/src/response.rs +720 -399
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -87
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -98
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1593 -805
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -119
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -0
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -447
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -14
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -285
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -324
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -42
  113. data/vendor/crates/spikard-rb/build.rs +199 -8
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  116. data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +285 -294
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -453
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
  119. data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +375 -409
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -625
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  122. data/vendor/crates/spikard-rb/src/lib.rs +1806 -2771
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -274
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -0
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
  128. data/vendor/crates/spikard-rb/src/server.rs +305 -283
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +538 -404
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  132. data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -0
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -233
  135. metadata +60 -13
  136. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  137. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  138. data/vendor/crates/spikard-http/src/router.rs +0 -1
  139. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  140. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  141. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  142. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
@@ -1,274 +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
- pub fn mark(&self, marker: &Marker) {
37
- if let Ok(ruby) = magnus::Ruby::get() {
38
- marker.mark(self.func.get_inner_with(&ruby));
39
- }
40
- }
41
- }
42
-
43
- impl LifecycleHook<Request<Body>, Response<Body>> for RubyLifecycleHook {
44
- fn name(&self) -> &str {
45
- &self.name
46
- }
47
-
48
- fn execute_request<'a>(
49
- &'a self,
50
- req: Request<Body>,
51
- ) -> Pin<Box<dyn Future<Output = Result<HookResult<Request<Body>, Response<Body>>, String>> + Send + 'a>> {
52
- let func = self.func;
53
- let name = self.name.clone();
54
- let name_for_error = name.clone();
55
-
56
- Box::pin(async move {
57
- let (parts, body) = req.into_parts();
58
- let body_bytes = axum::body::to_bytes(body, usize::MAX)
59
- .await
60
- .map_err(|e| format!("Failed to read request body: {}", e))?;
61
-
62
- let body_value: JsonValue = if body_bytes.is_empty() {
63
- JsonValue::Null
64
- } else {
65
- serde_json::from_slice(&body_bytes)
66
- .unwrap_or_else(|_| JsonValue::String(String::from_utf8_lossy(&body_bytes).to_string()))
67
- };
68
-
69
- let result = magnus::Ruby::get()
70
- .map_err(|e| format!("Failed to get Ruby: {}", e))
71
- .and_then(|ruby| {
72
- let request_hash = RHash::new();
73
-
74
- request_hash
75
- .aset(ruby.to_symbol("method"), ruby.str_new(parts.method.as_str()))
76
- .map_err(|e| format!("Failed to set method: {}", e))?;
77
- request_hash
78
- .aset(ruby.to_symbol("path"), ruby.str_new(parts.uri.path()))
79
- .map_err(|e| format!("Failed to set path: {}", e))?;
80
-
81
- let headers_hash = RHash::new();
82
- for (key, value) in parts.headers.iter() {
83
- headers_hash
84
- .aset(ruby.str_new(key.as_str()), ruby.str_new(value.to_str().unwrap_or("")))
85
- .map_err(|e| format!("Failed to set header: {}", e))?;
86
- }
87
- request_hash
88
- .aset(ruby.to_symbol("headers"), headers_hash)
89
- .map_err(|e| format!("Failed to set headers: {}", e))?;
90
-
91
- let body_str =
92
- serde_json::to_string(&body_value).map_err(|e| format!("Failed to serialize body: {}", e))?;
93
- request_hash
94
- .aset(ruby.to_symbol("body"), ruby.str_new(&body_str))
95
- .map_err(|e| format!("Failed to set body: {}", e))?;
96
-
97
- let func_value = ruby.get_inner(func);
98
- let result: Value = func_value
99
- .funcall("call", (request_hash,))
100
- .map_err(|e| format!("Hook '{}' call failed: {}", name, e))?;
101
-
102
- if let Some(result_hash) = RHash::from_value(result) {
103
- if let Some(status_value) = result_hash.get(ruby.to_symbol("status_code")) {
104
- let status = i64::try_convert(status_value)
105
- .map_err(|e| format!("Failed to convert status code: {}", e))?;
106
-
107
- let content = result_hash
108
- .get(ruby.to_symbol("content"))
109
- .or_else(|| result_hash.get(ruby.to_symbol("body")))
110
- .unwrap_or_else(|| ruby.qnil().as_value());
111
-
112
- let body_str = if content.is_nil() {
113
- "{}".to_string()
114
- } else {
115
- String::try_convert(content).unwrap_or_else(|_| {
116
- content
117
- .to_r_string()
118
- .map(|s| s.to_string().unwrap_or_else(|_| "{}".to_string()))
119
- .unwrap_or_else(|_| "{}".to_string())
120
- })
121
- };
122
-
123
- let response = Response::builder()
124
- .status(StatusCode::from_u16(status as u16).unwrap_or(StatusCode::OK))
125
- .header("content-type", "application/json")
126
- .body(Body::from(body_str))
127
- .map_err(|e| format!("Failed to build response: {}", e))?;
128
-
129
- return Ok(HookResult::ShortCircuit(response));
130
- }
131
-
132
- let method = result_hash
133
- .get(ruby.to_symbol("method"))
134
- .and_then(|v| String::try_convert(v).ok())
135
- .unwrap_or_else(|| "GET".to_string());
136
- let path = result_hash
137
- .get(ruby.to_symbol("path"))
138
- .and_then(|v| String::try_convert(v).ok())
139
- .unwrap_or_else(|| "/".to_string());
140
-
141
- let req_builder = Request::builder().method(method.as_str()).uri(path);
142
-
143
- let body = if let Some(body_val) = result_hash.get(ruby.to_symbol("body")) {
144
- if body_val.is_nil() {
145
- Body::empty()
146
- } else {
147
- let body_str = String::try_convert(body_val).unwrap_or_else(|_| {
148
- body_val
149
- .to_r_string()
150
- .map(|s| s.to_string().unwrap_or_default())
151
- .unwrap_or_default()
152
- });
153
- Body::from(body_str)
154
- }
155
- } else {
156
- Body::empty()
157
- };
158
-
159
- let request = req_builder
160
- .body(body)
161
- .map_err(|e| format!("Failed to build request: {}", e))?;
162
-
163
- Ok(HookResult::Continue(request))
164
- } else {
165
- Err(format!("Hook must return a Hash, got {}", unsafe {
166
- result.classname()
167
- }))
168
- }
169
- });
170
-
171
- result.map_err(|e| format!("Hook '{}' task error: {}", name_for_error, e))
172
- })
173
- }
174
-
175
- fn execute_response<'a>(
176
- &'a self,
177
- resp: Response<Body>,
178
- ) -> Pin<Box<dyn Future<Output = Result<HookResult<Response<Body>, Response<Body>>, String>> + Send + 'a>> {
179
- let func = self.func;
180
- let name = self.name.clone();
181
- let name_for_error = name.clone();
182
-
183
- Box::pin(async move {
184
- let (parts, body) = resp.into_parts();
185
- let body_bytes = axum::body::to_bytes(body, usize::MAX)
186
- .await
187
- .map_err(|e| format!("Failed to read response body: {}", e))?;
188
-
189
- let body_value: JsonValue = if body_bytes.is_empty() {
190
- JsonValue::Null
191
- } else {
192
- serde_json::from_slice(&body_bytes)
193
- .unwrap_or_else(|_| JsonValue::String(String::from_utf8_lossy(&body_bytes).to_string()))
194
- };
195
-
196
- let result = magnus::Ruby::get()
197
- .map_err(|e| format!("Failed to get Ruby: {}", e))
198
- .and_then(|ruby| {
199
- let response_hash = RHash::new();
200
-
201
- response_hash
202
- .aset(
203
- ruby.to_symbol("status_code"),
204
- ruby.integer_from_i64(parts.status.as_u16() as i64),
205
- )
206
- .map_err(|e| format!("Failed to set status_code: {}", e))?;
207
-
208
- let headers_hash = RHash::new();
209
- for (key, value) in parts.headers.iter() {
210
- headers_hash
211
- .aset(ruby.str_new(key.as_str()), ruby.str_new(value.to_str().unwrap_or("")))
212
- .map_err(|e| format!("Failed to set header: {}", e))?;
213
- }
214
- response_hash
215
- .aset(ruby.to_symbol("headers"), headers_hash)
216
- .map_err(|e| format!("Failed to set headers: {}", e))?;
217
-
218
- let body_str =
219
- serde_json::to_string(&body_value).map_err(|e| format!("Failed to serialize body: {}", e))?;
220
- response_hash
221
- .aset(ruby.to_symbol("content"), ruby.str_new(&body_str))
222
- .map_err(|e| format!("Failed to set content: {}", e))?;
223
-
224
- let func_value = ruby.get_inner(func);
225
- let result: Value = func_value
226
- .funcall("call", (response_hash,))
227
- .map_err(|e| format!("Hook '{}' call failed: {}", name, e))?;
228
-
229
- if let Some(result_hash) = RHash::from_value(result) {
230
- let status = result_hash
231
- .get(ruby.to_symbol("status_code"))
232
- .and_then(|v| i64::try_convert(v).ok())
233
- .unwrap_or(200);
234
-
235
- let content = result_hash
236
- .get(ruby.to_symbol("content"))
237
- .or_else(|| result_hash.get(ruby.to_symbol("body")))
238
- .unwrap_or_else(|| ruby.qnil().as_value());
239
-
240
- let body_str = if content.is_nil() {
241
- "{}".to_string()
242
- } else {
243
- String::try_convert(content).unwrap_or_else(|_| {
244
- content
245
- .to_r_string()
246
- .map(|s| s.to_string().unwrap_or_else(|_| "{}".to_string()))
247
- .unwrap_or_else(|_| "{}".to_string())
248
- })
249
- };
250
-
251
- let mut response_builder =
252
- Response::builder().status(StatusCode::from_u16(status as u16).unwrap_or(StatusCode::OK));
253
-
254
- response_builder = response_builder.header("content-type", "application/json");
255
-
256
- let response = response_builder
257
- .body(Body::from(body_str))
258
- .map_err(|e| format!("Failed to build response: {}", e))?;
259
-
260
- Ok(HookResult::Continue(response))
261
- } else {
262
- Err(format!("Hook must return a Hash, got {}", unsafe {
263
- result.classname()
264
- }))
265
- }
266
- });
267
-
268
- result.map_err(|e| format!("Hook '{}' task error: {}", name_for_error, e))
269
- })
270
- }
271
- }
272
-
273
- unsafe impl Send for RubyLifecycleHook {}
274
- 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 {}
@@ -0,0 +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};