use std::time::Duration;
use crate::{
JsonValue,
element::{CallCx, JsError, JsObject, System, module},
};
#[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, JsError> {
let timeout = match options.and_then(|o| o.timeout) {
Some(ms) if !ms.is_finite() || ms < 0.0 => {
return Err(JsError::Range(format!("nsh/host: invalid timeout {ms}")));
}
Some(ms) => Duration::try_from_secs_f64(ms / 1000.0).unwrap_or(Duration::ZERO),
None => crate::host_channel::DEFAULT_CALL_TIMEOUT,
};
let options = crate::host_channel::HostCallOptions::default().timeout(timeout);
crate::element::host_call_with(name, args.unwrap_or_default(), options)
.await
.map_err(JsError::from)
}
pub(crate) fn post(
name: String,
args: Option<JsonValue>,
sys: System,
cx: CallCx,
) -> Result<(), JsError> {
crate::host_channel::check_call(&sys.access, &name)?;
let args = args.unwrap_or_default();
cx.start(async move { crate::element::host_post(name, args) });
Ok(())
}
}