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