use std::{future::Future, task::Poll, time::Duration};
use crate::{
JsonValue,
element::{JsObject, module},
};
pub(crate) const NO_HOST: &str = "nsh/host: this platform has no host";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, Default, JsObject)]
pub(crate) struct HostCallOptions {
timeout: Option<f64>,
}
#[module]
pub(crate) struct Host;
#[module(name = "host")]
impl Host {
pub(crate) async fn call(
name: String,
args: Option<JsonValue>,
options: Option<HostCallOptions>,
) -> Result<JsonValue, String> {
let deadline = match options.and_then(|o| o.timeout) {
Some(ms) if !ms.is_finite() || ms < 0.0 => {
return Err(format!("nsh/host: invalid timeout {ms}"));
}
Some(0.0) => None,
Some(ms) => Duration::try_from_secs_f64(ms / 1000.0)
.ok()
.and_then(|t| Some((t, crate::time::now().checked_add(t)?))),
None => Some((DEFAULT_TIMEOUT, crate::time::now() + DEFAULT_TIMEOUT)),
};
let answer = crate::element::ambient::host_call(name.clone(), args.unwrap_or_default());
let Some((timeout, at)) = deadline else {
return answer.await;
};
let answered = {
let mut answer = std::pin::pin!(answer);
let mut delay = std::pin::pin!(crate::element::ambient::timer_until(at));
std::future::poll_fn(|cx| {
if let Poll::Ready(result) = answer.as_mut().poll(cx) {
return Poll::Ready(Some(result));
}
if delay.as_mut().poll(cx).is_ready() {
return Poll::Ready(None);
}
Poll::Pending
})
.await
};
answered.unwrap_or_else(|| {
crate::element::ambient::forget_host_calls();
Err(format!(
"nsh/host: {name} timed out after {} ms",
timeout.as_millis()
))
})
}
}