-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.rs
More file actions
381 lines (336 loc) · 12.3 KB
/
client.rs
File metadata and controls
381 lines (336 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
Copyright 2024-2025 The Spice.ai OSS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//! Client implementations for system adapter JSON-RPC communication.
use crate::{JsonRpcError, JsonRpcRequest, JsonRpcResponse, methods};
use serde::{Serialize, de::DeserializeOwned};
use std::collections::HashMap;
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
process::{Child, ChildStdin, ChildStdout, Command},
};
/// Result type for client operations
pub type Result<T> = std::result::Result<T, ClientError>;
/// Errors that can occur during client operations
#[derive(Debug)]
pub enum ClientError {
/// JSON-RPC error returned by the server
JsonRpc(JsonRpcError),
/// I/O error during communication
Io(std::io::Error),
/// JSON serialization/deserialization error
Json(serde_json::Error),
/// HTTP transport error
#[cfg(feature = "client")]
Http(reqwest::Error),
/// Invalid response format
InvalidResponse(String),
/// Transport-specific error
Transport(String),
}
impl std::fmt::Display for ClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::JsonRpc(e) => write!(f, "JSON-RPC error: {}", e.message),
Self::Io(e) => write!(f, "I/O error: {e}"),
Self::Json(e) => write!(f, "JSON error: {e}"),
#[cfg(feature = "client")]
Self::Http(e) => write!(f, "HTTP error: {e}"),
Self::InvalidResponse(msg) => write!(f, "Invalid response: {msg}"),
Self::Transport(msg) => write!(f, "Transport error: {msg}"),
}
}
}
impl std::error::Error for ClientError {}
impl From<std::io::Error> for ClientError {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
impl From<serde_json::Error> for ClientError {
fn from(e: serde_json::Error) -> Self {
Self::Json(e)
}
}
#[cfg(feature = "client")]
impl From<reqwest::Error> for ClientError {
fn from(e: reqwest::Error) -> Self {
Self::Http(e)
}
}
/// System adapter client for JSON-RPC communication
pub enum Client {
/// Stdio transport - communicate via stdin/stdout with a child process
Stdio {
_child: Box<Child>,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
},
/// HTTP transport - communicate via HTTP POST requests
#[cfg(feature = "client")]
Http {
client: reqwest::Client,
endpoint: String,
},
}
impl Client {
/// Create a client using stdio transport by spawning a command
pub fn stdio(
command: impl AsRef<str>,
args: Vec<String>,
env: HashMap<String, String>,
) -> Result<Self> {
let command_str = command.as_ref();
let mut cmd = Command::new(command_str);
cmd.args(args);
for (key, value) in env {
cmd.env(key, value);
}
cmd.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit());
let mut child = cmd.spawn().map_err(|e| {
ClientError::Transport(format!(
"Failed to start stdio command '{command_str}': {e}"
))
})?;
let stdin = child
.stdin
.take()
.ok_or_else(|| ClientError::Transport("Stdio child missing stdin".to_string()))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| ClientError::Transport("Stdio child missing stdout".to_string()))?;
Ok(Self::Stdio {
_child: Box::new(child),
stdin,
stdout: BufReader::new(stdout),
})
}
/// Create a client using HTTP transport
#[cfg(feature = "client")]
pub fn http(endpoint: impl Into<String>) -> Self {
Self::Http {
client: reqwest::Client::new(),
endpoint: endpoint.into(),
}
}
/// Get the transport name
pub fn transport_name(&self) -> &'static str {
match self {
Self::Stdio { .. } => "stdio",
#[cfg(feature = "client")]
Self::Http { .. } => "http",
}
}
/// Query available RPC methods from the server
pub async fn rpc_methods(&mut self) -> Result<Vec<String>> {
let request = JsonRpcRequest::new(1, methods::RPC_METHODS, serde_json::json!({}));
let response: JsonRpcResponse<serde_json::Value> = self.call_typed(request).await?;
let methods = response
.result
.as_ref()
.and_then(|v| v.get("methods"))
.and_then(|v| v.as_array())
.ok_or_else(|| {
ClientError::InvalidResponse("Response missing result.methods array".to_string())
})?
.iter()
.filter_map(|v| v.as_str().map(ToString::to_string))
.collect();
Ok(methods)
}
/// Setup a benchmark run
pub async fn setup(
&mut self,
run_id: uuid::Uuid,
metadata: std::collections::HashMap<String, serde_json::Value>,
) -> Result<crate::SetupResponse> {
let request = crate::SetupRequest { run_id, metadata };
let rpc_request = JsonRpcRequest::new(1, crate::methods::SETUP, request);
let response = self.call_typed(rpc_request).await?;
response
.result
.ok_or_else(|| ClientError::InvalidResponse("Missing result".to_string()))
}
/// Create benchmark tables for a benchmark run
pub async fn create_tables(
&mut self,
run_id: uuid::Uuid,
datasets: std::collections::HashMap<String, crate::DatasetConfig>,
) -> Result<crate::CreateTablesResponse> {
let request = crate::CreateTablesRequest { run_id, datasets };
let rpc_request = JsonRpcRequest::new(1, crate::methods::CREATE_TABLES, request);
let response = self.call_typed(rpc_request).await?;
response
.result
.ok_or_else(|| ClientError::InvalidResponse("Missing result".to_string()))
}
/// Teardown a benchmark run
pub async fn teardown(&mut self, run_id: uuid::Uuid) -> Result<crate::TeardownResponse> {
let request = crate::TeardownRequest { run_id };
let rpc_request = JsonRpcRequest::new(1, crate::methods::TEARDOWN, request);
let response = self.call_typed(rpc_request).await?;
response
.result
.ok_or_else(|| ClientError::InvalidResponse("Missing result".to_string()))
}
/// Collect current metrics from the system under test
pub async fn metrics(&mut self, run_id: uuid::Uuid) -> Result<crate::MetricsResponse> {
let request = crate::MetricsRequest { run_id };
let rpc_request = JsonRpcRequest::new(1, crate::methods::METRICS, request);
let response = self.call_typed(rpc_request).await?;
response
.result
.ok_or_else(|| ClientError::InvalidResponse("Missing result".to_string()))
}
/// Make a typed JSON-RPC call with request and response types
async fn call_typed<Req: Serialize, Resp: DeserializeOwned>(
&mut self,
request: JsonRpcRequest<Req>,
) -> Result<JsonRpcResponse<Resp>> {
let request_value = serde_json::to_value(request)?;
let response_value = self.call_raw(request_value).await?;
let response: JsonRpcResponse<Resp> = serde_json::from_value(response_value)?;
Ok(response)
}
/// Make a raw JSON-RPC call with serde_json::Value
async fn call_raw(&mut self, request: serde_json::Value) -> Result<serde_json::Value> {
match self {
Self::Stdio {
_child: _,
stdin,
stdout,
} => {
let payload = serde_json::to_string(&request)?;
stdin.write_all(payload.as_bytes()).await?;
stdin.write_all(b"\n").await?;
stdin.flush().await?;
let mut line = String::new();
let read = stdout.read_line(&mut line).await?;
if read == 0 {
return Err(ClientError::Transport(
"Stdio process closed stdout before responding".to_string(),
));
}
let response: serde_json::Value = serde_json::from_str(line.trim_end())?;
if let Some(error) = response.get("error") {
let error: JsonRpcError = serde_json::from_value(error.clone())?;
return Err(ClientError::JsonRpc(error));
}
Ok(response)
}
#[cfg(feature = "client")]
Self::Http { client, endpoint } => {
let response = client
.post(endpoint.as_str())
.json(&request)
.send()
.await
.map_err(|e| {
ClientError::Transport(format!("Failed to POST to {endpoint}: {e}"))
})?;
let status = response.status();
let value: serde_json::Value = response.json().await.map_err(|e| {
ClientError::Transport(format!(
"Failed to parse response body (status {status}): {e}"
))
})?;
if let Some(error) = value.get("error") {
let error: JsonRpcError = serde_json::from_value(error.clone())?;
return Err(ClientError::JsonRpc(error));
}
Ok(value)
}
}
}
}
/// Builder for creating a `Client` with various configuration options
pub struct ClientBuilder {
transport: TransportConfig,
}
enum TransportConfig {
Stdio {
command: String,
args: Vec<String>,
env: HashMap<String, String>,
},
#[cfg(feature = "client")]
Http { endpoint: String },
}
impl ClientBuilder {
/// Create a builder for stdio transport
pub fn stdio(command: impl Into<String>) -> Self {
Self {
transport: TransportConfig::Stdio {
command: command.into(),
args: Vec::new(),
env: HashMap::new(),
},
}
}
/// Create a builder for HTTP transport
#[cfg(feature = "client")]
pub fn http(endpoint: impl Into<String>) -> Self {
Self {
transport: TransportConfig::Http {
endpoint: endpoint.into(),
},
}
}
/// Add command-line arguments (stdio only)
pub fn with_args(mut self, args: Vec<String>) -> Self {
if let TransportConfig::Stdio {
args: ref mut a, ..
} = self.transport
{
*a = args;
}
self
}
/// Add environment variables (stdio only)
pub fn with_env(mut self, env: HashMap<String, String>) -> Self {
if let TransportConfig::Stdio { env: ref mut e, .. } = self.transport {
*e = env;
}
self
}
/// Build the client
pub fn build(self) -> Result<Client> {
match self.transport {
TransportConfig::Stdio { command, args, env } => Client::stdio(command, args, env),
#[cfg(feature = "client")]
TransportConfig::Http { endpoint } => Ok(Client::http(endpoint)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_client_error_display() {
let error = ClientError::Transport("test error".to_string());
assert_eq!(format!("{error}"), "Transport error: test error");
}
#[test]
fn test_builder_stdio() {
let builder = ClientBuilder::stdio("python");
assert!(matches!(builder.transport, TransportConfig::Stdio { .. }));
}
#[cfg(feature = "client")]
#[test]
fn test_builder_http() {
let builder = ClientBuilder::http("http://localhost:8080");
assert!(matches!(builder.transport, TransportConfig::Http { .. }));
}
}