1use 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
49type Handler = Arc<dyn Fn(HostCall) + Send + Sync>;
51
52fn 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
62pub(crate) enum HostRefusal {
64 Unconfigured(HostRequest),
66 NoHandler(u64, HostError),
68}
69
70type UrlHandler = Arc<dyn Fn(OpenUrlRequest) + Send + Sync>;
72
73#[derive(Clone, Default)]
97pub struct HostChannel {
98 inner: Arc<Mutex<Inner>>,
99 calls: Arc<CallCount>,
102}
103
104#[derive(Default)]
106struct CallCount {
107 in_flight: AtomicUsize,
109 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 engine: Option<(u64, Arc<Caller>)>,
123 next_engine: u64,
124 pending: HostInbox,
126 module_fakes: Vec<(String, String, ModuleFake)>,
129 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 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 #[doc(hidden)]
164 pub fn calls_in_flight(&self) -> usize {
165 self.calls.in_flight.load(Ordering::SeqCst)
166 }
167
168 #[doc(hidden)]
174 pub fn calls_answered(&self) -> u64 {
175 self.calls.answered.load(Ordering::SeqCst)
176 }
177
178 pub fn set_params(&self, params: serde_json::Map<String, JsonValue>) {
189 self.lock().params = params;
190 }
191
192 pub fn params(&self) -> serde_json::Map<String, JsonValue> {
194 self.lock().params.clone()
195 }
196
197 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 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 pub fn remove_handler(&self, name: &str) {
246 self.lock().handlers.remove(name);
247 }
248
249 #[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 #[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 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 #[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 if let Some(caller) = caller {
375 caller.close();
376 }
377 }
378
379 #[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 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 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 pub fn remove_open_url_handler(&self) {
425 self.lock().url_handler = None;
426 }
427
428 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 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 if let Some((_, engine)) = replaced {
463 engine.close();
464 }
465 HostAttachment {
466 channel: self.clone(),
467 id,
468 rx,
469 }
470 }
471
472 #[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
487pub(crate) struct HostAttachment {
489 channel: HostChannel,
490 id: u64,
491 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 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 drop(discarded);
527 }
528}
529
530#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
533pub(crate) struct EngineBridge {
534 params: JsonValue,
535 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 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#[derive(Default)]
622#[non_exhaustive]
623pub struct HostCall {
624 name: String,
625 data: JsonValue,
626 reply: Option<HostReply>,
627 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 pub fn name(&self) -> &str {
644 &self.name
645 }
646
647 pub fn data(&self) -> &JsonValue {
649 &self.data
650 }
651
652 pub fn take_data(&mut self) -> JsonValue {
654 std::mem::take(&mut self.data)
655 }
656
657 pub fn is_post(&self) -> bool {
659 self.reply.is_none()
660 }
661
662 pub fn resolve(self, value: JsonValue) {
664 self.reply(Ok(value));
665 }
666
667 pub fn reject(self, message: impl Into<String>) {
670 self.reply(Err(message.into()));
671 }
672
673 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 pub fn into_reply(mut self) -> Option<HostReply> {
683 self.reply.take()
684 }
685
686 pub fn sender(&self) -> HostSender {
694 HostSender {
695 caller: self.caller.clone(),
696 }
697 }
698}
699
700struct Caller {
703 tx: Sender<Message>,
704 closed: AtomicBool,
705 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 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#[derive(Clone, Default)]
741pub struct HostSender {
742 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 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 pub fn is_closed(&self) -> bool {
775 self.caller.as_ref().is_none_or(|c| c.is_closed())
776 }
777
778 pub fn closed(&self) -> HostSenderClosed {
781 HostSenderClosed {
782 caller: self.caller.clone(),
783 id: None,
784 }
785 }
786}
787
788#[must_use = "futures do nothing unless polled"]
790pub struct HostSenderClosed {
791 caller: Option<Arc<Caller>>,
792 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 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#[derive(Default)]
844#[non_exhaustive]
845pub struct OpenUrlRequest {
846 url: String,
847 reply: Option<UrlReply>,
848}
849
850struct 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 pub fn url(&self) -> &str {
869 &self.url
870 }
871
872 pub fn handled(self) {
875 self.answer(true);
876 }
877
878 pub fn decline(self) {
880 self.answer(false);
881 }
882
883 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#[derive(Default)]
911#[non_exhaustive]
912pub struct HostReply {
913 id: u64,
914 name: String,
915 tx: Option<Sender<Message>>,
917 calls: Option<Arc<CallCount>>,
919 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 pub fn resolve(self, value: JsonValue) {
935 self.reply(Ok(value));
936 }
937
938 pub fn reject(self, message: impl Into<String>) {
940 self.reply(Err(message.into()));
941 }
942
943 pub fn reply(mut self, result: Result<JsonValue, String>) {
945 self.send(result);
946 self.answered();
947 }
948
949 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 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 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 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 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 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 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 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 {
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 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}