use socket2::{Domain, SockAddr, Socket, Type};
use std::io::Write as _;
use std::os::unix::net::UnixStream;
use std::path::Path;
use std::time::Duration;
use crate::protocol::{
Identity, Info, PutMeta, Request, StatsSnapshot, read_response, split_status_payload,
};
pub const TIMEOUT: Duration = Duration::from_secs(10);
pub const PROBE_TIMEOUT: Duration = Duration::from_millis(25);
const PUT_WINDOW: usize = 64;
pub fn connect_stream(path: &Path, timeout: Duration) -> std::io::Result<UnixStream> {
if timeout.is_zero() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Unix connection timeout must be nonzero",
));
}
let socket = Socket::new(Domain::UNIX, Type::STREAM, None)?;
socket.connect_timeout(&SockAddr::unix(path)?, timeout)?;
let fd: std::os::fd::OwnedFd = socket.into();
let stream = UnixStream::from(fd);
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
Ok(stream)
}
pub fn probe_listener(path: &Path) -> std::io::Result<bool> {
match connect_stream(path, PROBE_TIMEOUT) {
Ok(_) => Ok(true),
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused
) =>
{
Ok(false)
}
Err(error) => Err(error),
}
}
#[derive(Debug)]
pub struct Client {
stream: UnixStream,
}
impl Client {
pub fn connect(path: &Path) -> std::io::Result<Self> {
Self::connect_with_timeout(path, TIMEOUT)
}
pub fn connect_with_timeout(path: &Path, timeout: Duration) -> std::io::Result<Self> {
Ok(Self {
stream: connect_stream(path, timeout)?,
})
}
fn call(&mut self, req: &Request) -> std::io::Result<Vec<u8>> {
req.write(&mut self.stream)?;
read_response(&mut self.stream)
}
pub fn hello(&mut self, solver_path: &str) -> std::io::Result<Identity> {
self.hello_in_mode(solver_path, crate::protocol::VerificationMode::Default)
}
pub fn hello_in_mode(
&mut self,
solver_path: &str,
mode: crate::protocol::VerificationMode,
) -> std::io::Result<Identity> {
let body = self.call(&Request::Hello(crate::protocol::Hello {
solver_path: solver_path.to_owned(),
mode,
}))?;
let (status, payload) = split_status_payload(&body)?;
if status == 0 {
let id: Identity = serde_json::from_slice(payload).map_err(std::io::Error::other)?;
if id.protocol_version == crate::protocol::PROTOCOL_VERSION {
Ok(id)
} else {
Err(std::io::Error::other(format!(
"daemon speaks protocol {}, client {}",
id.protocol_version,
crate::protocol::PROTOCOL_VERSION
)))
}
} else {
Err(std::io::Error::other(
String::from_utf8_lossy(payload).into_owned(),
))
}
}
pub fn get(&mut self, key: &[u8; 32]) -> std::io::Result<Option<Vec<u8>>> {
Ok(self.get_with_effort(key)?.map(|(reply, _)| reply))
}
pub fn get_with_effort(
&mut self,
key: &[u8; 32],
) -> std::io::Result<Option<(Vec<u8>, Option<crate::protocol::Effort>)>> {
let body = self.call(&Request::Get(*key))?;
let (status, payload) = split_status_payload(&body)?;
if status != 1 {
return Ok(None);
}
Ok(Some((
payload.to_vec(),
crate::protocol::get_effort_trailer(&body),
)))
}
pub fn put(&mut self, key: &[u8; 32], meta: PutMeta, reply: Vec<u8>) -> std::io::Result<()> {
self.call(&Request::Put {
key: *key,
meta,
reply,
})
.map(|_| ())
}
pub fn put_all(
&mut self,
puts: impl IntoIterator<Item = ([u8; 32], PutMeta, Vec<u8>)>,
) -> std::io::Result<()> {
let mut puts = puts.into_iter().peekable();
let mut frames = Vec::new();
while puts.peek().is_some() {
frames.clear();
let mut sent = 0usize;
for (key, meta, reply) in puts.by_ref().take(PUT_WINDOW) {
Request::Put { key, meta, reply }.write(&mut frames)?;
sent += 1;
}
(&self.stream).write_all(&frames)?;
let mut acks = std::io::BufReader::new(&self.stream);
for _ in 0..sent {
read_response(&mut acks)?;
}
}
Ok(())
}
pub fn stats(&mut self) -> std::io::Result<StatsSnapshot> {
let body = self.call(&Request::Stats)?;
let (_, payload) = split_status_payload(&body)?;
serde_json::from_slice(payload).map_err(std::io::Error::other)
}
pub fn info(&mut self) -> std::io::Result<Info> {
let body = self.call(&Request::Info)?;
let (_, payload) = split_status_payload(&body)?;
serde_json::from_slice(payload).map_err(std::io::Error::other)
}
}