Skip to main content

nsh_engine/
host_channel.rs

1//! [`HostChannel`]: the embedding app's side of the message channel with
2//! the app a surface runs (`nsh/host`; `nsh_core::host_channel`).
3//!
4//! A platform's view (`AppView`, `NshAppView`, `NshView`) keeps one channel
5//! for every app it runs and hands it to each engine
6//! ([`crate::EngineConfig::host`]). The engine attaches to it while it
7//! runs: [`HostChannel::send`] queues the event on that engine (kept for
8//! the next app while none runs), and the app's calls and posts reach the
9//! handlers registered with [`HostChannel::handle`]. Handlers run on the
10//! engine thread and must not block it: they answer at once or move the
11//! [`HostCall`] (or its [`HostReply`]) to another thread and answer from
12//! there. The SDKs' handlers (Swift, Java) run on the main thread: their
13//! glue hops there.
14//!
15//! The channel also carries the embedding app's URL handler
16//! ([`HostChannel::handle_open_url`]): the URLs the app opens (`openUrl` of
17//! `nsh/device`) reach it before the system, so a host routes them through
18//! its own router. It is a typed hook of the channel rather than a named
19//! message: it takes only what passed the URL check and the `openUrl`
20//! capability, and no app's `host.call` name can reach it.
21
22use std::{
23    collections::HashMap,
24    sync::{Arc, Mutex, MutexGuard},
25};
26
27use crossbeam_channel::{Receiver, Sender};
28#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
29use nsh_core::host_channel::HostBridge;
30use nsh_core::{
31    JsonValue,
32    host_channel::{HostInbox, ModuleFake, check_name},
33};
34
35use crate::Message;
36
37/// A handler of the app's calls and posts of one name.
38type Handler = Arc<dyn Fn(HostCall) + Send + Sync>;
39
40/// The embedding app's handler of the URLs the app opens.
41type UrlHandler = Arc<dyn Fn(OpenUrlRequest) + Send + Sync>;
42
43/// The embedding app's side of the channel with the apps one of its views
44/// runs: launch parameters, events to the app (`host.on` in TSX), and
45/// handlers of the app's calls (`host.call`) and posts (`host.post`).
46///
47/// Cheap to clone (the clones are one channel); usable from any thread.
48/// One per view, shared by the apps it runs one after another.
49///
50/// ```
51/// use nsh_engine::{HostChannel, JsonValue};
52///
53/// let channel = HostChannel::new();
54/// // What the next app reads synchronously at start (`host.params`).
55/// let mut params = serde_json::Map::new();
56/// params.insert("conversation".into(), JsonValue::from("c-42"));
57/// channel.set_params(params);
58/// // `await host.call("profile", { id })` in the app.
59/// channel.handle("profile", |call| {
60///     let id = call.data()["id"].clone();
61///     call.resolve(serde_json::json!({ "id": id, "name": "Ada" }));
62/// });
63/// // `host.on("user.changed", ...)` in the app.
64/// channel.send("user.changed", serde_json::json!({ "id": 7 })).unwrap();
65/// ```
66#[derive(Clone, Default)]
67pub struct HostChannel {
68    inner: Arc<Mutex<Inner>>,
69}
70
71#[derive(Default)]
72struct Inner {
73    params: serde_json::Map<String, JsonValue>,
74    configured: bool,
75    handlers: HashMap<String, Handler>,
76    url_handler: Option<UrlHandler>,
77    /// The engine running the view's app: its attachment's id and queue.
78    engine: Option<(u64, Sender<Message>)>,
79    next_engine: u64,
80    /// Events sent while no app ran, for the next one.
81    pending: HostInbox,
82    /// The stand-ins for native modules' exports: specifier, export (or
83    /// `Export.member`), stand-in.
84    module_fakes: Vec<(String, String, ModuleFake)>,
85    /// The handlers of the stand-ins' calls, apart from the embedding
86    /// app's: they configure nothing and `host.call` never reaches them.
87    fake_handlers: HashMap<String, Handler>,
88}
89
90impl std::fmt::Debug for HostChannel {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        let inner = self.lock();
93        let mut handlers: Vec<&String> = inner.handlers.keys().collect();
94        handlers.sort();
95        f.debug_struct("HostChannel")
96            .field("params", &inner.params)
97            .field("handlers", &handlers)
98            .field("configured", &inner.configured)
99            .field("url_handler", &inner.url_handler.is_some())
100            .field("attached", &inner.engine.is_some())
101            .field("pending", &inner.pending.len())
102            .finish()
103    }
104}
105
106impl HostChannel {
107    /// A channel with no parameters and no handlers.
108    pub fn new() -> Self {
109        Self::default()
110    }
111
112    fn lock(&self) -> MutexGuard<'_, Inner> {
113        self.inner.lock().unwrap_or_else(|e| e.into_inner())
114    }
115
116    /// The launch parameters of the apps started from now on
117    /// (`host.params`, read synchronously when they start; a running app
118    /// keeps the ones it started with). Later requests are events
119    /// ([`HostChannel::send`]).
120    ///
121    /// Parameters alone answer no call, so they leave the channel as it
122    /// was: until a handler ([`HostChannel::handle`]) or an event
123    /// configures it, the app's calls keep going to the platform's own
124    /// host, as on the web, where the page passes parameters and answers
125    /// calls with its player's host.
126    pub fn set_params(&self, params: serde_json::Map<String, JsonValue>) {
127        self.lock().params = params;
128    }
129
130    /// The launch parameters ([`HostChannel::set_params`]).
131    pub fn params(&self) -> serde_json::Map<String, JsonValue> {
132        self.lock().params.clone()
133    }
134
135    /// Sends event `name` with `data` to the running app (`host.on(name,
136    /// listener)`). The app keeps events of names it does not listen to
137    /// yet until it does; while no app runs, events wait for the next one
138    /// (up to [`nsh_core::host_channel::MAX_QUEUED_EVENTS`] each, then the
139    /// oldest go). Any thread; it never waits for the app. `Err` for a name
140    /// that is empty or longer than
141    /// [`nsh_core::host_channel::MAX_NAME_LEN`] bytes.
142    pub fn send(&self, name: impl Into<String>, data: JsonValue) -> Result<(), String> {
143        let name = name.into();
144        check_name(&name)?;
145        let mut inner = self.lock();
146        inner.configured = true;
147        if let Some((_, tx)) = &inner.engine
148            && tx
149                .send(Message::HostEvent(name.clone(), data.clone()))
150                .is_ok()
151        {
152            return Ok(());
153        }
154        if let Some((dropped, _)) = inner.pending.push(name, data) {
155            log::warn!(
156                "nsh/host: no app ran to take the embedding app's events; the oldest (\"{dropped}\") was dropped"
157            );
158        }
159        Ok(())
160    }
161
162    /// Handles the app's calls (`host.call(name, data)`) and posts
163    /// (`host.post(name, data)`) of `name`, replacing the handler it had.
164    /// `handler` runs on the engine thread and must return quickly: it
165    /// answers a call with [`HostCall::resolve`] / [`HostCall::reject`] at
166    /// once, or moves the call to where its answer comes from and answers
167    /// there, from any thread. A post's answer goes nowhere. A call that
168    /// is dropped unanswered fails in the app.
169    pub fn handle(
170        &self,
171        name: impl Into<String>,
172        handler: impl Fn(HostCall) + Send + Sync + 'static,
173    ) {
174        let mut inner = self.lock();
175        inner.configured = true;
176        inner.handlers.insert(name.into(), Arc::new(handler));
177    }
178
179    /// Removes the handler of `name`: the app's calls of it fail at once
180    /// from now on, its posts are dropped.
181    pub fn remove_handler(&self, name: &str) {
182        self.lock().handlers.remove(name);
183    }
184
185    /// Puts `fake` in the place of export `path` of native module
186    /// `specifier` (`"Keychain"`, or a member of an export,
187    /// `"Keychain.get"`) in the apps started from now on, as `nsh test`'s
188    /// `open` does for the app a test opens: their imports of the module
189    /// get the stand-in. A [`ModuleFake::Call`] is answered by the
190    /// handler of its name [`HostChannel::handle_module_fake`] registers.
191    /// `nsh test`'s hook, not part of the embedding API.
192    #[doc(hidden)]
193    pub fn fake_module_export(
194        &self,
195        specifier: impl Into<String>,
196        path: impl Into<String>,
197        fake: ModuleFake,
198    ) {
199        self.lock()
200            .module_fakes
201            .push((specifier.into(), path.into(), fake));
202    }
203
204    /// Handles the calls of the stand-ins whose [`ModuleFake::Call`] is
205    /// `name`, as [`HostChannel::handle`] does the app's `host.call`s, but
206    /// apart from them: the app's `host.call` never reaches it, and the
207    /// channel stays as the embedding app configured it (`host.available()`).
208    /// `nsh test`'s hook, not part of the embedding API.
209    #[doc(hidden)]
210    pub fn handle_module_fake(
211        &self,
212        name: impl Into<String>,
213        handler: impl Fn(HostCall) + Send + Sync + 'static,
214    ) {
215        self.lock()
216            .fake_handlers
217            .insert(name.into(), Arc::new(handler));
218    }
219
220    #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
221    fn handler(&self, name: &str) -> Option<Handler> {
222        self.lock().handlers.get(name).cloned()
223    }
224
225    #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
226    fn fake_handler(&self, name: &str) -> Option<Handler> {
227        self.lock().fake_handlers.get(name).cloned()
228    }
229
230    /// Asks the engine to stop without interrupting JS, so its quit
231    /// listeners run ([`HostChannel::shutdown`] follows): events sent
232    /// meanwhile follow the shutdown message, kept for the next app.
233    #[cfg(not(target_arch = "wasm32"))]
234    pub(crate) fn request_shutdown(&self, tx: &Sender<Message>) {
235        let _inner = self.lock();
236        let _ = tx.send(Message::Shutdown);
237    }
238
239    /// Events sent once JS is interrupted must follow the shutdown
240    /// message, so the attachment can recover them for the next app.
241    #[cfg(not(target_arch = "wasm32"))]
242    pub(crate) fn shutdown(&self, tx: &Sender<Message>, stop: &std::sync::atomic::AtomicBool) {
243        let _inner = self.lock();
244        stop.store(true, std::sync::atomic::Ordering::Relaxed);
245        let _ = tx.send(Message::Shutdown);
246    }
247
248    /// Takes the URLs the app opens (`openUrl` of `nsh/device`, a
249    /// `TextView`'s links) before the system does, replacing the handler
250    /// it had: a host routes them through its own router. The URL passed
251    /// the URL check and the app's `openUrl` capability
252    /// ([`nsh_core::open_url`]). `handler` runs on the engine thread and
253    /// must return quickly: it answers with [`OpenUrlRequest::handled`]
254    /// (the app's `openUrl` resolves `true`) or
255    /// [`OpenUrlRequest::decline`] (the system opens it), at once or from
256    /// any thread later. A request dropped unanswered is declined.
257    pub fn handle_open_url(&self, handler: impl Fn(OpenUrlRequest) + Send + Sync + 'static) {
258        self.lock().url_handler = Some(Arc::new(handler));
259    }
260
261    /// Removes the URL handler: the system opens the app's URLs from now
262    /// on.
263    pub fn remove_open_url_handler(&self) {
264        self.lock().url_handler = None;
265    }
266
267    /// Hands URL request `id` of the engine whose queue is `tx` to the
268    /// embedding app's URL handler; without one, `None`: the system opens
269    /// it.
270    pub(crate) fn open_url(&self, id: u32, url: String, tx: &Sender<Message>) -> Option<()> {
271        let handler = self.lock().url_handler.clone()?;
272        let request = OpenUrlRequest {
273            reply: Some(UrlReply {
274                id,
275                url: url.clone(),
276                tx: tx.clone(),
277            }),
278            url,
279        };
280        if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(request))).is_err() {
281            log::error!("nsh/device: the embedding app's URL handler panicked");
282        }
283        Some(())
284    }
285
286    /// Attaches the engine whose queue is `tx`: events go to it from now
287    /// on, those waiting first. Detached when the attachment drops (unless
288    /// another engine attached since).
289    pub(crate) fn attach(&self, tx: Sender<Message>, rx: Receiver<Message>) -> HostAttachment {
290        let mut inner = self.lock();
291        inner.next_engine += 1;
292        let id = inner.next_engine;
293        for (name, data) in inner.pending.take_all() {
294            let _ = tx.send(Message::HostEvent(name, data));
295        }
296        inner.engine = Some((id, tx));
297        HostAttachment {
298            channel: self.clone(),
299            id,
300            rx,
301        }
302    }
303
304    /// The bridge an app's `nsh/host` reaches this channel through, from
305    /// the engine whose queue is `tx`: its parameters and module stand-ins
306    /// as they are now.
307    #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
308    pub(crate) fn bridge(&self, tx: Sender<Message>) -> EngineBridge {
309        let inner = self.lock();
310        EngineBridge {
311            params: JsonValue::Object(inner.params.clone()),
312            module_fakes: inner.module_fakes.clone(),
313            channel: self.clone(),
314            tx,
315        }
316    }
317}
318
319/// An engine's attachment to its view's channel ([`HostChannel::attach`]).
320pub(crate) struct HostAttachment {
321    channel: HostChannel,
322    id: u64,
323    /// Events behind a shutdown message still belong to this channel.
324    rx: Receiver<Message>,
325}
326
327impl Drop for HostAttachment {
328    fn drop(&mut self) {
329        let discarded = {
330            let mut inner = self.channel.lock();
331            if !inner.engine.as_ref().is_some_and(|(id, _)| *id == self.id) {
332                return;
333            }
334            inner.engine = None;
335            // Detach and drain under the same lock as `send`: every event
336            // either waits here or is kept by `send` for the next app.
337            let mut messages: Vec<_> = self.rx.try_iter().collect();
338            for message in &mut messages {
339                if let Message::HostEvent(name, data) = message
340                    && let Some((dropped, _)) = inner
341                        .pending
342                        .push(std::mem::take(name), std::mem::take(data))
343                {
344                    log::warn!(
345                        "nsh/host: the app stopped; the oldest kept event (\"{dropped}\") was dropped"
346                    );
347                }
348            }
349            messages
350        };
351        // Other messages can own closures whose destructors reach the
352        // channel. Release them without its lock held.
353        drop(discarded);
354    }
355}
356
357/// What an engine's `nsh/host` reaches of the channel
358/// ([`nsh_core::host_channel::HostBridge`]).
359#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
360pub(crate) struct EngineBridge {
361    params: JsonValue,
362    // A copy, so making a module's exports takes no lock.
363    module_fakes: Vec<(String, String, ModuleFake)>,
364    channel: HostChannel,
365    tx: Sender<Message>,
366}
367
368#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
369impl EngineBridge {
370    /// Runs `handler` with `call`; a handler that panics drops the call,
371    /// which fails it in the app.
372    fn run(handler: &Handler, call: HostCall) {
373        let name = call.name.clone();
374        let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(call)));
375        if ran.is_err() {
376            log::error!("nsh/host: the embedding app's handler of \"{name}\" panicked");
377        }
378    }
379
380    /// Runs `handler` with call `id` of `name`, answered back to this
381    /// engine.
382    fn start(&self, handler: &Handler, id: u64, name: &str, data: JsonValue) {
383        let call = HostCall {
384            name: name.to_owned(),
385            data,
386            reply: Some(HostReply {
387                id,
388                name: name.to_owned(),
389                tx: Some(self.tx.clone()),
390            }),
391        };
392        Self::run(handler, call);
393    }
394}
395
396#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
397impl HostBridge for EngineBridge {
398    fn available(&self) -> bool {
399        self.channel.lock().configured
400    }
401
402    fn params(&self) -> JsonValue {
403        self.params.clone()
404    }
405
406    fn call(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
407        let Some(handler) = self.channel.handler(name) else {
408            return Err(format!(
409                "host.call(\"{name}\"): the embedding app handles no \"{name}\""
410            ));
411        };
412        self.start(&handler, id, name, data);
413        Ok(())
414    }
415
416    fn module_fakes(&self, specifier: &str) -> Vec<(String, ModuleFake)> {
417        self.module_fakes
418            .iter()
419            .filter(|(s, _, _)| s == specifier)
420            .map(|(_, path, fake)| (path.clone(), fake.clone()))
421            .collect()
422    }
423
424    fn call_module_fake(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
425        let Some(handler) = self.channel.fake_handler(name) else {
426            return Err(format!("no stand-in answers \"{name}\""));
427        };
428        self.start(&handler, id, name, data);
429        Ok(())
430    }
431
432    fn post(&self, name: &str, data: JsonValue) {
433        match self.channel.handler(name) {
434            Some(handler) => Self::run(
435                &handler,
436                HostCall {
437                    name: name.to_owned(),
438                    data,
439                    reply: None,
440                },
441            ),
442            None => log::debug!(
443                "nsh/host: the embedding app handles no \"{name}\"; the post was dropped"
444            ),
445        }
446    }
447}
448
449/// A call (`host.call(name, data)`) or a post (`host.post(name, data)`) of
450/// the app, as the embedding app's handler gets it. A call is answered once,
451/// from any thread; dropped unanswered, it fails in the app.
452#[derive(Default)]
453#[non_exhaustive]
454pub struct HostCall {
455    name: String,
456    data: JsonValue,
457    reply: Option<HostReply>,
458}
459
460impl std::fmt::Debug for HostCall {
461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462        f.debug_struct("HostCall")
463            .field("name", &self.name)
464            .field("data", &self.data)
465            .field("post", &self.is_post())
466            .finish()
467    }
468}
469
470impl HostCall {
471    /// Its name.
472    pub fn name(&self) -> &str {
473        &self.name
474    }
475
476    /// Its data (`null` when the app sent none).
477    pub fn data(&self) -> &JsonValue {
478        &self.data
479    }
480
481    /// Takes its data, leaving `null`.
482    pub fn take_data(&mut self) -> JsonValue {
483        std::mem::take(&mut self.data)
484    }
485
486    /// Whether it is a post, whose answer goes nowhere.
487    pub fn is_post(&self) -> bool {
488        self.reply.is_none()
489    }
490
491    /// Answers the call: the app's promise resolves with `value`.
492    pub fn resolve(self, value: JsonValue) {
493        self.reply(Ok(value));
494    }
495
496    /// Fails the call: the app's promise rejects with an `Error` of
497    /// `message`.
498    pub fn reject(self, message: impl Into<String>) {
499        self.reply(Err(message.into()));
500    }
501
502    /// Answers the call with `result` ([`HostCall::resolve`],
503    /// [`HostCall::reject`]).
504    pub fn reply(mut self, result: Result<JsonValue, String>) {
505        if let Some(reply) = self.reply.take() {
506            reply.reply(result);
507        }
508    }
509
510    /// The reply alone, to answer from elsewhere (`None` for a post).
511    pub fn into_reply(mut self) -> Option<HostReply> {
512        self.reply.take()
513    }
514}
515
516/// A URL the app opens (`openUrl` of `nsh/device`), as the embedding app's
517/// URL handler gets it ([`HostChannel::handle_open_url`]). Answered once,
518/// from any thread: [`OpenUrlRequest::handled`] when the embedding app
519/// took it, [`OpenUrlRequest::decline`] for the system to open it (also
520/// what dropping it unanswered does).
521#[derive(Default)]
522#[non_exhaustive]
523pub struct OpenUrlRequest {
524    url: String,
525    reply: Option<UrlReply>,
526}
527
528/// Where an [`OpenUrlRequest`]'s answer goes.
529struct UrlReply {
530    id: u32,
531    url: String,
532    tx: Sender<Message>,
533}
534
535impl std::fmt::Debug for OpenUrlRequest {
536    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537        f.debug_struct("OpenUrlRequest")
538            .field("url", &self.url)
539            .finish()
540    }
541}
542
543impl OpenUrlRequest {
544    /// The URL: absolute, of a scheme that opens another app
545    /// ([`nsh_core::open_url::check_url`]).
546    pub fn url(&self) -> &str {
547        &self.url
548    }
549
550    /// The embedding app took the URL (routed it its own way): the app's
551    /// `openUrl` resolves `true` and the system does not open it.
552    pub fn handled(self) {
553        self.answer(true);
554    }
555
556    /// The embedding app leaves the URL to the system, which opens it.
557    pub fn decline(self) {
558        self.answer(false);
559    }
560
561    /// [`OpenUrlRequest::handled`] when `handled`, else
562    /// [`OpenUrlRequest::decline`].
563    pub fn answer(mut self, handled: bool) {
564        if let Some(reply) = self.reply.take() {
565            let _ = reply.tx.send(Message::UrlHandled {
566                id: reply.id,
567                url: reply.url,
568                handled,
569            });
570        }
571    }
572}
573
574impl Drop for OpenUrlRequest {
575    fn drop(&mut self) {
576        if let Some(reply) = self.reply.take() {
577            let _ = reply.tx.send(Message::UrlHandled {
578                id: reply.id,
579                url: reply.url,
580                handled: false,
581            });
582        }
583    }
584}
585
586/// How a call is answered (a [`HostCall`]'s): once, from any thread.
587/// Dropped unanswered, the call fails in the app.
588#[derive(Default)]
589#[non_exhaustive]
590pub struct HostReply {
591    id: u64,
592    name: String,
593    /// The queue of the engine that made the call; `None` once answered.
594    tx: Option<Sender<Message>>,
595}
596
597impl std::fmt::Debug for HostReply {
598    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
599        f.debug_struct("HostReply")
600            .field("name", &self.name)
601            .finish()
602    }
603}
604
605impl HostReply {
606    /// The app's promise resolves with `value`.
607    pub fn resolve(self, value: JsonValue) {
608        self.reply(Ok(value));
609    }
610
611    /// The app's promise rejects with an `Error` of `message`.
612    pub fn reject(self, message: impl Into<String>) {
613        self.reply(Err(message.into()));
614    }
615
616    /// Answers with `result`. An app that stopped meanwhile drops it.
617    pub fn reply(mut self, result: Result<JsonValue, String>) {
618        if let Some(tx) = self.tx.take() {
619            let _ = tx.send(Message::HostReply(self.id, result));
620        }
621    }
622}
623
624impl Drop for HostReply {
625    fn drop(&mut self) {
626        if let Some(tx) = self.tx.take() {
627            let message = format!(
628                "host.call(\"{}\"): the embedding app did not answer",
629                self.name
630            );
631            let _ = tx.send(Message::HostReply(self.id, Err(message)));
632        }
633    }
634}
635
636#[cfg(all(test, feature = "js-core", not(target_arch = "wasm32")))]
637mod tests {
638    use std::time::Duration;
639
640    use nsh_core::{ApproxTextEngine, MountBatch};
641    use serde_json::json;
642
643    use super::*;
644    use crate::{Bundle, Engine, EngineConfig, MountSink};
645
646    struct Sink;
647
648    impl MountSink for Sink {
649        fn submit(&self, _: MountBatch) {}
650    }
651
652    #[test]
653    fn events_sent_while_the_engine_stops_reach_the_next_app() {
654        let channel = HostChannel::new();
655        let (entered_tx, entered_rx) = crossbeam_channel::bounded(1);
656        let (release_tx, release_rx) = crossbeam_channel::bounded(1);
657        channel.handle("hold", move |_| {
658            entered_tx.send(()).unwrap();
659            release_rx.recv_timeout(Duration::from_secs(5)).unwrap();
660        });
661        let mut config = EngineConfig::new(Bundle::source(
662            "import { host } from 'nsh'; host.post('hold');".to_owned(),
663        ));
664        if let crate::App::Js(bundle) = &mut config.app {
665            bundle.policy.declared =
666                Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
667        }
668        config.host = channel.clone();
669        let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
670        entered_rx.recv_timeout(Duration::from_secs(5)).unwrap();
671        // Hold the engine while the platform drops it, as a reload does
672        // while the old app is still finishing a callback.
673        let stop = engine.stop.clone();
674        let dropping = std::thread::spawn(move || drop(engine));
675        let deadline = std::time::Instant::now() + Duration::from_secs(5);
676        while !stop.load(std::sync::atomic::Ordering::Relaxed) {
677            assert!(
678                std::time::Instant::now() < deadline,
679                "shutdown did not start"
680            );
681            std::thread::yield_now();
682        }
683        for id in 1..=3 {
684            channel.send("open", json!(id)).unwrap();
685        }
686        release_tx.send(()).unwrap();
687        dropping.join().unwrap();
688
689        let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
690        channel.handle("seen", move |mut call| {
691            seen_tx.send(call.take_data()).unwrap();
692        });
693        let mut config = EngineConfig::new(Bundle::source(
694            "import { host } from 'nsh'; host.on('open', data => host.post('seen', data));"
695                .to_owned(),
696        ));
697        if let crate::App::Js(bundle) = &mut config.app {
698            bundle.policy.declared =
699                Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
700        }
701        config.host = channel;
702        let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
703        for id in 1..=3 {
704            assert_eq!(
705                seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
706                json!(id)
707            );
708        }
709        assert!(seen_rx.try_recv().is_err());
710        drop(engine);
711    }
712
713    fn start(channel: &HostChannel, source: &str) -> Engine {
714        let mut config = EngineConfig::new(Bundle::source(source.to_owned()));
715        if let crate::App::Js(bundle) = &mut config.app {
716            bundle.policy.declared =
717                Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
718        }
719        config.host = channel.clone();
720        Engine::start(config, || ApproxTextEngine, Sink).unwrap()
721    }
722
723    #[test]
724    fn a_stand_in_leaves_the_app_without_an_embedding_app() {
725        let channel = HostChannel::new();
726        let (tx, rx) = crossbeam_channel::unbounded();
727        channel.handle_module_fake("probe", move |mut call| {
728            tx.send(call.take_data()).unwrap();
729            call.resolve(JsonValue::Null);
730        });
731        channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
732        let engine = start(
733            &channel,
734            "import { host, Image } from 'nsh'; Image.prefetch(host.available());",
735        );
736        assert_eq!(
737            rx.recv_timeout(Duration::from_secs(5)).unwrap(),
738            json!([false])
739        );
740        drop(engine);
741    }
742
743    #[test]
744    fn the_app_s_calls_never_reach_a_stand_in() {
745        let channel = HostChannel::new();
746        let (faked_tx, faked_rx) = crossbeam_channel::unbounded();
747        channel.handle_module_fake("probe", move |call| {
748            faked_tx.send(()).unwrap();
749            call.resolve(json!("faked"));
750        });
751        channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
752        let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
753        channel.handle("seen", move |mut call| {
754            seen_tx.send(call.take_data()).unwrap();
755        });
756        let engine = start(
757            &channel,
758            "import { host } from 'nsh'; host.call('probe').then((v) => host.post('seen', v), (e) => host.post('seen', e.message));",
759        );
760        assert_eq!(
761            seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
762            json!("host.call(\"probe\"): the embedding app handles no \"probe\"")
763        );
764        assert!(faked_rx.try_recv().is_err());
765        drop(engine);
766    }
767
768    #[test]
769    fn recovered_events_keep_the_queue_limit_and_order() {
770        let channel = HostChannel::new();
771        let (tx, rx) = crossbeam_channel::unbounded();
772        let attachment = channel.attach(tx, rx);
773        let limit = nsh_core::host_channel::MAX_QUEUED_EVENTS;
774        for id in 0..limit + 2 {
775            channel.send("open", json!(id)).unwrap();
776        }
777        drop(attachment);
778        let mut inner = channel.lock();
779        let kept = inner.pending.take("open");
780        assert_eq!(kept.len(), limit);
781        assert_eq!(kept[0], json!(2));
782        assert_eq!(kept[limit - 1], json!(limit + 1));
783    }
784
785    #[test]
786    fn an_old_attachment_does_not_detach_its_replacement() {
787        let channel = HostChannel::new();
788        let (old_tx, old_rx) = crossbeam_channel::unbounded();
789        let old = channel.attach(old_tx, old_rx);
790        let (tx, rx) = crossbeam_channel::unbounded();
791        let current = channel.attach(tx, rx.clone());
792        drop(old);
793        channel.send("open", json!(1)).unwrap();
794        assert!(matches!(
795            rx.try_recv().unwrap(),
796            Message::HostEvent(name, data) if name == "open" && data == json!(1)
797        ));
798        drop(current);
799    }
800}