spikard 0.2.5 → 0.3.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 (92) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +34 -1
  3. data/ext/spikard_rb/Cargo.toml +3 -3
  4. data/lib/spikard/app.rb +61 -49
  5. data/lib/spikard/converters.rb +3 -75
  6. data/lib/spikard/handler_wrapper.rb +6 -9
  7. data/lib/spikard/provide.rb +14 -28
  8. data/lib/spikard/response.rb +75 -11
  9. data/lib/spikard/streaming_response.rb +24 -1
  10. data/lib/spikard/testing.rb +1 -1
  11. data/lib/spikard/version.rb +1 -1
  12. data/sig/spikard.rbs +14 -3
  13. data/vendor/bundle/ruby/3.3.0/gems/rake-compiler-dock-1.10.0/build/buildkitd.toml +2 -0
  14. metadata +3 -80
  15. data/vendor/crates/spikard-core/Cargo.toml +0 -40
  16. data/vendor/crates/spikard-core/src/bindings/mod.rs +0 -3
  17. data/vendor/crates/spikard-core/src/bindings/response.rs +0 -133
  18. data/vendor/crates/spikard-core/src/debug.rs +0 -63
  19. data/vendor/crates/spikard-core/src/di/container.rs +0 -726
  20. data/vendor/crates/spikard-core/src/di/dependency.rs +0 -273
  21. data/vendor/crates/spikard-core/src/di/error.rs +0 -118
  22. data/vendor/crates/spikard-core/src/di/factory.rs +0 -538
  23. data/vendor/crates/spikard-core/src/di/graph.rs +0 -545
  24. data/vendor/crates/spikard-core/src/di/mod.rs +0 -192
  25. data/vendor/crates/spikard-core/src/di/resolved.rs +0 -411
  26. data/vendor/crates/spikard-core/src/di/value.rs +0 -283
  27. data/vendor/crates/spikard-core/src/http.rs +0 -153
  28. data/vendor/crates/spikard-core/src/lib.rs +0 -28
  29. data/vendor/crates/spikard-core/src/lifecycle.rs +0 -422
  30. data/vendor/crates/spikard-core/src/parameters.rs +0 -719
  31. data/vendor/crates/spikard-core/src/problem.rs +0 -310
  32. data/vendor/crates/spikard-core/src/request_data.rs +0 -189
  33. data/vendor/crates/spikard-core/src/router.rs +0 -249
  34. data/vendor/crates/spikard-core/src/schema_registry.rs +0 -183
  35. data/vendor/crates/spikard-core/src/type_hints.rs +0 -304
  36. data/vendor/crates/spikard-core/src/validation.rs +0 -699
  37. data/vendor/crates/spikard-http/Cargo.toml +0 -58
  38. data/vendor/crates/spikard-http/src/auth.rs +0 -247
  39. data/vendor/crates/spikard-http/src/background.rs +0 -249
  40. data/vendor/crates/spikard-http/src/bindings/mod.rs +0 -3
  41. data/vendor/crates/spikard-http/src/bindings/response.rs +0 -1
  42. data/vendor/crates/spikard-http/src/body_metadata.rs +0 -8
  43. data/vendor/crates/spikard-http/src/cors.rs +0 -490
  44. data/vendor/crates/spikard-http/src/debug.rs +0 -63
  45. data/vendor/crates/spikard-http/src/di_handler.rs +0 -423
  46. data/vendor/crates/spikard-http/src/handler_response.rs +0 -190
  47. data/vendor/crates/spikard-http/src/handler_trait.rs +0 -228
  48. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +0 -284
  49. data/vendor/crates/spikard-http/src/lib.rs +0 -529
  50. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +0 -149
  51. data/vendor/crates/spikard-http/src/lifecycle.rs +0 -428
  52. data/vendor/crates/spikard-http/src/middleware/mod.rs +0 -285
  53. data/vendor/crates/spikard-http/src/middleware/multipart.rs +0 -86
  54. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +0 -147
  55. data/vendor/crates/spikard-http/src/middleware/validation.rs +0 -287
  56. data/vendor/crates/spikard-http/src/openapi/mod.rs +0 -309
  57. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +0 -190
  58. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +0 -308
  59. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +0 -195
  60. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  61. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  62. data/vendor/crates/spikard-http/src/query_parser.rs +0 -369
  63. data/vendor/crates/spikard-http/src/response.rs +0 -399
  64. data/vendor/crates/spikard-http/src/router.rs +0 -1
  65. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  66. data/vendor/crates/spikard-http/src/server/handler.rs +0 -80
  67. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +0 -98
  68. data/vendor/crates/spikard-http/src/server/mod.rs +0 -805
  69. data/vendor/crates/spikard-http/src/server/request_extraction.rs +0 -119
  70. data/vendor/crates/spikard-http/src/sse.rs +0 -447
  71. data/vendor/crates/spikard-http/src/testing/form.rs +0 -14
  72. data/vendor/crates/spikard-http/src/testing/multipart.rs +0 -60
  73. data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -285
  74. data/vendor/crates/spikard-http/src/testing.rs +0 -377
  75. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  76. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  77. data/vendor/crates/spikard-http/src/websocket.rs +0 -324
  78. data/vendor/crates/spikard-rb/Cargo.toml +0 -42
  79. data/vendor/crates/spikard-rb/build.rs +0 -8
  80. data/vendor/crates/spikard-rb/src/background.rs +0 -63
  81. data/vendor/crates/spikard-rb/src/config.rs +0 -294
  82. data/vendor/crates/spikard-rb/src/conversion.rs +0 -392
  83. data/vendor/crates/spikard-rb/src/di.rs +0 -409
  84. data/vendor/crates/spikard-rb/src/handler.rs +0 -534
  85. data/vendor/crates/spikard-rb/src/lib.rs +0 -2020
  86. data/vendor/crates/spikard-rb/src/lifecycle.rs +0 -267
  87. data/vendor/crates/spikard-rb/src/server.rs +0 -283
  88. data/vendor/crates/spikard-rb/src/sse.rs +0 -231
  89. data/vendor/crates/spikard-rb/src/test_client.rs +0 -404
  90. data/vendor/crates/spikard-rb/src/test_sse.rs +0 -143
  91. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
  92. data/vendor/crates/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
- }