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