spikard 0.3.4 → 0.3.6

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 (180) 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 +366 -360
  23. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  24. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  25. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  26. data/vendor/crates/spikard-core/src/debug.rs +63 -63
  27. data/vendor/crates/spikard-core/src/di/container.rs +726 -726
  28. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  29. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  30. data/vendor/crates/spikard-core/src/di/factory.rs +538 -538
  31. data/vendor/crates/spikard-core/src/di/graph.rs +545 -545
  32. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  33. data/vendor/crates/spikard-core/src/di/resolved.rs +411 -411
  34. data/vendor/crates/spikard-core/src/di/value.rs +283 -283
  35. data/vendor/crates/spikard-core/src/errors.rs +39 -39
  36. data/vendor/crates/spikard-core/src/http.rs +153 -153
  37. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  38. data/vendor/crates/spikard-core/src/lifecycle.rs +422 -422
  39. data/vendor/crates/spikard-core/src/parameters.rs +722 -722
  40. data/vendor/crates/spikard-core/src/problem.rs +310 -310
  41. data/vendor/crates/spikard-core/src/request_data.rs +189 -189
  42. data/vendor/crates/spikard-core/src/router.rs +249 -249
  43. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  44. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  45. data/vendor/crates/spikard-core/src/validation.rs +699 -699
  46. data/vendor/crates/spikard-http/Cargo.toml +68 -58
  47. data/vendor/crates/spikard-http/src/auth.rs +247 -247
  48. data/vendor/crates/spikard-http/src/background.rs +249 -249
  49. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  50. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  51. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  52. data/vendor/crates/spikard-http/src/cors.rs +490 -490
  53. data/vendor/crates/spikard-http/src/debug.rs +63 -63
  54. data/vendor/crates/spikard-http/src/di_handler.rs +423 -423
  55. data/vendor/crates/spikard-http/src/handler_response.rs +190 -190
  56. data/vendor/crates/spikard-http/src/handler_trait.rs +228 -228
  57. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -284
  58. data/vendor/crates/spikard-http/src/lib.rs +529 -529
  59. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -149
  60. data/vendor/crates/spikard-http/src/lifecycle.rs +428 -428
  61. data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -285
  62. data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -86
  63. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -147
  64. data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -287
  65. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  66. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -190
  67. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -308
  68. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -195
  69. data/vendor/crates/spikard-http/src/parameters.rs +1 -1
  70. data/vendor/crates/spikard-http/src/problem.rs +1 -1
  71. data/vendor/crates/spikard-http/src/query_parser.rs +369 -369
  72. data/vendor/crates/spikard-http/src/response.rs +399 -399
  73. data/vendor/crates/spikard-http/src/router.rs +1 -1
  74. data/vendor/crates/spikard-http/src/schema_registry.rs +1 -1
  75. data/vendor/crates/spikard-http/src/server/handler.rs +87 -87
  76. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -98
  77. data/vendor/crates/spikard-http/src/server/mod.rs +805 -805
  78. data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -119
  79. data/vendor/crates/spikard-http/src/sse.rs +447 -447
  80. data/vendor/crates/spikard-http/src/testing/form.rs +14 -14
  81. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
  82. data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -285
  83. data/vendor/crates/spikard-http/src/testing.rs +377 -377
  84. data/vendor/crates/spikard-http/src/type_hints.rs +1 -1
  85. data/vendor/crates/spikard-http/src/validation.rs +1 -1
  86. data/vendor/crates/spikard-http/src/websocket.rs +324 -324
  87. data/vendor/crates/spikard-rb/Cargo.toml +42 -42
  88. data/vendor/crates/spikard-rb/build.rs +8 -8
  89. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  90. data/vendor/crates/spikard-rb/src/config.rs +294 -294
  91. data/vendor/crates/spikard-rb/src/conversion.rs +453 -453
  92. data/vendor/crates/spikard-rb/src/di.rs +409 -409
  93. data/vendor/crates/spikard-rb/src/handler.rs +625 -625
  94. data/vendor/crates/spikard-rb/src/lib.rs +2771 -2771
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +274 -274
  96. data/vendor/crates/spikard-rb/src/server.rs +283 -283
  97. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  98. data/vendor/crates/spikard-rb/src/test_client.rs +404 -404
  99. data/vendor/crates/spikard-rb/src/test_sse.rs +143 -143
  100. data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -221
  101. data/vendor/crates/spikard-rb/src/websocket.rs +233 -233
  102. metadata +1 -79
  103. data/vendor/spikard-core/Cargo.toml +0 -40
  104. data/vendor/spikard-core/src/bindings/mod.rs +0 -3
  105. data/vendor/spikard-core/src/bindings/response.rs +0 -133
  106. data/vendor/spikard-core/src/debug.rs +0 -63
  107. data/vendor/spikard-core/src/di/container.rs +0 -726
  108. data/vendor/spikard-core/src/di/dependency.rs +0 -273
  109. data/vendor/spikard-core/src/di/error.rs +0 -118
  110. data/vendor/spikard-core/src/di/factory.rs +0 -538
  111. data/vendor/spikard-core/src/di/graph.rs +0 -545
  112. data/vendor/spikard-core/src/di/mod.rs +0 -192
  113. data/vendor/spikard-core/src/di/resolved.rs +0 -411
  114. data/vendor/spikard-core/src/di/value.rs +0 -283
  115. data/vendor/spikard-core/src/http.rs +0 -153
  116. data/vendor/spikard-core/src/lib.rs +0 -28
  117. data/vendor/spikard-core/src/lifecycle.rs +0 -422
  118. data/vendor/spikard-core/src/parameters.rs +0 -719
  119. data/vendor/spikard-core/src/problem.rs +0 -310
  120. data/vendor/spikard-core/src/request_data.rs +0 -189
  121. data/vendor/spikard-core/src/router.rs +0 -249
  122. data/vendor/spikard-core/src/schema_registry.rs +0 -183
  123. data/vendor/spikard-core/src/type_hints.rs +0 -304
  124. data/vendor/spikard-core/src/validation.rs +0 -699
  125. data/vendor/spikard-http/Cargo.toml +0 -58
  126. data/vendor/spikard-http/src/auth.rs +0 -247
  127. data/vendor/spikard-http/src/background.rs +0 -249
  128. data/vendor/spikard-http/src/bindings/mod.rs +0 -3
  129. data/vendor/spikard-http/src/bindings/response.rs +0 -1
  130. data/vendor/spikard-http/src/body_metadata.rs +0 -8
  131. data/vendor/spikard-http/src/cors.rs +0 -490
  132. data/vendor/spikard-http/src/debug.rs +0 -63
  133. data/vendor/spikard-http/src/di_handler.rs +0 -423
  134. data/vendor/spikard-http/src/handler_response.rs +0 -190
  135. data/vendor/spikard-http/src/handler_trait.rs +0 -228
  136. data/vendor/spikard-http/src/handler_trait_tests.rs +0 -284
  137. data/vendor/spikard-http/src/lib.rs +0 -529
  138. data/vendor/spikard-http/src/lifecycle/adapter.rs +0 -149
  139. data/vendor/spikard-http/src/lifecycle.rs +0 -428
  140. data/vendor/spikard-http/src/middleware/mod.rs +0 -285
  141. data/vendor/spikard-http/src/middleware/multipart.rs +0 -86
  142. data/vendor/spikard-http/src/middleware/urlencoded.rs +0 -147
  143. data/vendor/spikard-http/src/middleware/validation.rs +0 -287
  144. data/vendor/spikard-http/src/openapi/mod.rs +0 -309
  145. data/vendor/spikard-http/src/openapi/parameter_extraction.rs +0 -190
  146. data/vendor/spikard-http/src/openapi/schema_conversion.rs +0 -308
  147. data/vendor/spikard-http/src/openapi/spec_generation.rs +0 -195
  148. data/vendor/spikard-http/src/parameters.rs +0 -1
  149. data/vendor/spikard-http/src/problem.rs +0 -1
  150. data/vendor/spikard-http/src/query_parser.rs +0 -369
  151. data/vendor/spikard-http/src/response.rs +0 -399
  152. data/vendor/spikard-http/src/router.rs +0 -1
  153. data/vendor/spikard-http/src/schema_registry.rs +0 -1
  154. data/vendor/spikard-http/src/server/handler.rs +0 -80
  155. data/vendor/spikard-http/src/server/lifecycle_execution.rs +0 -98
  156. data/vendor/spikard-http/src/server/mod.rs +0 -805
  157. data/vendor/spikard-http/src/server/request_extraction.rs +0 -119
  158. data/vendor/spikard-http/src/sse.rs +0 -447
  159. data/vendor/spikard-http/src/testing/form.rs +0 -14
  160. data/vendor/spikard-http/src/testing/multipart.rs +0 -60
  161. data/vendor/spikard-http/src/testing/test_client.rs +0 -285
  162. data/vendor/spikard-http/src/testing.rs +0 -377
  163. data/vendor/spikard-http/src/type_hints.rs +0 -1
  164. data/vendor/spikard-http/src/validation.rs +0 -1
  165. data/vendor/spikard-http/src/websocket.rs +0 -324
  166. data/vendor/spikard-rb/Cargo.toml +0 -42
  167. data/vendor/spikard-rb/build.rs +0 -8
  168. data/vendor/spikard-rb/src/background.rs +0 -63
  169. data/vendor/spikard-rb/src/config.rs +0 -294
  170. data/vendor/spikard-rb/src/conversion.rs +0 -392
  171. data/vendor/spikard-rb/src/di.rs +0 -409
  172. data/vendor/spikard-rb/src/handler.rs +0 -534
  173. data/vendor/spikard-rb/src/lib.rs +0 -2020
  174. data/vendor/spikard-rb/src/lifecycle.rs +0 -267
  175. data/vendor/spikard-rb/src/server.rs +0 -283
  176. data/vendor/spikard-rb/src/sse.rs +0 -231
  177. data/vendor/spikard-rb/src/test_client.rs +0 -404
  178. data/vendor/spikard-rb/src/test_sse.rs +0 -143
  179. data/vendor/spikard-rb/src/test_websocket.rs +0 -221
  180. data/vendor/spikard-rb/src/websocket.rs +0 -233
@@ -1,267 +0,0 @@
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 {}
@@ -1,283 +0,0 @@
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
- }