spikard 0.3.0 → 0.3.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 (182) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +659 -659
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +10 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +386 -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 +221 -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 +360 -360
  23. data/vendor/crates/spikard-core/Cargo.toml +40 -0
  24. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -0
  25. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -0
  26. data/vendor/crates/spikard-core/src/debug.rs +63 -0
  27. data/vendor/crates/spikard-core/src/di/container.rs +726 -0
  28. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -0
  29. data/vendor/crates/spikard-core/src/di/error.rs +118 -0
  30. data/vendor/crates/spikard-core/src/di/factory.rs +538 -0
  31. data/vendor/crates/spikard-core/src/di/graph.rs +545 -0
  32. data/vendor/crates/spikard-core/src/di/mod.rs +192 -0
  33. data/vendor/crates/spikard-core/src/di/resolved.rs +411 -0
  34. data/vendor/crates/spikard-core/src/di/value.rs +283 -0
  35. data/vendor/crates/spikard-core/src/errors.rs +39 -0
  36. data/vendor/crates/spikard-core/src/http.rs +153 -0
  37. data/vendor/crates/spikard-core/src/lib.rs +29 -0
  38. data/vendor/crates/spikard-core/src/lifecycle.rs +422 -0
  39. data/vendor/crates/spikard-core/src/parameters.rs +722 -0
  40. data/vendor/crates/spikard-core/src/problem.rs +310 -0
  41. data/vendor/crates/spikard-core/src/request_data.rs +189 -0
  42. data/vendor/crates/spikard-core/src/router.rs +249 -0
  43. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -0
  44. data/vendor/crates/spikard-core/src/type_hints.rs +304 -0
  45. data/vendor/crates/spikard-core/src/validation.rs +699 -0
  46. data/vendor/crates/spikard-http/Cargo.toml +58 -0
  47. data/vendor/crates/spikard-http/src/auth.rs +247 -0
  48. data/vendor/crates/spikard-http/src/background.rs +249 -0
  49. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -0
  50. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -0
  51. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -0
  52. data/vendor/crates/spikard-http/src/cors.rs +490 -0
  53. data/vendor/crates/spikard-http/src/debug.rs +63 -0
  54. data/vendor/crates/spikard-http/src/di_handler.rs +423 -0
  55. data/vendor/crates/spikard-http/src/handler_response.rs +190 -0
  56. data/vendor/crates/spikard-http/src/handler_trait.rs +228 -0
  57. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -0
  58. data/vendor/crates/spikard-http/src/lib.rs +529 -0
  59. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -0
  60. data/vendor/crates/spikard-http/src/lifecycle.rs +428 -0
  61. data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -0
  62. data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -0
  63. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -0
  64. data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -0
  65. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -0
  66. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -0
  67. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -0
  68. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -0
  69. data/vendor/crates/spikard-http/src/parameters.rs +1 -0
  70. data/vendor/crates/spikard-http/src/problem.rs +1 -0
  71. data/vendor/crates/spikard-http/src/query_parser.rs +369 -0
  72. data/vendor/crates/spikard-http/src/response.rs +399 -0
  73. data/vendor/crates/spikard-http/src/router.rs +1 -0
  74. data/vendor/crates/spikard-http/src/schema_registry.rs +1 -0
  75. data/vendor/crates/spikard-http/src/server/handler.rs +87 -0
  76. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -0
  77. data/vendor/crates/spikard-http/src/server/mod.rs +805 -0
  78. data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -0
  79. data/vendor/crates/spikard-http/src/sse.rs +447 -0
  80. data/vendor/crates/spikard-http/src/testing/form.rs +14 -0
  81. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -0
  82. data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -0
  83. data/vendor/crates/spikard-http/src/testing.rs +377 -0
  84. data/vendor/crates/spikard-http/src/type_hints.rs +1 -0
  85. data/vendor/crates/spikard-http/src/validation.rs +1 -0
  86. data/vendor/crates/spikard-http/src/websocket.rs +324 -0
  87. data/vendor/crates/spikard-rb/Cargo.toml +42 -0
  88. data/vendor/crates/spikard-rb/build.rs +8 -0
  89. data/vendor/crates/spikard-rb/src/background.rs +63 -0
  90. data/vendor/crates/spikard-rb/src/config.rs +294 -0
  91. data/vendor/crates/spikard-rb/src/conversion.rs +453 -0
  92. data/vendor/crates/spikard-rb/src/di.rs +409 -0
  93. data/vendor/crates/spikard-rb/src/handler.rs +625 -0
  94. data/vendor/crates/spikard-rb/src/lib.rs +2771 -0
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +274 -0
  96. data/vendor/crates/spikard-rb/src/server.rs +283 -0
  97. data/vendor/crates/spikard-rb/src/sse.rs +231 -0
  98. data/vendor/crates/spikard-rb/src/test_client.rs +404 -0
  99. data/vendor/crates/spikard-rb/src/test_sse.rs +143 -0
  100. data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -0
  101. data/vendor/crates/spikard-rb/src/websocket.rs +233 -0
  102. data/vendor/spikard-core/Cargo.toml +40 -0
  103. data/vendor/spikard-core/src/bindings/mod.rs +3 -0
  104. data/vendor/spikard-core/src/bindings/response.rs +133 -0
  105. data/vendor/spikard-core/src/debug.rs +63 -0
  106. data/vendor/spikard-core/src/di/container.rs +726 -0
  107. data/vendor/spikard-core/src/di/dependency.rs +273 -0
  108. data/vendor/spikard-core/src/di/error.rs +118 -0
  109. data/vendor/spikard-core/src/di/factory.rs +538 -0
  110. data/vendor/spikard-core/src/di/graph.rs +545 -0
  111. data/vendor/spikard-core/src/di/mod.rs +192 -0
  112. data/vendor/spikard-core/src/di/resolved.rs +411 -0
  113. data/vendor/spikard-core/src/di/value.rs +283 -0
  114. data/vendor/spikard-core/src/http.rs +153 -0
  115. data/vendor/spikard-core/src/lib.rs +28 -0
  116. data/vendor/spikard-core/src/lifecycle.rs +422 -0
  117. data/vendor/spikard-core/src/parameters.rs +719 -0
  118. data/vendor/spikard-core/src/problem.rs +310 -0
  119. data/vendor/spikard-core/src/request_data.rs +189 -0
  120. data/vendor/spikard-core/src/router.rs +249 -0
  121. data/vendor/spikard-core/src/schema_registry.rs +183 -0
  122. data/vendor/spikard-core/src/type_hints.rs +304 -0
  123. data/vendor/spikard-core/src/validation.rs +699 -0
  124. data/vendor/spikard-http/Cargo.toml +58 -0
  125. data/vendor/spikard-http/src/auth.rs +247 -0
  126. data/vendor/spikard-http/src/background.rs +249 -0
  127. data/vendor/spikard-http/src/bindings/mod.rs +3 -0
  128. data/vendor/spikard-http/src/bindings/response.rs +1 -0
  129. data/vendor/spikard-http/src/body_metadata.rs +8 -0
  130. data/vendor/spikard-http/src/cors.rs +490 -0
  131. data/vendor/spikard-http/src/debug.rs +63 -0
  132. data/vendor/spikard-http/src/di_handler.rs +423 -0
  133. data/vendor/spikard-http/src/handler_response.rs +190 -0
  134. data/vendor/spikard-http/src/handler_trait.rs +228 -0
  135. data/vendor/spikard-http/src/handler_trait_tests.rs +284 -0
  136. data/vendor/spikard-http/src/lib.rs +529 -0
  137. data/vendor/spikard-http/src/lifecycle/adapter.rs +149 -0
  138. data/vendor/spikard-http/src/lifecycle.rs +428 -0
  139. data/vendor/spikard-http/src/middleware/mod.rs +285 -0
  140. data/vendor/spikard-http/src/middleware/multipart.rs +86 -0
  141. data/vendor/spikard-http/src/middleware/urlencoded.rs +147 -0
  142. data/vendor/spikard-http/src/middleware/validation.rs +287 -0
  143. data/vendor/spikard-http/src/openapi/mod.rs +309 -0
  144. data/vendor/spikard-http/src/openapi/parameter_extraction.rs +190 -0
  145. data/vendor/spikard-http/src/openapi/schema_conversion.rs +308 -0
  146. data/vendor/spikard-http/src/openapi/spec_generation.rs +195 -0
  147. data/vendor/spikard-http/src/parameters.rs +1 -0
  148. data/vendor/spikard-http/src/problem.rs +1 -0
  149. data/vendor/spikard-http/src/query_parser.rs +369 -0
  150. data/vendor/spikard-http/src/response.rs +399 -0
  151. data/vendor/spikard-http/src/router.rs +1 -0
  152. data/vendor/spikard-http/src/schema_registry.rs +1 -0
  153. data/vendor/spikard-http/src/server/handler.rs +80 -0
  154. data/vendor/spikard-http/src/server/lifecycle_execution.rs +98 -0
  155. data/vendor/spikard-http/src/server/mod.rs +805 -0
  156. data/vendor/spikard-http/src/server/request_extraction.rs +119 -0
  157. data/vendor/spikard-http/src/sse.rs +447 -0
  158. data/vendor/spikard-http/src/testing/form.rs +14 -0
  159. data/vendor/spikard-http/src/testing/multipart.rs +60 -0
  160. data/vendor/spikard-http/src/testing/test_client.rs +285 -0
  161. data/vendor/spikard-http/src/testing.rs +377 -0
  162. data/vendor/spikard-http/src/type_hints.rs +1 -0
  163. data/vendor/spikard-http/src/validation.rs +1 -0
  164. data/vendor/spikard-http/src/websocket.rs +324 -0
  165. data/vendor/spikard-rb/Cargo.toml +42 -0
  166. data/vendor/spikard-rb/build.rs +8 -0
  167. data/vendor/spikard-rb/src/background.rs +63 -0
  168. data/vendor/spikard-rb/src/config.rs +294 -0
  169. data/vendor/spikard-rb/src/conversion.rs +392 -0
  170. data/vendor/spikard-rb/src/di.rs +409 -0
  171. data/vendor/spikard-rb/src/handler.rs +534 -0
  172. data/vendor/spikard-rb/src/lib.rs +2020 -0
  173. data/vendor/spikard-rb/src/lifecycle.rs +267 -0
  174. data/vendor/spikard-rb/src/server.rs +283 -0
  175. data/vendor/spikard-rb/src/sse.rs +231 -0
  176. data/vendor/spikard-rb/src/test_client.rs +404 -0
  177. data/vendor/spikard-rb/src/test_sse.rs +143 -0
  178. data/vendor/spikard-rb/src/test_websocket.rs +221 -0
  179. data/vendor/spikard-rb/src/websocket.rs +233 -0
  180. metadata +162 -8
  181. /data/vendor/bundle/ruby/{3.3.0 → 3.4.0}/gems/diff-lcs-1.6.2/mise.toml +0 -0
  182. /data/vendor/bundle/ruby/{3.3.0 → 3.4.0}/gems/rake-compiler-dock-1.10.0/build/buildkitd.toml +0 -0
