1use std::{
23 collections::HashMap,
24 sync::{
25 Arc, Mutex, MutexGuard,
26 atomic::{AtomicU64, AtomicUsize, Ordering},
27 },
28};
29
30use crossbeam_channel::{Receiver, Sender};
31#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
32use nsh_core::host_channel::HostBridge;
33use nsh_core::{
34 JsonValue,
35 host_channel::{HostError, HostInbox, HostRequest, ModuleFake, check_name},
36};
37
38use crate::Message;
39
40type Handler = Arc<dyn Fn(HostCall) + Send + Sync>;
42
43fn run_handler(handler: &Handler, call: HostCall) {
46 let name = call.name.clone();
47 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(call)));
48 if ran.is_err() {
49 log::error!("nsh/host: the embedding app's handler of \"{name}\" panicked");
50 }
51}
52
53pub(crate) enum HostRefusal {
55 Unconfigured(HostRequest),
57 NoHandler(u64, HostError),
59}
60
61type UrlHandler = Arc<dyn Fn(OpenUrlRequest) + Send + Sync>;
63
64#[derive(Clone, Default)]
88pub struct HostChannel {
89 inner: Arc<Mutex<Inner>>,
90 calls: Arc<CallCount>,
93}
94
95#[derive(Default)]
97struct CallCount {
98 in_flight: AtomicUsize,
100 answered: AtomicU64,
103}
104
105#[derive(Default)]
106struct Inner {
107 params: serde_json::Map<String, JsonValue>,
108 configured: bool,
109 handlers: HashMap<String, Handler>,
110 url_handler: Option<UrlHandler>,
111 engine: Option<(u64, Sender<Message>)>,
113 next_engine: u64,
114 pending: HostInbox,
116 module_fakes: Vec<(String, String, ModuleFake)>,
119 fake_handlers: HashMap<String, Handler>,
122}
123
124impl std::fmt::Debug for HostChannel {
125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126 let inner = self.lock();
127 let mut handlers: Vec<&String> = inner.handlers.keys().collect();
128 handlers.sort();
129 f.debug_struct("HostChannel")
130 .field("params", &inner.params)
131 .field("handlers", &handlers)
132 .field("configured", &inner.configured)
133 .field("url_handler", &inner.url_handler.is_some())
134 .field("attached", &inner.engine.is_some())
135 .field("pending", &inner.pending.len())
136 .finish()
137 }
138}
139
140impl HostChannel {
141 pub fn new() -> Self {
143 Self::default()
144 }
145
146 fn lock(&self) -> MutexGuard<'_, Inner> {
147 self.inner.lock().unwrap_or_else(|e| e.into_inner())
148 }
149
150 #[doc(hidden)]
154 pub fn calls_in_flight(&self) -> usize {
155 self.calls.in_flight.load(Ordering::SeqCst)
156 }
157
158 #[doc(hidden)]
164 pub fn calls_answered(&self) -> u64 {
165 self.calls.answered.load(Ordering::SeqCst)
166 }
167
168 pub fn set_params(&self, params: serde_json::Map<String, JsonValue>) {
179 self.lock().params = params;
180 }
181
182 pub fn params(&self) -> serde_json::Map<String, JsonValue> {
184 self.lock().params.clone()
185 }
186
187 pub fn send(&self, name: impl Into<String>, data: JsonValue) -> Result<(), String> {
196 let name = name.into();
197 check_name(&name)?;
198 let mut inner = self.lock();
199 inner.configured = true;
200 if let Some((_, tx)) = &inner.engine
201 && tx
202 .send(Message::HostEvent(name.clone(), data.clone()))
203 .is_ok()
204 {
205 return Ok(());
206 }
207 if let Some((dropped, _)) = inner.pending.push(name, data) {
208 log::warn!(
209 "nsh/host: no app ran to take the embedding app's events; the oldest (\"{dropped}\") was dropped"
210 );
211 }
212 Ok(())
213 }
214
215 pub fn handle(
223 &self,
224 name: impl Into<String>,
225 handler: impl Fn(HostCall) + Send + Sync + 'static,
226 ) {
227 let mut inner = self.lock();
228 inner.configured = true;
229 inner.handlers.insert(name.into(), Arc::new(handler));
230 }
231
232 pub fn remove_handler(&self, name: &str) {
235 self.lock().handlers.remove(name);
236 }
237
238 #[doc(hidden)]
246 pub fn fake_module_export(
247 &self,
248 specifier: impl Into<String>,
249 path: impl Into<String>,
250 fake: ModuleFake,
251 ) {
252 self.lock()
253 .module_fakes
254 .push((specifier.into(), path.into(), fake));
255 }
256
257 #[doc(hidden)]
263 pub fn handle_module_fake(
264 &self,
265 name: impl Into<String>,
266 handler: impl Fn(HostCall) + Send + Sync + 'static,
267 ) {
268 self.lock()
269 .fake_handlers
270 .insert(name.into(), Arc::new(handler));
271 }
272
273 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
274 fn handler(&self, name: &str) -> Option<Handler> {
275 self.lock().handlers.get(name).cloned()
276 }
277
278 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
279 fn fake_handler(&self, name: &str) -> Option<Handler> {
280 self.lock().fake_handlers.get(name).cloned()
281 }
282
283 pub(crate) fn start_request(
290 &self,
291 request: HostRequest,
292 tx: &Sender<Message>,
293 ) -> Result<(), HostRefusal> {
294 let (handler, configured) = {
295 let inner = self.lock();
296 let name = match &request {
297 HostRequest::Call { name, .. } | HostRequest::Post { name, .. } => name,
298 _ => return Err(HostRefusal::Unconfigured(request)),
299 };
300 (inner.handlers.get(name).cloned(), inner.configured)
301 };
302 if !configured {
303 return Err(HostRefusal::Unconfigured(request));
304 }
305 match request {
306 HostRequest::Call { id, name, args } => {
307 let Some(handler) = handler else {
308 return Err(HostRefusal::NoHandler(
309 id,
310 HostError::Failed(format!(
311 "host.call(\"{name}\"): the embedding app handles no \"{name}\""
312 )),
313 ));
314 };
315 self.calls.in_flight.fetch_add(1, Ordering::SeqCst);
316 let reply = HostReply {
317 id,
318 name: name.clone(),
319 tx: Some(tx.clone()),
320 calls: Some(self.calls.clone()),
321 to_core: true,
322 };
323 run_handler(
324 &handler,
325 HostCall {
326 name,
327 data: args,
328 reply: Some(reply),
329 },
330 );
331 }
332 HostRequest::Post { name, args } => match handler {
333 Some(handler) => run_handler(
334 &handler,
335 HostCall {
336 name,
337 data: args,
338 reply: None,
339 },
340 ),
341 None => log::debug!(
342 "nsh/host: the embedding app handles no \"{name}\"; the post was dropped"
343 ),
344 },
345 _ => {}
346 }
347 Ok(())
348 }
349
350 #[cfg(not(target_arch = "wasm32"))]
354 pub(crate) fn request_shutdown(&self, tx: &Sender<Message>) {
355 let _inner = self.lock();
356 let _ = tx.send(Message::Shutdown);
357 }
358
359 #[cfg(not(target_arch = "wasm32"))]
362 pub(crate) fn shutdown(&self, tx: &Sender<Message>, stop: &std::sync::atomic::AtomicBool) {
363 let _inner = self.lock();
364 stop.store(true, std::sync::atomic::Ordering::Relaxed);
365 let _ = tx.send(Message::Shutdown);
366 }
367
368 pub fn handle_open_url(&self, handler: impl Fn(OpenUrlRequest) + Send + Sync + 'static) {
378 self.lock().url_handler = Some(Arc::new(handler));
379 }
380
381 pub fn remove_open_url_handler(&self) {
384 self.lock().url_handler = None;
385 }
386
387 pub(crate) fn open_url(&self, id: u32, url: String, tx: &Sender<Message>) -> Option<()> {
391 let handler = self.lock().url_handler.clone()?;
392 let request = OpenUrlRequest {
393 reply: Some(UrlReply {
394 id,
395 url: url.clone(),
396 tx: tx.clone(),
397 }),
398 url,
399 };
400 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(request))).is_err() {
401 log::error!("nsh/device: the embedding app's URL handler panicked");
402 }
403 Some(())
404 }
405
406 pub(crate) fn attach(&self, tx: Sender<Message>, rx: Receiver<Message>) -> HostAttachment {
410 let mut inner = self.lock();
411 inner.next_engine += 1;
412 let id = inner.next_engine;
413 for (name, data) in inner.pending.take_all() {
414 let _ = tx.send(Message::HostEvent(name, data));
415 }
416 inner.engine = Some((id, tx));
417 HostAttachment {
418 channel: self.clone(),
419 id,
420 rx,
421 }
422 }
423
424 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
428 pub(crate) fn bridge(&self, tx: Sender<Message>) -> EngineBridge {
429 let inner = self.lock();
430 EngineBridge {
431 params: JsonValue::Object(inner.params.clone()),
432 module_fakes: inner.module_fakes.clone(),
433 channel: self.clone(),
434 tx,
435 }
436 }
437}
438
439pub(crate) struct HostAttachment {
441 channel: HostChannel,
442 id: u64,
443 rx: Receiver<Message>,
445}
446
447impl Drop for HostAttachment {
448 fn drop(&mut self) {
449 let discarded = {
450 let mut inner = self.channel.lock();
451 if !inner.engine.as_ref().is_some_and(|(id, _)| *id == self.id) {
452 return;
453 }
454 inner.engine = None;
455 let mut messages: Vec<_> = self.rx.try_iter().collect();
458 for message in &mut messages {
459 if let Message::HostEvent(name, data) = message
460 && let Some((dropped, _)) = inner
461 .pending
462 .push(std::mem::take(name), std::mem::take(data))
463 {
464 log::warn!(
465 "nsh/host: the app stopped; the oldest kept event (\"{dropped}\") was dropped"
466 );
467 }
468 }
469 messages
470 };
471 drop(discarded);
474 }
475}
476
477#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
480pub(crate) struct EngineBridge {
481 params: JsonValue,
482 module_fakes: Vec<(String, String, ModuleFake)>,
484 channel: HostChannel,
485 tx: Sender<Message>,
486}
487
488#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
489impl EngineBridge {
490 fn start(&self, handler: &Handler, id: u64, name: &str, data: JsonValue) {
493 let calls = self.channel.calls.clone();
494 calls.in_flight.fetch_add(1, Ordering::SeqCst);
495 let call = HostCall {
496 name: name.to_owned(),
497 data,
498 reply: Some(HostReply {
499 id,
500 name: name.to_owned(),
501 tx: Some(self.tx.clone()),
502 calls: Some(calls),
503 to_core: false,
504 }),
505 };
506 run_handler(handler, call);
507 }
508}
509
510#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
511impl HostBridge for EngineBridge {
512 fn available(&self) -> bool {
513 self.channel.lock().configured
514 }
515
516 fn params(&self) -> JsonValue {
517 self.params.clone()
518 }
519
520 fn call(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
521 let Some(handler) = self.channel.handler(name) else {
522 return Err(format!(
523 "host.call(\"{name}\"): the embedding app handles no \"{name}\""
524 ));
525 };
526 self.start(&handler, id, name, data);
527 Ok(())
528 }
529
530 fn module_fakes(&self, specifier: &str) -> Vec<(String, ModuleFake)> {
531 self.module_fakes
532 .iter()
533 .filter(|(s, _, _)| s == specifier)
534 .map(|(_, path, fake)| (path.clone(), fake.clone()))
535 .collect()
536 }
537
538 fn call_module_fake(&self, id: u64, name: &str, data: JsonValue) -> Result<(), String> {
539 let Some(handler) = self.channel.fake_handler(name) else {
540 return Err(format!("no stand-in answers \"{name}\""));
541 };
542 self.start(&handler, id, name, data);
543 Ok(())
544 }
545
546 fn post(&self, name: &str, data: JsonValue) {
547 match self.channel.handler(name) {
548 Some(handler) => run_handler(
549 &handler,
550 HostCall {
551 name: name.to_owned(),
552 data,
553 reply: None,
554 },
555 ),
556 None => log::debug!(
557 "nsh/host: the embedding app handles no \"{name}\"; the post was dropped"
558 ),
559 }
560 }
561}
562
563#[derive(Default)]
567#[non_exhaustive]
568pub struct HostCall {
569 name: String,
570 data: JsonValue,
571 reply: Option<HostReply>,
572}
573
574impl std::fmt::Debug for HostCall {
575 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
576 f.debug_struct("HostCall")
577 .field("name", &self.name)
578 .field("data", &self.data)
579 .field("post", &self.is_post())
580 .finish()
581 }
582}
583
584impl HostCall {
585 pub fn name(&self) -> &str {
587 &self.name
588 }
589
590 pub fn data(&self) -> &JsonValue {
592 &self.data
593 }
594
595 pub fn take_data(&mut self) -> JsonValue {
597 std::mem::take(&mut self.data)
598 }
599
600 pub fn is_post(&self) -> bool {
602 self.reply.is_none()
603 }
604
605 pub fn resolve(self, value: JsonValue) {
607 self.reply(Ok(value));
608 }
609
610 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>) {
619 if let Some(reply) = self.reply.take() {
620 reply.reply(result);
621 }
622 }
623
624 pub fn into_reply(mut self) -> Option<HostReply> {
626 self.reply.take()
627 }
628}
629
630#[derive(Default)]
636#[non_exhaustive]
637pub struct OpenUrlRequest {
638 url: String,
639 reply: Option<UrlReply>,
640}
641
642struct UrlReply {
644 id: u32,
645 url: String,
646 tx: Sender<Message>,
647}
648
649impl std::fmt::Debug for OpenUrlRequest {
650 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
651 f.debug_struct("OpenUrlRequest")
652 .field("url", &self.url)
653 .finish()
654 }
655}
656
657impl OpenUrlRequest {
658 pub fn url(&self) -> &str {
661 &self.url
662 }
663
664 pub fn handled(self) {
667 self.answer(true);
668 }
669
670 pub fn decline(self) {
672 self.answer(false);
673 }
674
675 pub fn answer(mut self, handled: bool) {
678 if let Some(reply) = self.reply.take() {
679 let _ = reply.tx.send(Message::UrlHandled {
680 id: reply.id,
681 url: reply.url,
682 handled,
683 });
684 }
685 }
686}
687
688impl Drop for OpenUrlRequest {
689 fn drop(&mut self) {
690 if let Some(reply) = self.reply.take() {
691 let _ = reply.tx.send(Message::UrlHandled {
692 id: reply.id,
693 url: reply.url,
694 handled: false,
695 });
696 }
697 }
698}
699
700#[derive(Default)]
703#[non_exhaustive]
704pub struct HostReply {
705 id: u64,
706 name: String,
707 tx: Option<Sender<Message>>,
709 calls: Option<Arc<CallCount>>,
711 to_core: bool,
714}
715
716impl std::fmt::Debug for HostReply {
717 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
718 f.debug_struct("HostReply")
719 .field("name", &self.name)
720 .finish()
721 }
722}
723
724impl HostReply {
725 pub fn resolve(self, value: JsonValue) {
727 self.reply(Ok(value));
728 }
729
730 pub fn reject(self, message: impl Into<String>) {
732 self.reply(Err(message.into()));
733 }
734
735 pub fn reply(mut self, result: Result<JsonValue, String>) {
737 self.send(result);
738 self.answered();
739 }
740
741 fn send(&mut self, result: Result<JsonValue, String>) {
743 if let Some(tx) = self.tx.take() {
744 let _ = tx.send(if self.to_core {
745 Message::CoreHostReply(self.id, result)
746 } else {
747 Message::HostReply(self.id, result)
748 });
749 }
750 }
751
752 fn answered(&mut self) {
754 if let Some(calls) = self.calls.take() {
755 calls.answered.fetch_add(1, Ordering::SeqCst);
756 calls.in_flight.fetch_sub(1, Ordering::SeqCst);
757 }
758 }
759}
760
761impl Drop for HostReply {
762 fn drop(&mut self) {
763 if self.tx.is_some() {
764 let message = format!(
765 "host.call(\"{}\"): the embedding app did not answer",
766 self.name
767 );
768 self.send(Err(message));
769 }
770 self.answered();
771 }
772}
773
774#[cfg(all(test, feature = "js-core", not(target_arch = "wasm32")))]
775mod tests {
776 use std::time::Duration;
777
778 use nsh_core::{ApproxTextEngine, MountBatch};
779 use serde_json::json;
780
781 use super::*;
782 use crate::{Bundle, Engine, EngineConfig, MountSink};
783
784 struct Sink;
785
786 impl MountSink for Sink {
787 fn submit(&self, _: MountBatch) {}
788 }
789
790 #[test]
791 fn events_sent_while_the_engine_stops_reach_the_next_app() {
792 let channel = HostChannel::new();
793 let (entered_tx, entered_rx) = crossbeam_channel::bounded(1);
794 let (release_tx, release_rx) = crossbeam_channel::bounded(1);
795 channel.handle("hold", move |_| {
796 entered_tx.send(()).unwrap();
797 release_rx.recv_timeout(Duration::from_secs(5)).unwrap();
798 });
799 let mut config = EngineConfig::new(Bundle::source(
800 "import { host } from 'nsh'; host.post('hold');".to_owned(),
801 ));
802 if let crate::App::Js(bundle) = &mut config.app {
803 bundle.policy.declared =
804 Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
805 }
806 config.host = channel.clone();
807 let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
808 entered_rx.recv_timeout(Duration::from_secs(5)).unwrap();
809 let stop = engine.stop.clone();
812 let dropping = std::thread::spawn(move || drop(engine));
813 let deadline = std::time::Instant::now() + Duration::from_secs(5);
814 while !stop.load(std::sync::atomic::Ordering::Relaxed) {
815 assert!(
816 std::time::Instant::now() < deadline,
817 "shutdown did not start"
818 );
819 std::thread::yield_now();
820 }
821 for id in 1..=3 {
822 channel.send("open", json!(id)).unwrap();
823 }
824 release_tx.send(()).unwrap();
825 dropping.join().unwrap();
826
827 let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
828 channel.handle("seen", move |mut call| {
829 seen_tx.send(call.take_data()).unwrap();
830 });
831 let mut config = EngineConfig::new(Bundle::source(
832 "import { host } from 'nsh'; host.on('open', data => host.post('seen', data));"
833 .to_owned(),
834 ));
835 if let crate::App::Js(bundle) = &mut config.app {
836 bundle.policy.declared =
837 Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
838 }
839 config.host = channel;
840 let engine = Engine::start(config, || ApproxTextEngine, Sink).unwrap();
841 for id in 1..=3 {
842 assert_eq!(
843 seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
844 json!(id)
845 );
846 }
847 assert!(seen_rx.try_recv().is_err());
848 drop(engine);
849 }
850
851 fn start(channel: &HostChannel, source: &str) -> Engine {
852 let mut config = EngineConfig::new(Bundle::source(source.to_owned()));
853 if let crate::App::Js(bundle) = &mut config.app {
854 bundle.policy.declared =
855 Some(nsh_core::access::Capabilities::from_json(&json!({ "host": true })).unwrap());
856 }
857 config.host = channel.clone();
858 Engine::start(config, || ApproxTextEngine, Sink).unwrap()
859 }
860
861 #[test]
862 fn a_stand_in_leaves_the_app_without_an_embedding_app() {
863 let channel = HostChannel::new();
864 let (tx, rx) = crossbeam_channel::unbounded();
865 channel.handle_module_fake("probe", move |mut call| {
866 tx.send(call.take_data()).unwrap();
867 call.resolve(JsonValue::Null);
868 });
869 channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
870 let engine = start(
871 &channel,
872 "import { host, Image } from 'nsh'; Image.prefetch(host.available());",
873 );
874 assert_eq!(
875 rx.recv_timeout(Duration::from_secs(5)).unwrap(),
876 json!([false])
877 );
878 drop(engine);
879 }
880
881 #[test]
882 fn the_app_s_calls_never_reach_a_stand_in() {
883 let channel = HostChannel::new();
884 let (faked_tx, faked_rx) = crossbeam_channel::unbounded();
885 channel.handle_module_fake("probe", move |call| {
886 faked_tx.send(()).unwrap();
887 call.resolve(json!("faked"));
888 });
889 channel.fake_module_export("nsh", "Image.prefetch", ModuleFake::Call("probe".into()));
890 let (seen_tx, seen_rx) = crossbeam_channel::unbounded();
891 channel.handle("seen", move |mut call| {
892 seen_tx.send(call.take_data()).unwrap();
893 });
894 let engine = start(
895 &channel,
896 "import { host } from 'nsh'; host.call('probe').then((v) => host.post('seen', v), (e) => host.post('seen', e.message));",
897 );
898 assert_eq!(
899 seen_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
900 json!("host.call(\"probe\"): the embedding app handles no \"probe\"")
901 );
902 assert!(faked_rx.try_recv().is_err());
903 drop(engine);
904 }
905
906 #[test]
907 fn recovered_events_keep_the_queue_limit_and_order() {
908 let channel = HostChannel::new();
909 let (tx, rx) = crossbeam_channel::unbounded();
910 let attachment = channel.attach(tx, rx);
911 let limit = nsh_core::host_channel::MAX_QUEUED_EVENTS;
912 for id in 0..limit + 2 {
913 channel.send("open", json!(id)).unwrap();
914 }
915 drop(attachment);
916 let mut inner = channel.lock();
917 let kept = inner.pending.take("open");
918 assert_eq!(kept.len(), limit);
919 assert_eq!(kept[0], json!(2));
920 assert_eq!(kept[limit - 1], json!(limit + 1));
921 }
922
923 #[test]
924 fn an_old_attachment_does_not_detach_its_replacement() {
925 let channel = HostChannel::new();
926 let (old_tx, old_rx) = crossbeam_channel::unbounded();
927 let old = channel.attach(old_tx, old_rx);
928 let (tx, rx) = crossbeam_channel::unbounded();
929 let current = channel.attach(tx, rx.clone());
930 drop(old);
931 channel.send("open", json!(1)).unwrap();
932 assert!(matches!(
933 rx.try_recv().unwrap(),
934 Message::HostEvent(name, data) if name == "open" && data == json!(1)
935 ));
936 drop(current);
937 }
938}