use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Deserializer, to_writer};
use super::{Request, Response};
use crate::error::Error;
#[derive(Debug)]
pub struct Client {
sockpath: PathBuf,
timeout: Option<Duration>,
}
impl Client {
pub fn new<P: AsRef<Path>>(sockpath: P) -> Client {
Client {
sockpath: sockpath.as_ref().to_path_buf(),
timeout: None,
}
}
pub fn set_timeout(&mut self, timeout: Option<Duration>) {
self.timeout = timeout;
}
pub fn send_request<S: Serialize, D: DeserializeOwned>(&self, method: &str, params: S) -> Result<Response<D>, Error> {
let mut stream = UnixStream::connect(&self.sockpath)?;
stream.set_read_timeout(self.timeout)?;
stream.set_write_timeout(self.timeout)?;
to_writer(&mut stream, &Request {
method,
params,
id: 0, jsonrpc: "2.0",
})?;
let response: Response<D> = Deserializer::from_reader(&mut stream)
.into_iter()
.next()
.map_or(Err(Error::NoErrorOrResult), |res| Ok(res?))?;
if response.jsonrpc.as_ref().map_or(false, |version| version != "2.0") {
return Err(Error::VersionMismatch);
}
if response.id != 0 {
return Err(Error::NonceMismatch);
}
Ok(response)
}
}