@@ -0,0 +1,274 @@
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 {}
@@ -0,0 +1,283 @@
1
+ //! HTTP server setup and lifecycle management.
2
+ //!
3
+ //! This module handles the creation and startup of the Spikard HTTP server
4
+ //! including route registration, middleware configuration, and lifecycle hooks.
5
+
6
+ #![allow(dead_code)]
7
+
8
+ use axum::body::Body;
9
+ use axum::http::Request;
10
+ use axum::http::Response;
11
+ use magnus::prelude::*;
12
+ use magnus::{Error, RArray, RHash, Ruby, Value, r_hash::ForEach};
13
+ use once_cell::sync::Lazy;
14
+ use spikard_http::{Handler, Route, RouteMetadata, SchemaRegistry, Server};
15
+ use std::sync::Arc;
16
+ use tokio::runtime::{Builder, Runtime};
17
+ use tracing::{error, info, warn};
18
+
19
+ use crate::config::extract_server_config;
20
+ use crate::handler::RubyHandler;
21
+
22
+ /// Global Tokio runtime for async operations.
23
+ ///
24
+ /// Initialized once and reused for all async operations throughout the lifetime
25
+ /// of the Ruby process.
26
+ pub static GLOBAL_RUNTIME: Lazy<Runtime> = Lazy::new(|| {
27
+ Builder::new_current_thread().enable_all().build().unwrap_or_else(|e| {
28
+ eprintln!("Failed to initialise global Tokio runtime: {}", e);
29
+ panic!("Cannot continue without Tokio runtime");
30
+ })
31
+ });
32
+
33
+ /// Start the Spikard HTTP server from Ruby
34
+ ///
35
+ /// Creates an Axum HTTP server in a dedicated background thread with its own Tokio runtime.
36
+ ///
37
+ /// # Arguments
38
+ ///
39
+ /// * `ruby` - Ruby VM reference
40
+ /// * `routes_json` - JSON string containing route metadata
41
+ /// * `handlers` - Ruby Hash mapping handler_name => Proc
42
+ /// * `config_value` - Ruby ServerConfig object with all middleware settings
43
+ /// * `hooks_value` - Ruby Hash of lifecycle hooks (optional)
44
+ /// * `ws_handlers` - Ruby Hash of WebSocket handlers (optional)
45
+ /// * `sse_producers` - Ruby Hash of SSE producers (optional)
46
+ ///
47
+ /// # Example (Ruby)
48
+ ///
49
+ /// ```ruby
50
+ /// config = Spikard::ServerConfig.new(host: '0.0.0.0', port: 8000)
51
+ /// Spikard::Native.run_server(routes_json, handlers, config, hooks, ws_handlers, sse_producers)
52
+ /// ```
53
+ pub fn run_server(
54
+ ruby: &Ruby,
55
+ routes_json: String,
56
+ handlers: Value,
57
+ config_value: Value,
58
+ hooks_value: Value,
59
+ ws_handlers: Value,
60
+ sse_producers: Value,
61
+ ) -> Result<(), Error> {
62
+ let mut config = extract_server_config(ruby, config_value)?;
63
+
64
+ let host = config.host.clone();
65
+ let port = config.port;
66
+
67
+ let metadata: Vec<RouteMetadata> = serde_json::from_str(&routes_json)
68
+ .map_err(|err| Error::new(ruby.exception_arg_error(), format!("Invalid routes JSON: {}", err)))?;
69
+
70
+ let handlers_hash = RHash::from_value(handlers).ok_or_else(|| {
71
+ Error::new(
72
+ ruby.exception_arg_error(),
73
+ "handlers parameter must be a Hash of handler_name => Proc",
74
+ )
75
+ })?;
76
+
77
+ let json_module = ruby
78
+ .class_object()
79
+ .funcall::<_, _, Value>("const_get", ("JSON",))
80
+ .map_err(|err| Error::new(ruby.exception_name_error(), format!("JSON module not found: {}", err)))?;
81
+
82
+ let schema_registry = SchemaRegistry::new();
83
+
84
+ let mut routes_with_handlers: Vec<(Route, Arc<dyn Handler>)> = Vec::new();
85
+
86
+ for route_meta in metadata {
87
+ let route = Route::from_metadata(route_meta.clone(), &schema_registry)
88
+ .map_err(|e| Error::new(ruby.exception_runtime_error(), format!("Failed to create route: {}", e)))?;
89
+
90
+ let handler_key = ruby.str_new(&route_meta.handler_name);
91
+ let handler_value: Value = match handlers_hash.lookup(handler_key) {
92
+ Ok(val) => val,
93
+ Err(_) => {
94
+ return Err(Error::new(
95
+ ruby.exception_arg_error(),
96
+ format!("Handler '{}' not found in handlers hash", route_meta.handler_name),
97
+ ));
98
+ }
99
+ };
100
+
101
+ let ruby_handler = RubyHandler::new_for_server(
102
+ ruby,
103
+ handler_value,
104
+ route_meta.handler_name.clone(),
105
+ route_meta.method.clone(),
106
+ route_meta.path.clone(),
107
+ json_module,
108
+ &route,
109
+ )?;
110
+
111
+ routes_with_handlers.push((route, Arc::new(ruby_handler) as Arc<dyn Handler>));
112
+ }
113
+
114
+ let lifecycle_hooks = if !hooks_value.is_nil() {
115
+ let hooks_hash = RHash::from_value(hooks_value)
116
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "lifecycle_hooks parameter must be a Hash"))?;
117
+
118
+ let mut hooks = spikard_http::LifecycleHooks::new();
119
+ type RubyHookVec = Vec<Arc<dyn spikard_http::lifecycle::LifecycleHook<Request<Body>, Response<Body>>>>;
120
+
121
+ let extract_hooks = |key: &str| -> Result<RubyHookVec, Error> {
122
+ let key_sym = ruby.to_symbol(key);
123
+ if let Some(hooks_array) = hooks_hash.get(key_sym)
124
+ && !hooks_array.is_nil()
125
+ {
126
+ let array = RArray::from_value(hooks_array)
127
+ .ok_or_else(|| Error::new(ruby.exception_type_error(), format!("{} must be an Array", key)))?;
128
+
129
+ let mut result = Vec::new();
130
+ let len = array.len();
131
+ for i in 0..len {
132
+ let hook_value: Value = array.entry(i as isize)?;
133
+ let name = format!("{}_{}", key, i);
134
+ let ruby_hook = crate::lifecycle::RubyLifecycleHook::new(name, hook_value);
135
+ result.push(Arc::new(ruby_hook)
136
+ as Arc<
137
+ dyn spikard_http::lifecycle::LifecycleHook<Request<Body>, Response<Body>>,
138
+ >);
139
+ }
140
+ return Ok(result);
141
+ }
142
+ Ok(Vec::new())
143
+ };
144
+
145
+ for hook in extract_hooks("on_request")? {
146
+ hooks.add_on_request(hook);
147
+ }
148
+
149
+ for hook in extract_hooks("pre_validation")? {
150
+ hooks.add_pre_validation(hook);
151
+ }
152
+
153
+ for hook in extract_hooks("pre_handler")? {
154
+ hooks.add_pre_handler(hook);
155
+ }
156
+
157
+ for hook in extract_hooks("on_response")? {
158
+ hooks.add_on_response(hook);
159
+ }
160
+
161
+ for hook in extract_hooks("on_error")? {
162
+ hooks.add_on_error(hook);
163
+ }
164
+
165
+ Some(hooks)
166
+ } else {
167
+ None
168
+ };
169
+
170
+ config.lifecycle_hooks = lifecycle_hooks.map(Arc::new);
171
+
172
+ Server::init_logging();
173
+
174
+ info!("Starting Spikard server on {}:{}", host, port);
175
+ info!("Registered {} routes", routes_with_handlers.len());
176
+
177
+ let mut app_router = Server::with_handlers(config.clone(), routes_with_handlers)
178
+ .map_err(|e| Error::new(ruby.exception_runtime_error(), format!("Failed to build router: {}", e)))?;
179
+
180
+ let mut ws_endpoints = Vec::new();
181
+ if !ws_handlers.is_nil() {
182
+ let ws_hash = RHash::from_value(ws_handlers)
183
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "WebSocket handlers must be a Hash"))?;
184
+
185
+ ws_hash.foreach(|path: String, factory: Value| -> Result<ForEach, Error> {
186
+ let handler_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
187
+ Error::new(
188
+ ruby.exception_runtime_error(),
189
+ format!("Failed to create WebSocket handler: {}", e),
190
+ )
191
+ })?;
192
+
193
+ let ws_state = crate::websocket::create_websocket_state(ruby, handler_instance)?;
194
+
195
+ ws_endpoints.push((path, ws_state));
196
+
197
+ Ok(ForEach::Continue)
198
+ })?;
199
+ }
200
+
201
+ let mut sse_endpoints = Vec::new();
202
+ if !sse_producers.is_nil() {
203
+ let sse_hash = RHash::from_value(sse_producers)
204
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "SSE producers must be a Hash"))?;
205
+
206
+ sse_hash.foreach(|path: String, factory: Value| -> Result<ForEach, Error> {
207
+ let producer_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
208
+ Error::new(
209
+ ruby.exception_runtime_error(),
210
+ format!("Failed to create SSE producer: {}", e),
211
+ )
212
+ })?;
213
+
214
+ let sse_state = crate::sse::create_sse_state(ruby, producer_instance)?;
215
+
216
+ sse_endpoints.push((path, sse_state));
217
+
218
+ Ok(ForEach::Continue)
219
+ })?;
220
+ }
221
+
222
+ use axum::routing::get;
223
+ for (path, ws_state) in ws_endpoints {
224
+ info!("Registered WebSocket endpoint: {}", path);
225
+ app_router = app_router.route(
226
+ &path,
227
+ get(spikard_http::websocket_handler::<crate::websocket::RubyWebSocketHandler>).with_state(ws_state),
228
+ );
229
+ }
230
+
231
+ for (path, sse_state) in sse_endpoints {
232
+ info!("Registered SSE endpoint: {}", path);
233
+ app_router = app_router.route(
234
+ &path,
235
+ get(spikard_http::sse_handler::<crate::sse::RubySseEventProducer>).with_state(sse_state),
236
+ );
237
+ }
238
+
239
+ let addr = format!("{}:{}", config.host, config.port);
240
+ let socket_addr: std::net::SocketAddr = addr.parse().map_err(|e| {
241
+ Error::new(
242
+ ruby.exception_arg_error(),
243
+ format!("Invalid socket address {}: {}", addr, e),
244
+ )
245
+ })?;
246
+
247
+ let runtime = tokio::runtime::Builder::new_current_thread()
248
+ .enable_all()
249
+ .build()
250
+ .map_err(|e| {
251
+ Error::new(
252
+ ruby.exception_runtime_error(),
253
+ format!("Failed to create Tokio runtime: {}", e),
254
+ )
255
+ })?;
256
+
257
+ let background_config = config.background_tasks.clone();
258
+
259
+ runtime.block_on(async move {
260
+ let listener = tokio::net::TcpListener::bind(socket_addr)
261
+ .await
262
+ .unwrap_or_else(|_| panic!("Failed to bind to {}", socket_addr));
263
+
264
+ info!("Server listening on {}", socket_addr);
265
+
266
+ let background_runtime = spikard_http::BackgroundRuntime::start(background_config.clone()).await;
267
+ crate::background::install_handle(background_runtime.handle());
268
+
269
+ let serve_result = axum::serve(listener, app_router).await;
270
+
271
+ crate::background::clear_handle();
272
+
273
+ if let Err(err) = background_runtime.shutdown().await {
274
+ warn!("Failed to drain background tasks during shutdown: {:?}", err);
275
+ }
276
+
277
+ if let Err(e) = serve_result {
278
+ error!("Server error: {}", e);
279
+ }
280
+ });
281
+
282
+ Ok(())
283
+ }