use futures::StreamExt;
use plexus_client::{ClientError, Content, Frame, MethodRef, MethodStream, Transport, WsTransport};
use serde_json::{json, Map, Value};
use std::time::Duration;
fn usage() -> ! {
eprintln!("kit_client --url URL --service NAME PATH... [--name VALUE]...");
std::process::exit(2)
}
fn leak(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
fn main() {
if std::env::args().nth(1).as_deref() == Some("--url") {
tokio::runtime::Builder::new_current_thread().enable_all().build().expect("a runtime").block_on(client());
} else {
kit();
}
}
fn kit() {
let here = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let wire = std::env::var_os("PLEXUS_WIRE").map(std::path::PathBuf::from).unwrap_or_else(|| here.join("../../plexus-wire"));
let run = wire.join("conformance/run.py");
assert!(run.exists(), "plexus-wire's kit is not at {} (PLEXUS_WIRE names another)", run.display());
let me = std::env::current_exe().expect("this test's path");
let cmd = format!("{} --url {{url}} --service {{backend}} {{path}} {{flags}}", me.display());
let status = std::process::Command::new("python3")
.args(["-I"])
.arg(&run)
.args(["run", "--role", "client", "--cmd", &cmd, "--expect-fail"])
.arg(here.join("tests/kit_client.expect"))
.status()
.expect("python3 runs the kit");
assert!(status.success(), "the kit's client role: plexus-client failed a case it does not expect to ({status})");
}
async fn client() {
let mut args = std::env::args().skip(1).peekable();
let (mut url, mut service, mut path, mut params) = (None, None, Vec::new(), Map::new());
while let Some(arg) = args.next() {
match arg.as_str() {
"--url" => url = args.next(),
"--service" => service = args.next(),
flag if flag.starts_with("--") => {
let value = args.next().unwrap_or_else(|| usage());
let value = serde_json::from_str(&value).unwrap_or(Value::String(value));
params.insert(flag[2..].replace('-', "_"), value);
}
segment => path.push(segment.to_owned()),
}
}
let (Some(url), Some(service), Some(method)) = (url, service, path.pop()) else { usage() };
if path.is_empty() {
usage();
}
let method = MethodRef::new(leak(path.join(".")), leak(method));
let transport = match WsTransport::connect(&url, &service).await {
Ok(t) => t,
Err(e) => {
println!("{}", json!({"error": {"connect": e.to_string()}}));
std::process::exit(1)
}
};
let mut events = MethodStream::<Value, Value, Value>::new(
transport.call_raw(method, Value::Object(params)),
Content::decode::<Value>,
|v| v,
)
.with_progress();
loop {
tokio::select! {
event = events.next() => match event {
None => break,
Some(Ok(Frame::Item(data))) => println!("{data}"),
Some(Ok(Frame::Progress(progress))) => println!("{}", json!({"progress": progress})),
Some(Err(e)) => {
println!("{}", json!({"error": described(&e)}));
std::process::exit(1)
}
},
_ = tokio::signal::ctrl_c() => {
drop(events);
tokio::time::sleep(Duration::from_millis(300)).await;
std::process::exit(130)
}
}
}
}
fn described(e: &ClientError) -> Value {
match e {
ClientError::Remote(error) => json!({"remote": error.to_string(), "kind": error.kind(), "error": error}),
other => json!({"client": other.to_string(), "debug": format!("{other:?}")}),
}
}