use std::future::Future;
use std::time::Duration;
use anyhow::{Result, anyhow};
use openlogi_ipc::client::{self, ConnectError};
use openlogi_ipc::{AgentClient, AgentSnapshot, ClientKind};
use tarpc::client::RpcError;
use tarpc::context;
const CALL_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CallFailure {
TimedOut,
Disconnected,
}
pub(crate) async fn call<T>(
request: impl Future<Output = Result<T, RpcError>>,
) -> Result<T, CallFailure> {
match tokio::time::timeout(CALL_TIMEOUT, request).await {
Ok(Ok(answer)) => Ok(answer),
Ok(Err(_)) => Err(CallFailure::Disconnected),
Err(_) => Err(CallFailure::TimedOut),
}
}
pub(crate) async fn connect() -> Result<AgentClient, ConnectError> {
client::connect_as(ClientKind::Cli).await
}
pub(crate) async fn snapshot(client: &AgentClient) -> Result<AgentSnapshot> {
call(client.snapshot(context::current()))
.await
.map_err(|failure| match failure {
CallFailure::TimedOut => {
anyhow!("the running Agent timed out while providing its device snapshot")
}
CallFailure::Disconnected => {
anyhow!("the running Agent disconnected while providing its device snapshot")
}
})
}