1 unstable release
0.1.12 | Aug 8, 2024 |
---|
#238 in WebSocket
100KB
2K
SLoC
tdx Volt client library
This library provides a Rust client for the Volt API via websockets.
The client uses JSON to send requests and receive responses from the Volt.
build
cargo build
usage
The following demonstrates creating and initialising a VoltClient
instance, and calling the get_resource
method to retrieve a resource from the Volt.
use serde_json::json;
use volt_client_rs::{
volt_client::VoltClient,
websocket_rpc::{Event, EventType},
};
#[tokio::main]
async fn main() {
// Load the Volt configuration JSON.
let config_json = match std::fs::read_to_string("volt.config.json") {
Ok(config_json) => config_json,
Err(e) => {
println!("failed to read config file: {:?}", e);
return;
}
};
// Create the Volt API client
let mut client = match VoltClient::create(&config_json).await {
Ok(client) => client,
Err(e) => {
println!("failed to create API client: {:?}", e);
return;
}
};
// Call methods on the client
let get_request = json!({
"resource_id": "did:volt:46c42b5f-22f1-4a7a-af76-c2eb78dbc8ca",
});
match client.get_resource(&get_request).await {
Ok(response) => println!("main: received response: {:?}", response),
Err(e) => println!("failed to get resource: {:?}", e),
}
// Keep the main thread alive to listen for incoming messages
tokio::signal::ctrl_c()
.await
.expect("Failed to listen for ctrl_c signal");
}
The get_resource
method used above is a unary RPC, i.e. it sends a single request and receives a single response. The VoltClient
also supports server streaming and client streaming RPCs.
// Start a `connect` call to the Volt.
let connect_call = match client.connect(&serde_json::Value::Null).await {
Ok(connect1) => connect1,
Err(e) => {
println!("failed to connect: {:?}", e);
return;
}
};
{
// Register a callback for the `Data` event.
let connect_rpc = connect_call.lock().await;
connect_rpc.on(EventType::Data, |response| {
if let Event::Data(data) = response {
// Do something with the data
println!("main: received data response: {:?}", data);
}
});
// Send the initial connect request.
let connect_request = json!({
"hello": {
"subscribe_resource_events": true,
"accept_invocation": false,
"ping_interval": 10000,
},
});
let _ = connect_rpc.send(&connect_request).await;
}
Dependencies
~9–16MB
~219K SLoC