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>) {
121 let mut inner = self.lock();
122 inner.params = params;
123 inner.configured = true;
124 }
125
126 pub fn params(&self) -> serde_json::Map<String, JsonValue> {
128 self.lock().params.clone()
129 }
130
131 pub fn send(&self, name: impl Into<String>, data: JsonValue) -> Result<(), String> {
139 let name = name.into();
140 check_name(&name)?;
141 let mut inner = self.lock();
142 inner.configured = true;
143 if let Some((_, tx)) = &inner.engine
144 && tx
145 .send(Message::HostEvent(name.clone(), data.clone()))
146 .is_ok()
147 {
148 return Ok(());
149 }
150 if let Some((dropped, _)) = inner.pending.push(name, data) {
151 log::warn!(
152 "nsh/host: no app ran to take the embedding app's events; the oldest (\"{dropped}\") was dropped"
153 );
154 }
155 Ok(())
156 }
157
158 pub fn handle(
166 &self,
167 name: impl Into<String>,
168 handler: impl Fn(HostCall) + Send + Sync + 'static,
169 ) {
170 let mut inner = self.lock();
171 inner.configured = true;
172 inner.handlers.insert(name.into(), Arc::new(handler));
173 }
174
175 pub fn remove_handler(&self, name: &str) {
178 self.lock().handlers.remove(name);
179 }
180
181 #[doc(hidden)]
189 pub fn fake_module_export(
190 &self,
191 specifier: impl Into<String>,
192 path: impl Into<String>,
193 fake: ModuleFake,
194 ) {
195 self.lock()
196 .module_fakes
197 .push((specifier.into(), path.into(), fake));
198 }
199
200 #[doc(hidden)]
206 pub fn handle_module_fake(
207 &self,
208 name: impl Into<String>,
209 handler: impl Fn(HostCall) + Send + Sync + 'static,
210 ) {
211 self.lock()
212 .fake_handlers
213 .insert(name.into(), Arc::new(handler));
214 }
215
216 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
217 fn handler(&self, name: &str) -> Option<Handler> {
218 self.lock().handlers.get(name).cloned()
219 }
220
221 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
222 fn fake_handler(&self, name: &str) -> Option<Handler> {
223 self.lock().fake_handlers.get(name).cloned()
224 }
225
226 #[cfg(not(target_arch = "wasm32"))]
230 pub(crate) fn request_shutdown(&self, tx: &Sender<Message>) {
231 let _inner = self.lock();
232 let _ = tx.send(Message::Shutdown);
233 }
234
235 #[cfg(not(target_arch = "wasm32"))]
238 pub(crate) fn shutdown(&self, tx: &Sender<Message>, stop: &std::sync::atomic::AtomicBool) {
239 let _inner = self.lock();
240 stop.store(true, std::sync::atomic::Ordering::Relaxed);
241 let _ = tx.send(Message::Shutdown);
242 }
243
244 pub fn handle_open_url(&self, handler: impl Fn(OpenUrlRequest) + Send + Sync + 'static) {
254 self.lock().url_handler = Some(Arc::new(handler));
255 }
256
257 pub fn remove_open_url_handler(&self) {
260 self.lock().url_handler = None;
261 }
262
263 pub(crate) fn open_url(&self, id: u32, url: String, tx: &Sender<Message>) -> Option<()> {
267 let handler = self.lock().url_handler.clone()?;
268 let request = OpenUrlRequest {
269 reply: Some(UrlReply {
270 id,
271 url: url.clone(),
272 tx: tx.clone(),
273 }),
274 url,
275 };
276 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(request))).is_err() {
277 log::error!("nsh/device: the embedding app's URL handler panicked");
278 }
279 Some(())
280 }
281
282 pub(crate) fn attach(&self, tx: Sender<Message>, rx: Receiver<Message>) -> HostAttachment {
286 let mut inner = self.lock();
287 inner.next_engine += 1;
288 let id = inner.next_engine;
289 for (name, data) in inner.pending.take_all() {
290 let _ = tx.send(Message::HostEvent(name, data));
291 }
292 inner.engine = Some((id, tx));
293 HostAttachment {
294 channel: self.clone(),
295 id,
296 rx,
297 }
298 }
299
300 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
304 pub(crate) fn bridge(&self, tx: Sender<Message>) -> EngineBridge {
305 let inner = self.lock();
306 EngineBridge {
307 params: JsonValue::Object(inner.params.clone()),
308 module_fakes: inner.module_fakes.clone(),
309 channel: self.clone(),
310 tx,
311 }
312 }
313}
314
315pub(crate) struct HostAttachment {
317 channel: HostChannel,
318 id: u64,
319 rx: Receiver<Message>,
321}
322
323impl Drop for HostAttachment {
324 fn drop(&mut self) {
325 let discarded = {
326 let mut inner = self.channel.lock();
327 if !inner.engine.as_ref().is_some_and(|(id, _)| *id == self.id) {
328 return;
329 }
330 inner.engine = None;
331 let mut messages: Vec<_> = self.rx.try_iter().collect();
334 for message in &mut messages {
335 if let Message::HostEvent(name, data) = message
336 && let Some((dropped, _)) = inner
337 .pending
338 .push(std::mem::take(name), std::mem::take(data))
339 {
340 log::warn!(
341 "nsh/host: the app stopped; the oldest kept event (\"{dropped}\") was dropped"
342 );
343 }
344 }
345 messages
346 };
347 drop(discarded);
350 }
351}
352
353#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
356pub(crate) struct EngineBridge {
357 params: JsonValue,
358 module_fakes: Vec<(String, String, ModuleFake)>,
360 channel: HostChannel,
361 tx: Sender<Message>,
362}
363
364#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
365impl EngineBridge {
366 fn run(handler: &Handler, call: HostCall) {
369 let name = call.name.clone();
370 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(call)));
371 if ran.is_err() {
372 log::error!("nsh/host: the embedding app's handler of \"{name}\" panicked");
373 }
374 }
375
376 fn start(&self, handler: &Handler, id: u64, name: &str, data: JsonValue) {
379 let call = HostCall {
380 name: name.to_owned(),
381 data,
382 reply: Some(HostReply {
383 id,
384 name: name.to_owned(),
385 tx: Some(self.tx.clone()),
386 }),
387 };
388 Self::run(handler, call);
389 }
390}
391
392#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
393impl HostBridge for EngineBridge {
394 fn available(&self) -> bool {
395 self.channel.lock().configured
396 }
397
398 fn params(&self) -> JsonValue {
399 self.params.clone()
400 }
401
402 fn call(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
403 let Some(handler) = self.channel.handler(name) else {
404 return Err(format!(
405 "host.call(\"{name}\"): the embedding app handles no \"{name}\""
406 ));
407 };
408 self.start(&handler, id, name, data);
409 Ok(())
410 }
411
412 fn module_fakes(&self, specifier: &str) -> Vec<(String, ModuleFake)> {
413 self.module_fakes
414 .iter()
415 .filter(|(s, _, _)| s == specifier)
416 .map(|(_, path, fake)| (path.clone(), fake.clone()))
417 .collect()
418 }
419
420 fn call_module_fake(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
421 let Some(handler) = self.channel.fake_handler(name) else {
422 return Err(format!("no stand-in answers \"{name}\""));
423 };
424 self.start(&handler, id, name, data);
425 Ok(())
426 }
427
428 fn post(&self, name: &str, data: JsonValue) {
429 match self.channel.handler(name) {
430 Some(handler) => Self::run(
431 &handler,
432 HostCall {
433 name: name.to_owned(),
434 data,
435 reply: None,
436 },
437 ),
438 None => log::debug!(
439 "nsh/host: the embedding app handles no \"{name}\"; the post was dropped"
440 ),
441 }
442 }
443}
444
445#[derive(Default)]
449#[non_exhaustive]
450pub struct HostCall {
451 name: String,
452 data: JsonValue,
453 reply: Option<HostReply>,
454}
455
456impl std::fmt::Debug for HostCall {
457 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
458 f.debug_struct("HostCall")
459 .field("name", &self.name)
460 .field("data", &self.data)
461 .field("post", &self.is_post())
462 .finish()
463 }
464}
465
466impl HostCall {
467 pub fn name(&self) -> &str {
469 &self.name
470 }
471
472 pub fn data(&self) -> &JsonValue {
474 &self.data
475 }
476
477 pub fn take_data(&mut self) -> JsonValue {
479 std::mem::take(&mut self.data)
480 }
481
482 pub fn is_post(&self) -> bool {
484 self.reply.is_none()
485 }
486
487 pub fn resolve(self, value: JsonValue) {
489 self.reply(Ok(value));
490 }
491
492 pub fn reject(self, message: impl Into<String>) {
495 self.reply(Err(message.into()));
496 }
497
498 pub fn reply(mut self, result: Result<JsonValue, String>) {
501 if let Some(reply) = self.reply.take() {
502 reply.reply(result);
503 }
504 }
505
506 pub fn into_reply(mut self) -> Option<HostReply> {
508 self.reply.take()
509 }
510}
511
512#[derive(Default)]
518#[non_exhaustive]
519pub struct OpenUrlRequest {
520 url: String,
521 reply: Option<UrlReply>,
522}
523
524struct UrlReply {
526 id: u32,
527 url: String,
528 tx: Sender<Message>,
529}
530
531impl std::fmt::Debug for OpenUrlRequest {
532 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
533 f.debug_struct("OpenUrlRequest")
534 .field("url", &self.url)
535 .finish()
536 }
537}
538
539impl OpenUrlRequest {
540 pub fn url(&self) -> &str {
543 &self.url
544 }
545
546 pub fn handled(self) {
549 self.answer(true);
550 }
551
552 pub fn decline(self) {
554 self.answer(false);
555 }
556
557 pub fn answer(mut self, handled: bool) {
560 if let Some(reply) = self.reply.take() {
561 let _ = reply.tx.send(Message::UrlHandled {
562 id: reply.id,
563 url: reply.url,
564 handled,
565 });
566 }
567 }
568}
569
570impl Drop for OpenUrlRequest {
571 fn drop(&mut self) {
572 if let Some(reply) = self.reply.take() {
573 let _ = reply.tx.send(Message::UrlHandled {
574 id: reply.id,
575 url: reply.url,
576 handled: false,
577 });
578 }
579 }
580}
581
582#[derive(Default)]
585#[non_exhaustive]
586pub struct HostReply {
587 id: u64,
588 name: String,
589 tx: Option<Sender<Message>>,
591}
592
593impl std::fmt::Debug for HostReply {
594 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
595 f.debug_struct("HostReply")
596 .field("name", &self.name)
597 .finish()
598 }
599}
600
601impl HostReply {
602 pub fn resolve(self, value: JsonValue) {
604 self.reply(Ok(value));
605 }
606
607 pub fn reject(self, message: impl Into<String>) {
609 self.reply(Err(message.into()));
610 }
611
612 pub fn reply(mut self, result: Result<JsonValue, String>) {
614 if let Some(tx) = self.tx.take() {
615 let _ = tx.send(Message::HostReply(self.id, result));
616 }
617 }
618}
619
620impl Drop for HostReply {
621 fn drop(&mut self) {
622 if let Some(tx) = self.tx.take() {
623 let message = format!(
624 "host.call(\"{}\"): the embedding app did not answer",
625 self.name
626 );
627 let _ = tx.send(Message::HostReply(self.id, Err(message)));
628 }
629 }
630}
631
632#[cfg(all(test, feature = "js-core", not(target_arch = "wasm32")))]
633mod tests {
634 use std::time::Duration;
635
636 use nsh_core::{ApproxTextEngine, MountBatch};
637 use serde_json::json;
638
639 use super::*;
640 use crate::{Bundle, Engine, EngineConfig, MountSink};
641
642 struct Sink;
643
644 impl MountSink for Sink {
645 fn submit(&self, _: MountBatch) {}
646 }
647
648 #[test]
649 fn events_sent_while_the_engine_stops_reach_the_next_app() {
650 let channel = HostChannel::new();
651 let (entered_tx, entered_rx) = crossbeam_channel::bounded(1);
652 let (release_tx, release_rx) = crossbeam_channel::bounded(1);
653 channel.handle("hold", move |_| {
654 entered_tx.send(()).unwrap();
655 release_rx.recv_timeout(Duration::from_secs(5)).unwrap();
656 });
657 let mut config = EngineConfig::new(Bundle::source(
658 "import { host } from 'nsh'; host.post('hold');".to_owned(),
659 ));
660 if let crate::App::Js(bundle) = &mut config.app {
661 bundle.policy.declared =
662 Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
663 }
664 config.host = channel.clone();
665 let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
666 entered_rx.recv_timeout(Duration::from_secs(5)).unwrap();
667 let stop = engine.stop.clone();
670 let dropping = std::thread::spawn(move || drop(engine));
671 let deadline = std::time::Instant::now() + Duration::from_secs(5);
672 while !stop.load(std::sync::atomic::Ordering::Relaxed) {
673 assert!(
674 std::time::Instant::now() < deadline,
675 "shutdown did not start"
676 );
677 std::thread::yield_now();
678 }
679 for id in 1..=3 {
680 channel.send("open", json!(id)).unwrap();
681 }
682 release_tx.send(()).unwrap();
683 dropping.join().unwrap();
684
685 let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
686 channel.handle("seen", move |mut call| {
687 seen_tx.send(call.take_data()).unwrap();
688 });
689 let mut config = EngineConfig::new(Bundle::source(
690 "import { host } from 'nsh'; host.on('open', data => host.post('seen', data));"
691 .to_owned(),
692 ));
693 if let crate::App::Js(bundle) = &mut config.app {
694 bundle.policy.declared =
695 Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
696 }
697 config.host = channel;
698 let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
699 for id in 1..=3 {
700 assert_eq!(
701 seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
702 json!(id)
703 );
704 }
705 assert!(seen_rx.try_recv().is_err());
706 drop(engine);
707 }
708
709 fn start(channel: &HostChannel, source: &str) -> Engine {
710 let mut config = EngineConfig::new(Bundle::source(source.to_owned()));
711 if let crate::App::Js(bundle) = &mut config.app {
712 bundle.policy.declared =
713 Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
714 }
715 config.host = channel.clone();
716 Engine::start(config, || ApproxTextEngine, Sink).unwrap()
717 }
718
719 #[test]
720 fn a_stand_in_leaves_the_app_without_an_embedding_app() {
721 let channel = HostChannel::new();
722 let (tx, rx) = crossbeam_channel::unbounded();
723 channel.handle_module_fake("probe", move |mut call| {
724 tx.send(call.take_data()).unwrap();
725 call.resolve(JsonValue::Null);
726 });
727 channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
728 let engine = start(
729 &channel,
730 "import { host, Image } from 'nsh'; Image.prefetch(host.available());",
731 );
732 assert_eq!(
733 rx.recv_timeout(Duration::from_secs(5)).unwrap(),
734 json!([false])
735 );
736 drop(engine);
737 }
738
739 #[test]
740 fn the_app_s_calls_never_reach_a_stand_in() {
741 let channel = HostChannel::new();
742 let (faked_tx, faked_rx) = crossbeam_channel::unbounded();
743 channel.handle_module_fake("probe", move |call| {
744 faked_tx.send(()).unwrap();
745 call.resolve(json!("faked"));
746 });
747 channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
748 let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
749 channel.handle("seen", move |mut call| {
750 seen_tx.send(call.take_data()).unwrap();
751 });
752 let engine = start(
753 &channel,
754 "import { host } from 'nsh'; host.call('probe').then((v) => host.post('seen', v), (e) => host.post('seen', e.message));",
755 );
756 assert_eq!(
757 seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
758 json!("host.call(\"probe\"): the embedding app handles no \"probe\"")
759 );
760 assert!(faked_rx.try_recv().is_err());
761 drop(engine);
762 }
763
764 #[test]
765 fn recovered_events_keep_the_queue_limit_and_order() {
766 let channel = HostChannel::new();
767 let (tx, rx) = crossbeam_channel::unbounded();
768 let attachment = channel.attach(tx, rx);
769 let limit = nsh_core::host_channel::MAX_QUEUED_EVENTS;
770 for id in 0..limit + 2 {
771 channel.send("open", json!(id)).unwrap();
772 }
773 drop(attachment);
774 let mut inner = channel.lock();
775 let kept = inner.pending.take("open");
776 assert_eq!(kept.len(), limit);
777 assert_eq!(kept[0], json!(2));
778 assert_eq!(kept[limit - 1], json!(limit + 1));
779 }
780
781 #[test]
782 fn an_old_attachment_does_not_detach_its_replacement() {
783 let channel = HostChannel::new();
784 let (old_tx, old_rx) = crossbeam_channel::unbounded();
785 let old = channel.attach(old_tx, old_rx);
786 let (tx, rx) = crossbeam_channel::unbounded();
787 let current = channel.attach(tx, rx.clone());
788 drop(old);
789 channel.send("open", json!(1)).unwrap();
790 assert!(matches!(
791 rx.try_recv().unwrap(),
792 Message::HostEvent(name, data) if name == "open" && data == json!(1)
793 ));
794 drop(current);
795 }
796}