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//!
22//! A handler that answers over time (progress of a sign-in, a long
23//! request) sends its events to the app that made the call alone with the
24//! call's [`HostCall::sender`]: once that app stops or another takes the
25//! view, they go nowhere instead of to the next app, and
26//! [`HostSender::closed`] tells the handler to stop.
27
28use std::{
29    collections::HashMap,
30    future::Future,
31    pin::Pin,
32    sync::{
33        Arc, Mutex, MutexGuard,
34        atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
35    },
36    task::{Context, Poll, Waker},
37};
38
39use crossbeam_channel::{Receiver, Sender};
40#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
41use nsh_core::host_channel::HostBridge;
42use nsh_core::{
43    JsonValue,
44    host_channel::{HostError, HostInbox, HostRequest, ModuleFake, check_name},
45};
46
47use crate::Message;
48
49/// A handler of the app's calls and posts of one name.
50type Handler = Arc<dyn Fn(HostCall) + Send + Sync>;
51
52/// Runs `handler` with `call`; a handler that panics drops the call, which
53/// fails it in the app.
54fn run_handler(handler: &Handler, call: HostCall) {
55    let name = call.name.clone();
56    let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(call)));
57    if ran.is_err() {
58        log::error!("nsh/host: the embedding app's handler of \"{name}\" panicked");
59    }
60}
61
62/// Why [`HostChannel::start_request`] did not hand a request to a handler.
63pub(crate) enum HostRefusal {
64    /// The channel is not configured: the platform's host takes it.
65    Unconfigured(HostRequest),
66    /// No handler of the call's name: the call (its id) fails so.
67    NoHandler(u64, HostError),
68}
69
70/// The embedding app's handler of the URLs the app opens.
71type UrlHandler = Arc<dyn Fn(OpenUrlRequest) + Send + Sync>;
72
73/// The embedding app's side of the channel with the apps one of its views
74/// runs: launch parameters, events to the app (`host.on` in TSX), and
75/// handlers of the app's calls (`host.call`) and posts (`host.post`).
76///
77/// Cheap to clone (the clones are one channel); usable from any thread.
78/// One per view, shared by the apps it runs one after another.
79///
80/// ```
81/// use nsh_engine::{HostChannel, JsonValue};
82///
83/// let channel = HostChannel::new();
84/// // What the next app reads synchronously at start (`host.params`).
85/// let mut params = serde_json::Map::new();
86/// params.insert("conversation".into(), JsonValue::from("c-42"));
87/// channel.set_params(params);
88/// // `await host.call("profile", { id })` in the app.
89/// channel.handle("profile", |call| {
90///     let id = call.data()["id"].clone();
91///     call.resolve(serde_json::json!({ "id": id, "name": "Ada" }));
92/// });
93/// // `host.on("user.changed", ...)` in the app.
94/// channel.send("user.changed", serde_json::json!({ "id": 7 })).unwrap();
95/// ```
96#[derive(Clone, Default)]
97pub struct HostChannel {
98    inner: Arc<Mutex<Inner>>,
99    /// The app's calls handed to a handler and not yet answered, and
100    /// those answered.
101    calls: Arc<CallCount>,
102}
103
104/// A channel's count of the calls its handlers took ([`HostReply`]).
105#[derive(Default)]
106struct CallCount {
107    /// Taken and not yet answered.
108    in_flight: AtomicUsize,
109    /// Answered so far: counted before the call leaves `in_flight`, so a
110    /// reader that saw none in flight sees every answer that came.
111    answered: AtomicU64,
112}
113
114#[derive(Default)]
115struct Inner {
116    params: serde_json::Map<String, JsonValue>,
117    configured: bool,
118    handlers: HashMap<String, Handler>,
119    url_handler: Option<UrlHandler>,
120    /// The engine running the view's app: its attachment's id, and its
121    /// queue as the calls it makes see it ([`HostCall::sender`]).
122    engine: Option<(u64, Arc<Caller>)>,
123    next_engine: u64,
124    /// Events sent while no app ran, for the next one.
125    pending: HostInbox,
126    /// The stand-ins for native modules' exports: specifier, export (or
127    /// `Export.member`), stand-in.
128    module_fakes: Vec<(String, String, ModuleFake)>,
129    /// The handlers of the stand-ins' calls, apart from the embedding
130    /// app's: they configure nothing and `host.call` never reaches them.
131    fake_handlers: HashMap<String, Handler>,
132}
133
134impl std::fmt::Debug for HostChannel {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        let inner = self.lock();
137        let mut handlers: Vec<&String> = inner.handlers.keys().collect();
138        handlers.sort();
139        f.debug_struct("HostChannel")
140            .field("params", &inner.params)
141            .field("handlers", &handlers)
142            .field("configured", &inner.configured)
143            .field("url_handler", &inner.url_handler.is_some())
144            .field("attached", &inner.engine.is_some())
145            .field("pending", &inner.pending.len())
146            .finish()
147    }
148}
149
150impl HostChannel {
151    /// A channel with no parameters and no handlers.
152    pub fn new() -> Self {
153        Self::default()
154    }
155
156    fn lock(&self) -> MutexGuard<'_, Inner> {
157        self.inner.lock().unwrap_or_else(|e| e.into_inner())
158    }
159
160    /// How many of the apps' calls a handler has and has not answered yet.
161    /// A headless test driver waits for them before it ends a step: their
162    /// answer comes from another thread, in real time.
163    #[doc(hidden)]
164    pub fn calls_in_flight(&self) -> usize {
165        self.calls.in_flight.load(Ordering::SeqCst)
166    }
167
168    /// How many of the apps' calls a handler has answered so far. An
169    /// answer is on the engine's queue once counted, and may land after
170    /// the engine said it was idle: a headless test driver that read this
171    /// before asking, and finds no call in flight and this count changed,
172    /// asks again ([`HostChannel::calls_in_flight`] first, then this).
173    #[doc(hidden)]
174    pub fn calls_answered(&self) -> u64 {
175        self.calls.answered.load(Ordering::SeqCst)
176    }
177
178    /// The launch parameters of the apps started from now on
179    /// (`host.params`, read synchronously when they start; a running app
180    /// keeps the ones it started with). Later requests are events
181    /// ([`HostChannel::send`]).
182    ///
183    /// Parameters alone answer no call, so they leave the channel as it
184    /// was: until a handler ([`HostChannel::handle`]) or an event
185    /// configures it, the app's calls keep going to the platform's own
186    /// host, as on the web, where the page passes parameters and answers
187    /// calls with its player's host.
188    pub fn set_params(&self, params: serde_json::Map<String, JsonValue>) {
189        self.lock().params = params;
190    }
191
192    /// The launch parameters ([`HostChannel::set_params`]).
193    pub fn params(&self) -> serde_json::Map<String, JsonValue> {
194        self.lock().params.clone()
195    }
196
197    /// Sends event `name` with `data` to the running app (`host.on(name,
198    /// listener)`, Rust's `on_host_event`). The app keeps events of names
199    /// it does not listen to yet until it does; while no app runs, events
200    /// wait for the next one
201    /// (up to [`nsh_core::host_channel::MAX_QUEUED_EVENTS`] each, then the
202    /// oldest go). Any thread; it never waits for the app. `Err` for a name
203    /// that is empty or longer than
204    /// [`nsh_core::host_channel::MAX_NAME_LEN`] bytes.
205    pub fn send(&self, name: impl Into<String>, data: JsonValue) -> Result<(), String> {
206        let name = name.into();
207        check_name(&name)?;
208        let mut inner = self.lock();
209        inner.configured = true;
210        if let Some((_, engine)) = &inner.engine
211            && engine
212                .tx
213                .send(Message::HostEvent(name.clone(), data.clone()))
214                .is_ok()
215        {
216            return Ok(());
217        }
218        if let Some((dropped, _)) = inner.pending.push(name, data) {
219            log::warn!(
220                "nsh/host: no app ran to take the embedding app's events; the oldest (\"{dropped}\") was dropped"
221            );
222        }
223        Ok(())
224    }
225
226    /// Handles the app's calls (`host.call(name, data)`) and posts
227    /// (`host.post(name, data)`) of `name`, replacing the handler it had.
228    /// `handler` runs on the engine thread and must return quickly: it
229    /// answers a call with [`HostCall::resolve`] / [`HostCall::reject`] at
230    /// once, or moves the call to where its answer comes from and answers
231    /// there, from any thread. A post's answer goes nowhere. A call that
232    /// is dropped unanswered fails in the app.
233    pub fn handle(
234        &self,
235        name: impl Into<String>,
236        handler: impl Fn(HostCall) + Send + Sync + 'static,
237    ) {
238        let mut inner = self.lock();
239        inner.configured = true;
240        inner.handlers.insert(name.into(), Arc::new(handler));
241    }
242
243    /// Removes the handler of `name`: the app's calls of it fail at once
244    /// from now on, its posts are dropped.
245    pub fn remove_handler(&self, name: &str) {
246        self.lock().handlers.remove(name);
247    }
248
249    /// Puts `fake` in the place of export `path` of native module
250    /// `specifier` (`"Keychain"`, or a member of an export,
251    /// `"Keychain.get"`) in the apps started from now on, as `nsh test`'s
252    /// `open` does for the app a test opens: their imports of the module
253    /// get the stand-in. A [`ModuleFake::Call`] is answered by the
254    /// handler of its name [`HostChannel::handle_module_fake`] registers.
255    /// `nsh test`'s hook, not part of the embedding API.
256    #[doc(hidden)]
257    pub fn fake_module_export(
258        &self,
259        specifier: impl Into<String>,
260        path: impl Into<String>,
261        fake: ModuleFake,
262    ) {
263        self.lock()
264            .module_fakes
265            .push((specifier.into(), path.into(), fake));
266    }
267
268    /// Handles the calls of the stand-ins whose [`ModuleFake::Call`] is
269    /// `name`, as [`HostChannel::handle`] does the app's `host.call`s, but
270    /// apart from them: the app's `host.call` never reaches it, and the
271    /// channel stays as the embedding app configured it (`host.available()`).
272    /// `nsh test`'s hook, not part of the embedding API.
273    #[doc(hidden)]
274    pub fn handle_module_fake(
275        &self,
276        name: impl Into<String>,
277        handler: impl Fn(HostCall) + Send + Sync + 'static,
278    ) {
279        self.lock()
280            .fake_handlers
281            .insert(name.into(), Arc::new(handler));
282    }
283
284    #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
285    fn handler(&self, name: &str) -> Option<Handler> {
286        self.lock().handlers.get(name).cloned()
287    }
288
289    #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
290    fn fake_handler(&self, name: &str) -> Option<Handler> {
291        self.lock().fake_handlers.get(name).cloned()
292    }
293
294    /// Hands a call or post of the core (the app's Rust, or JS's without
295    /// a channel of its own) to the handler of its name, answered back to
296    /// the core through `tx` (`Message::CoreHostReply`). Without handlers
297    /// or events the channel is not configured: the request comes back for
298    /// the platform's host. A configured channel without a handler of the
299    /// name fails the call at once and drops the post, as it does JS's.
300    pub(crate) fn start_request(
301        &self,
302        request: HostRequest,
303        tx: &Sender<Message>,
304    ) -> Result<(), HostRefusal> {
305        let (handler, configured) = {
306            let inner = self.lock();
307            let name = match &request {
308                HostRequest::Call { name, .. } | HostRequest::Post { name, .. } => name,
309                _ => return Err(HostRefusal::Unconfigured(request)),
310            };
311            (inner.handlers.get(name).cloned(), inner.configured)
312        };
313        if !configured {
314            return Err(HostRefusal::Unconfigured(request));
315        }
316        match request {
317            HostRequest::Call { id, name, args } => {
318                let Some(handler) = handler else {
319                    return Err(HostRefusal::NoHandler(
320                        id,
321                        HostError::Failed(format!(
322                            "host.call(\"{name}\"): the embedding app handles no \"{name}\""
323                        )),
324                    ));
325                };
326                self.calls.in_flight.fetch_add(1, Ordering::SeqCst);
327                let reply = HostReply {
328                    id,
329                    name: name.clone(),
330                    tx: Some(tx.clone()),
331                    calls: Some(self.calls.clone()),
332                    to_core: true,
333                };
334                run_handler(
335                    &handler,
336                    HostCall {
337                        name,
338                        data: args,
339                        reply: Some(reply),
340                        caller: self.caller(tx),
341                    },
342                );
343            }
344            HostRequest::Post { name, args } => match handler {
345                Some(handler) => run_handler(
346                    &handler,
347                    HostCall {
348                        name,
349                        data: args,
350                        reply: None,
351                        caller: self.caller(tx),
352                    },
353                ),
354                None => log::debug!(
355                    "nsh/host: the embedding app handles no \"{name}\"; the post was dropped"
356                ),
357            },
358            _ => {}
359        }
360        Ok(())
361    }
362
363    /// Asks the engine to stop without interrupting JS, so its quit
364    /// listeners run ([`HostChannel::shutdown`] follows): events sent
365    /// meanwhile follow the shutdown message, kept for the next app.
366    #[cfg(not(target_arch = "wasm32"))]
367    pub(crate) fn request_shutdown(&self, tx: &Sender<Message>) {
368        let caller = {
369            let inner = self.lock();
370            let _ = tx.send(Message::Shutdown);
371            self.caller_locked(&inner, tx)
372        };
373        // The app is leaving: its calls' senders close.
374        if let Some(caller) = caller {
375            caller.close();
376        }
377    }
378
379    /// Events sent once JS is interrupted must follow the shutdown
380    /// message, so the attachment can recover them for the next app.
381    #[cfg(not(target_arch = "wasm32"))]
382    pub(crate) fn shutdown(&self, tx: &Sender<Message>, stop: &std::sync::atomic::AtomicBool) {
383        let caller = {
384            let inner = self.lock();
385            stop.store(true, std::sync::atomic::Ordering::Relaxed);
386            let _ = tx.send(Message::Shutdown);
387            self.caller_locked(&inner, tx)
388        };
389        if let Some(caller) = caller {
390            caller.close();
391        }
392    }
393
394    /// The attached engine as the calls of the engine whose queue is `tx`
395    /// see it: `None` (their senders closed) when another engine runs the
396    /// view, or none does.
397    fn caller(&self, tx: &Sender<Message>) -> Option<Arc<Caller>> {
398        self.caller_locked(&self.lock(), tx)
399    }
400
401    fn caller_locked(&self, inner: &Inner, tx: &Sender<Message>) -> Option<Arc<Caller>> {
402        inner
403            .engine
404            .as_ref()
405            .filter(|(_, engine)| engine.tx.same_channel(tx) && !engine.is_closed())
406            .map(|(_, engine)| engine.clone())
407    }
408
409    /// Takes the URLs the app opens (`openUrl` of `nsh/device`, a
410    /// `TextView`'s links) before the system does, replacing the handler
411    /// it had: a host routes them through its own router. The URL passed
412    /// the URL check and the app's `openUrl` capability
413    /// ([`nsh_core::open_url`]). `handler` runs on the engine thread and
414    /// must return quickly: it answers with [`OpenUrlRequest::handled`]
415    /// (the app's `openUrl` resolves `true`) or
416    /// [`OpenUrlRequest::decline`] (the system opens it), at once or from
417    /// any thread later. A request dropped unanswered is declined.
418    pub fn handle_open_url(&self, handler: impl Fn(OpenUrlRequest) + Send + Sync + 'static) {
419        self.lock().url_handler = Some(Arc::new(handler));
420    }
421
422    /// Removes the URL handler: the system opens the app's URLs from now
423    /// on.
424    pub fn remove_open_url_handler(&self) {
425        self.lock().url_handler = None;
426    }
427
428    /// Hands URL request `id` of the engine whose queue is `tx` to the
429    /// embedding app's URL handler; without one, `None`: the system opens
430    /// it.
431    pub(crate) fn open_url(&self, id: u32, url: String, tx: &Sender<Message>) -> Option<()> {
432        let handler = self.lock().url_handler.clone()?;
433        let request = OpenUrlRequest {
434            reply: Some(UrlReply {
435                id,
436                url: url.clone(),
437                tx: tx.clone(),
438            }),
439            url,
440        };
441        if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(request))).is_err() {
442            log::error!("nsh/device: the embedding app's URL handler panicked");
443        }
444        Some(())
445    }
446
447    /// Attaches the engine whose queue is `tx`: events go to it from now
448    /// on, those waiting first. Detached when the attachment drops (unless
449    /// another engine attached since).
450    pub(crate) fn attach(&self, tx: Sender<Message>, rx: Receiver<Message>) -> HostAttachment {
451        let (id, replaced) = {
452            let mut inner = self.lock();
453            inner.next_engine += 1;
454            let id = inner.next_engine;
455            for (name, data) in inner.pending.take_all() {
456                let _ = tx.send(Message::HostEvent(name, data));
457            }
458            let replaced = inner.engine.replace((id, Arc::new(Caller::new(tx))));
459            (id, replaced)
460        };
461        // The engine this one replaces no longer gets its calls' events.
462        if let Some((_, engine)) = replaced {
463            engine.close();
464        }
465        HostAttachment {
466            channel: self.clone(),
467            id,
468            rx,
469        }
470    }
471
472    /// The bridge an app's `nsh/host` reaches this channel through, from
473    /// the engine whose queue is `tx`: its parameters and module stand-ins
474    /// as they are now.
475    #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
476    pub(crate) fn bridge(&self, tx: Sender<Message>) -> EngineBridge {
477        let inner = self.lock();
478        EngineBridge {
479            params: JsonValue::Object(inner.params.clone()),
480            module_fakes: inner.module_fakes.clone(),
481            channel: self.clone(),
482            tx,
483        }
484    }
485}
486
487/// An engine's attachment to its view's channel ([`HostChannel::attach`]).
488pub(crate) struct HostAttachment {
489    channel: HostChannel,
490    id: u64,
491    /// Events behind a shutdown message still belong to this channel.
492    rx: Receiver<Message>,
493}
494
495impl Drop for HostAttachment {
496    fn drop(&mut self) {
497        let (discarded, engine) = {
498            let mut inner = self.channel.lock();
499            if !inner.engine.as_ref().is_some_and(|(id, _)| *id == self.id) {
500                return;
501            }
502            let engine = inner.engine.take();
503            // Detach and drain under the same lock as `send`: every event
504            // either waits here or is kept by `send` for the next app. The
505            // events of its calls' senders (`Message::CallerEvent`) were for
506            // this app alone: they go with the rest.
507            let mut messages: Vec<_> = self.rx.try_iter().collect();
508            for message in &mut messages {
509                if let Message::HostEvent(name, data) = message
510                    && let Some((dropped, _)) = inner
511                        .pending
512                        .push(std::mem::take(name), std::mem::take(data))
513                {
514                    log::warn!(
515                        "nsh/host: the app stopped; the oldest kept event (\"{dropped}\") was dropped"
516                    );
517                }
518            }
519            (messages, engine)
520        };
521        if let Some((_, engine)) = engine {
522            engine.close();
523        }
524        // Other messages can own closures whose destructors reach the
525        // channel. Release them without its lock held.
526        drop(discarded);
527    }
528}
529
530/// What an engine's `nsh/host` reaches of the channel
531/// ([`nsh_core::host_channel::HostBridge`]).
532#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
533pub(crate) struct EngineBridge {
534    params: JsonValue,
535    // A copy, so making a module's exports takes no lock.
536    module_fakes: Vec<(String, String, ModuleFake)>,
537    channel: HostChannel,
538    tx: Sender<Message>,
539}
540
541#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
542impl EngineBridge {
543    /// Runs `handler` with call `id` of `name`, answered back to this
544    /// engine.
545    fn start(&self, handler: &Handler, id: u64, name: &str, data: JsonValue) {
546        let calls = self.channel.calls.clone();
547        calls.in_flight.fetch_add(1, Ordering::SeqCst);
548        let call = HostCall {
549            name: name.to_owned(),
550            data,
551            reply: Some(HostReply {
552                id,
553                name: name.to_owned(),
554                tx: Some(self.tx.clone()),
555                calls: Some(calls),
556                to_core: false,
557            }),
558            caller: self.channel.caller(&self.tx),
559        };
560        run_handler(handler, call);
561    }
562}
563
564#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
565impl HostBridge for EngineBridge {
566    fn available(&self) -> bool {
567        self.channel.lock().configured
568    }
569
570    fn params(&self) -> JsonValue {
571        self.params.clone()
572    }
573
574    fn call(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
575        let Some(handler) = self.channel.handler(name) else {
576            return Err(format!(
577                "host.call(\"{name}\"): the embedding app handles no \"{name}\""
578            ));
579        };
580        self.start(&handler, id, name, data);
581        Ok(())
582    }
583
584    fn module_fakes(&self, specifier: &str) -> Vec<(String, ModuleFake)> {
585        self.module_fakes
586            .iter()
587            .filter(|(s, _, _)| s == specifier)
588            .map(|(_, path, fake)| (path.clone(), fake.clone()))
589            .collect()
590    }
591
592    fn call_module_fake(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
593        let Some(handler) = self.channel.fake_handler(name) else {
594            return Err(format!("no stand-in answers \"{name}\""));
595        };
596        self.start(&handler, id, name, data);
597        Ok(())
598    }
599
600    fn post(&self, name: &str, data: JsonValue) {
601        match self.channel.handler(name) {
602            Some(handler) => run_handler(
603                &handler,
604                HostCall {
605                    name: name.to_owned(),
606                    data,
607                    reply: None,
608                    caller: self.channel.caller(&self.tx),
609                },
610            ),
611            None => log::debug!(
612                "nsh/host: the embedding app handles no \"{name}\"; the post was dropped"
613            ),
614        }
615    }
616}
617
618/// A call (`host.call(name, data)`) or a post (`host.post(name, data)`) of
619/// the app, as the embedding app's handler gets it. A call is answered once,
620/// from any thread; dropped unanswered, it fails in the app.
621#[derive(Default)]
622#[non_exhaustive]
623pub struct HostCall {
624    name: String,
625    data: JsonValue,
626    reply: Option<HostReply>,
627    /// The engine that made it, while it ran the view when it did.
628    caller: Option<Arc<Caller>>,
629}
630
631impl std::fmt::Debug for HostCall {
632    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
633        f.debug_struct("HostCall")
634            .field("name", &self.name)
635            .field("data", &self.data)
636            .field("post", &self.is_post())
637            .finish()
638    }
639}
640
641impl HostCall {
642    /// Its name.
643    pub fn name(&self) -> &str {
644        &self.name
645    }
646
647    /// Its data (`null` when the app sent none).
648    pub fn data(&self) -> &JsonValue {
649        &self.data
650    }
651
652    /// Takes its data, leaving `null`.
653    pub fn take_data(&mut self) -> JsonValue {
654        std::mem::take(&mut self.data)
655    }
656
657    /// Whether it is a post, whose answer goes nowhere.
658    pub fn is_post(&self) -> bool {
659        self.reply.is_none()
660    }
661
662    /// Answers the call: the app's promise resolves with `value`.
663    pub fn resolve(self, value: JsonValue) {
664        self.reply(Ok(value));
665    }
666
667    /// Fails the call: the app's promise rejects with an `Error` of
668    /// `message`.
669    pub fn reject(self, message: impl Into<String>) {
670        self.reply(Err(message.into()));
671    }
672
673    /// Answers the call with `result` ([`HostCall::resolve`],
674    /// [`HostCall::reject`]).
675    pub fn reply(mut self, result: Result<JsonValue, String>) {
676        if let Some(reply) = self.reply.take() {
677            reply.reply(result);
678        }
679    }
680
681    /// The reply alone, to answer from elsewhere (`None` for a post).
682    pub fn into_reply(mut self) -> Option<HostReply> {
683        self.reply.take()
684    }
685
686    /// Sends events to the app that made this call or post alone, as
687    /// [`HostChannel::send`] does to the running app: for progress while a
688    /// handler answers over time. Once that app stops, or another app
689    /// takes the view (a reload), the sender closes: its events go nowhere
690    /// rather than to the next app, and [`HostSender::closed`] resolves so
691    /// the handler can stop its work. Take it before
692    /// [`HostCall::into_reply`]; it outlives the call.
693    pub fn sender(&self) -> HostSender {
694        HostSender {
695            caller: self.caller.clone(),
696        }
697    }
698}
699
700/// An engine's queue as the calls it makes see it: open while it runs the
701/// view ([`HostCall::sender`]).
702struct Caller {
703    tx: Sender<Message>,
704    closed: AtomicBool,
705    /// The [`HostSenderClosed`] futures waiting, by id, and the next id.
706    waiting: Mutex<(u64, HashMap<u64, Waker>)>,
707}
708
709impl Caller {
710    fn new(tx: Sender<Message>) -> Self {
711        Self {
712            tx,
713            closed: AtomicBool::new(false),
714            waiting: Mutex::default(),
715        }
716    }
717
718    fn is_closed(&self) -> bool {
719        self.closed.load(Ordering::SeqCst)
720    }
721
722    fn waiting(&self) -> MutexGuard<'_, (u64, HashMap<u64, Waker>)> {
723        self.waiting.lock().unwrap_or_else(|e| e.into_inner())
724    }
725
726    /// Closes the senders of its calls and wakes those waiting on it, once.
727    fn close(&self) {
728        if self.closed.swap(true, Ordering::SeqCst) {
729            return;
730        }
731        let wakers = std::mem::take(&mut self.waiting().1);
732        for (_, waker) in wakers {
733            waker.wake();
734        }
735    }
736}
737
738/// Sends events to the app that made one call or post
739/// ([`HostCall::sender`]). Cheap to clone; usable from any thread.
740#[derive(Clone, Default)]
741pub struct HostSender {
742    /// `None` when the app had already stopped or been replaced when it
743    /// made the call (and for a [`HostCall`] made by hand).
744    caller: Option<Arc<Caller>>,
745}
746
747impl std::fmt::Debug for HostSender {
748    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
749        f.debug_struct("HostSender")
750            .field("closed", &self.is_closed())
751            .finish()
752    }
753}
754
755impl HostSender {
756    /// Sends event `name` with `data` to the app that made the call
757    /// (`host.on(name, listener)`, as [`HostChannel::send`]). `Ok(false)`
758    /// once that app stopped or another took the view: the event is
759    /// dropped, never kept for the next app. `Ok(true)` puts it on the
760    /// app's queue; an app that stops before it reads the event drops it.
761    /// `Err` for a name that is empty or longer than
762    /// [`nsh_core::host_channel::MAX_NAME_LEN`] bytes.
763    pub fn send(&self, name: impl Into<String>, data: JsonValue) -> Result<bool, String> {
764        let name = name.into();
765        check_name(&name)?;
766        let Some(caller) = self.caller.as_ref().filter(|c| !c.is_closed()) else {
767            return Ok(false);
768        };
769        Ok(caller.tx.send(Message::CallerEvent(name, data)).is_ok())
770    }
771
772    /// Whether the app that made the call stopped or was replaced: its
773    /// events go nowhere from now on.
774    pub fn is_closed(&self) -> bool {
775        self.caller.as_ref().is_none_or(|c| c.is_closed())
776    }
777
778    /// Resolves once the app that made the call stops or another app takes
779    /// the view (at once if it already has). Any executor.
780    pub fn closed(&self) -> HostSenderClosed {
781        HostSenderClosed {
782            caller: self.caller.clone(),
783            id: None,
784        }
785    }
786}
787
788/// The future of [`HostSender::closed`].
789#[must_use = "futures do nothing unless polled"]
790pub struct HostSenderClosed {
791    caller: Option<Arc<Caller>>,
792    /// Its place among the caller's wakers, once it waited.
793    id: Option<u64>,
794}
795
796impl std::fmt::Debug for HostSenderClosed {
797    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
798        f.debug_struct("HostSenderClosed").finish_non_exhaustive()
799    }
800}
801
802impl Future for HostSenderClosed {
803    type Output = ();
804
805    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
806        let this = self.get_mut();
807        let Some(caller) = &this.caller else {
808            return Poll::Ready(());
809        };
810        if caller.is_closed() {
811            return Poll::Ready(());
812        }
813        {
814            let mut waiting = caller.waiting();
815            let id = *this.id.get_or_insert_with(|| {
816                waiting.0 += 1;
817                waiting.0
818            });
819            waiting.1.insert(id, cx.waker().clone());
820        }
821        // `close` sets the flag before it takes the wakers: one that ran
822        // meanwhile is seen here.
823        if caller.is_closed() {
824            return Poll::Ready(());
825        }
826        Poll::Pending
827    }
828}
829
830impl Drop for HostSenderClosed {
831    fn drop(&mut self) {
832        if let (Some(caller), Some(id)) = (&self.caller, self.id) {
833            caller.waiting().1.remove(&id);
834        }
835    }
836}
837
838/// A URL the app opens (`openUrl` of `nsh/device`), as the embedding app's
839/// URL handler gets it ([`HostChannel::handle_open_url`]). Answered once,
840/// from any thread: [`OpenUrlRequest::handled`] when the embedding app
841/// took it, [`OpenUrlRequest::decline`] for the system to open it (also
842/// what dropping it unanswered does).
843#[derive(Default)]
844#[non_exhaustive]
845pub struct OpenUrlRequest {
846    url: String,
847    reply: Option<UrlReply>,
848}
849
850/// Where an [`OpenUrlRequest`]'s answer goes.
851struct UrlReply {
852    id: u32,
853    url: String,
854    tx: Sender<Message>,
855}
856
857impl std::fmt::Debug for OpenUrlRequest {
858    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
859        f.debug_struct("OpenUrlRequest")
860            .field("url", &self.url)
861            .finish()
862    }
863}
864
865impl OpenUrlRequest {
866    /// The URL: absolute, of a scheme that opens another app
867    /// ([`nsh_core::open_url::check_url`]).
868    pub fn url(&self) -> &str {
869        &self.url
870    }
871
872    /// The embedding app took the URL (routed it its own way): the app's
873    /// `openUrl` resolves `true` and the system does not open it.
874    pub fn handled(self) {
875        self.answer(true);
876    }
877
878    /// The embedding app leaves the URL to the system, which opens it.
879    pub fn decline(self) {
880        self.answer(false);
881    }
882
883    /// [`OpenUrlRequest::handled`] when `handled`, else
884    /// [`OpenUrlRequest::decline`].
885    pub fn answer(mut self, handled: bool) {
886        if let Some(reply) = self.reply.take() {
887            let _ = reply.tx.send(Message::UrlHandled {
888                id: reply.id,
889                url: reply.url,
890                handled,
891            });
892        }
893    }
894}
895
896impl Drop for OpenUrlRequest {
897    fn drop(&mut self) {
898        if let Some(reply) = self.reply.take() {
899            let _ = reply.tx.send(Message::UrlHandled {
900                id: reply.id,
901                url: reply.url,
902                handled: false,
903            });
904        }
905    }
906}
907
908/// How a call is answered (a [`HostCall`]'s): once, from any thread.
909/// Dropped unanswered, the call fails in the app.
910#[derive(Default)]
911#[non_exhaustive]
912pub struct HostReply {
913    id: u64,
914    name: String,
915    /// The queue of the engine that made the call; `None` once answered.
916    tx: Option<Sender<Message>>,
917    /// Its channel's count of calls, until answered.
918    calls: Option<Arc<CallCount>>,
919    /// The core made the call (`Message::CoreHostReply`), not JS's channel
920    /// (`Message::HostReply`).
921    to_core: bool,
922}
923
924impl std::fmt::Debug for HostReply {
925    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
926        f.debug_struct("HostReply")
927            .field("name", &self.name)
928            .finish()
929    }
930}
931
932impl HostReply {
933    /// The app's promise resolves with `value`.
934    pub fn resolve(self, value: JsonValue) {
935        self.reply(Ok(value));
936    }
937
938    /// The app's promise rejects with an `Error` of `message`.
939    pub fn reject(self, message: impl Into<String>) {
940        self.reply(Err(message.into()));
941    }
942
943    /// Answers with `result`. An app that stopped meanwhile drops it.
944    pub fn reply(mut self, result: Result<JsonValue, String>) {
945        self.send(result);
946        self.answered();
947    }
948
949    /// Puts `result` on the queue of the engine that made the call, once.
950    fn send(&mut self, result: Result<JsonValue, String>) {
951        if let Some(tx) = self.tx.take() {
952            let _ = tx.send(if self.to_core {
953                Message::CoreHostReply(self.id, result)
954            } else {
955                Message::HostReply(self.id, result)
956            });
957        }
958    }
959
960    /// Counts the call answered, once its answer is on the engine's queue.
961    fn answered(&mut self) {
962        if let Some(calls) = self.calls.take() {
963            calls.answered.fetch_add(1, Ordering::SeqCst);
964            calls.in_flight.fetch_sub(1, Ordering::SeqCst);
965        }
966    }
967}
968
969impl Drop for HostReply {
970    fn drop(&mut self) {
971        if self.tx.is_some() {
972            let message = format!(
973                "host.call(\"{}\"): the embedding app did not answer",
974                self.name
975            );
976            self.send(Err(message));
977        }
978        self.answered();
979    }
980}
981
982#[cfg(all(test, feature = "js-core", not(target_arch = "wasm32")))]
983mod tests {
984    use std::time::Duration;
985
986    use nsh_core::{ApproxTextEngine, MountBatch};
987    use serde_json::json;
988
989    use super::*;
990    use crate::{Bundle, Engine, EngineConfig, MountSink};
991
992    struct Sink;
993
994    impl MountSink for Sink {
995        fn submit(&self, _: MountBatch) {}
996    }
997
998    #[test]
999    fn events_sent_while_the_engine_stops_reach_the_next_app() {
1000        let channel = HostChannel::new();
1001        let (entered_tx, entered_rx) = crossbeam_channel::bounded(1);
1002        let (release_tx, release_rx) = crossbeam_channel::bounded(1);
1003        channel.handle("hold", move |_| {
1004            entered_tx.send(()).unwrap();
1005            release_rx.recv_timeout(Duration::from_secs(5)).unwrap();
1006        });
1007        let mut config = EngineConfig::new(Bundle::source(
1008            "import { host } from 'nsh'; host.post('hold');".to_owned(),
1009        ));
1010        if let crate::App::Js(bundle) = &mut config.app {
1011            bundle.policy.declared =
1012                Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
1013        }
1014        config.host = channel.clone();
1015        let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
1016        entered_rx.recv_timeout(Duration::from_secs(5)).unwrap();
1017        // Hold the engine while the platform drops it, as a reload does
1018        // while the old app is still finishing a callback.
1019        let stop = engine.stop.clone();
1020        let dropping = std::thread::spawn(move || drop(engine));
1021        let deadline = std::time::Instant::now() + Duration::from_secs(5);
1022        while !stop.load(std::sync::atomic::Ordering::Relaxed) {
1023            assert!(
1024                std::time::Instant::now() < deadline,
1025                "shutdown did not start"
1026            );
1027            std::thread::yield_now();
1028        }
1029        for id in 1..=3 {
1030            channel.send("open", json!(id)).unwrap();
1031        }
1032        release_tx.send(()).unwrap();
1033        dropping.join().unwrap();
1034
1035        let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
1036        channel.handle("seen", move |mut call| {
1037            seen_tx.send(call.take_data()).unwrap();
1038        });
1039        let mut config = EngineConfig::new(Bundle::source(
1040            "import { host } from 'nsh'; host.on('open', data => host.post('seen', data));"
1041                .to_owned(),
1042        ));
1043        if let crate::App::Js(bundle) = &mut config.app {
1044            bundle.policy.declared =
1045                Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
1046        }
1047        config.host = channel;
1048        let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
1049        for id in 1..=3 {
1050            assert_eq!(
1051                seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
1052                json!(id)
1053            );
1054        }
1055        assert!(seen_rx.try_recv().is_err());
1056        drop(engine);
1057    }
1058
1059    fn start(channel: &HostChannel, source: &str) -> Engine {
1060        let mut config = EngineConfig::new(Bundle::source(source.to_owned()));
1061        if let crate::App::Js(bundle) = &mut config.app {
1062            bundle.policy.declared =
1063                Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
1064        }
1065        config.host = channel.clone();
1066        Engine::start(config, || ApproxTextEngine, Sink).unwrap()
1067    }
1068
1069    #[test]
1070    fn a_stand_in_leaves_the_app_without_an_embedding_app() {
1071        let channel = HostChannel::new();
1072        let (tx, rx) = crossbeam_channel::unbounded();
1073        channel.handle_module_fake("probe", move |mut call| {
1074            tx.send(call.take_data()).unwrap();
1075            call.resolve(JsonValue::Null);
1076        });
1077        channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
1078        let engine = start(
1079            &channel,
1080            "import { host, Image } from 'nsh'; Image.prefetch(host.available());",
1081        );
1082        assert_eq!(
1083            rx.recv_timeout(Duration::from_secs(5)).unwrap(),
1084            json!([false])
1085        );
1086        drop(engine);
1087    }
1088
1089    #[test]
1090    fn the_app_s_calls_never_reach_a_stand_in() {
1091        let channel = HostChannel::new();
1092        let (faked_tx, faked_rx) = crossbeam_channel::unbounded();
1093        channel.handle_module_fake("probe", move |call| {
1094            faked_tx.send(()).unwrap();
1095            call.resolve(json!("faked"));
1096        });
1097        channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
1098        let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
1099        channel.handle("seen", move |mut call| {
1100            seen_tx.send(call.take_data()).unwrap();
1101        });
1102        let engine = start(
1103            &channel,
1104            "import { host } from 'nsh'; host.call('probe').then((v) => host.post('seen', v), (e) => host.post('seen', e.message));",
1105        );
1106        assert_eq!(
1107            seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
1108            json!("host.call(\"probe\"): the embedding app handles no \"probe\"")
1109        );
1110        assert!(faked_rx.try_recv().is_err());
1111        drop(engine);
1112    }
1113
1114    #[test]
1115    fn recovered_events_keep_the_queue_limit_and_order() {
1116        let channel = HostChannel::new();
1117        let (tx, rx) = crossbeam_channel::unbounded();
1118        let attachment = channel.attach(tx, rx);
1119        let limit = nsh_core::host_channel::MAX_QUEUED_EVENTS;
1120        for id in 0..limit + 2 {
1121            channel.send("open", json!(id)).unwrap();
1122        }
1123        drop(attachment);
1124        let mut inner = channel.lock();
1125        let kept = inner.pending.take("open");
1126        assert_eq!(kept.len(), limit);
1127        assert_eq!(kept[0], json!(2));
1128        assert_eq!(kept[limit - 1], json!(limit + 1));
1129    }
1130
1131    /// A call or post made by the engine whose queue is `tx`.
1132    fn call_from(channel: &HostChannel, tx: &Sender<Message>) -> HostCall {
1133        HostCall {
1134            name: "progress".into(),
1135            caller: channel.caller(tx),
1136            ..HostCall::default()
1137        }
1138    }
1139
1140    #[test]
1141    fn a_caller_s_events_reach_it_alone() {
1142        let channel = HostChannel::new();
1143        let (old_tx, old_rx) = crossbeam_channel::unbounded();
1144        let old = channel.attach(old_tx.clone(), old_rx.clone());
1145        let sender = call_from(&channel, &old_tx).sender();
1146        assert!(!sender.is_closed());
1147        assert_eq!(sender.send("progress", json!(1)), Ok(true));
1148        assert!(matches!(
1149            old_rx.try_recv().unwrap(),
1150            Message::CallerEvent(name, data) if name == "progress" && data == json!(1)
1151        ));
1152        assert!(sender.send("", json!(1)).is_err());
1153
1154        // A reload: another engine takes the view before the old one drops.
1155        let (tx, rx) = crossbeam_channel::unbounded();
1156        let current = channel.attach(tx.clone(), rx.clone());
1157        assert!(sender.is_closed());
1158        assert_eq!(sender.send("progress", json!(2)), Ok(false));
1159        assert!(old_rx.try_recv().is_err());
1160        assert!(rx.try_recv().is_err());
1161        // The replaced engine's later calls are closed from the start.
1162        assert!(call_from(&channel, &old_tx).sender().is_closed());
1163        drop(old);
1164        assert!(!call_from(&channel, &tx).sender().is_closed());
1165        drop(current);
1166    }
1167
1168    #[test]
1169    fn a_caller_s_events_are_not_kept_for_the_next_app() {
1170        let channel = HostChannel::new();
1171        let (tx, rx) = crossbeam_channel::unbounded();
1172        let attachment = channel.attach(tx.clone(), rx);
1173        let sender = call_from(&channel, &tx).sender();
1174        assert_eq!(sender.send("progress", json!(1)), Ok(true));
1175        channel.send("open", json!(1)).unwrap();
1176        // The engine stops before it reads them.
1177        drop(attachment);
1178        assert!(sender.is_closed());
1179        assert_eq!(sender.send("progress", json!(2)), Ok(false));
1180        let mut inner = channel.lock();
1181        assert!(inner.pending.take("progress").is_empty());
1182        assert_eq!(inner.pending.take("open"), vec![json!(1)]);
1183    }
1184
1185    #[test]
1186    fn a_call_made_while_detached_has_a_closed_sender() {
1187        let channel = HostChannel::new();
1188        let (tx, _rx) = crossbeam_channel::unbounded();
1189        let sender = call_from(&channel, &tx).sender();
1190        assert!(sender.is_closed());
1191        assert_eq!(sender.send("progress", json!(1)), Ok(false));
1192        assert!(HostCall::default().sender().is_closed());
1193        block_on(HostCall::default().sender().closed());
1194    }
1195
1196    /// Runs `future` to completion on this thread.
1197    fn block_on<F: Future>(future: F) -> F::Output {
1198        struct Unpark(std::thread::Thread);
1199        impl std::task::Wake for Unpark {
1200            fn wake(self: Arc<Self>) {
1201                self.0.unpark();
1202            }
1203        }
1204        let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
1205        let mut cx = Context::from_waker(&waker);
1206        let mut future = std::pin::pin!(future);
1207        loop {
1208            if let Poll::Ready(output) = future.as_mut().poll(&mut cx) {
1209                return output;
1210            }
1211            std::thread::park_timeout(Duration::from_secs(5));
1212        }
1213    }
1214
1215    #[test]
1216    fn closed_resolves_when_the_caller_detaches() {
1217        let channel = HostChannel::new();
1218        let (tx, rx) = crossbeam_channel::unbounded();
1219        let attachment = channel.attach(tx.clone(), rx);
1220        let sender = call_from(&channel, &tx).sender();
1221        // A future dropped while it waits leaves no waker behind.
1222        {
1223            let mut closed = std::pin::pin!(sender.closed());
1224            let waker = Waker::noop();
1225            assert!(
1226                closed
1227                    .as_mut()
1228                    .poll(&mut Context::from_waker(waker))
1229                    .is_pending()
1230            );
1231        }
1232        assert!(sender.caller.as_ref().unwrap().waiting().1.is_empty());
1233        let waiting = std::thread::spawn({
1234            let sender = sender.clone();
1235            move || block_on(sender.closed())
1236        });
1237        std::thread::sleep(Duration::from_millis(50));
1238        assert!(!waiting.is_finished());
1239        drop(attachment);
1240        waiting.join().unwrap();
1241        block_on(sender.closed());
1242    }
1243
1244    #[test]
1245    fn a_stopped_app_s_handler_sees_its_sender_closed() {
1246        let channel = HostChannel::new();
1247        let (sender_tx, sender_rx) = crossbeam_channel::unbounded();
1248        channel.handle("progress", move |call| {
1249            sender_tx.send(call.sender()).unwrap();
1250            call.resolve(JsonValue::Null);
1251        });
1252        let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
1253        channel.handle("seen", move |mut call| {
1254            seen_tx.send(call.take_data()).unwrap();
1255        });
1256        let engine = start(
1257            &channel,
1258            "import { host } from 'nsh'; host.on('progress', data => host.post('seen', data)); host.call('progress');",
1259        );
1260        let sender = sender_rx.recv_timeout(Duration::from_secs(5)).unwrap();
1261        assert_eq!(sender.send("progress", json!(1)), Ok(true));
1262        assert_eq!(
1263            seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
1264            json!(1)
1265        );
1266        drop(engine);
1267        assert!(sender.is_closed());
1268        assert_eq!(sender.send("progress", json!(2)), Ok(false));
1269
1270        // The next app gets nothing of the old app's call.
1271        let engine = start(
1272            &channel,
1273            "import { host } from 'nsh'; host.on('progress', data => host.post('seen', data));",
1274        );
1275        channel.send("progress", json!("next")).unwrap();
1276        assert_eq!(
1277            seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
1278            json!("next")
1279        );
1280        assert!(seen_rx.try_recv().is_err());
1281        drop(engine);
1282    }
1283
1284    #[test]
1285    fn an_old_attachment_does_not_detach_its_replacement() {
1286        let channel = HostChannel::new();
1287        let (old_tx, old_rx) = crossbeam_channel::unbounded();
1288        let old = channel.attach(old_tx, old_rx);
1289        let (tx, rx) = crossbeam_channel::unbounded();
1290        let current = channel.attach(tx, rx.clone());
1291        drop(old);
1292        channel.send("open", json!(1)).unwrap();
1293        assert!(matches!(
1294            rx.try_recv().unwrap(),
1295            Message::HostEvent(name, data) if name == "open" && data == json!(1)
1296        ));
1297        drop(current);
1298    }
1299}