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,409 +0,0 @@
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
- }