spikard 0.2.0 → 0.2.5
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.
- checksums.yaml +4 -4
- data/README.md +2 -2
- data/ext/spikard_rb/Cargo.toml +3 -2
- data/lib/spikard/version.rb +1 -1
- data/vendor/bundle/ruby/3.3.0/gems/diff-lcs-1.6.2/mise.toml +5 -0
- data/vendor/crates/spikard-core/Cargo.toml +40 -0
- data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -0
- data/vendor/crates/spikard-core/src/bindings/response.rs +133 -0
- data/vendor/crates/spikard-core/src/debug.rs +63 -0
- data/vendor/crates/spikard-core/src/di/container.rs +726 -0
- data/vendor/crates/spikard-core/src/di/dependency.rs +273 -0
- data/vendor/crates/spikard-core/src/di/error.rs +118 -0
- data/vendor/crates/spikard-core/src/di/factory.rs +538 -0
- data/vendor/crates/spikard-core/src/di/graph.rs +545 -0
- data/vendor/crates/spikard-core/src/di/mod.rs +192 -0
- data/vendor/crates/spikard-core/src/di/resolved.rs +411 -0
- data/vendor/crates/spikard-core/src/di/value.rs +283 -0
- data/vendor/crates/spikard-core/src/http.rs +153 -0
- data/vendor/crates/spikard-core/src/lib.rs +28 -0
- data/vendor/crates/spikard-core/src/lifecycle.rs +422 -0
- data/vendor/crates/spikard-core/src/parameters.rs +719 -0
- data/vendor/crates/spikard-core/src/problem.rs +310 -0
- data/vendor/crates/spikard-core/src/request_data.rs +189 -0
- data/vendor/crates/spikard-core/src/router.rs +249 -0
- data/vendor/crates/spikard-core/src/schema_registry.rs +183 -0
- data/vendor/crates/spikard-core/src/type_hints.rs +304 -0
- data/vendor/crates/spikard-core/src/validation.rs +699 -0
- data/vendor/crates/spikard-http/Cargo.toml +58 -0
- data/vendor/crates/spikard-http/src/auth.rs +247 -0
- data/vendor/crates/spikard-http/src/background.rs +249 -0
- data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -0
- data/vendor/crates/spikard-http/src/bindings/response.rs +1 -0
- data/vendor/crates/spikard-http/src/body_metadata.rs +8 -0
- data/vendor/crates/spikard-http/src/cors.rs +490 -0
- data/vendor/crates/spikard-http/src/debug.rs +63 -0
- data/vendor/crates/spikard-http/src/di_handler.rs +423 -0
- data/vendor/crates/spikard-http/src/handler_response.rs +190 -0
- data/vendor/crates/spikard-http/src/handler_trait.rs +228 -0
- data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -0
- data/vendor/crates/spikard-http/src/lib.rs +529 -0
- data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -0
- data/vendor/crates/spikard-http/src/lifecycle.rs +428 -0
- data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -0
- data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -0
- data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -0
- data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -0
- data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -0
- data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -0
- data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -0
- data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -0
- data/vendor/crates/spikard-http/src/parameters.rs +1 -0
- data/vendor/crates/spikard-http/src/problem.rs +1 -0
- data/vendor/crates/spikard-http/src/query_parser.rs +369 -0
- data/vendor/crates/spikard-http/src/response.rs +399 -0
- data/vendor/crates/spikard-http/src/router.rs +1 -0
- data/vendor/crates/spikard-http/src/schema_registry.rs +1 -0
- data/vendor/crates/spikard-http/src/server/handler.rs +80 -0
- data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -0
- data/vendor/crates/spikard-http/src/server/mod.rs +805 -0
- data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -0
- data/vendor/crates/spikard-http/src/sse.rs +447 -0
- data/vendor/crates/spikard-http/src/testing/form.rs +14 -0
- data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -0
- data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -0
- data/vendor/crates/spikard-http/src/testing.rs +377 -0
- data/vendor/crates/spikard-http/src/type_hints.rs +1 -0
- data/vendor/crates/spikard-http/src/validation.rs +1 -0
- data/vendor/crates/spikard-http/src/websocket.rs +324 -0
- data/vendor/crates/spikard-rb/Cargo.toml +42 -0
- data/vendor/crates/spikard-rb/build.rs +8 -0
- data/vendor/crates/spikard-rb/src/background.rs +63 -0
- data/vendor/crates/spikard-rb/src/config.rs +294 -0
- data/vendor/crates/spikard-rb/src/conversion.rs +392 -0
- data/vendor/crates/spikard-rb/src/di.rs +409 -0
- data/vendor/crates/spikard-rb/src/handler.rs +534 -0
- data/vendor/crates/spikard-rb/src/lib.rs +2020 -0
- data/vendor/crates/spikard-rb/src/lifecycle.rs +267 -0
- data/vendor/crates/spikard-rb/src/server.rs +283 -0
- data/vendor/crates/spikard-rb/src/sse.rs +231 -0
- data/vendor/crates/spikard-rb/src/test_client.rs +404 -0
- data/vendor/crates/spikard-rb/src/test_sse.rs +143 -0
- data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -0
- data/vendor/crates/spikard-rb/src/websocket.rs +233 -0
- metadata +81 -2
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
//! Ruby SSE producer bindings
|
|
2
|
+
//!
|
|
3
|
+
//! This module provides the bridge between Ruby blocks/procs and Rust's SSE system.
|
|
4
|
+
//! Uses magnus to safely call Ruby code from Rust async tasks.
|
|
5
|
+
|
|
6
|
+
use magnus::{RHash, Value, prelude::*, value::Opaque};
|
|
7
|
+
use serde_json::Value as JsonValue;
|
|
8
|
+
use spikard_http::{SseEvent, SseEventProducer};
|
|
9
|
+
use tracing::{debug, error};
|
|
10
|
+
|
|
11
|
+
/// Ruby implementation of SseEventProducer
|
|
12
|
+
pub struct RubySseEventProducer {
|
|
13
|
+
/// Producer name for debugging
|
|
14
|
+
name: String,
|
|
15
|
+
/// Ruby proc/callable for next_event (Opaque for Send safety)
|
|
16
|
+
next_event_proc: Opaque<Value>,
|
|
17
|
+
/// Ruby proc/callable for on_connect (Opaque for Send safety)
|
|
18
|
+
on_connect_proc: Option<Opaque<Value>>,
|
|
19
|
+
/// Ruby proc/callable for on_disconnect (Opaque for Send safety)
|
|
20
|
+
on_disconnect_proc: Option<Opaque<Value>>,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
impl RubySseEventProducer {
|
|
24
|
+
/// Create a new Ruby SSE event producer
|
|
25
|
+
#[allow(dead_code)]
|
|
26
|
+
pub fn new(
|
|
27
|
+
name: String,
|
|
28
|
+
next_event_proc: Value,
|
|
29
|
+
on_connect_proc: Option<Value>,
|
|
30
|
+
on_disconnect_proc: Option<Value>,
|
|
31
|
+
) -> Self {
|
|
32
|
+
Self {
|
|
33
|
+
name,
|
|
34
|
+
next_event_proc: next_event_proc.into(),
|
|
35
|
+
on_connect_proc: on_connect_proc.map(|v| v.into()),
|
|
36
|
+
on_disconnect_proc: on_disconnect_proc.map(|v| v.into()),
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// Convert Ruby value to JSON
|
|
41
|
+
fn ruby_to_json(ruby: &magnus::Ruby, value: Value) -> Result<JsonValue, String> {
|
|
42
|
+
if value.is_nil() {
|
|
43
|
+
return Ok(JsonValue::Null);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let json_module: Value = ruby
|
|
47
|
+
.class_object()
|
|
48
|
+
.const_get("JSON")
|
|
49
|
+
.map_err(|e| format!("JSON module not available: {}", e))?;
|
|
50
|
+
|
|
51
|
+
let json_str: String = json_module
|
|
52
|
+
.funcall("generate", (value,))
|
|
53
|
+
.map_err(|e| format!("Failed to generate JSON: {}", e))?;
|
|
54
|
+
|
|
55
|
+
serde_json::from_str(&json_str).map_err(|e| format!("Failed to parse JSON: {}", e))
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
impl SseEventProducer for RubySseEventProducer {
|
|
60
|
+
async fn next_event(&self) -> Option<SseEvent> {
|
|
61
|
+
debug!("Ruby SSE producer '{}': next_event", self.name);
|
|
62
|
+
|
|
63
|
+
match magnus::Ruby::get()
|
|
64
|
+
.map_err(|e| format!("Failed to get Ruby: {}", e))
|
|
65
|
+
.and_then(|ruby| {
|
|
66
|
+
debug!("Ruby SSE producer: acquired Ruby VM");
|
|
67
|
+
|
|
68
|
+
let proc_value = ruby.get_inner(self.next_event_proc);
|
|
69
|
+
let result: Value = proc_value
|
|
70
|
+
.funcall("call", ())
|
|
71
|
+
.map_err(|e| format!("Producer '{}' call failed: {}", self.name, e))?;
|
|
72
|
+
|
|
73
|
+
debug!("Ruby SSE producer: called next_event proc");
|
|
74
|
+
|
|
75
|
+
if result.is_nil() {
|
|
76
|
+
debug!("Ruby SSE producer: received nil, ending stream");
|
|
77
|
+
return Ok(None);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let result_hash = if let Some(hash) = RHash::from_value(result) {
|
|
81
|
+
hash
|
|
82
|
+
} else {
|
|
83
|
+
let hash_value: Value = result.funcall("to_h", ()).map_err(|e| {
|
|
84
|
+
format!(
|
|
85
|
+
"next_event must return a Hash/SseEvent convertible via to_h ({}): {}",
|
|
86
|
+
unsafe { result.classname() },
|
|
87
|
+
e
|
|
88
|
+
)
|
|
89
|
+
})?;
|
|
90
|
+
RHash::from_value(hash_value).ok_or_else(|| {
|
|
91
|
+
format!("next_event to_h must return a Hash, got {}", unsafe {
|
|
92
|
+
hash_value.classname()
|
|
93
|
+
})
|
|
94
|
+
})?
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
let data_value = result_hash
|
|
98
|
+
.get(ruby.to_symbol("data"))
|
|
99
|
+
.ok_or_else(|| "next_event Hash must have :data key".to_string())?;
|
|
100
|
+
|
|
101
|
+
let data_json = Self::ruby_to_json(&ruby, data_value)?;
|
|
102
|
+
|
|
103
|
+
let event_type: Option<String> = result_hash
|
|
104
|
+
.get(ruby.to_symbol("event_type"))
|
|
105
|
+
.and_then(|v| if v.is_nil() { None } else { String::try_convert(v).ok() });
|
|
106
|
+
|
|
107
|
+
let id: Option<String> = result_hash
|
|
108
|
+
.get(ruby.to_symbol("id"))
|
|
109
|
+
.and_then(|v| if v.is_nil() { None } else { String::try_convert(v).ok() });
|
|
110
|
+
|
|
111
|
+
let retry: Option<u64> = result_hash
|
|
112
|
+
.get(ruby.to_symbol("retry"))
|
|
113
|
+
.and_then(|v| if v.is_nil() { None } else { u64::try_convert(v).ok() });
|
|
114
|
+
|
|
115
|
+
let mut event = if let Some(et) = event_type {
|
|
116
|
+
SseEvent::with_type(et, data_json)
|
|
117
|
+
} else {
|
|
118
|
+
SseEvent::new(data_json)
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
if let Some(id_str) = id {
|
|
122
|
+
event = event.with_id(id_str);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if let Some(retry_ms) = retry {
|
|
126
|
+
event = event.with_retry(retry_ms);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
Ok(Some(event))
|
|
130
|
+
}) {
|
|
131
|
+
Ok(event) => event,
|
|
132
|
+
Err(e) => {
|
|
133
|
+
error!("Ruby error in next_event: {}", e);
|
|
134
|
+
None
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async fn on_connect(&self) {
|
|
140
|
+
debug!("Ruby SSE producer '{}': on_connect", self.name);
|
|
141
|
+
|
|
142
|
+
if let Some(on_connect_proc) = self.on_connect_proc
|
|
143
|
+
&& let Err(e) = magnus::Ruby::get()
|
|
144
|
+
.map_err(|e| format!("Failed to get Ruby: {}", e))
|
|
145
|
+
.and_then(|ruby| {
|
|
146
|
+
debug!("Ruby SSE producer: on_connect acquired Ruby VM");
|
|
147
|
+
let proc_value = ruby.get_inner(on_connect_proc);
|
|
148
|
+
proc_value
|
|
149
|
+
.funcall::<_, _, Value>("call", ())
|
|
150
|
+
.map_err(|e| format!("on_connect '{}' call failed: {}", self.name, e))?;
|
|
151
|
+
debug!("Ruby SSE producer: on_connect completed");
|
|
152
|
+
Ok(())
|
|
153
|
+
})
|
|
154
|
+
{
|
|
155
|
+
error!("on_connect error: {}", e);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async fn on_disconnect(&self) {
|
|
160
|
+
debug!("Ruby SSE producer '{}': on_disconnect", self.name);
|
|
161
|
+
|
|
162
|
+
if let Some(on_disconnect_proc) = self.on_disconnect_proc
|
|
163
|
+
&& let Err(e) = magnus::Ruby::get()
|
|
164
|
+
.map_err(|e| format!("Failed to get Ruby: {}", e))
|
|
165
|
+
.and_then(|ruby| {
|
|
166
|
+
let proc_value = ruby.get_inner(on_disconnect_proc);
|
|
167
|
+
proc_value
|
|
168
|
+
.funcall::<_, _, Value>("call", ())
|
|
169
|
+
.map_err(|e| format!("on_disconnect '{}' call failed: {}", self.name, e))?;
|
|
170
|
+
debug!("Ruby SSE producer: on_disconnect completed");
|
|
171
|
+
Ok(())
|
|
172
|
+
})
|
|
173
|
+
{
|
|
174
|
+
error!("on_disconnect error: {}", e);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
unsafe impl Send for RubySseEventProducer {}
|
|
180
|
+
unsafe impl Sync for RubySseEventProducer {}
|
|
181
|
+
|
|
182
|
+
/// Create SseState from Ruby producer object
|
|
183
|
+
///
|
|
184
|
+
/// This function is designed to be called from Ruby to register SSE producers.
|
|
185
|
+
#[allow(dead_code)]
|
|
186
|
+
pub fn create_sse_state(
|
|
187
|
+
ruby: &magnus::Ruby,
|
|
188
|
+
producer_obj: Value,
|
|
189
|
+
) -> Result<spikard_http::SseState<RubySseEventProducer>, magnus::Error> {
|
|
190
|
+
let next_event_proc: Value = producer_obj
|
|
191
|
+
.funcall("method", (ruby.to_symbol("next_event"),))
|
|
192
|
+
.map_err(|e| {
|
|
193
|
+
magnus::Error::new(
|
|
194
|
+
ruby.exception_arg_error(),
|
|
195
|
+
format!("next_event method not found: {}", e),
|
|
196
|
+
)
|
|
197
|
+
})?;
|
|
198
|
+
|
|
199
|
+
let on_connect_proc = producer_obj
|
|
200
|
+
.funcall::<_, _, Value>("method", (ruby.to_symbol("on_connect"),))
|
|
201
|
+
.ok();
|
|
202
|
+
|
|
203
|
+
let on_disconnect_proc = producer_obj
|
|
204
|
+
.funcall::<_, _, Value>("method", (ruby.to_symbol("on_disconnect"),))
|
|
205
|
+
.ok();
|
|
206
|
+
|
|
207
|
+
let event_schema = producer_obj
|
|
208
|
+
.funcall::<_, _, Value>("instance_variable_get", (ruby.to_symbol("@_event_schema"),))
|
|
209
|
+
.ok()
|
|
210
|
+
.and_then(|v| {
|
|
211
|
+
if v.is_nil() {
|
|
212
|
+
None
|
|
213
|
+
} else {
|
|
214
|
+
RubySseEventProducer::ruby_to_json(ruby, v).ok()
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
let ruby_producer = RubySseEventProducer::new(
|
|
219
|
+
"SseEventProducer".to_string(),
|
|
220
|
+
next_event_proc,
|
|
221
|
+
on_connect_proc,
|
|
222
|
+
on_disconnect_proc,
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
if event_schema.is_some() {
|
|
226
|
+
spikard_http::SseState::with_schema(ruby_producer, event_schema)
|
|
227
|
+
.map_err(|e| magnus::Error::new(ruby.exception_runtime_error(), e))
|
|
228
|
+
} else {
|
|
229
|
+
Ok(spikard_http::SseState::new(ruby_producer))
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
//! Native Ruby test client for HTTP testing.
|
|
2
|
+
//!
|
|
3
|
+
//! This module implements `NativeTestClient`, a wrapped Ruby class that provides
|
|
4
|
+
//! HTTP testing capabilities against a Spikard server. It manages test servers
|
|
5
|
+
//! for both HTTP and WebSocket/SSE transports.
|
|
6
|
+
|
|
7
|
+
#![allow(dead_code)]
|
|
8
|
+
|
|
9
|
+
use axum::http::Method;
|
|
10
|
+
use axum_test::{TestServer, TestServerConfig, Transport};
|
|
11
|
+
use bytes::Bytes;
|
|
12
|
+
use cookie::Cookie;
|
|
13
|
+
use magnus::prelude::*;
|
|
14
|
+
use magnus::{Error, RHash, Ruby, Value, gc::Marker};
|
|
15
|
+
use serde_json::Value as JsonValue;
|
|
16
|
+
use spikard_http::testing::{
|
|
17
|
+
MultipartFilePart, SnapshotError, build_multipart_body, encode_urlencoded_body, snapshot_response,
|
|
18
|
+
};
|
|
19
|
+
use spikard_http::{Route, RouteMetadata};
|
|
20
|
+
use std::cell::RefCell;
|
|
21
|
+
use std::collections::HashMap;
|
|
22
|
+
use std::sync::Arc;
|
|
23
|
+
|
|
24
|
+
use crate::conversion::{parse_request_config, response_to_ruby};
|
|
25
|
+
use crate::handler::RubyHandler;
|
|
26
|
+
use crate::server::GLOBAL_RUNTIME;
|
|
27
|
+
|
|
28
|
+
/// Request configuration built from Ruby options hash.
|
|
29
|
+
pub struct RequestConfig {
|
|
30
|
+
pub query: Option<JsonValue>,
|
|
31
|
+
pub headers: HashMap<String, String>,
|
|
32
|
+
pub cookies: HashMap<String, String>,
|
|
33
|
+
pub body: Option<RequestBody>,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// HTTP request body variants.
|
|
37
|
+
pub enum RequestBody {
|
|
38
|
+
Json(JsonValue),
|
|
39
|
+
Form(JsonValue),
|
|
40
|
+
Raw(String),
|
|
41
|
+
Multipart {
|
|
42
|
+
form_data: Vec<(String, String)>,
|
|
43
|
+
files: Vec<MultipartFilePart>,
|
|
44
|
+
},
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// Snapshot of an HTTP response.
|
|
48
|
+
pub struct TestResponseData {
|
|
49
|
+
pub status: u16,
|
|
50
|
+
pub headers: HashMap<String, String>,
|
|
51
|
+
pub body_text: Option<String>,
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// Error wrapper for native request failures.
|
|
55
|
+
#[derive(Debug)]
|
|
56
|
+
pub struct NativeRequestError(pub String);
|
|
57
|
+
|
|
58
|
+
/// Inner client state containing the test servers and handlers.
|
|
59
|
+
pub struct ClientInner {
|
|
60
|
+
pub http_server: Arc<TestServer>,
|
|
61
|
+
pub transport_server: Arc<TestServer>,
|
|
62
|
+
/// Keep Ruby handler closures alive for GC; accessed via the `mark` hook.
|
|
63
|
+
#[allow(dead_code)]
|
|
64
|
+
pub handlers: Vec<RubyHandler>,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/// Native Ruby TestClient wrapper for integration testing.
|
|
68
|
+
///
|
|
69
|
+
/// Wraps an optional `ClientInner` that holds the HTTP test servers
|
|
70
|
+
/// and keeps handler references alive for Ruby's garbage collector.
|
|
71
|
+
#[derive(Default)]
|
|
72
|
+
#[magnus::wrap(class = "Spikard::Native::TestClient", free_immediately, mark)]
|
|
73
|
+
pub struct NativeTestClient {
|
|
74
|
+
pub inner: RefCell<Option<ClientInner>>,
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
impl NativeTestClient {
|
|
78
|
+
/// Initialize the test client with routes, handlers, and server config.
|
|
79
|
+
///
|
|
80
|
+
/// # Arguments
|
|
81
|
+
///
|
|
82
|
+
/// * `ruby` - Ruby VM reference
|
|
83
|
+
/// * `this` - The wrapped NativeTestClient instance
|
|
84
|
+
/// * `routes_json` - JSON string containing route metadata
|
|
85
|
+
/// * `handlers` - Ruby Hash mapping handler_name => Proc
|
|
86
|
+
/// * `config_value` - Ruby ServerConfig object
|
|
87
|
+
/// * `ws_handlers` - Ruby Hash of WebSocket handlers (optional)
|
|
88
|
+
/// * `sse_producers` - Ruby Hash of SSE producers (optional)
|
|
89
|
+
pub fn initialize(
|
|
90
|
+
ruby: &Ruby,
|
|
91
|
+
this: &Self,
|
|
92
|
+
routes_json: String,
|
|
93
|
+
handlers: Value,
|
|
94
|
+
config_value: Value,
|
|
95
|
+
ws_handlers: Value,
|
|
96
|
+
sse_producers: Value,
|
|
97
|
+
) -> Result<(), Error> {
|
|
98
|
+
let metadata: Vec<RouteMetadata> = serde_json::from_str(&routes_json)
|
|
99
|
+
.map_err(|err| Error::new(ruby.exception_arg_error(), format!("Invalid routes JSON: {err}")))?;
|
|
100
|
+
|
|
101
|
+
let handlers_hash = RHash::from_value(handlers).ok_or_else(|| {
|
|
102
|
+
Error::new(
|
|
103
|
+
ruby.exception_arg_error(),
|
|
104
|
+
"handlers parameter must be a Hash of handler_name => Proc",
|
|
105
|
+
)
|
|
106
|
+
})?;
|
|
107
|
+
|
|
108
|
+
let json_module = ruby
|
|
109
|
+
.class_object()
|
|
110
|
+
.const_get("JSON")
|
|
111
|
+
.map_err(|_| Error::new(ruby.exception_runtime_error(), "JSON module not available"))?;
|
|
112
|
+
|
|
113
|
+
let server_config = crate::config::extract_server_config(ruby, config_value)?;
|
|
114
|
+
|
|
115
|
+
let schema_registry = spikard_http::SchemaRegistry::new();
|
|
116
|
+
let mut prepared_routes = Vec::with_capacity(metadata.len());
|
|
117
|
+
let mut handler_refs = Vec::with_capacity(metadata.len());
|
|
118
|
+
let mut route_metadata_vec = Vec::with_capacity(metadata.len());
|
|
119
|
+
|
|
120
|
+
for meta in metadata.clone() {
|
|
121
|
+
let handler_value = crate::conversion::fetch_handler(ruby, &handlers_hash, &meta.handler_name)?;
|
|
122
|
+
let route = Route::from_metadata(meta.clone(), &schema_registry)
|
|
123
|
+
.map_err(|err| Error::new(ruby.exception_runtime_error(), format!("Failed to build route: {err}")))?;
|
|
124
|
+
|
|
125
|
+
let handler = RubyHandler::new(&route, handler_value, json_module)?;
|
|
126
|
+
prepared_routes.push((route, Arc::new(handler.clone()) as Arc<dyn spikard_http::Handler>));
|
|
127
|
+
handler_refs.push(handler);
|
|
128
|
+
route_metadata_vec.push(meta);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
let mut router = spikard_http::server::build_router_with_handlers_and_config(
|
|
132
|
+
prepared_routes,
|
|
133
|
+
server_config,
|
|
134
|
+
route_metadata_vec,
|
|
135
|
+
)
|
|
136
|
+
.map_err(|err| Error::new(ruby.exception_runtime_error(), format!("Failed to build router: {err}")))?;
|
|
137
|
+
|
|
138
|
+
let mut ws_endpoints = Vec::new();
|
|
139
|
+
if !ws_handlers.is_nil() {
|
|
140
|
+
let ws_hash = RHash::from_value(ws_handlers)
|
|
141
|
+
.ok_or_else(|| Error::new(ruby.exception_arg_error(), "WebSocket handlers must be a Hash"))?;
|
|
142
|
+
|
|
143
|
+
ws_hash.foreach(
|
|
144
|
+
|path: String, factory: Value| -> Result<magnus::r_hash::ForEach, Error> {
|
|
145
|
+
let handler_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
|
|
146
|
+
Error::new(
|
|
147
|
+
ruby.exception_runtime_error(),
|
|
148
|
+
format!("Failed to create WebSocket handler: {}", e),
|
|
149
|
+
)
|
|
150
|
+
})?;
|
|
151
|
+
|
|
152
|
+
let ws_state = crate::websocket::create_websocket_state(ruby, handler_instance)?;
|
|
153
|
+
|
|
154
|
+
ws_endpoints.push((path, ws_state));
|
|
155
|
+
|
|
156
|
+
Ok(magnus::r_hash::ForEach::Continue)
|
|
157
|
+
},
|
|
158
|
+
)?;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
let mut sse_endpoints = Vec::new();
|
|
162
|
+
if !sse_producers.is_nil() {
|
|
163
|
+
let sse_hash = RHash::from_value(sse_producers)
|
|
164
|
+
.ok_or_else(|| Error::new(ruby.exception_arg_error(), "SSE producers must be a Hash"))?;
|
|
165
|
+
|
|
166
|
+
sse_hash.foreach(
|
|
167
|
+
|path: String, factory: Value| -> Result<magnus::r_hash::ForEach, Error> {
|
|
168
|
+
let producer_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
|
|
169
|
+
Error::new(
|
|
170
|
+
ruby.exception_runtime_error(),
|
|
171
|
+
format!("Failed to create SSE producer: {}", e),
|
|
172
|
+
)
|
|
173
|
+
})?;
|
|
174
|
+
|
|
175
|
+
let sse_state = crate::sse::create_sse_state(ruby, producer_instance)?;
|
|
176
|
+
|
|
177
|
+
sse_endpoints.push((path, sse_state));
|
|
178
|
+
|
|
179
|
+
Ok(magnus::r_hash::ForEach::Continue)
|
|
180
|
+
},
|
|
181
|
+
)?;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
use axum::routing::get;
|
|
185
|
+
for (path, ws_state) in ws_endpoints {
|
|
186
|
+
router = router.route(
|
|
187
|
+
&path,
|
|
188
|
+
get(spikard_http::websocket_handler::<crate::websocket::RubyWebSocketHandler>).with_state(ws_state),
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
for (path, sse_state) in sse_endpoints {
|
|
193
|
+
router = router.route(
|
|
194
|
+
&path,
|
|
195
|
+
get(spikard_http::sse_handler::<crate::sse::RubySseEventProducer>).with_state(sse_state),
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
let http_server = GLOBAL_RUNTIME
|
|
200
|
+
.block_on(async { TestServer::new(router.clone()) })
|
|
201
|
+
.map_err(|err| {
|
|
202
|
+
Error::new(
|
|
203
|
+
ruby.exception_runtime_error(),
|
|
204
|
+
format!("Failed to initialise test server: {err}"),
|
|
205
|
+
)
|
|
206
|
+
})?;
|
|
207
|
+
|
|
208
|
+
let ws_config = TestServerConfig {
|
|
209
|
+
transport: Some(Transport::HttpRandomPort),
|
|
210
|
+
..Default::default()
|
|
211
|
+
};
|
|
212
|
+
let transport_server = GLOBAL_RUNTIME
|
|
213
|
+
.block_on(async { TestServer::new_with_config(router, ws_config) })
|
|
214
|
+
.map_err(|err| {
|
|
215
|
+
Error::new(
|
|
216
|
+
ruby.exception_runtime_error(),
|
|
217
|
+
format!("Failed to initialise WebSocket transport server: {err}"),
|
|
218
|
+
)
|
|
219
|
+
})?;
|
|
220
|
+
|
|
221
|
+
*this.inner.borrow_mut() = Some(ClientInner {
|
|
222
|
+
http_server: Arc::new(http_server),
|
|
223
|
+
transport_server: Arc::new(transport_server),
|
|
224
|
+
handlers: handler_refs,
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
Ok(())
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/// Execute an HTTP request against the test server.
|
|
231
|
+
///
|
|
232
|
+
/// # Arguments
|
|
233
|
+
///
|
|
234
|
+
/// * `ruby` - Ruby VM reference
|
|
235
|
+
/// * `this` - The wrapped NativeTestClient instance
|
|
236
|
+
/// * `method` - HTTP method (GET, POST, etc.)
|
|
237
|
+
/// * `path` - URL path
|
|
238
|
+
/// * `options` - Ruby Hash with query, headers, cookies, body, etc.
|
|
239
|
+
pub fn request(ruby: &Ruby, this: &Self, method: String, path: String, options: Value) -> Result<Value, Error> {
|
|
240
|
+
let inner_borrow = this.inner.borrow();
|
|
241
|
+
let inner = inner_borrow
|
|
242
|
+
.as_ref()
|
|
243
|
+
.ok_or_else(|| Error::new(ruby.exception_runtime_error(), "TestClient not initialised"))?;
|
|
244
|
+
let method_upper = method.to_ascii_uppercase();
|
|
245
|
+
let http_method = Method::from_bytes(method_upper.as_bytes()).map_err(|err| {
|
|
246
|
+
Error::new(
|
|
247
|
+
ruby.exception_arg_error(),
|
|
248
|
+
format!("Unsupported method {method_upper}: {err}"),
|
|
249
|
+
)
|
|
250
|
+
})?;
|
|
251
|
+
|
|
252
|
+
let request_config = parse_request_config(ruby, options)?;
|
|
253
|
+
|
|
254
|
+
let response = GLOBAL_RUNTIME
|
|
255
|
+
.block_on(execute_request(
|
|
256
|
+
inner.http_server.clone(),
|
|
257
|
+
http_method,
|
|
258
|
+
path.clone(),
|
|
259
|
+
request_config,
|
|
260
|
+
))
|
|
261
|
+
.map_err(|err| {
|
|
262
|
+
Error::new(
|
|
263
|
+
ruby.exception_runtime_error(),
|
|
264
|
+
format!("Request failed for {method_upper} {path}: {}", err.0),
|
|
265
|
+
)
|
|
266
|
+
})?;
|
|
267
|
+
|
|
268
|
+
response_to_ruby(ruby, response)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/// Close the test client and clean up resources.
|
|
272
|
+
pub fn close(&self) -> Result<(), Error> {
|
|
273
|
+
*self.inner.borrow_mut() = None;
|
|
274
|
+
Ok(())
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/// Connect to a WebSocket endpoint on the test server.
|
|
278
|
+
pub fn websocket(ruby: &Ruby, this: &Self, path: String) -> Result<Value, Error> {
|
|
279
|
+
let inner_borrow = this.inner.borrow();
|
|
280
|
+
let inner = inner_borrow
|
|
281
|
+
.as_ref()
|
|
282
|
+
.ok_or_else(|| Error::new(ruby.exception_runtime_error(), "TestClient not initialised"))?;
|
|
283
|
+
|
|
284
|
+
let server = Arc::clone(&inner.transport_server);
|
|
285
|
+
|
|
286
|
+
drop(inner_borrow);
|
|
287
|
+
|
|
288
|
+
let handle =
|
|
289
|
+
GLOBAL_RUNTIME.spawn(async move { spikard_http::testing::connect_websocket(&server, &path).await });
|
|
290
|
+
|
|
291
|
+
let ws = GLOBAL_RUNTIME.block_on(async {
|
|
292
|
+
handle
|
|
293
|
+
.await
|
|
294
|
+
.map_err(|e| Error::new(ruby.exception_runtime_error(), format!("WebSocket task failed: {}", e)))
|
|
295
|
+
})?;
|
|
296
|
+
|
|
297
|
+
let ws_conn = crate::test_websocket::WebSocketTestConnection::new(ws);
|
|
298
|
+
Ok(ruby.obj_wrap(ws_conn).as_value())
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/// Connect to an SSE endpoint on the test server.
|
|
302
|
+
pub fn sse(ruby: &Ruby, this: &Self, path: String) -> Result<Value, Error> {
|
|
303
|
+
let inner_borrow = this.inner.borrow();
|
|
304
|
+
let inner = inner_borrow
|
|
305
|
+
.as_ref()
|
|
306
|
+
.ok_or_else(|| Error::new(ruby.exception_runtime_error(), "TestClient not initialised"))?;
|
|
307
|
+
|
|
308
|
+
let response = GLOBAL_RUNTIME
|
|
309
|
+
.block_on(async {
|
|
310
|
+
let axum_response = inner.transport_server.get(&path).await;
|
|
311
|
+
snapshot_response(axum_response).await
|
|
312
|
+
})
|
|
313
|
+
.map_err(|e| Error::new(ruby.exception_runtime_error(), format!("SSE request failed: {}", e)))?;
|
|
314
|
+
|
|
315
|
+
crate::test_sse::sse_stream_from_response(ruby, &response)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/// GC mark hook so Ruby keeps handler closures alive.
|
|
319
|
+
#[allow(dead_code)]
|
|
320
|
+
pub fn mark(&self, marker: &Marker) {
|
|
321
|
+
let inner_ref = self.inner.borrow();
|
|
322
|
+
if let Some(inner) = inner_ref.as_ref() {
|
|
323
|
+
for handler in &inner.handlers {
|
|
324
|
+
handler.mark(marker);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/// Execute an HTTP request against a test server.
|
|
331
|
+
///
|
|
332
|
+
/// Handles method routing, query params, headers, cookies, and various body formats.
|
|
333
|
+
pub async fn execute_request(
|
|
334
|
+
server: Arc<TestServer>,
|
|
335
|
+
method: Method,
|
|
336
|
+
path: String,
|
|
337
|
+
config: RequestConfig,
|
|
338
|
+
) -> Result<TestResponseData, NativeRequestError> {
|
|
339
|
+
let mut request = match method {
|
|
340
|
+
Method::GET => server.get(&path),
|
|
341
|
+
Method::POST => server.post(&path),
|
|
342
|
+
Method::PUT => server.put(&path),
|
|
343
|
+
Method::PATCH => server.patch(&path),
|
|
344
|
+
Method::DELETE => server.delete(&path),
|
|
345
|
+
Method::HEAD => server.method(Method::HEAD, &path),
|
|
346
|
+
Method::OPTIONS => server.method(Method::OPTIONS, &path),
|
|
347
|
+
Method::TRACE => server.method(Method::TRACE, &path),
|
|
348
|
+
other => return Err(NativeRequestError(format!("Unsupported HTTP method {other}"))),
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
if let Some(query) = config.query {
|
|
352
|
+
request = request.add_query_params(&query);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
for (name, value) in config.headers {
|
|
356
|
+
request = request.add_header(name.as_str(), value.as_str());
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
for (name, value) in config.cookies {
|
|
360
|
+
request = request.add_cookie(Cookie::new(name, value));
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if let Some(body) = config.body {
|
|
364
|
+
match body {
|
|
365
|
+
RequestBody::Json(json_value) => {
|
|
366
|
+
request = request.json(&json_value);
|
|
367
|
+
}
|
|
368
|
+
RequestBody::Form(form_value) => {
|
|
369
|
+
let encoded = encode_urlencoded_body(&form_value)
|
|
370
|
+
.map_err(|err| NativeRequestError(format!("Failed to encode form body: {err}")))?;
|
|
371
|
+
request = request
|
|
372
|
+
.content_type("application/x-www-form-urlencoded")
|
|
373
|
+
.bytes(Bytes::from(encoded));
|
|
374
|
+
}
|
|
375
|
+
RequestBody::Raw(raw) => {
|
|
376
|
+
request = request.bytes(Bytes::from(raw));
|
|
377
|
+
}
|
|
378
|
+
RequestBody::Multipart { form_data, files } => {
|
|
379
|
+
let (multipart_body, boundary) = build_multipart_body(&form_data, &files);
|
|
380
|
+
request = request
|
|
381
|
+
.content_type(&format!("multipart/form-data; boundary={}", boundary))
|
|
382
|
+
.bytes(Bytes::from(multipart_body));
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
let response = request.await;
|
|
388
|
+
let snapshot = snapshot_response(response).await.map_err(snapshot_err_to_native)?;
|
|
389
|
+
let body_text = if snapshot.body.is_empty() {
|
|
390
|
+
None
|
|
391
|
+
} else {
|
|
392
|
+
Some(String::from_utf8_lossy(&snapshot.body).into_owned())
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
Ok(TestResponseData {
|
|
396
|
+
status: snapshot.status,
|
|
397
|
+
headers: snapshot.headers,
|
|
398
|
+
body_text,
|
|
399
|
+
})
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
fn snapshot_err_to_native(err: SnapshotError) -> NativeRequestError {
|
|
403
|
+
NativeRequestError(err.to_string())
|
|
404
|
+
}
|