use std::{collections::VecDeque, time::Duration};
use crate::{
JsonValue,
element::{JsError, codes},
};
pub const MAX_QUEUED_EVENTS: usize = 256;
pub const MAX_PENDING_CALLS: usize = 1024;
pub const MAX_NAME_LEN: usize = 256;
pub fn check_name(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err("a message name is not empty".into());
}
if name.len() > MAX_NAME_LEN {
return Err(format!(
"a message name has at most {MAX_NAME_LEN} bytes (this one has {})",
name.len()
));
}
Ok(())
}
pub fn no_host() -> JsError {
JsError::Error("nsh/host: this platform has no host".into()).with_code(codes::UNAVAILABLE)
}
pub fn host_error(message: &str) -> JsError {
JsError::Error(message.to_owned()).with_code(codes::HOST_ERROR)
}
pub fn invalid_name(name: &str) -> JsError {
JsError::Type(format!(
"nsh/host: invalid function name {name:?} ({})",
crate::access::HOST_NAME_CHARS
))
}
pub fn not_granted(name: &str) -> JsError {
JsError::access_denied(
format!("nsh/host: `{name}` is not granted: add it to capabilities.host in nsh.json"),
"host",
name,
)
}
pub fn check_call(access: &crate::access::Access, name: &str) -> Result<(), JsError> {
refusal(access, name).map_or(Ok(()), |error| Err(error.into()))
}
pub fn timed_out(name: &str, timeout: Duration) -> JsError {
JsError::Error(format!(
"nsh/host: {name} timed out after {} ms",
timeout.as_millis()
))
.with_code(codes::TIMED_OUT)
}
pub fn too_many_calls(name: &str) -> JsError {
JsError::Error(format!(
"host.call(\"{name}\"): {MAX_PENDING_CALLS} calls already wait for the embedding app's answers"
))
.with_code(codes::QUOTA_EXCEEDED)
}
pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HostError {
Failed(String),
Denied {
name: String,
},
InvalidName {
name: String,
},
Unavailable,
TimedOut {
name: String,
timeout: Duration,
},
TooManyCalls {
name: String,
},
}
impl HostError {
pub fn code(&self) -> Option<&'static str> {
match self {
Self::Failed(_) => Some(codes::HOST_ERROR),
Self::Denied { .. } => Some(codes::ACCESS_DENIED),
Self::InvalidName { .. } => None,
Self::Unavailable => Some(codes::UNAVAILABLE),
Self::TimedOut { .. } => Some(codes::TIMED_OUT),
Self::TooManyCalls { .. } => Some(codes::QUOTA_EXCEEDED),
}
}
}
impl From<HostError> for JsError {
fn from(error: HostError) -> Self {
match error {
HostError::Failed(message) => host_error(&message),
HostError::Denied { name } => not_granted(&name),
HostError::InvalidName { name } => invalid_name(&name),
HostError::Unavailable => no_host(),
HostError::TimedOut { name, timeout } => timed_out(&name, timeout),
HostError::TooManyCalls { name } => too_many_calls(&name),
}
}
}
impl std::fmt::Display for HostError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(JsError::from(self.clone()).message())
}
}
impl std::error::Error for HostError {}
pub(crate) fn refusal(access: &crate::access::Access, name: &str) -> Option<HostError> {
if !crate::access::valid_host_name(name) {
Some(HostError::InvalidName { name: name.into() })
} else if !access.allows_host(name) {
Some(HostError::Denied { name: name.into() })
} else {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct HostCallOptions {
pub timeout: Duration,
}
impl Default for HostCallOptions {
fn default() -> Self {
Self {
timeout: DEFAULT_CALL_TIMEOUT,
}
}
}
impl HostCallOptions {
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
}
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum HostRequest {
Call {
id: u64,
name: String,
args: JsonValue,
},
Post {
name: String,
args: JsonValue,
},
}
pub trait HostBridge {
fn available(&self) -> bool {
true
}
fn params(&self) -> JsonValue;
fn call(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String>;
fn post(&self, name: &str, data: JsonValue);
#[doc(hidden)]
fn module_fakes(&self, specifier: &str) -> Vec<(String, ModuleFake)> {
let _ = specifier;
Vec::new()
}
#[doc(hidden)]
fn call_module_fake(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
let _ = (id, data);
Err(format!("no stand-in answers \"{name}\""))
}
}
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ModuleFake {
Value(JsonValue),
Call(String),
}
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct HostInbox {
events: VecDeque<(String, JsonValue)>,
}
impl HostInbox {
pub fn push(&mut self, name: String, data: JsonValue) -> Option<(String, JsonValue)> {
let dropped = (self.events.len() >= MAX_QUEUED_EVENTS)
.then(|| self.events.pop_front())
.flatten();
self.events.push_back((name, data));
dropped
}
pub fn has(&self, name: &str) -> bool {
self.events.iter().any(|(n, _)| n == name)
}
pub fn pop(&mut self, name: &str) -> Option<JsonValue> {
let index = self.events.iter().position(|(n, _)| n == name)?;
self.events.remove(index).map(|(_, data)| data)
}
pub fn take(&mut self, name: &str) -> Vec<JsonValue> {
let mut taken = Vec::new();
self.events.retain_mut(|(n, data)| {
if n == name {
taken.push(std::mem::take(data));
false
} else {
true
}
});
taken
}
pub fn take_all(&mut self) -> Vec<(String, JsonValue)> {
self.events.drain(..).collect()
}
pub fn len(&self) -> usize {
self.events.len()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn names_are_checked() {
assert!(check_name("user.changed").is_ok());
assert!(check_name("").is_err());
assert!(check_name(&"x".repeat(MAX_NAME_LEN)).is_ok());
assert!(check_name(&"x".repeat(MAX_NAME_LEN + 1)).is_err());
}
#[test]
fn the_inbox_keeps_events_by_name_in_order() {
let mut inbox = HostInbox::default();
inbox.push("a".into(), json!(1));
inbox.push("b".into(), json!(2));
inbox.push("a".into(), json!(3));
assert!(inbox.has("a"));
assert_eq!(inbox.take("a"), vec![json!(1), json!(3)]);
assert!(!inbox.has("a"));
assert_eq!(inbox.len(), 1);
assert_eq!(inbox.take_all(), vec![("b".to_owned(), json!(2))]);
assert!(inbox.is_empty());
}
#[test]
fn popping_one_event_preserves_the_age_of_the_rest() {
let mut inbox = HostInbox::default();
inbox.push("a".into(), json!(1));
inbox.push("b".into(), json!(2));
inbox.push("a".into(), json!(3));
assert_eq!(inbox.pop("missing"), None);
assert_eq!(inbox.pop("a"), Some(json!(1)));
assert_eq!(inbox.len(), 2);
assert_eq!(
inbox.take_all(),
vec![("b".to_owned(), json!(2)), ("a".to_owned(), json!(3))]
);
}
#[test]
fn a_full_inbox_drops_the_oldest() {
let mut inbox = HostInbox::default();
for i in 0..MAX_QUEUED_EVENTS {
assert_eq!(inbox.push("e".into(), json!(i)), None);
}
assert_eq!(
inbox.push("e".into(), json!("last")),
Some(("e".to_owned(), json!(0)))
);
let kept = inbox.take("e");
assert_eq!(kept.len(), MAX_QUEUED_EVENTS);
assert_eq!(kept[0], json!(1));
assert_eq!(kept[MAX_QUEUED_EVENTS - 1], json!("last"));
}
}