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