1use std::{
23 collections::HashMap,
24 sync::{Arc, Mutex, MutexGuard},
25};
26
27use crossbeam_channel::{Receiver, Sender};
28#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
29use nsh_core::host_channel::HostBridge;
30use nsh_core::{
31 JsonValue,
32 host_channel::{HostInbox, ModuleFake, check_name},
33};
34
35use crate::Message;
36
37type Handler = Arc<dyn Fn(HostCall) + Send + Sync>;
39
40type UrlHandler = Arc<dyn Fn(OpenUrlRequest) + Send + Sync>;
42
43#[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 engine: Option<(u64, Sender<Message>)>,
79 next_engine: u64,
80 pending: HostInbox,
82 module_fakes: Vec<(String, String, ModuleFake)>,
85 fake_handlers: HashMap<String, Handler>,
88}
89
90impl std::fmt::Debug for HostChannel {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 let inner = self.lock();
93 let mut handlers: Vec<&String> = inner.handlers.keys().collect();
94 handlers.sort();
95 f.debug_struct("HostChannel")
96 .field("params", &inner.params)
97 .field("handlers", &handlers)
98 .field("configured", &inner.configured)
99 .field("url_handler", &inner.url_handler.is_some())
100 .field("attached", &inner.engine.is_some())
101 .field("pending", &inner.pending.len())
102 .finish()
103 }
104}
105
106impl HostChannel {
107 pub fn new() -> Self {
109 Self::default()
110 }
111
112 fn lock(&self) -> MutexGuard<'_, Inner> {
113 self.inner.lock().unwrap_or_else(|e| e.into_inner())
114 }
115
116 pub fn set_params(&self, params: serde_json::Map<String, JsonValue>) {
127 self.lock().params = params;
128 }
129
130 pub fn params(&self) -> serde_json::Map<String, JsonValue> {
132 self.lock().params.clone()
133 }
134
135 pub fn send(&self, name: impl Into<String>, data: JsonValue) -> Result<(), String> {
143 let name = name.into();
144 check_name(&name)?;
145 let mut inner = self.lock();
146 inner.configured = true;
147 if let Some((_, tx)) = &inner.engine
148 && tx
149 .send(Message::HostEvent(name.clone(), data.clone()))
150 .is_ok()
151 {
152 return Ok(());
153 }
154 if let Some((dropped, _)) = inner.pending.push(name, data) {
155 log::warn!(
156 "nsh/host: no app ran to take the embedding app's events; the oldest (\"{dropped}\") was dropped"
157 );
158 }
159 Ok(())
160 }
161
162 pub fn handle(
170 &self,
171 name: impl Into<String>,
172 handler: impl Fn(HostCall) + Send + Sync + 'static,
173 ) {
174 let mut inner = self.lock();
175 inner.configured = true;
176 inner.handlers.insert(name.into(), Arc::new(handler));
177 }
178
179 pub fn remove_handler(&self, name: &str) {
182 self.lock().handlers.remove(name);
183 }
184
185 #[doc(hidden)]
193 pub fn fake_module_export(
194 &self,
195 specifier: impl Into<String>,
196 path: impl Into<String>,
197 fake: ModuleFake,
198 ) {
199 self.lock()
200 .module_fakes
201 .push((specifier.into(), path.into(), fake));
202 }
203
204 #[doc(hidden)]
210 pub fn handle_module_fake(
211 &self,
212 name: impl Into<String>,
213 handler: impl Fn(HostCall) + Send + Sync + 'static,
214 ) {
215 self.lock()
216 .fake_handlers
217 .insert(name.into(), Arc::new(handler));
218 }
219
220 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
221 fn handler(&self, name: &str) -> Option<Handler> {
222 self.lock().handlers.get(name).cloned()
223 }
224
225 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
226 fn fake_handler(&self, name: &str) -> Option<Handler> {
227 self.lock().fake_handlers.get(name).cloned()
228 }
229
230 #[cfg(not(target_arch = "wasm32"))]
234 pub(crate) fn request_shutdown(&self, tx: &Sender<Message>) {
235 let _inner = self.lock();
236 let _ = tx.send(Message::Shutdown);
237 }
238
239 #[cfg(not(target_arch = "wasm32"))]
242 pub(crate) fn shutdown(&self, tx: &Sender<Message>, stop: &std::sync::atomic::AtomicBool) {
243 let _inner = self.lock();
244 stop.store(true, std::sync::atomic::Ordering::Relaxed);
245 let _ = tx.send(Message::Shutdown);
246 }
247
248 pub fn handle_open_url(&self, handler: impl Fn(OpenUrlRequest) + Send + Sync + 'static) {
258 self.lock().url_handler = Some(Arc::new(handler));
259 }
260
261 pub fn remove_open_url_handler(&self) {
264 self.lock().url_handler = None;
265 }
266
267 pub(crate) fn open_url(&self, id: u32, url: String, tx: &Sender<Message>) -> Option<()> {
271 let handler = self.lock().url_handler.clone()?;
272 let request = OpenUrlRequest {
273 reply: Some(UrlReply {
274 id,
275 url: url.clone(),
276 tx: tx.clone(),
277 }),
278 url,
279 };
280 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(request))).is_err() {
281 log::error!("nsh/device: the embedding app's URL handler panicked");
282 }
283 Some(())
284 }
285
286 pub(crate) fn attach(&self, tx: Sender<Message>, rx: Receiver<Message>) -> HostAttachment {
290 let mut inner = self.lock();
291 inner.next_engine += 1;
292 let id = inner.next_engine;
293 for (name, data) in inner.pending.take_all() {
294 let _ = tx.send(Message::HostEvent(name, data));
295 }
296 inner.engine = Some((id, tx));
297 HostAttachment {
298 channel: self.clone(),
299 id,
300 rx,
301 }
302 }
303
304 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
308 pub(crate) fn bridge(&self, tx: Sender<Message>) -> EngineBridge {
309 let inner = self.lock();
310 EngineBridge {
311 params: JsonValue::Object(inner.params.clone()),
312 module_fakes: inner.module_fakes.clone(),
313 channel: self.clone(),
314 tx,
315 }
316 }
317}
318
319pub(crate) struct HostAttachment {
321 channel: HostChannel,
322 id: u64,
323 rx: Receiver<Message>,
325}
326
327impl Drop for HostAttachment {
328 fn drop(&mut self) {
329 let discarded = {
330 let mut inner = self.channel.lock();
331 if !inner.engine.as_ref().is_some_and(|(id, _)| *id == self.id) {
332 return;
333 }
334 inner.engine = None;
335 let mut messages: Vec<_> = self.rx.try_iter().collect();
338 for message in &mut messages {
339 if let Message::HostEvent(name, data) = message
340 && let Some((dropped, _)) = inner
341 .pending
342 .push(std::mem::take(name), std::mem::take(data))
343 {
344 log::warn!(
345 "nsh/host: the app stopped; the oldest kept event (\"{dropped}\") was dropped"
346 );
347 }
348 }
349 messages
350 };
351 drop(discarded);
354 }
355}
356
357#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
360pub(crate) struct EngineBridge {
361 params: JsonValue,
362 module_fakes: Vec<(String, String, ModuleFake)>,
364 channel: HostChannel,
365 tx: Sender<Message>,
366}
367
368#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
369impl EngineBridge {
370 fn run(handler: &Handler, call: HostCall) {
373 let name = call.name.clone();
374 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(call)));
375 if ran.is_err() {
376 log::error!("nsh/host: the embedding app's handler of \"{name}\" panicked");
377 }
378 }
379
380 fn start(&self, handler: &Handler, id: u64, name: &str, data: JsonValue) {
383 let call = HostCall {
384 name: name.to_owned(),
385 data,
386 reply: Some(HostReply {
387 id,
388 name: name.to_owned(),
389 tx: Some(self.tx.clone()),
390 }),
391 };
392 Self::run(handler, call);
393 }
394}
395
396#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
397impl HostBridge for EngineBridge {
398 fn available(&self) -> bool {
399 self.channel.lock().configured
400 }
401
402 fn params(&self) -> JsonValue {
403 self.params.clone()
404 }
405
406 fn call(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
407 let Some(handler) = self.channel.handler(name) else {
408 return Err(format!(
409 "host.call(\"{name}\"): the embedding app handles no \"{name}\""
410 ));
411 };
412 self.start(&handler, id, name, data);
413 Ok(())
414 }
415
416 fn module_fakes(&self, specifier: &str) -> Vec<(String, ModuleFake)> {
417 self.module_fakes
418 .iter()
419 .filter(|(s, _, _)| s == specifier)
420 .map(|(_, path, fake)| (path.clone(), fake.clone()))
421 .collect()
422 }
423
424 fn call_module_fake(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
425 let Some(handler) = self.channel.fake_handler(name) else {
426 return Err(format!("no stand-in answers \"{name}\""));
427 };
428 self.start(&handler, id, name, data);
429 Ok(())
430 }
431
432 fn post(&self, name: &str, data: JsonValue) {
433 match self.channel.handler(name) {
434 Some(handler) => Self::run(
435 &handler,
436 HostCall {
437 name: name.to_owned(),
438 data,
439 reply: None,
440 },
441 ),
442 None => log::debug!(
443 "nsh/host: the embedding app handles no \"{name}\"; the post was dropped"
444 ),
445 }
446 }
447}
448
449#[derive(Default)]
453#[non_exhaustive]
454pub struct HostCall {
455 name: String,
456 data: JsonValue,
457 reply: Option<HostReply>,
458}
459
460impl std::fmt::Debug for HostCall {
461 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462 f.debug_struct("HostCall")
463 .field("name", &self.name)
464 .field("data", &self.data)
465 .field("post", &self.is_post())
466 .finish()
467 }
468}
469
470impl HostCall {
471 pub fn name(&self) -> &str {
473 &self.name
474 }
475
476 pub fn data(&self) -> &JsonValue {
478 &self.data
479 }
480
481 pub fn take_data(&mut self) -> JsonValue {
483 std::mem::take(&mut self.data)
484 }
485
486 pub fn is_post(&self) -> bool {
488 self.reply.is_none()
489 }
490
491 pub fn resolve(self, value: JsonValue) {
493 self.reply(Ok(value));
494 }
495
496 pub fn reject(self, message: impl Into<String>) {
499 self.reply(Err(message.into()));
500 }
501
502 pub fn reply(mut self, result: Result<JsonValue, String>) {
505 if let Some(reply) = self.reply.take() {
506 reply.reply(result);
507 }
508 }
509
510 pub fn into_reply(mut self) -> Option<HostReply> {
512 self.reply.take()
513 }
514}
515
516#[derive(Default)]
522#[non_exhaustive]
523pub struct OpenUrlRequest {
524 url: String,
525 reply: Option<UrlReply>,
526}
527
528struct UrlReply {
530 id: u32,
531 url: String,
532 tx: Sender<Message>,
533}
534
535impl std::fmt::Debug for OpenUrlRequest {
536 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537 f.debug_struct("OpenUrlRequest")
538 .field("url", &self.url)
539 .finish()
540 }
541}
542
543impl OpenUrlRequest {
544 pub fn url(&self) -> &str {
547 &self.url
548 }
549
550 pub fn handled(self) {
553 self.answer(true);
554 }
555
556 pub fn decline(self) {
558 self.answer(false);
559 }
560
561 pub fn answer(mut self, handled: bool) {
564 if let Some(reply) = self.reply.take() {
565 let _ = reply.tx.send(Message::UrlHandled {
566 id: reply.id,
567 url: reply.url,
568 handled,
569 });
570 }
571 }
572}
573
574impl Drop for OpenUrlRequest {
575 fn drop(&mut self) {
576 if let Some(reply) = self.reply.take() {
577 let _ = reply.tx.send(Message::UrlHandled {
578 id: reply.id,
579 url: reply.url,
580 handled: false,
581 });
582 }
583 }
584}
585
586#[derive(Default)]
589#[non_exhaustive]
590pub struct HostReply {
591 id: u64,
592 name: String,
593 tx: Option<Sender<Message>>,
595}
596
597impl std::fmt::Debug for HostReply {
598 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
599 f.debug_struct("HostReply")
600 .field("name", &self.name)
601 .finish()
602 }
603}
604
605impl HostReply {
606 pub fn resolve(self, value: JsonValue) {
608 self.reply(Ok(value));
609 }
610
611 pub fn reject(self, message: impl Into<String>) {
613 self.reply(Err(message.into()));
614 }
615
616 pub fn reply(mut self, result: Result<JsonValue, String>) {
618 if let Some(tx) = self.tx.take() {
619 let _ = tx.send(Message::HostReply(self.id, result));
620 }
621 }
622}
623
624impl Drop for HostReply {
625 fn drop(&mut self) {
626 if let Some(tx) = self.tx.take() {
627 let message = format!(
628 "host.call(\"{}\"): the embedding app did not answer",
629 self.name
630 );
631 let _ = tx.send(Message::HostReply(self.id, Err(message)));
632 }
633 }
634}
635
636#[cfg(all(test, feature = "js-core", not(target_arch = "wasm32")))]
637mod tests {
638 use std::time::Duration;
639
640 use nsh_core::{ApproxTextEngine, MountBatch};
641 use serde_json::json;
642
643 use super::*;
644 use crate::{Bundle, Engine, EngineConfig, MountSink};
645
646 struct Sink;
647
648 impl MountSink for Sink {
649 fn submit(&self, _: MountBatch) {}
650 }
651
652 #[test]
653 fn events_sent_while_the_engine_stops_reach_the_next_app() {
654 let channel = HostChannel::new();
655 let (entered_tx, entered_rx) = crossbeam_channel::bounded(1);
656 let (release_tx, release_rx) = crossbeam_channel::bounded(1);
657 channel.handle("hold", move |_| {
658 entered_tx.send(()).unwrap();
659 release_rx.recv_timeout(Duration::from_secs(5)).unwrap();
660 });
661 let mut config = EngineConfig::new(Bundle::source(
662 "import { host } from 'nsh'; host.post('hold');".to_owned(),
663 ));
664 if let crate::App::Js(bundle) = &mut config.app {
665 bundle.policy.declared =
666 Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
667 }
668 config.host = channel.clone();
669 let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
670 entered_rx.recv_timeout(Duration::from_secs(5)).unwrap();
671 let stop = engine.stop.clone();
674 let dropping = std::thread::spawn(move || drop(engine));
675 let deadline = std::time::Instant::now() + Duration::from_secs(5);
676 while !stop.load(std::sync::atomic::Ordering::Relaxed) {
677 assert!(
678 std::time::Instant::now() < deadline,
679 "shutdown did not start"
680 );
681 std::thread::yield_now();
682 }
683 for id in 1..=3 {
684 channel.send("open", json!(id)).unwrap();
685 }
686 release_tx.send(()).unwrap();
687 dropping.join().unwrap();
688
689 let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
690 channel.handle("seen", move |mut call| {
691 seen_tx.send(call.take_data()).unwrap();
692 });
693 let mut config = EngineConfig::new(Bundle::source(
694 "import { host } from 'nsh'; host.on('open', data => host.post('seen', data));"
695 .to_owned(),
696 ));
697 if let crate::App::Js(bundle) = &mut config.app {
698 bundle.policy.declared =
699 Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
700 }
701 config.host = channel;
702 let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
703 for id in 1..=3 {
704 assert_eq!(
705 seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
706 json!(id)
707 );
708 }
709 assert!(seen_rx.try_recv().is_err());
710 drop(engine);
711 }
712
713 fn start(channel: &HostChannel, source: &str) -> Engine {
714 let mut config = EngineConfig::new(Bundle::source(source.to_owned()));
715 if let crate::App::Js(bundle) = &mut config.app {
716 bundle.policy.declared =
717 Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
718 }
719 config.host = channel.clone();
720 Engine::start(config, || ApproxTextEngine, Sink).unwrap()
721 }
722
723 #[test]
724 fn a_stand_in_leaves_the_app_without_an_embedding_app() {
725 let channel = HostChannel::new();
726 let (tx, rx) = crossbeam_channel::unbounded();
727 channel.handle_module_fake("probe", move |mut call| {
728 tx.send(call.take_data()).unwrap();
729 call.resolve(JsonValue::Null);
730 });
731 channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
732 let engine = start(
733 &channel,
734 "import { host, Image } from 'nsh'; Image.prefetch(host.available());",
735 );
736 assert_eq!(
737 rx.recv_timeout(Duration::from_secs(5)).unwrap(),
738 json!([false])
739 );
740 drop(engine);
741 }
742
743 #[test]
744 fn the_app_s_calls_never_reach_a_stand_in() {
745 let channel = HostChannel::new();
746 let (faked_tx, faked_rx) = crossbeam_channel::unbounded();
747 channel.handle_module_fake("probe", move |call| {
748 faked_tx.send(()).unwrap();
749 call.resolve(json!("faked"));
750 });
751 channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
752 let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
753 channel.handle("seen", move |mut call| {
754 seen_tx.send(call.take_data()).unwrap();
755 });
756 let engine = start(
757 &channel,
758 "import { host } from 'nsh'; host.call('probe').then((v) => host.post('seen', v), (e) => host.post('seen', e.message));",
759 );
760 assert_eq!(
761 seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
762 json!("host.call(\"probe\"): the embedding app handles no \"probe\"")
763 );
764 assert!(faked_rx.try_recv().is_err());
765 drop(engine);
766 }
767
768 #[test]
769 fn recovered_events_keep_the_queue_limit_and_order() {
770 let channel = HostChannel::new();
771 let (tx, rx) = crossbeam_channel::unbounded();
772 let attachment = channel.attach(tx, rx);
773 let limit = nsh_core::host_channel::MAX_QUEUED_EVENTS;
774 for id in 0..limit + 2 {
775 channel.send("open", json!(id)).unwrap();
776 }
777 drop(attachment);
778 let mut inner = channel.lock();
779 let kept = inner.pending.take("open");
780 assert_eq!(kept.len(), limit);
781 assert_eq!(kept[0], json!(2));
782 assert_eq!(kept[limit - 1], json!(limit + 1));
783 }
784
785 #[test]
786 fn an_old_attachment_does_not_detach_its_replacement() {
787 let channel = HostChannel::new();
788 let (old_tx, old_rx) = crossbeam_channel::unbounded();
789 let old = channel.attach(old_tx, old_rx);
790 let (tx, rx) = crossbeam_channel::unbounded();
791 let current = channel.attach(tx, rx.clone());
792 drop(old);
793 channel.send("open", json!(1)).unwrap();
794 assert!(matches!(
795 rx.try_recv().unwrap(),
796 Message::HostEvent(name, data) if name == "open" && data == json!(1)
797 ));
798 drop(current);
799 }
800}