spikard 0.3.5 → 0.5.0

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 +10 -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 -360
  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 +688 -0
  63. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +457 -699
  64. data/vendor/crates/spikard-http/Cargo.toml +64 -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 +830 -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 +540 -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 +735 -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 +1502 -805
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +770 -119
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +599 -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 +60 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +283 -285
  100. data/vendor/crates/spikard-http/src/testing.rs +377 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1375 -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 +1810 -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 +447 -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 +308 -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} +551 -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 +635 -0
  134. data/vendor/crates/spikard-rb/src/websocket.rs +374 -233
  135. metadata +46 -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,283 +1,308 @@
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
- }
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::{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<Result<Runtime, std::io::Error>> = Lazy::new(|| {
27
+ Builder::new_multi_thread()
28
+ .enable_all()
29
+ .build()
30
+ });
31
+
32
+ pub fn global_runtime_raw() -> Result<&'static Runtime, std::io::Error> {
33
+ match &*GLOBAL_RUNTIME {
34
+ Ok(runtime) => Ok(runtime),
35
+ Err(err) => Err(std::io::Error::new(err.kind(), err.to_string())),
36
+ }
37
+ }
38
+
39
+ pub fn global_runtime(ruby: &Ruby) -> Result<&'static Runtime, Error> {
40
+ global_runtime_raw().map_err(|err| {
41
+ Error::new(
42
+ ruby.exception_runtime_error(),
43
+ format!("Failed to initialise global Tokio runtime: {err}"),
44
+ )
45
+ })
46
+ }
47
+
48
+ pub fn global_runtime_or_err() -> Result<&'static Runtime, Error> {
49
+ global_runtime_raw().map_err(|err| {
50
+ Error::new(
51
+ magnus::exception::runtime_error(),
52
+ format!("Failed to initialise global Tokio runtime: {err}"),
53
+ )
54
+ })
55
+ }
56
+
57
+ /// Start the Spikard HTTP server from Ruby
58
+ ///
59
+ /// Creates an Axum HTTP server in a dedicated background thread with its own Tokio runtime.
60
+ ///
61
+ /// # Arguments
62
+ ///
63
+ /// * `ruby` - Ruby VM reference
64
+ /// * `routes_json` - JSON string containing route metadata
65
+ /// * `handlers` - Ruby Hash mapping handler_name => Proc
66
+ /// * `config_value` - Ruby ServerConfig object with all middleware settings
67
+ /// * `hooks_value` - Ruby Hash of lifecycle hooks (optional)
68
+ /// * `ws_handlers` - Ruby Hash of WebSocket handlers (optional)
69
+ /// * `sse_producers` - Ruby Hash of SSE producers (optional)
70
+ ///
71
+ /// # Example (Ruby)
72
+ ///
73
+ /// ```ruby
74
+ /// config = Spikard::ServerConfig.new(host: '0.0.0.0', port: 8000)
75
+ /// Spikard::Native.run_server(routes_json, handlers, config, hooks, ws_handlers, sse_producers)
76
+ /// ```
77
+ pub fn run_server(
78
+ ruby: &Ruby,
79
+ routes_json: String,
80
+ handlers: Value,
81
+ config_value: Value,
82
+ hooks_value: Value,
83
+ ws_handlers: Value,
84
+ sse_producers: Value,
85
+ ) -> Result<(), Error> {
86
+ let mut config = extract_server_config(ruby, config_value)?;
87
+
88
+ let host = config.host.clone();
89
+ let port = config.port;
90
+
91
+ let metadata: Vec<RouteMetadata> = serde_json::from_str(&routes_json)
92
+ .map_err(|err| Error::new(ruby.exception_arg_error(), format!("Invalid routes JSON: {}", err)))?;
93
+
94
+ let handlers_hash = RHash::from_value(handlers).ok_or_else(|| {
95
+ Error::new(
96
+ ruby.exception_arg_error(),
97
+ "handlers parameter must be a Hash of handler_name => Proc",
98
+ )
99
+ })?;
100
+
101
+ let json_module = ruby
102
+ .class_object()
103
+ .funcall::<_, _, Value>("const_get", ("JSON",))
104
+ .map_err(|err| Error::new(ruby.exception_name_error(), format!("JSON module not found: {}", err)))?;
105
+
106
+ let schema_registry = SchemaRegistry::new();
107
+
108
+ let mut routes_with_handlers: Vec<(Route, Arc<dyn Handler>)> = Vec::new();
109
+
110
+ for route_meta in metadata {
111
+ let route = Route::from_metadata(route_meta.clone(), &schema_registry)
112
+ .map_err(|e| Error::new(ruby.exception_runtime_error(), format!("Failed to create route: {}", e)))?;
113
+
114
+ let handler_key = ruby.str_new(&route_meta.handler_name);
115
+ let handler_value: Value = match handlers_hash.lookup(handler_key) {
116
+ Ok(val) => val,
117
+ Err(_) => {
118
+ return Err(Error::new(
119
+ ruby.exception_arg_error(),
120
+ format!("Handler '{}' not found in handlers hash", route_meta.handler_name),
121
+ ));
122
+ }
123
+ };
124
+
125
+ let ruby_handler = RubyHandler::new_for_server(
126
+ ruby,
127
+ handler_value,
128
+ route_meta.handler_name.clone(),
129
+ route_meta.method.clone(),
130
+ route_meta.path.clone(),
131
+ json_module,
132
+ &route,
133
+ )?;
134
+
135
+ routes_with_handlers.push((route, Arc::new(ruby_handler) as Arc<dyn Handler>));
136
+ }
137
+
138
+ let lifecycle_hooks = if !hooks_value.is_nil() {
139
+ let hooks_hash = RHash::from_value(hooks_value)
140
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "lifecycle_hooks parameter must be a Hash"))?;
141
+
142
+ let mut hooks = spikard_http::LifecycleHooks::new();
143
+ type RubyHookVec = Vec<Arc<dyn spikard_http::lifecycle::LifecycleHook<Request<Body>, Response<Body>>>>;
144
+
145
+ let extract_hooks = |key: &str| -> Result<RubyHookVec, Error> {
146
+ let key_sym = ruby.to_symbol(key);
147
+ if let Some(hooks_array) = hooks_hash.get(key_sym)
148
+ && !hooks_array.is_nil()
149
+ {
150
+ let array = RArray::from_value(hooks_array)
151
+ .ok_or_else(|| Error::new(ruby.exception_type_error(), format!("{} must be an Array", key)))?;
152
+
153
+ let mut result = Vec::new();
154
+ let len = array.len();
155
+ for i in 0..len {
156
+ let hook_value: Value = array.entry(i as isize)?;
157
+ let name = format!("{}_{}", key, i);
158
+ let ruby_hook = crate::lifecycle::RubyLifecycleHook::new(name, hook_value);
159
+ result.push(Arc::new(ruby_hook)
160
+ as Arc<
161
+ dyn spikard_http::lifecycle::LifecycleHook<Request<Body>, Response<Body>>,
162
+ >);
163
+ }
164
+ return Ok(result);
165
+ }
166
+ Ok(Vec::new())
167
+ };
168
+
169
+ for hook in extract_hooks("on_request")? {
170
+ hooks.add_on_request(hook);
171
+ }
172
+
173
+ for hook in extract_hooks("pre_validation")? {
174
+ hooks.add_pre_validation(hook);
175
+ }
176
+
177
+ for hook in extract_hooks("pre_handler")? {
178
+ hooks.add_pre_handler(hook);
179
+ }
180
+
181
+ for hook in extract_hooks("on_response")? {
182
+ hooks.add_on_response(hook);
183
+ }
184
+
185
+ for hook in extract_hooks("on_error")? {
186
+ hooks.add_on_error(hook);
187
+ }
188
+
189
+ Some(hooks)
190
+ } else {
191
+ None
192
+ };
193
+
194
+ config.lifecycle_hooks = lifecycle_hooks.map(Arc::new);
195
+
196
+ Server::init_logging();
197
+
198
+ info!("Starting Spikard server on {}:{}", host, port);
199
+ info!("Registered {} routes", routes_with_handlers.len());
200
+
201
+ let mut app_router = Server::with_handlers(config.clone(), routes_with_handlers)
202
+ .map_err(|e| Error::new(ruby.exception_runtime_error(), format!("Failed to build router: {}", e)))?;
203
+
204
+ let mut ws_endpoints = Vec::new();
205
+ if !ws_handlers.is_nil() {
206
+ let ws_hash = RHash::from_value(ws_handlers)
207
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "WebSocket handlers must be a Hash"))?;
208
+
209
+ ws_hash.foreach(|path: String, factory: Value| -> Result<ForEach, Error> {
210
+ let handler_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
211
+ Error::new(
212
+ ruby.exception_runtime_error(),
213
+ format!("Failed to create WebSocket handler: {}", e),
214
+ )
215
+ })?;
216
+
217
+ let ws_state = crate::websocket::create_websocket_state(ruby, handler_instance)?;
218
+
219
+ ws_endpoints.push((path, ws_state));
220
+
221
+ Ok(ForEach::Continue)
222
+ })?;
223
+ }
224
+
225
+ let mut sse_endpoints = Vec::new();
226
+ if !sse_producers.is_nil() {
227
+ let sse_hash = RHash::from_value(sse_producers)
228
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "SSE producers must be a Hash"))?;
229
+
230
+ sse_hash.foreach(|path: String, factory: Value| -> Result<ForEach, Error> {
231
+ let producer_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
232
+ Error::new(
233
+ ruby.exception_runtime_error(),
234
+ format!("Failed to create SSE producer: {}", e),
235
+ )
236
+ })?;
237
+
238
+ let sse_state = crate::sse::create_sse_state(ruby, producer_instance)?;
239
+
240
+ sse_endpoints.push((path, sse_state));
241
+
242
+ Ok(ForEach::Continue)
243
+ })?;
244
+ }
245
+
246
+ use axum::routing::get;
247
+ for (path, ws_state) in ws_endpoints {
248
+ info!("Registered WebSocket endpoint: {}", path);
249
+ app_router = app_router.route(
250
+ &path,
251
+ get(spikard_http::websocket_handler::<crate::websocket::RubyWebSocketHandler>).with_state(ws_state),
252
+ );
253
+ }
254
+
255
+ for (path, sse_state) in sse_endpoints {
256
+ info!("Registered SSE endpoint: {}", path);
257
+ app_router = app_router.route(
258
+ &path,
259
+ get(spikard_http::sse_handler::<crate::sse::RubySseEventProducer>).with_state(sse_state),
260
+ );
261
+ }
262
+
263
+ let addr = format!("{}:{}", config.host, config.port);
264
+ let socket_addr: std::net::SocketAddr = addr.parse().map_err(|e| {
265
+ Error::new(
266
+ ruby.exception_arg_error(),
267
+ format!("Invalid socket address {}: {}", addr, e),
268
+ )
269
+ })?;
270
+
271
+ let runtime = tokio::runtime::Builder::new_current_thread()
272
+ .enable_all()
273
+ .build()
274
+ .map_err(|e| {
275
+ Error::new(
276
+ ruby.exception_runtime_error(),
277
+ format!("Failed to create Tokio runtime: {}", e),
278
+ )
279
+ })?;
280
+
281
+ let background_config = config.background_tasks.clone();
282
+
283
+ runtime
284
+ .block_on(async move {
285
+ let listener = tokio::net::TcpListener::bind(socket_addr)
286
+ .await
287
+ .map_err(|err| format!("Failed to bind to {socket_addr}: {err}"))?;
288
+
289
+ info!("Server listening on {}", socket_addr);
290
+
291
+ let background_runtime = spikard_http::BackgroundRuntime::start(background_config.clone()).await;
292
+ crate::background::install_handle(background_runtime.handle());
293
+
294
+ let serve_result = axum::serve(listener, app_router).await;
295
+
296
+ crate::background::clear_handle();
297
+
298
+ if let Err(err) = background_runtime.shutdown().await {
299
+ warn!("Failed to drain background tasks during shutdown: {:?}", err);
300
+ }
301
+
302
+ serve_result.map_err(|e| format!("Server error: {e}"))?;
303
+ Ok::<(), String>(())
304
+ })
305
+ .map_err(|msg| Error::new(ruby.exception_runtime_error(), msg))?;
306
+
307
+ Ok(())
308
+ }