spikard 0.3.6 → 0.6.1

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 +13 -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 -366
  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 +696 -0
  63. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +457 -699
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -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 +838 -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 +560 -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 +768 -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 +1593 -805
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -119
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -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 +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -285
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -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 +1806 -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 +442 -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 +305 -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} +538 -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 +608 -0
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -233
  135. metadata +60 -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,409 +1,375 @@
1
- //! Ruby dependency injection implementations
2
- //!
3
- //! This module provides Ruby-specific implementations of the Dependency trait,
4
- //! bridging Ruby values and Procs to the Rust DI system.
5
-
6
- #![allow(dead_code)]
7
-
8
- use http::Request;
9
- use magnus::prelude::*;
10
- use magnus::value::{InnerValue, Opaque};
11
- use magnus::{Error, RHash, Ruby, TryConvert, Value};
12
- use serde_json::Value as JsonValue;
13
- use spikard_core::di::{Dependency, DependencyError, ResolvedDependencies};
14
- use spikard_core::request_data::RequestData;
15
- use std::any::Any;
16
- use std::pin::Pin;
17
- use std::sync::Arc;
18
-
19
- /// Ruby value dependency
20
- ///
21
- /// Wraps a Ruby object as a static dependency value
22
- pub struct RubyValueDependency {
23
- key: String,
24
- value: Opaque<Value>,
25
- }
26
-
27
- impl RubyValueDependency {
28
- pub fn new(key: String, value: Value) -> Self {
29
- Self {
30
- key,
31
- value: Opaque::from(value),
32
- }
33
- }
34
- }
35
-
36
- impl Dependency for RubyValueDependency {
37
- fn key(&self) -> &str {
38
- &self.key
39
- }
40
-
41
- fn depends_on(&self) -> Vec<String> {
42
- Vec::new() // Value dependencies have no dependencies
43
- }
44
-
45
- fn resolve(
46
- &self,
47
- _request: &Request<()>,
48
- _request_data: &RequestData,
49
- _resolved: &ResolvedDependencies,
50
- ) -> Pin<Box<dyn std::future::Future<Output = Result<Arc<dyn Any + Send + Sync>, DependencyError>> + Send + '_>>
51
- {
52
- Box::pin(async move {
53
- // Get the Ruby value
54
- let ruby = Ruby::get().map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?;
55
-
56
- let value = self.value.get_inner_with(&ruby);
57
-
58
- // Convert to JSON and back to make it Send + Sync
59
- let json_value = ruby_value_to_json(&ruby, value)
60
- .map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?;
61
-
62
- Ok(Arc::new(json_value) as Arc<dyn Any + Send + Sync>)
63
- })
64
- }
65
-
66
- fn singleton(&self) -> bool {
67
- true // Value dependencies are always singletons
68
- }
69
-
70
- fn cacheable(&self) -> bool {
71
- true
72
- }
73
- }
74
-
75
- /// Ruby factory dependency
76
- ///
77
- /// Wraps a Ruby Proc as a factory dependency
78
- pub struct RubyFactoryDependency {
79
- key: String,
80
- factory: Opaque<Value>,
81
- depends_on: Vec<String>,
82
- singleton: bool,
83
- cacheable: bool,
84
- }
85
-
86
- impl RubyFactoryDependency {
87
- pub fn new(key: String, factory: Value, depends_on: Vec<String>, singleton: bool, cacheable: bool) -> Self {
88
- Self {
89
- key,
90
- factory: Opaque::from(factory),
91
- depends_on,
92
- singleton,
93
- cacheable,
94
- }
95
- }
96
- }
97
-
98
- impl Dependency for RubyFactoryDependency {
99
- fn key(&self) -> &str {
100
- &self.key
101
- }
102
-
103
- fn depends_on(&self) -> Vec<String> {
104
- self.depends_on.clone()
105
- }
106
-
107
- fn resolve(
108
- &self,
109
- _request: &Request<()>,
110
- _request_data: &RequestData,
111
- resolved: &ResolvedDependencies,
112
- ) -> Pin<Box<dyn std::future::Future<Output = Result<Arc<dyn Any + Send + Sync>, DependencyError>> + Send + '_>>
113
- {
114
- // Clone data needed in async block
115
- let factory = self.factory;
116
- let depends_on = self.depends_on.clone();
117
- let key = self.key.clone();
118
- let is_singleton = self.singleton;
119
- let resolved_clone = resolved.clone();
120
-
121
- // Extract resolved dependencies now (before async)
122
- // Need to handle both JsonValue and RubyValueWrapper types
123
- let resolved_deps: Vec<(String, JsonValue)> = depends_on
124
- .iter()
125
- .filter_map(|dep_key| {
126
- // Try JsonValue first
127
- if let Some(json_value) = resolved.get::<JsonValue>(dep_key) {
128
- return Some((dep_key.clone(), (*json_value).clone()));
129
- }
130
- // Try RubyValueWrapper (for singletons)
131
- if let Some(wrapper) = resolved.get::<RubyValueWrapper>(dep_key) {
132
- // Convert wrapper to JSON synchronously
133
- if let Ok(ruby) = Ruby::get()
134
- && let Ok(json) = wrapper.to_json(&ruby)
135
- {
136
- return Some((dep_key.clone(), json));
137
- }
138
- }
139
- None
140
- })
141
- .collect();
142
-
143
- Box::pin(async move {
144
- let ruby = Ruby::get().map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?;
145
-
146
- // Build positional arguments array from resolved dependencies
147
- // Dependencies must be passed in the order specified by depends_on
148
- // Important: preserve the order from depends_on, not from resolved_deps iteration
149
- let args: Result<Vec<Value>, DependencyError> = depends_on
150
- .iter()
151
- .filter_map(|dep_key| {
152
- // Find this dependency in resolved_deps
153
- resolved_deps.iter().find(|(k, _)| k == dep_key).map(|(_, v)| v)
154
- })
155
- .map(|dep_value| {
156
- json_to_ruby(&ruby, dep_value).map_err(|e| DependencyError::ResolutionFailed {
157
- message: format!("Failed to convert dependency value: {}", e),
158
- })
159
- })
160
- .collect();
161
- let args = args?;
162
-
163
- // Call the factory Proc with positional arguments
164
- let factory_value = factory.get_inner_with(&ruby);
165
-
166
- // Check if factory responds to call
167
- if !factory_value
168
- .respond_to("call", false)
169
- .map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?
170
- {
171
- return Err(DependencyError::ResolutionFailed {
172
- message: format!("Dependency factory for '{}' is not callable", key),
173
- });
174
- }
175
-
176
- // Call factory with positional arguments
177
- // Use a Ruby helper to call with splatted arguments
178
- let result: Value = if !args.is_empty() {
179
- // Create a Ruby array of arguments
180
- let args_array = ruby.ary_new();
181
- for arg in &args {
182
- args_array.push(*arg).map_err(|e| DependencyError::ResolutionFailed {
183
- message: format!("Failed to push arg to array: {}", e),
184
- })?;
185
- }
186
-
187
- // Use Ruby's send with * to splat arguments
188
- // Equivalent to: factory_value.call(*args_array)
189
- let splat_lambda = ruby
190
- .eval::<Value>("lambda { |proc, args| proc.call(*args) }")
191
- .map_err(|e| DependencyError::ResolutionFailed {
192
- message: format!("Failed to create splat lambda: {}", e),
193
- })?;
194
-
195
- splat_lambda.funcall("call", (factory_value, args_array))
196
- } else {
197
- factory_value.funcall("call", ())
198
- }
199
- .map_err(|e| DependencyError::ResolutionFailed {
200
- message: format!("Failed to call factory for '{}': {}", key, e),
201
- })?;
202
-
203
- // Check if result is an array with cleanup callback (Ruby pattern: [resource, cleanup_proc])
204
- let (value_to_convert, cleanup_callback) = if result.is_kind_of(ruby.class_array()) {
205
- let array = magnus::RArray::from_value(result).ok_or_else(|| DependencyError::ResolutionFailed {
206
- message: format!("Failed to convert result to array for '{}'", key),
207
- })?;
208
-
209
- let len = array.len();
210
- if len == 2 {
211
- // Extract the resource (first element)
212
- let resource: Value = array.entry(0).map_err(|e| DependencyError::ResolutionFailed {
213
- message: format!("Failed to extract resource from array for '{}': {}", key, e),
214
- })?;
215
-
216
- // Extract cleanup callback (second element)
217
- let cleanup: Value = array.entry(1).map_err(|e| DependencyError::ResolutionFailed {
218
- message: format!("Failed to extract cleanup callback for '{}': {}", key, e),
219
- })?;
220
-
221
- (resource, Some(cleanup))
222
- } else {
223
- // Not a cleanup pattern, use the array as-is
224
- (result, None)
225
- }
226
- } else {
227
- // Not an array, use the value as-is
228
- (result, None)
229
- };
230
-
231
- // Register cleanup callback if present
232
- if let Some(cleanup_proc) = cleanup_callback {
233
- let cleanup_opaque = Opaque::from(cleanup_proc);
234
-
235
- resolved_clone.add_cleanup_task(Box::new(move || {
236
- Box::pin(async move {
237
- // Get Ruby runtime and call cleanup proc
238
- if let Ok(ruby) = Ruby::get() {
239
- let proc = cleanup_opaque.get_inner_with(&ruby);
240
- // Call the cleanup proc - ignore errors during cleanup
241
- let _ = proc.funcall::<_, _, Value>("call", ());
242
- }
243
- })
244
- }));
245
- }
246
-
247
- // For singleton dependencies, store Ruby value wrapper to preserve mutations
248
- // For non-singleton, convert to JSON immediately (no need to preserve mutations)
249
- if is_singleton {
250
- let wrapper = RubyValueWrapper::new(value_to_convert);
251
- return Ok(Arc::new(wrapper) as Arc<dyn Any + Send + Sync>);
252
- }
253
-
254
- // Convert result to JSON for non-singleton dependencies
255
- let json_value = ruby_value_to_json(&ruby, value_to_convert)
256
- .map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?;
257
-
258
- Ok(Arc::new(json_value) as Arc<dyn Any + Send + Sync>)
259
- })
260
- }
261
-
262
- fn singleton(&self) -> bool {
263
- self.singleton
264
- }
265
-
266
- fn cacheable(&self) -> bool {
267
- self.cacheable
268
- }
269
- }
270
-
271
- /// Wrapper around a Ruby Value that preserves object identity for singleton mutations
272
- ///
273
- /// This stores the Ruby object itself rather than a JSON snapshot, allowing
274
- /// singleton dependencies to maintain mutable state across requests.
275
- #[derive(Clone)]
276
- pub struct RubyValueWrapper {
277
- /// Thread-safe wrapper around Ruby Value
278
- /// Opaque<Value> is Send + Sync per magnus design
279
- value: Opaque<Value>,
280
- }
281
-
282
- impl RubyValueWrapper {
283
- /// Create a new wrapper around a Ruby value
284
- pub fn new(value: Value) -> Self {
285
- Self {
286
- value: Opaque::from(value),
287
- }
288
- }
289
-
290
- /// Get the raw Ruby value directly
291
- ///
292
- /// This preserves object identity for singletons, allowing mutations
293
- /// to persist across requests.
294
- pub fn get_value(&self, ruby: &Ruby) -> Value {
295
- self.value.get_inner_with(ruby)
296
- }
297
-
298
- /// Convert the wrapped Ruby value to JSON
299
- ///
300
- /// This is called fresh each time to capture any mutations to the object.
301
- /// For singletons, this means we see updated counter values, etc.
302
- pub fn to_json(&self, ruby: &Ruby) -> Result<JsonValue, Error> {
303
- let value = self.value.get_inner_with(ruby);
304
- ruby_value_to_json(ruby, value)
305
- }
306
- }
307
-
308
- // Safety: Opaque<Value> is designed to be Send + Sync by magnus
309
- // It holds a stable pointer that's safe to share across threads
310
- unsafe impl Send for RubyValueWrapper {}
311
- unsafe impl Sync for RubyValueWrapper {}
312
-
313
- /// Convert Ruby Value to serde_json::Value
314
- fn ruby_value_to_json(ruby: &Ruby, value: Value) -> Result<JsonValue, Error> {
315
- if value.is_nil() {
316
- return Ok(JsonValue::Null);
317
- }
318
-
319
- let json_module: Value = ruby
320
- .class_object()
321
- .const_get("JSON")
322
- .map_err(|_| Error::new(ruby.exception_runtime_error(), "JSON module not available"))?;
323
-
324
- let json_string: String = json_module.funcall("generate", (value,))?;
325
- serde_json::from_str(&json_string).map_err(|err| {
326
- Error::new(
327
- ruby.exception_runtime_error(),
328
- format!("Failed to convert Ruby value to JSON: {err}"),
329
- )
330
- })
331
- }
332
-
333
- /// Convert serde_json::Value to Ruby Value
334
- pub fn json_to_ruby(ruby: &Ruby, value: &JsonValue) -> Result<Value, Error> {
335
- match value {
336
- JsonValue::Null => Ok(ruby.qnil().as_value()),
337
- JsonValue::Bool(b) => Ok(if *b {
338
- ruby.qtrue().as_value()
339
- } else {
340
- ruby.qfalse().as_value()
341
- }),
342
- JsonValue::Number(num) => {
343
- if let Some(i) = num.as_i64() {
344
- Ok(ruby.integer_from_i64(i).as_value())
345
- } else if let Some(f) = num.as_f64() {
346
- Ok(ruby.float_from_f64(f).as_value())
347
- } else {
348
- Ok(ruby.qnil().as_value())
349
- }
350
- }
351
- JsonValue::String(str_val) => Ok(ruby.str_new(str_val).as_value()),
352
- JsonValue::Array(items) => {
353
- let array = ruby.ary_new();
354
- for item in items {
355
- array.push(json_to_ruby(ruby, item)?)?;
356
- }
357
- Ok(array.as_value())
358
- }
359
- JsonValue::Object(map) => {
360
- let hash = ruby.hash_new();
361
- for (key, item) in map {
362
- hash.aset(ruby.str_new(key), json_to_ruby(ruby, item)?)?;
363
- }
364
- Ok(hash.as_value())
365
- }
366
- }
367
- }
368
-
369
- /// Helper to extract keyword arguments from Ruby options hash
370
- pub fn extract_di_options(ruby: &Ruby, options: Value) -> Result<(Vec<String>, bool, bool), Error> {
371
- if options.is_nil() {
372
- return Ok((Vec::new(), false, true));
373
- }
374
-
375
- let hash = RHash::try_convert(options)?;
376
-
377
- // Extract depends_on
378
- let depends_on = if let Some(deps_value) = get_kw(ruby, hash, "depends_on") {
379
- if deps_value.is_nil() {
380
- Vec::new()
381
- } else {
382
- Vec::<String>::try_convert(deps_value)?
383
- }
384
- } else {
385
- Vec::new()
386
- };
387
-
388
- // Extract singleton (default false)
389
- let singleton = if let Some(singleton_value) = get_kw(ruby, hash, "singleton") {
390
- bool::try_convert(singleton_value).unwrap_or(false)
391
- } else {
392
- false
393
- };
394
-
395
- // Extract cacheable (default true)
396
- let cacheable = if let Some(cacheable_value) = get_kw(ruby, hash, "cacheable") {
397
- bool::try_convert(cacheable_value).unwrap_or(true)
398
- } else {
399
- true
400
- };
401
-
402
- Ok((depends_on, singleton, cacheable))
403
- }
404
-
405
- /// Get keyword argument from Ruby hash (tries both symbol and string keys)
406
- fn get_kw(ruby: &Ruby, hash: RHash, name: &str) -> Option<Value> {
407
- let sym = ruby.intern(name);
408
- hash.get(sym).or_else(|| hash.get(name))
409
- }
1
+ //! Ruby dependency injection implementations
2
+ //!
3
+ //! This module provides Ruby-specific implementations of the Dependency trait,
4
+ //! bridging Ruby values and Procs to the Rust DI system.
5
+
6
+ #![allow(dead_code)]
7
+
8
+ pub mod builder;
9
+
10
+ pub use builder::build_dependency_container;
11
+
12
+ use http::Request;
13
+ use magnus::prelude::*;
14
+ use magnus::value::{InnerValue, Opaque};
15
+ use magnus::{Error, RHash, Ruby, TryConvert, Value};
16
+ use serde_json::Value as JsonValue;
17
+ use spikard_core::di::{Dependency, DependencyError, ResolvedDependencies};
18
+ use spikard_core::request_data::RequestData;
19
+ use std::any::Any;
20
+ use std::pin::Pin;
21
+ use std::sync::Arc;
22
+
23
+ /// Ruby value dependency
24
+ ///
25
+ /// Wraps a Ruby object as a static dependency value
26
+ pub struct RubyValueDependency {
27
+ key: String,
28
+ value: Opaque<Value>,
29
+ }
30
+
31
+ impl RubyValueDependency {
32
+ pub fn new(key: String, value: Value) -> Self {
33
+ Self {
34
+ key,
35
+ value: Opaque::from(value),
36
+ }
37
+ }
38
+ }
39
+
40
+ impl Dependency for RubyValueDependency {
41
+ fn key(&self) -> &str {
42
+ &self.key
43
+ }
44
+
45
+ fn depends_on(&self) -> Vec<String> {
46
+ Vec::new()
47
+ }
48
+
49
+ fn resolve(
50
+ &self,
51
+ _request: &Request<()>,
52
+ _request_data: &RequestData,
53
+ _resolved: &ResolvedDependencies,
54
+ ) -> Pin<Box<dyn std::future::Future<Output = Result<Arc<dyn Any + Send + Sync>, DependencyError>> + Send + '_>>
55
+ {
56
+ Box::pin(async move {
57
+ let ruby = Ruby::get().map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?;
58
+
59
+ let value = self.value.get_inner_with(&ruby);
60
+
61
+ let json_value = ruby_value_to_json(&ruby, value)
62
+ .map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?;
63
+
64
+ Ok(Arc::new(json_value) as Arc<dyn Any + Send + Sync>)
65
+ })
66
+ }
67
+
68
+ fn singleton(&self) -> bool {
69
+ true
70
+ }
71
+
72
+ fn cacheable(&self) -> bool {
73
+ true
74
+ }
75
+ }
76
+
77
+ /// Ruby factory dependency
78
+ ///
79
+ /// Wraps a Ruby Proc as a factory dependency
80
+ pub struct RubyFactoryDependency {
81
+ key: String,
82
+ factory: Opaque<Value>,
83
+ depends_on: Vec<String>,
84
+ singleton: bool,
85
+ cacheable: bool,
86
+ }
87
+
88
+ impl RubyFactoryDependency {
89
+ pub fn new(key: String, factory: Value, depends_on: Vec<String>, singleton: bool, cacheable: bool) -> Self {
90
+ Self {
91
+ key,
92
+ factory: Opaque::from(factory),
93
+ depends_on,
94
+ singleton,
95
+ cacheable,
96
+ }
97
+ }
98
+ }
99
+
100
+ impl Dependency for RubyFactoryDependency {
101
+ fn key(&self) -> &str {
102
+ &self.key
103
+ }
104
+
105
+ fn depends_on(&self) -> Vec<String> {
106
+ self.depends_on.clone()
107
+ }
108
+
109
+ fn resolve(
110
+ &self,
111
+ _request: &Request<()>,
112
+ _request_data: &RequestData,
113
+ resolved: &ResolvedDependencies,
114
+ ) -> Pin<Box<dyn std::future::Future<Output = Result<Arc<dyn Any + Send + Sync>, DependencyError>> + Send + '_>>
115
+ {
116
+ let factory = self.factory;
117
+ let depends_on = self.depends_on.clone();
118
+ let key = self.key.clone();
119
+ let is_singleton = self.singleton;
120
+ let resolved_clone = resolved.clone();
121
+
122
+ let resolved_deps: Vec<(String, JsonValue)> = depends_on
123
+ .iter()
124
+ .filter_map(|dep_key| {
125
+ if let Some(json_value) = resolved.get::<JsonValue>(dep_key) {
126
+ return Some((dep_key.clone(), (*json_value).clone()));
127
+ }
128
+ if let Some(wrapper) = resolved.get::<RubyValueWrapper>(dep_key)
129
+ && let Ok(ruby) = Ruby::get()
130
+ && let Ok(json) = wrapper.to_json(&ruby)
131
+ {
132
+ return Some((dep_key.clone(), json));
133
+ }
134
+ None
135
+ })
136
+ .collect();
137
+
138
+ Box::pin(async move {
139
+ let ruby = Ruby::get().map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?;
140
+
141
+ let args: Result<Vec<Value>, DependencyError> = depends_on
142
+ .iter()
143
+ .filter_map(|dep_key| resolved_deps.iter().find(|(k, _)| k == dep_key).map(|(_, v)| v))
144
+ .map(|dep_value| {
145
+ json_to_ruby(&ruby, dep_value).map_err(|e| DependencyError::ResolutionFailed {
146
+ message: format!("Failed to convert dependency value: {}", e),
147
+ })
148
+ })
149
+ .collect();
150
+ let args = args?;
151
+
152
+ let factory_value = factory.get_inner_with(&ruby);
153
+
154
+ if !factory_value
155
+ .respond_to("call", false)
156
+ .map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?
157
+ {
158
+ return Err(DependencyError::ResolutionFailed {
159
+ message: format!("Dependency factory for '{}' is not callable", key),
160
+ });
161
+ }
162
+
163
+ let result: Value = if !args.is_empty() {
164
+ let args_array = ruby.ary_new();
165
+ for arg in &args {
166
+ args_array.push(*arg).map_err(|e| DependencyError::ResolutionFailed {
167
+ message: format!("Failed to push arg to array: {}", e),
168
+ })?;
169
+ }
170
+
171
+ let splat_lambda = ruby
172
+ .eval::<Value>("lambda { |proc, args| proc.call(*args) }")
173
+ .map_err(|e| DependencyError::ResolutionFailed {
174
+ message: format!("Failed to create splat lambda: {}", e),
175
+ })?;
176
+
177
+ splat_lambda.funcall("call", (factory_value, args_array))
178
+ } else {
179
+ factory_value.funcall("call", ())
180
+ }
181
+ .map_err(|e| DependencyError::ResolutionFailed {
182
+ message: format!("Failed to call factory for '{}': {}", key, e),
183
+ })?;
184
+
185
+ let (value_to_convert, cleanup_callback) = if result.is_kind_of(ruby.class_array()) {
186
+ let array = magnus::RArray::from_value(result).ok_or_else(|| DependencyError::ResolutionFailed {
187
+ message: format!("Failed to convert result to array for '{}'", key),
188
+ })?;
189
+
190
+ let len = array.len();
191
+ if len == 2 {
192
+ let resource: Value = array.entry(0).map_err(|e| DependencyError::ResolutionFailed {
193
+ message: format!("Failed to extract resource from array for '{}': {}", key, e),
194
+ })?;
195
+
196
+ let cleanup: Value = array.entry(1).map_err(|e| DependencyError::ResolutionFailed {
197
+ message: format!("Failed to extract cleanup callback for '{}': {}", key, e),
198
+ })?;
199
+
200
+ (resource, Some(cleanup))
201
+ } else {
202
+ (result, None)
203
+ }
204
+ } else {
205
+ (result, None)
206
+ };
207
+
208
+ if let Some(cleanup_proc) = cleanup_callback {
209
+ let cleanup_opaque = Opaque::from(cleanup_proc);
210
+
211
+ resolved_clone.add_cleanup_task(Box::new(move || {
212
+ Box::pin(async move {
213
+ if let Ok(ruby) = Ruby::get() {
214
+ let proc = cleanup_opaque.get_inner_with(&ruby);
215
+ let _ = proc.funcall::<_, _, Value>("call", ());
216
+ }
217
+ })
218
+ }));
219
+ }
220
+
221
+ if is_singleton {
222
+ let wrapper = RubyValueWrapper::new(value_to_convert);
223
+ return Ok(Arc::new(wrapper) as Arc<dyn Any + Send + Sync>);
224
+ }
225
+
226
+ let json_value = ruby_value_to_json(&ruby, value_to_convert)
227
+ .map_err(|e| DependencyError::ResolutionFailed { message: e.to_string() })?;
228
+
229
+ Ok(Arc::new(json_value) as Arc<dyn Any + Send + Sync>)
230
+ })
231
+ }
232
+
233
+ fn singleton(&self) -> bool {
234
+ self.singleton
235
+ }
236
+
237
+ fn cacheable(&self) -> bool {
238
+ self.cacheable
239
+ }
240
+ }
241
+
242
+ /// Wrapper around a Ruby Value that preserves object identity for singleton mutations
243
+ ///
244
+ /// This stores the Ruby object itself rather than a JSON snapshot, allowing
245
+ /// singleton dependencies to maintain mutable state across requests.
246
+ #[derive(Clone)]
247
+ pub struct RubyValueWrapper {
248
+ /// Thread-safe wrapper around Ruby Value
249
+ /// Opaque<Value> is Send + Sync per magnus design
250
+ value: Opaque<Value>,
251
+ }
252
+
253
+ impl RubyValueWrapper {
254
+ /// Create a new wrapper around a Ruby value
255
+ pub fn new(value: Value) -> Self {
256
+ Self {
257
+ value: Opaque::from(value),
258
+ }
259
+ }
260
+
261
+ /// Get the raw Ruby value directly
262
+ ///
263
+ /// This preserves object identity for singletons, allowing mutations
264
+ /// to persist across requests.
265
+ pub fn get_value(&self, ruby: &Ruby) -> Value {
266
+ self.value.get_inner_with(ruby)
267
+ }
268
+
269
+ /// Convert the wrapped Ruby value to JSON
270
+ ///
271
+ /// This is called fresh each time to capture any mutations to the object.
272
+ /// For singletons, this means we see updated counter values, etc.
273
+ pub fn to_json(&self, ruby: &Ruby) -> Result<JsonValue, Error> {
274
+ let value = self.value.get_inner_with(ruby);
275
+ ruby_value_to_json(ruby, value)
276
+ }
277
+ }
278
+
279
+ unsafe impl Send for RubyValueWrapper {}
280
+ unsafe impl Sync for RubyValueWrapper {}
281
+
282
+ /// Convert Ruby Value to serde_json::Value
283
+ fn ruby_value_to_json(ruby: &Ruby, value: Value) -> Result<JsonValue, Error> {
284
+ if value.is_nil() {
285
+ return Ok(JsonValue::Null);
286
+ }
287
+
288
+ let json_module: Value = ruby
289
+ .class_object()
290
+ .const_get("JSON")
291
+ .map_err(|_| Error::new(ruby.exception_runtime_error(), "JSON module not available"))?;
292
+
293
+ let json_string: String = json_module.funcall("generate", (value,))?;
294
+ serde_json::from_str(&json_string).map_err(|err| {
295
+ Error::new(
296
+ ruby.exception_runtime_error(),
297
+ format!("Failed to convert Ruby value to JSON: {err}"),
298
+ )
299
+ })
300
+ }
301
+
302
+ /// Convert serde_json::Value to Ruby Value
303
+ pub fn json_to_ruby(ruby: &Ruby, value: &JsonValue) -> Result<Value, Error> {
304
+ match value {
305
+ JsonValue::Null => Ok(ruby.qnil().as_value()),
306
+ JsonValue::Bool(b) => Ok(if *b {
307
+ ruby.qtrue().as_value()
308
+ } else {
309
+ ruby.qfalse().as_value()
310
+ }),
311
+ JsonValue::Number(num) => {
312
+ if let Some(i) = num.as_i64() {
313
+ Ok(ruby.integer_from_i64(i).as_value())
314
+ } else if let Some(f) = num.as_f64() {
315
+ Ok(ruby.float_from_f64(f).as_value())
316
+ } else {
317
+ Ok(ruby.qnil().as_value())
318
+ }
319
+ }
320
+ JsonValue::String(str_val) => Ok(ruby.str_new(str_val).as_value()),
321
+ JsonValue::Array(items) => {
322
+ let array = ruby.ary_new();
323
+ for item in items {
324
+ array.push(json_to_ruby(ruby, item)?)?;
325
+ }
326
+ Ok(array.as_value())
327
+ }
328
+ JsonValue::Object(map) => {
329
+ let hash = ruby.hash_new();
330
+ for (key, item) in map {
331
+ hash.aset(ruby.str_new(key), json_to_ruby(ruby, item)?)?;
332
+ }
333
+ Ok(hash.as_value())
334
+ }
335
+ }
336
+ }
337
+
338
+ /// Helper to extract keyword arguments from Ruby options hash
339
+ pub fn extract_di_options(ruby: &Ruby, options: Value) -> Result<(Vec<String>, bool, bool), Error> {
340
+ if options.is_nil() {
341
+ return Ok((Vec::new(), false, true));
342
+ }
343
+
344
+ let hash = RHash::try_convert(options)?;
345
+
346
+ let depends_on = if let Some(deps_value) = get_kw(ruby, hash, "depends_on") {
347
+ if deps_value.is_nil() {
348
+ Vec::new()
349
+ } else {
350
+ Vec::<String>::try_convert(deps_value)?
351
+ }
352
+ } else {
353
+ Vec::new()
354
+ };
355
+
356
+ let singleton = if let Some(singleton_value) = get_kw(ruby, hash, "singleton") {
357
+ bool::try_convert(singleton_value).unwrap_or(false)
358
+ } else {
359
+ false
360
+ };
361
+
362
+ let cacheable = if let Some(cacheable_value) = get_kw(ruby, hash, "cacheable") {
363
+ bool::try_convert(cacheable_value).unwrap_or(true)
364
+ } else {
365
+ true
366
+ };
367
+
368
+ Ok((depends_on, singleton, cacheable))
369
+ }
370
+
371
+ /// Get keyword argument from Ruby hash (tries both symbol and string keys)
372
+ fn get_kw(ruby: &Ruby, hash: RHash, name: &str) -> Option<Value> {
373
+ let sym = ruby.intern(name);
374
+ hash.get(sym).or_else(|| hash.get(name))
375
+ }