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,267 @@
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, prelude::*, 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
+
36
+ impl LifecycleHook<Request<Body>, Response<Body>> for RubyLifecycleHook {
37
+ fn name(&self) -> &str {
38
+ &self.name
39
+ }
40
+
41
+ fn execute_request<'a>(
42
+ &'a self,
43
+ req: Request<Body>,
44
+ ) -> Pin<Box<dyn Future<Output = Result<HookResult<Request<Body>, Response<Body>>, String>> + Send + 'a>> {
45
+ let func = self.func;
46
+ let name = self.name.clone();
47
+ let name_for_error = name.clone();
48
+
49
+ Box::pin(async move {
50
+ let (parts, body) = req.into_parts();
51
+ let body_bytes = axum::body::to_bytes(body, usize::MAX)
52
+ .await
53
+ .map_err(|e| format!("Failed to read request body: {}", e))?;
54
+
55
+ let body_value: JsonValue = if body_bytes.is_empty() {
56
+ JsonValue::Null
57
+ } else {
58
+ serde_json::from_slice(&body_bytes)
59
+ .unwrap_or_else(|_| JsonValue::String(String::from_utf8_lossy(&body_bytes).to_string()))
60
+ };
61
+
62
+ let result = magnus::Ruby::get()
63
+ .map_err(|e| format!("Failed to get Ruby: {}", e))
64
+ .and_then(|ruby| {
65
+ let request_hash = RHash::new();
66
+
67
+ request_hash
68
+ .aset(ruby.to_symbol("method"), ruby.str_new(parts.method.as_str()))
69
+ .map_err(|e| format!("Failed to set method: {}", e))?;
70
+ request_hash
71
+ .aset(ruby.to_symbol("path"), ruby.str_new(parts.uri.path()))
72
+ .map_err(|e| format!("Failed to set path: {}", e))?;
73
+
74
+ let headers_hash = RHash::new();
75
+ for (key, value) in parts.headers.iter() {
76
+ headers_hash
77
+ .aset(ruby.str_new(key.as_str()), ruby.str_new(value.to_str().unwrap_or("")))
78
+ .map_err(|e| format!("Failed to set header: {}", e))?;
79
+ }
80
+ request_hash
81
+ .aset(ruby.to_symbol("headers"), headers_hash)
82
+ .map_err(|e| format!("Failed to set headers: {}", e))?;
83
+
84
+ let body_str =
85
+ serde_json::to_string(&body_value).map_err(|e| format!("Failed to serialize body: {}", e))?;
86
+ request_hash
87
+ .aset(ruby.to_symbol("body"), ruby.str_new(&body_str))
88
+ .map_err(|e| format!("Failed to set body: {}", e))?;
89
+
90
+ let func_value = ruby.get_inner(func);
91
+ let result: Value = func_value
92
+ .funcall("call", (request_hash,))
93
+ .map_err(|e| format!("Hook '{}' call failed: {}", name, e))?;
94
+
95
+ if let Some(result_hash) = RHash::from_value(result) {
96
+ if let Some(status_value) = result_hash.get(ruby.to_symbol("status_code")) {
97
+ let status = i64::try_convert(status_value)
98
+ .map_err(|e| format!("Failed to convert status code: {}", e))?;
99
+
100
+ let content = result_hash
101
+ .get(ruby.to_symbol("content"))
102
+ .or_else(|| result_hash.get(ruby.to_symbol("body")))
103
+ .unwrap_or_else(|| ruby.qnil().as_value());
104
+
105
+ let body_str = if content.is_nil() {
106
+ "{}".to_string()
107
+ } else {
108
+ String::try_convert(content).unwrap_or_else(|_| {
109
+ content
110
+ .to_r_string()
111
+ .map(|s| s.to_string().unwrap_or_else(|_| "{}".to_string()))
112
+ .unwrap_or_else(|_| "{}".to_string())
113
+ })
114
+ };
115
+
116
+ let response = Response::builder()
117
+ .status(StatusCode::from_u16(status as u16).unwrap_or(StatusCode::OK))
118
+ .header("content-type", "application/json")
119
+ .body(Body::from(body_str))
120
+ .map_err(|e| format!("Failed to build response: {}", e))?;
121
+
122
+ return Ok(HookResult::ShortCircuit(response));
123
+ }
124
+
125
+ let method = result_hash
126
+ .get(ruby.to_symbol("method"))
127
+ .and_then(|v| String::try_convert(v).ok())
128
+ .unwrap_or_else(|| "GET".to_string());
129
+ let path = result_hash
130
+ .get(ruby.to_symbol("path"))
131
+ .and_then(|v| String::try_convert(v).ok())
132
+ .unwrap_or_else(|| "/".to_string());
133
+
134
+ let req_builder = Request::builder().method(method.as_str()).uri(path);
135
+
136
+ let body = if let Some(body_val) = result_hash.get(ruby.to_symbol("body")) {
137
+ if body_val.is_nil() {
138
+ Body::empty()
139
+ } else {
140
+ let body_str = String::try_convert(body_val).unwrap_or_else(|_| {
141
+ body_val
142
+ .to_r_string()
143
+ .map(|s| s.to_string().unwrap_or_default())
144
+ .unwrap_or_default()
145
+ });
146
+ Body::from(body_str)
147
+ }
148
+ } else {
149
+ Body::empty()
150
+ };
151
+
152
+ let request = req_builder
153
+ .body(body)
154
+ .map_err(|e| format!("Failed to build request: {}", e))?;
155
+
156
+ Ok(HookResult::Continue(request))
157
+ } else {
158
+ Err(format!("Hook must return a Hash, got {}", unsafe {
159
+ result.classname()
160
+ }))
161
+ }
162
+ });
163
+
164
+ result.map_err(|e| format!("Hook '{}' task error: {}", name_for_error, e))
165
+ })
166
+ }
167
+
168
+ fn execute_response<'a>(
169
+ &'a self,
170
+ resp: Response<Body>,
171
+ ) -> Pin<Box<dyn Future<Output = Result<HookResult<Response<Body>, Response<Body>>, String>> + Send + 'a>> {
172
+ let func = self.func;
173
+ let name = self.name.clone();
174
+ let name_for_error = name.clone();
175
+
176
+ Box::pin(async move {
177
+ let (parts, body) = resp.into_parts();
178
+ let body_bytes = axum::body::to_bytes(body, usize::MAX)
179
+ .await
180
+ .map_err(|e| format!("Failed to read response body: {}", e))?;
181
+
182
+ let body_value: JsonValue = if body_bytes.is_empty() {
183
+ JsonValue::Null
184
+ } else {
185
+ serde_json::from_slice(&body_bytes)
186
+ .unwrap_or_else(|_| JsonValue::String(String::from_utf8_lossy(&body_bytes).to_string()))
187
+ };
188
+
189
+ let result = magnus::Ruby::get()
190
+ .map_err(|e| format!("Failed to get Ruby: {}", e))
191
+ .and_then(|ruby| {
192
+ let response_hash = RHash::new();
193
+
194
+ response_hash
195
+ .aset(
196
+ ruby.to_symbol("status_code"),
197
+ ruby.integer_from_i64(parts.status.as_u16() as i64),
198
+ )
199
+ .map_err(|e| format!("Failed to set status_code: {}", e))?;
200
+
201
+ let headers_hash = RHash::new();
202
+ for (key, value) in parts.headers.iter() {
203
+ headers_hash
204
+ .aset(ruby.str_new(key.as_str()), ruby.str_new(value.to_str().unwrap_or("")))
205
+ .map_err(|e| format!("Failed to set header: {}", e))?;
206
+ }
207
+ response_hash
208
+ .aset(ruby.to_symbol("headers"), headers_hash)
209
+ .map_err(|e| format!("Failed to set headers: {}", e))?;
210
+
211
+ let body_str =
212
+ serde_json::to_string(&body_value).map_err(|e| format!("Failed to serialize body: {}", e))?;
213
+ response_hash
214
+ .aset(ruby.to_symbol("content"), ruby.str_new(&body_str))
215
+ .map_err(|e| format!("Failed to set content: {}", e))?;
216
+
217
+ let func_value = ruby.get_inner(func);
218
+ let result: Value = func_value
219
+ .funcall("call", (response_hash,))
220
+ .map_err(|e| format!("Hook '{}' call failed: {}", name, e))?;
221
+
222
+ if let Some(result_hash) = RHash::from_value(result) {
223
+ let status = result_hash
224
+ .get(ruby.to_symbol("status_code"))
225
+ .and_then(|v| i64::try_convert(v).ok())
226
+ .unwrap_or(200);
227
+
228
+ let content = result_hash
229
+ .get(ruby.to_symbol("content"))
230
+ .or_else(|| result_hash.get(ruby.to_symbol("body")))
231
+ .unwrap_or_else(|| ruby.qnil().as_value());
232
+
233
+ let body_str = if content.is_nil() {
234
+ "{}".to_string()
235
+ } else {
236
+ String::try_convert(content).unwrap_or_else(|_| {
237
+ content
238
+ .to_r_string()
239
+ .map(|s| s.to_string().unwrap_or_else(|_| "{}".to_string()))
240
+ .unwrap_or_else(|_| "{}".to_string())
241
+ })
242
+ };
243
+
244
+ let mut response_builder =
245
+ Response::builder().status(StatusCode::from_u16(status as u16).unwrap_or(StatusCode::OK));
246
+
247
+ response_builder = response_builder.header("content-type", "application/json");
248
+
249
+ let response = response_builder
250
+ .body(Body::from(body_str))
251
+ .map_err(|e| format!("Failed to build response: {}", e))?;
252
+
253
+ Ok(HookResult::Continue(response))
254
+ } else {
255
+ Err(format!("Hook must return a Hash, got {}", unsafe {
256
+ result.classname()
257
+ }))
258
+ }
259
+ });
260
+
261
+ result.map_err(|e| format!("Hook '{}' task error: {}", name_for_error, e))
262
+ })
263
+ }
264
+ }
265
+
266
+ unsafe impl Send for RubyLifecycleHook {}
267
+ 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
+ }