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, 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}
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 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 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 pub fn params(&self) -> serde_json::Map<String, JsonValue> {
122 self.lock().params.clone()
123 }
124
125 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 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 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 #[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 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 pub fn remove_open_url_handler(&self) {
205 self.lock().url_handler = None;
206 }
207
208 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 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 #[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
257pub(crate) struct HostAttachment {
259 channel: HostChannel,
260 id: u64,
261 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 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 drop(discarded);
292 }
293}
294
295#[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 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#[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 pub fn name(&self) -> &str {
387 &self.name
388 }
389
390 pub fn data(&self) -> &JsonValue {
392 &self.data
393 }
394
395 pub fn take_data(&mut self) -> JsonValue {
397 std::mem::take(&mut self.data)
398 }
399
400 pub fn is_post(&self) -> bool {
402 self.reply.is_none()
403 }
404
405 pub fn resolve(self, value: JsonValue) {
407 self.reply(Ok(value));
408 }
409
410 pub fn reject(self, message: impl Into<String>) {
413 self.reply(Err(message.into()));
414 }
415
416 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 pub fn into_reply(mut self) -> Option<HostReply> {
426 self.reply.take()
427 }
428}
429
430#[derive(Default)]
436#[non_exhaustive]
437pub struct OpenUrlRequest {
438 url: String,
439 reply: Option<UrlReply>,
440}
441
442struct 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 pub fn url(&self) -> &str {
461 &self.url
462 }
463
464 pub fn handled(self) {
467 self.answer(true);
468 }
469
470 pub fn decline(self) {
472 self.answer(false);
473 }
474
475 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#[derive(Default)]
503#[non_exhaustive]
504pub struct HostReply {
505 id: u64,
506 name: String,
507 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 pub fn resolve(self, value: JsonValue) {
522 self.reply(Ok(value));
523 }
524
525 pub fn reject(self, message: impl Into<String>) {
527 self.reply(Err(message.into()));
528 }
529
530 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 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}