Skip to main content

nsh_core/
host_channel.rs

1//! The message channel between an embedding app and the app one of its
2//! surfaces runs (`nsh/host`): the embedding app's launch parameters, its
3//! events to the app and the app's calls and posts to it, as JSON values.
4//!
5//! The pieces every side shares live here: the names' rules, the limits,
6//! [`HostBridge`] (what the app's module reaches of the embedding app; the
7//! engine's `HostChannel` implements it) and [`HostInbox`] (the events kept
8//! until a listener is there). The engine (`nsh_engine::HostChannel`) owns
9//! the embedding app's side, `nsh-js` (`host_channel.rs`) the app's.
10
11use std::{collections::VecDeque, time::Duration};
12
13use crate::{
14    JsonValue,
15    element::{JsError, codes},
16};
17
18/// Events kept at most for listeners not there yet: by an engine, until
19/// the app listens to their names, and by the embedding app's channel,
20/// while no app runs. Past it the oldest goes (logged).
21pub const MAX_QUEUED_EVENTS: usize = 256;
22
23/// Calls of one app waiting for the embedding app's answers at once; one
24/// more rejects ([`too_many_calls`]).
25pub const MAX_PENDING_CALLS: usize = 1024;
26
27/// The longest name of an event, a call or a post, in bytes.
28pub const MAX_NAME_LEN: usize = 256;
29
30/// Checks the name of an event, a call or a post: one to
31/// [`MAX_NAME_LEN`] bytes. The error says what is wrong.
32pub fn check_name(name: &str) -> Result<(), String> {
33    if name.is_empty() {
34        return Err("a message name is not empty".into());
35    }
36    if name.len() > MAX_NAME_LEN {
37        return Err(format!(
38            "a message name has at most {MAX_NAME_LEN} bytes (this one has {})",
39            name.len()
40        ));
41    }
42    Ok(())
43}
44
45/// What a call rejects with when the platform has no host
46/// ([`codes::UNAVAILABLE`]).
47pub fn no_host() -> JsError {
48    JsError::Error("nsh/host: this platform has no host".into()).with_code(codes::UNAVAILABLE)
49}
50
51/// What a call rejects with when the embedding app answered with error
52/// `message` (its handler failed, or it handles no such name): the host's
53/// message, [`codes::HOST_ERROR`].
54pub fn host_error(message: &str) -> JsError {
55    JsError::Error(message.to_owned()).with_code(codes::HOST_ERROR)
56}
57
58/// What a call or post of `name`, which no host function may have
59/// ([`crate::access::valid_host_name`]), fails with: a `TypeError`.
60pub fn invalid_name(name: &str) -> JsError {
61    JsError::Type(format!(
62        "nsh/host: invalid function name {name:?} ({})",
63        crate::access::HOST_NAME_CHARS
64    ))
65}
66
67/// What a call or post of `name` fails with when `capabilities.host` does
68/// not grant it ([`JsError::access_denied`], permission `"host"`).
69pub fn not_granted(name: &str) -> JsError {
70    JsError::access_denied(
71        format!("nsh/host: `{name}` is not granted: add it to capabilities.host in nsh.json"),
72        "host",
73        name,
74    )
75}
76
77/// Checks a call or post of `name` against the host names' rules and the
78/// app's `access`, before it crosses into the embedding app's code.
79pub fn check_call(access: &crate::access::Access, name: &str) -> Result<(), JsError> {
80    refusal(access, name).map_or(Ok(()), |error| Err(error.into()))
81}
82
83/// What a call of `name` rejects with when the embedding app did not answer
84/// within `timeout` ([`codes::TIMED_OUT`]).
85pub fn timed_out(name: &str, timeout: Duration) -> JsError {
86    JsError::Error(format!(
87        "nsh/host: {name} timed out after {} ms",
88        timeout.as_millis()
89    ))
90    .with_code(codes::TIMED_OUT)
91}
92
93/// What a call of `name` rejects with while [`MAX_PENDING_CALLS`] calls
94/// wait already ([`codes::QUOTA_EXCEEDED`]).
95pub fn too_many_calls(name: &str) -> JsError {
96    JsError::Error(format!(
97        "host.call(\"{name}\"): {MAX_PENDING_CALLS} calls already wait for the embedding app's answers"
98    ))
99    .with_code(codes::QUOTA_EXCEEDED)
100}
101
102/// How long a call waits for the host's answer unless its options say
103/// ([`HostCallOptions`]; TS: `host.call`'s `timeout`).
104pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(30);
105
106/// Why a call of the host's function failed
107/// ([`crate::element::host_call`]; TS: the `code` of `host.call`'s
108/// rejection, which [`HostError::code`] gives).
109#[derive(Debug, Clone, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum HostError {
112    /// The host's function failed, or the host has no function of the
113    /// name: the host's message (TS: `ERR_NSH_HOST_ERROR`).
114    Failed(String),
115    /// `capabilities.host` in nsh.json does not grant `name` (TS:
116    /// `ERR_ACCESS_DENIED`, permission `"host"`).
117    Denied {
118        /// The function's name.
119        name: String,
120    },
121    /// `name` is no host function's name
122    /// ([`crate::access::valid_host_name`]; TS: a `TypeError`).
123    InvalidName {
124        /// The name asked for.
125        name: String,
126    },
127    /// The app runs where nothing embeds it: no embedding app's channel and
128    /// no platform host (TS: `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`).
129    Unavailable,
130    /// The host did not answer within `timeout` (TS: `ETIMEDOUT`); its
131    /// answer, when it comes, is dropped.
132    TimedOut {
133        /// The function's name.
134        name: String,
135        /// How long the call waited.
136        timeout: Duration,
137    },
138    /// [`MAX_PENDING_CALLS`] calls wait for the host's answers already
139    /// (TS: `ERR_NSH_QUOTA_EXCEEDED`).
140    TooManyCalls {
141        /// The function's name.
142        name: String,
143    },
144}
145
146impl HostError {
147    /// The stable code TS's rejection carries (`ERR_NSH_HOST_ERROR`,
148    /// `ERR_ACCESS_DENIED`, ...); `None` for an invalid name, a
149    /// `TypeError` there.
150    pub fn code(&self) -> Option<&'static str> {
151        match self {
152            Self::Failed(_) => Some(codes::HOST_ERROR),
153            Self::Denied { .. } => Some(codes::ACCESS_DENIED),
154            Self::InvalidName { .. } => None,
155            Self::Unavailable => Some(codes::UNAVAILABLE),
156            Self::TimedOut { .. } => Some(codes::TIMED_OUT),
157            Self::TooManyCalls { .. } => Some(codes::QUOTA_EXCEEDED),
158        }
159    }
160}
161
162impl From<HostError> for JsError {
163    fn from(error: HostError) -> Self {
164        match error {
165            HostError::Failed(message) => host_error(&message),
166            HostError::Denied { name } => not_granted(&name),
167            HostError::InvalidName { name } => invalid_name(&name),
168            HostError::Unavailable => no_host(),
169            HostError::TimedOut { name, timeout } => timed_out(&name, timeout),
170            HostError::TooManyCalls { name } => too_many_calls(&name),
171        }
172    }
173}
174
175impl std::fmt::Display for HostError {
176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177        f.write_str(JsError::from(self.clone()).message())
178    }
179}
180
181impl std::error::Error for HostError {}
182
183/// Checks a call or post of `name` against the host names' rules (first:
184/// a host may put the name in a path or a URL, where `user.x/../admin`
185/// leaves `user.*`) and the app's `access`, as a [`HostError`].
186pub(crate) fn refusal(access: &crate::access::Access, name: &str) -> Option<HostError> {
187    if !crate::access::valid_host_name(name) {
188        Some(HostError::InvalidName { name: name.into() })
189    } else if !access.allows_host(name) {
190        Some(HostError::Denied { name: name.into() })
191    } else {
192        None
193    }
194}
195
196/// How a call of the host's function goes
197/// ([`crate::element::host_call_with`]).
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199#[non_exhaustive]
200pub struct HostCallOptions {
201    /// How long the call waits for the host's answer before it fails with
202    /// [`HostError::TimedOut`]: [`DEFAULT_CALL_TIMEOUT`] unless set.
203    /// [`Duration::ZERO`], or one so long the clock never gets there,
204    /// waits as long as the host takes (TS: `timeout: 0`).
205    pub timeout: Duration,
206}
207
208impl Default for HostCallOptions {
209    fn default() -> Self {
210        Self {
211            timeout: DEFAULT_CALL_TIMEOUT,
212        }
213    }
214}
215
216impl HostCallOptions {
217    /// Waits `timeout` for the host's answer ([`HostCallOptions::timeout`]).
218    pub fn timeout(mut self, timeout: Duration) -> Self {
219        self.timeout = timeout;
220        self
221    }
222}
223
224/// A call or post of the app's Rust or JS, checked and granted, that the
225/// engine hands to the embedding app's channel where it is configured,
226/// else to the platform's host ([`crate::Core::take_host_requests`]). The
227/// engine's, not part of the app's API.
228#[doc(hidden)]
229#[derive(Debug, Clone, PartialEq)]
230#[non_exhaustive]
231pub enum HostRequest {
232    /// Call `id`, answered with [`crate::Core::answer_host`].
233    Call {
234        /// The call's id.
235        id: u64,
236        /// The function's name.
237        name: String,
238        /// Its argument.
239        args: JsonValue,
240    },
241    /// A post, which has no answer.
242    Post {
243        /// The function's name.
244        name: String,
245        /// Its argument.
246        args: JsonValue,
247    },
248}
249
250/// What an app's `nsh/host` reaches of the embedding app, on the engine
251/// thread: the launch parameters, and where its calls and posts go. The
252/// engine implements it over the embedding app's channel; the answer to a
253/// call comes back to the VM later, by its id.
254pub trait HostBridge {
255    /// Whether the native embedding app configured this channel: it
256    /// handles calls or sent events (launch parameters alone do not). A
257    /// false value leaves calls to the platform transport (including the
258    /// web's page host).
259    fn available(&self) -> bool {
260        true
261    }
262
263    /// The launch parameters the embedding app set before the app started
264    /// (a JSON object; `{}` without any).
265    fn params(&self) -> JsonValue;
266
267    /// Hands call `id` (`host.call(name, data)`) to the embedding app's
268    /// handler of `name`. `Err` with the reason when there is none: the
269    /// call fails at once. Otherwise its answer comes back by `id`, once.
270    fn call(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String>;
271
272    /// Hands a post (`host.post(name, data)`) to the embedding app's
273    /// handler of `name`; without one it is dropped.
274    fn post(&self, name: &str, data: JsonValue);
275
276    /// The stand-ins for exports of native module `specifier`
277    /// ([`ModuleFake`]), by export (`"save"`) or member of one
278    /// (`"Keychain.get"`): none outside `nsh test`, whose hook it is (not
279    /// part of the embedding API).
280    #[doc(hidden)]
281    fn module_fakes(&self, specifier: &str) -> Vec<(String, ModuleFake)> {
282        let _ = specifier;
283        Vec::new()
284    }
285
286    /// Hands call `id` of a stand-in ([`ModuleFake::Call`] `name`), with
287    /// its arguments as an array, to the test's function of `name`, as
288    /// [`HostBridge::call`] does to the embedding app's handlers: the app's
289    /// `host.call` never reaches these. `nsh test`'s hook, not part of the
290    /// embedding API.
291    #[doc(hidden)]
292    fn call_module_fake(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
293        let _ = (id, data);
294        Err(format!("no stand-in answers \"{name}\""))
295    }
296}
297
298/// A stand-in `nsh test` gives an export of a native module, or a member of
299/// an export, in the app it opens (`open`'s `modules`): `nsh test`'s hook,
300/// not part of the embedding API.
301#[doc(hidden)]
302#[derive(Debug, Clone, PartialEq)]
303#[non_exhaustive]
304pub enum ModuleFake {
305    /// This value in its place; a function's stand-in is a function
306    /// returning it.
307    Value(JsonValue),
308    /// A function whose calls go to the test's function of this name
309    /// ([`HostBridge::call_module_fake`]), with the arguments as an array:
310    /// it returns a promise of the answer.
311    Call(String),
312}
313
314/// Events kept for listeners not there yet, oldest first, at most
315/// [`MAX_QUEUED_EVENTS`].
316#[derive(Debug, Default)]
317#[non_exhaustive]
318pub struct HostInbox {
319    events: VecDeque<(String, JsonValue)>,
320}
321
322impl HostInbox {
323    /// Keeps event `name` with `data`; when full, the oldest event goes
324    /// first and is returned.
325    pub fn push(&mut self, name: String, data: JsonValue) -> Option<(String, JsonValue)> {
326        let dropped = (self.events.len() >= MAX_QUEUED_EVENTS)
327            .then(|| self.events.pop_front())
328            .flatten();
329        self.events.push_back((name, data));
330        dropped
331    }
332
333    /// Whether an event named `name` is kept.
334    pub fn has(&self, name: &str) -> bool {
335        self.events.iter().any(|(n, _)| n == name)
336    }
337
338    /// Takes the oldest event named `name`, leaving every other event in
339    /// its original order.
340    pub fn pop(&mut self, name: &str) -> Option<JsonValue> {
341        let index = self.events.iter().position(|(n, _)| n == name)?;
342        self.events.remove(index).map(|(_, data)| data)
343    }
344
345    /// Takes the events named `name`, in the order they came.
346    pub fn take(&mut self, name: &str) -> Vec<JsonValue> {
347        let mut taken = Vec::new();
348        self.events.retain_mut(|(n, data)| {
349            if n == name {
350                taken.push(std::mem::take(data));
351                false
352            } else {
353                true
354            }
355        });
356        taken
357    }
358
359    /// Takes every event, in the order they came.
360    pub fn take_all(&mut self) -> Vec<(String, JsonValue)> {
361        self.events.drain(..).collect()
362    }
363
364    /// How many events are kept.
365    pub fn len(&self) -> usize {
366        self.events.len()
367    }
368
369    /// Whether no event is kept.
370    pub fn is_empty(&self) -> bool {
371        self.events.is_empty()
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use serde_json::json;
378
379    use super::*;
380
381    #[test]
382    fn names_are_checked() {
383        assert!(check_name("user.changed").is_ok());
384        assert!(check_name("").is_err());
385        assert!(check_name(&"x".repeat(MAX_NAME_LEN)).is_ok());
386        assert!(check_name(&"x".repeat(MAX_NAME_LEN + 1)).is_err());
387    }
388
389    #[test]
390    fn the_inbox_keeps_events_by_name_in_order() {
391        let mut inbox = HostInbox::default();
392        inbox.push("a".into(), json!(1));
393        inbox.push("b".into(), json!(2));
394        inbox.push("a".into(), json!(3));
395        assert!(inbox.has("a"));
396        assert_eq!(inbox.take("a"), vec![json!(1), json!(3)]);
397        assert!(!inbox.has("a"));
398        assert_eq!(inbox.len(), 1);
399        assert_eq!(inbox.take_all(), vec![("b".to_owned(), json!(2))]);
400        assert!(inbox.is_empty());
401    }
402
403    #[test]
404    fn popping_one_event_preserves_the_age_of_the_rest() {
405        let mut inbox = HostInbox::default();
406        inbox.push("a".into(), json!(1));
407        inbox.push("b".into(), json!(2));
408        inbox.push("a".into(), json!(3));
409        assert_eq!(inbox.pop("missing"), None);
410        assert_eq!(inbox.pop("a"), Some(json!(1)));
411        assert_eq!(inbox.len(), 2);
412        assert_eq!(
413            inbox.take_all(),
414            vec![("b".to_owned(), json!(2)), ("a".to_owned(), json!(3))]
415        );
416    }
417
418    #[test]
419    fn a_full_inbox_drops_the_oldest() {
420        let mut inbox = HostInbox::default();
421        for i in 0..MAX_QUEUED_EVENTS {
422            assert_eq!(inbox.push("e".into(), json!(i)), None);
423        }
424        assert_eq!(
425            inbox.push("e".into(), json!("last")),
426            Some(("e".to_owned(), json!(0)))
427        );
428        let kept = inbox.take("e");
429        assert_eq!(kept.len(), MAX_QUEUED_EVENTS);
430        assert_eq!(kept[0], json!(1));
431        assert_eq!(kept[MAX_QUEUED_EVENTS - 1], json!("last"));
432    }
433}