1use std::{
9 any::{Any, TypeId},
10 cell::RefCell,
11 fmt,
12 future::Future,
13 path::PathBuf,
14 pin::Pin,
15 rc::Rc,
16 sync::Arc,
17};
18
19use rustc_hash::FxHashMap;
20
21use super::{JsHost, Ret, Thrown, call::JsResult, module::ModuleFuture};
22use crate::{
23 JsonValue,
24 access::{Access, TrustedPaths},
25};
26
27#[derive(Clone, Default)]
33#[non_exhaustive]
34pub struct System {
35 pub access: Arc<Access>,
37 pub data_dir: Option<PathBuf>,
39 pub paths: TrustedPaths,
41 pub quotas: Quotas,
43 pub locals: Locals,
45 pub exit: Option<Rc<dyn Fn(i32)>>,
48 pub websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
50 pub filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
52 pub os: crate::platform::Os,
54}
55
56impl System {
57 pub fn new(
59 access: Arc<Access>,
60 data_dir: Option<PathBuf>,
61 paths: TrustedPaths,
62 quotas: Quotas,
63 ) -> Self {
64 Self {
65 access,
66 data_dir,
67 paths,
68 quotas,
69 locals: Locals::default(),
70 exit: None,
71 websocket: None,
72 filesystem: None,
73 os: crate::platform::Os::default(),
74 }
75 }
76
77 pub fn with_websocket(
79 mut self,
80 websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
81 ) -> Self {
82 self.websocket = websocket;
83 self
84 }
85
86 pub fn with_filesystem(
88 mut self,
89 filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
90 ) -> Self {
91 self.filesystem = filesystem;
92 self
93 }
94
95 pub fn with_os(mut self, os: crate::platform::Os) -> Self {
97 self.os = os;
98 self
99 }
100
101 pub fn with_locals(mut self, locals: Locals) -> Self {
103 self.locals = locals;
104 self
105 }
106
107 pub fn with_exit(mut self, exit: Option<Rc<dyn Fn(i32)>>) -> Self {
109 self.exit = exit;
110 self
111 }
112}
113
114pub trait Local: Default + 'static {
117 fn close(&self) {}
120}
121
122type Entry = (TypeId, Rc<dyn Any>, fn(&dyn Any));
123
124#[derive(Clone, Default)]
128pub struct Locals(Rc<RefCell<Vec<Entry>>>);
129
130impl Locals {
131 pub fn get<T: Local>(&self) -> Rc<T> {
133 let id = TypeId::of::<T>();
134 if let Some((_, local, _)) = self.0.borrow().iter().find(|(t, ..)| *t == id) {
135 return local
136 .clone()
137 .downcast()
138 .expect("the type it is filed under");
139 }
140 let local = Rc::new(T::default());
141 let close: fn(&dyn Any) = |local| {
142 if let Some(local) = local.downcast_ref::<T>() {
143 local.close();
144 }
145 };
146 self.0.borrow_mut().push((id, local.clone(), close));
147 local
148 }
149
150 pub fn close_all(&self) {
153 let locals = std::mem::take(&mut *self.0.borrow_mut());
154 for (_, local, close) in &locals {
155 close(&**local);
156 }
157 }
158}
159
160#[derive(Clone, Copy)]
164pub struct CallCx<'a> {
165 host: &'a dyn JsHost,
166}
167
168impl<'a> CallCx<'a> {
169 #[doc(hidden)]
170 pub fn new(host: &'a dyn JsHost) -> Self {
171 Self { host }
172 }
173
174 pub fn start(&self, work: impl Future<Output = ()> + 'static) {
177 self.host.start_task(Box::new(move || {
178 Box::pin(async move {
179 work.await;
180 Ok(Box::new(()) as Box<dyn super::ToJs>)
181 })
182 }));
183 }
184
185 pub fn on_cleanup(&self, f: impl FnOnce() + 'static) -> Cleanup {
191 Cleanup(Some(self.host.on_cleanup(Box::new(f))))
192 }
193}
194
195pub struct Cleanup(Option<Box<dyn FnOnce()>>);
198
199impl Cleanup {
200 pub fn release(mut self) {
202 if let Some(release) = self.0.take() {
203 release();
204 }
205 }
206}
207
208impl fmt::Debug for Cleanup {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.write_str("Cleanup")
211 }
212}
213
214impl fmt::Debug for System {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 f.debug_struct("System")
217 .field("data_dir", &self.data_dir)
218 .field("os", &self.os)
219 .finish_non_exhaustive()
220 }
221}
222
223#[derive(Clone, Default)]
227pub struct Quotas(Rc<RefCell<FxHashMap<&'static str, usize>>>);
228
229impl Quotas {
230 pub fn take(&self, kind: &'static str, max: usize) -> Option<Held> {
233 self.reserve(kind, 1, max)
234 }
235
236 pub fn reserve(&self, kind: &'static str, amount: usize, max: usize) -> Option<Held> {
239 let mut counts = self.0.borrow_mut();
240 let count = counts.entry(kind).or_default();
241 let total = count.checked_add(amount).filter(|&total| total <= max)?;
242 *count = total;
243 Some(Held {
244 quotas: self.clone(),
245 kind,
246 amount,
247 })
248 }
249
250 pub fn held(&self, kind: &'static str) -> usize {
252 self.0.borrow().get(kind).copied().unwrap_or(0)
253 }
254}
255
256pub struct Held {
259 quotas: Quotas,
260 kind: &'static str,
261 amount: usize,
262}
263
264impl Held {
265 pub fn amount(&self) -> usize {
267 self.amount
268 }
269}
270
271impl Drop for Held {
272 fn drop(&mut self) {
273 if let Some(count) = self.quotas.0.borrow_mut().get_mut(self.kind) {
274 *count -= self.amount;
275 }
276 }
277}
278
279impl fmt::Debug for Held {
280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 write!(f, "Held({} {})", self.amount, self.kind)
282 }
283}
284
285#[must_use = "the work runs only when the call returns it"]
292pub struct Later<T>(Pin<Box<dyn Future<Output = Result<T, Thrown>>>>);
293
294impl<T: Ret + 'static> Later<T> {
295 pub fn new<E: IntoThrown>(work: impl Future<Output = Result<T, E>> + 'static) -> Self {
297 Self(Box::pin(async move {
298 work.await.map_err(IntoThrown::into_thrown)
299 }))
300 }
301
302 pub(crate) fn into_future(self) -> ModuleFuture {
303 Box::pin(async move {
304 let result: JsResult = match self.0.await {
305 Ok(v) => Ok(Box::new(v)),
306 Err(e) => Err(e),
307 };
308 result
309 })
310 }
311}
312
313impl<T> fmt::Debug for Later<T> {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 f.write_str("Later")
316 }
317}
318
319#[derive(Debug, Clone, PartialEq, Eq)]
325pub enum JsError {
326 Type(String),
328 Range(String),
330 Error(String),
332 Fields(Box<ErrorFields>),
334}
335
336#[derive(Debug, Clone, Copy, PartialEq, Eq)]
338pub enum ErrorClass {
339 Type,
341 Range,
343 Error,
345}
346
347#[derive(Debug, Clone, PartialEq, Eq)]
350pub struct ErrorFields {
351 pub class: ErrorClass,
353 pub message: String,
355 pub fields: Vec<(&'static str, JsonValue)>,
357}
358
359impl ErrorFields {
360 fn of(class: ErrorClass, message: String) -> Self {
361 Self {
362 class,
363 message,
364 fields: Vec::new(),
365 }
366 }
367
368 pub fn field(&self, key: &str) -> Option<&JsonValue> {
370 self.fields.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
371 }
372}
373
374impl JsError {
375 pub fn with(self, key: &'static str, value: impl Into<JsonValue>) -> Self {
378 let mut fields = match self {
379 JsError::Type(m) => ErrorFields::of(ErrorClass::Type, m),
380 JsError::Range(m) => ErrorFields::of(ErrorClass::Range, m),
381 JsError::Error(m) => ErrorFields::of(ErrorClass::Error, m),
382 JsError::Fields(f) => *f,
383 };
384 fields.fields.retain(|(k, _)| *k != key);
385 fields.fields.push((key, value.into()));
386 JsError::Fields(Box::new(fields))
387 }
388
389 pub fn with_code(self, code: &str) -> Self {
391 self.with("code", code)
392 }
393
394 pub fn message(&self) -> &str {
396 match self {
397 JsError::Type(m) | JsError::Range(m) | JsError::Error(m) => m,
398 JsError::Fields(f) => &f.message,
399 }
400 }
401
402 pub fn code(&self) -> Option<&str> {
404 match self {
405 JsError::Fields(f) => f.field("code").and_then(JsonValue::as_str),
406 _ => None,
407 }
408 }
409}
410
411impl From<std::io::Error> for JsError {
415 fn from(error: std::io::Error) -> Self {
416 let message = error.to_string();
417 match io_code(&error) {
418 Some(code) => JsError::Error(message).with_code(code),
419 None => JsError::Error(message),
420 }
421 }
422}
423
424pub fn io_code(error: &std::io::Error) -> Option<&'static str> {
427 use std::io::ErrorKind as K;
428 #[cfg(unix)]
429 if let Some(code) = error.raw_os_error().and_then(errno_name) {
430 return Some(code);
431 }
432 Some(match error.kind() {
433 K::NotFound => "ENOENT",
434 K::PermissionDenied => "EACCES",
435 K::AlreadyExists => "EEXIST",
436 K::NotADirectory => "ENOTDIR",
437 K::IsADirectory => "EISDIR",
438 K::DirectoryNotEmpty => "ENOTEMPTY",
439 K::InvalidFilename => "ENAMETOOLONG",
440 K::ReadOnlyFilesystem => "EROFS",
441 K::CrossesDevices => "EXDEV",
442 K::StorageFull => "ENOSPC",
443 K::QuotaExceeded => "EDQUOT",
444 K::FileTooLarge => "EFBIG",
445 K::ResourceBusy => "EBUSY",
446 K::ExecutableFileBusy => "ETXTBSY",
447 K::Deadlock => "EDEADLK",
448 K::TooManyLinks => "EMLINK",
449 K::ArgumentListTooLong => "E2BIG",
450 K::Interrupted => "EINTR",
451 K::WouldBlock => "EAGAIN",
452 K::TimedOut => "ETIMEDOUT",
453 K::BrokenPipe => "EPIPE",
454 K::ConnectionRefused => "ECONNREFUSED",
455 K::ConnectionReset => "ECONNRESET",
456 K::ConnectionAborted => "ECONNABORTED",
457 K::NotConnected => "ENOTCONN",
458 K::AddrInUse => "EADDRINUSE",
459 K::AddrNotAvailable => "EADDRNOTAVAIL",
460 K::HostUnreachable => "EHOSTUNREACH",
461 K::NetworkUnreachable => "ENETUNREACH",
462 K::NetworkDown => "ENETDOWN",
463 K::InvalidInput => "EINVAL",
464 K::Unsupported => "ENOTSUP",
465 K::OutOfMemory => "ENOMEM",
466 _ => return None,
467 })
468}
469
470#[cfg(unix)]
473fn errno_name(errno: i32) -> Option<&'static str> {
474 let names: &[(i32, &str)] = &[
475 (libc::ENOENT, "ENOENT"),
476 (libc::EACCES, "EACCES"),
477 (libc::EPERM, "EPERM"),
478 (libc::EEXIST, "EEXIST"),
479 (libc::ENOTDIR, "ENOTDIR"),
480 (libc::EISDIR, "EISDIR"),
481 (libc::ENOTEMPTY, "ENOTEMPTY"),
482 (libc::ELOOP, "ELOOP"),
483 (libc::ENAMETOOLONG, "ENAMETOOLONG"),
484 (libc::EBADF, "EBADF"),
485 (libc::EBUSY, "EBUSY"),
486 (libc::EINVAL, "EINVAL"),
487 (libc::EMFILE, "EMFILE"),
488 (libc::ENFILE, "ENFILE"),
489 (libc::ENOSPC, "ENOSPC"),
490 (libc::EROFS, "EROFS"),
491 (libc::EXDEV, "EXDEV"),
492 (libc::EAGAIN, "EAGAIN"),
493 (libc::ENXIO, "ENXIO"),
494 (libc::ETXTBSY, "ETXTBSY"),
495 (libc::EFBIG, "EFBIG"),
496 (libc::EMLINK, "EMLINK"),
497 (libc::EPIPE, "EPIPE"),
498 (libc::ENOEXEC, "ENOEXEC"),
499 ];
500 names
501 .iter()
502 .find(|(n, _)| *n == errno)
503 .map(|(_, name)| *name)
504}
505
506pub trait IntoThrown {
509 fn into_thrown(self) -> Thrown;
511}
512
513impl<E: fmt::Display> IntoThrown for E {
514 fn into_thrown(self) -> Thrown {
515 Thrown::Error(self.to_string())
516 }
517}
518
519impl IntoThrown for JsError {
520 fn into_thrown(self) -> Thrown {
521 match self {
522 JsError::Type(m) => Thrown::Type(m),
523 JsError::Range(m) => Thrown::Range(m),
524 JsError::Error(m) => Thrown::Error(m),
525 JsError::Fields(f) => Thrown::Fields(f),
526 }
527 }
528}
529
530#[cfg(test)]
531mod tests {
532 use crate::{
533 JsonValue,
534 ui::{JsValue, Registry, declarations, json_host, prelude::*},
535 };
536
537 #[module]
538 struct Files;
539
540 #[module(flat)]
541 impl Files {
542 pub(crate) fn read(path: String, sys: System) -> Result<Later<Vec<u8>>, JsError> {
544 let _ = (path, sys);
545 Ok(Later::new(async { Ok::<_, String>(vec![1]) }))
546 }
547
548 pub(crate) fn write(sys: System, bytes: Vec<u8>) -> u32 {
550 let _ = sys;
551 bytes.len() as u32
552 }
553
554 pub(crate) fn watch(path: String, cx: CallCx<'_>) {
556 cx.on_cleanup(move || drop(path));
557 cx.start(async {});
558 }
559
560 #[getter]
562 pub(crate) fn root(sys: System) -> Option<String> {
563 sys.data_dir.map(|d| d.display().to_string())
564 }
565 }
566
567 #[class]
568 struct Handle;
569
570 #[class]
571 impl Handle {
572 pub(crate) fn next(&self, sys: System, size: Option<u32>) -> Later<Option<Vec<u8>>> {
574 let _ = (sys, size);
575 Later::new(async { Ok::<_, String>(None) })
576 }
577
578 #[overload(fn(event: String, #[args(index, label)] f: Callback<(u32, String)>) -> Instance<Handle>)]
580 pub(crate) fn on(this: Instance<Self>, event: String, cx: CallCx<'_>) -> Instance<Self> {
581 let _ = (event, cx);
582 this
583 }
584 }
585
586 #[test]
587 fn bytes_are_uint8_arrays_tasks_promises_and_the_system_no_parameter() {
588 let mut registry = Registry::ui_set("test/system");
589 registry.module::<Files>().class::<Handle>();
590 let d = declarations(®istry, &[]);
591 assert!(
592 d.contains("function read(path: string): Promise<Uint8Array>;"),
593 "{d}"
594 );
595 assert!(
596 d.contains("function write(bytes: Uint8Array): number;"),
597 "{d}"
598 );
599 assert!(
600 d.contains("next(size?: number | null): Promise<Uint8Array | null>;"),
601 "{d}"
602 );
603 assert!(d.contains("function watch(path: string): void;"), "{d}");
604 assert!(
605 d.contains(" on(event: string, f: (index: number, label: string) => void): Handle;"),
606 "{d}"
607 );
608 assert!(!d.contains("function root"), "{d}");
610 }
611
612 #[test]
613 fn bytes_convert_from_and_to_js() {
614 let host = json_host::JsonHost::default();
615 let raw = host.value(serde_json::json!([0, 7, 255]));
616 let bytes = <Vec<u8>>::from_js(crate::ui::JsIn::new(&host, raw)).unwrap();
617 assert_eq!(bytes, [0, 7, 255]);
618 let out = bytes.to_js(&host).unwrap();
619 assert_eq!(host.read(out), Some(serde_json::json!([0, 7, 255])));
620 let bad = host.value(JsonValue::from("x"));
621 assert!(<Vec<u8>>::from_js(crate::ui::JsIn::new(&host, bad)).is_err());
622 }
623
624 #[derive(Debug, JsObject)]
625 #[prop(exact)]
626 struct Options {
627 recursive: Option<bool>,
628 #[prop(skip_none)]
629 note: Option<String>,
630 }
631
632 #[test]
633 fn times_are_dates_and_exact_objects_refuse_other_keys() {
634 let host = json_host::JsonHost::default();
635 let time = std::time::UNIX_EPOCH + std::time::Duration::from_millis(1500);
636 let out = time.to_js(&host).unwrap();
637 assert_eq!(host.read(out), Some(serde_json::json!({ "$date": 1500.0 })));
638 let date = host.value(serde_json::json!({ "$date": -250.0 }));
639 let back = std::time::SystemTime::from_js(crate::ui::JsIn::new(&host, date)).unwrap();
640 assert_eq!(
641 std::time::UNIX_EPOCH
642 .duration_since(back)
643 .unwrap()
644 .as_millis(),
645 250
646 );
647 let options = host.value(serde_json::json!({ "recursive": true }));
648 let options = Options::from_js(crate::ui::JsIn::new(&host, options)).unwrap();
649 assert_eq!(options.recursive, Some(true));
650 let shown = Options {
651 recursive: None,
652 note: None,
653 }
654 .to_js(&host)
655 .unwrap();
656 assert_eq!(
657 host.read(shown),
658 Some(serde_json::json!({ "recursive": null }))
659 );
660 let typo = host.value(serde_json::json!({ "recursive": true, "typo": 1 }));
661 let error = Options::from_js(crate::ui::JsIn::new(&host, typo)).unwrap_err();
662 assert_eq!(error.0, "unknown field `typo`");
663 }
664
665 #[test]
666 fn errors_carry_node_s_codes_thrown_and_rejected() {
667 use super::{ErrorClass, JsError, io_code};
668 use crate::ui::{IntoThrown, Thrown};
669 let missing = std::io::Error::from(std::io::ErrorKind::NotFound);
670 assert_eq!(io_code(&missing), Some("ENOENT"));
671 #[cfg(unix)]
672 assert_eq!(
673 io_code(&std::io::Error::from_raw_os_error(libc::ELOOP)),
674 Some("ELOOP")
675 );
676 assert_eq!(io_code(&std::io::Error::other("x")), None);
677 let error = JsError::Type("denied".into())
678 .with_code("EPERM")
679 .with_code("EACCES")
680 .with("path", "a.txt");
681 assert_eq!((error.message(), error.code()), ("denied", Some("EACCES")));
682 let Thrown::Fields(fields) = error.clone().into_thrown() else {
683 panic!("fields go with the error");
684 };
685 assert_eq!(fields.class, ErrorClass::Type);
686 assert_eq!(fields.fields.len(), 2);
687 assert_eq!(JsError::from(missing).code(), Some("ENOENT"));
688 let later = super::Later::<u32>::new(async { Err::<u32, _>(error) });
690 let runtime = tokio::runtime::Builder::new_current_thread()
691 .build()
692 .unwrap();
693 let Err(Thrown::Fields(rejected)) = runtime.block_on(later.into_future()) else {
694 panic!("a rejection with fields");
695 };
696 assert_eq!(rejected.field("path"), Some(&serde_json::json!("a.txt")));
697 let later = super::Later::<u32>::new(async { Err::<u32, _>("plain") });
699 assert!(matches!(
700 runtime.block_on(later.into_future()),
701 Err(Thrown::Error(m)) if m == "plain"
702 ));
703 }
704
705 #[test]
706 fn quotas_count_what_is_held() {
707 let quotas = super::Quotas::default();
708 let a = quotas.take("k", 2).unwrap();
709 let _b = quotas.take("k", 2).unwrap();
710 assert!(quotas.take("k", 2).is_none());
711 drop(a);
712 assert_eq!(quotas.held("k"), 1);
713 assert!(quotas.take("other", 1).is_some());
714 }
715
716 #[test]
717 fn quotas_reserve_amounts_up_to_their_limit() {
718 let quotas = super::Quotas::default();
719 let a = quotas.reserve("bytes", 40, 64).unwrap();
720 assert!(quotas.reserve("bytes", 25, 64).is_none());
721 let b = quotas.reserve("bytes", 24, 64).unwrap();
722 assert_eq!((quotas.held("bytes"), a.amount()), (64, 40));
723 assert!(quotas.reserve("bytes", usize::MAX, usize::MAX).is_none());
724 drop(a);
725 assert_eq!(quotas.held("bytes"), 24);
726 drop(b);
727 assert!(quotas.reserve("bytes", 64, 64).is_some());
728 }
729}