use std::io::ErrorKind;
use anyhow::{Context, Result, bail};
use waos_dev_protocol::{Connection, FromWaOS, ToWaOS};
pub async fn ask(question: &ToWaOS) -> Result<FromWaOS> {
let socket = waos_dev_protocol::socket_path();
let mut connection = match Connection::connect(&socket).await {
Ok(connection) => connection,
Err(error)
if matches!(
error.kind(),
ErrorKind::NotFound | ErrorKind::ConnectionRefused
) =>
{
bail!(
"no WaOS answers at {}: run the program with `cargo waos run` first",
socket.display()
)
}
Err(error) => {
return Err(error)
.with_context(|| format!("connecting to WaOS at {}", socket.display()));
}
};
connection
.agree_on_protocol()
.await
.context("the WaOS that answered")?;
connection.send(question).await.context("sending to WaOS")?;
connection
.receive::<FromWaOS>()
.await
.context("reading from WaOS")?
.context("WaOS closed the connection without an answer")
}