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 element::{JsValue, Registry, declarations, json_host},
535 prelude::*,
536 };
537
538 #[module]
539 struct Files;
540
541 #[module(flat)]
542 impl Files {
543 pub(crate) fn read(path: String, sys: System) -> Result<Later<Vec<u8>>, JsError> {
545 let _ = (path, sys);
546 Ok(Later::new(async { Ok::<_, String>(vec![1]) }))
547 }
548
549 pub(crate) fn write(sys: System, bytes: Vec<u8>) -> u32 {
551 let _ = sys;
552 bytes.len() as u32
553 }
554
555 pub(crate) fn watch(path: String, cx: CallCx<'_>) {
557 cx.on_cleanup(move || drop(path));
558 cx.start(async {});
559 }
560
561 #[getter]
563 pub(crate) fn root(sys: System) -> Option<String> {
564 sys.data_dir.map(|d| d.display().to_string())
565 }
566 }
567
568 #[class]
569 struct Handle;
570
571 #[class]
572 impl Handle {
573 pub(crate) fn next(&self, sys: System, size: Option<u32>) -> Later<Option<Vec<u8>>> {
575 let _ = (sys, size);
576 Later::new(async { Ok::<_, String>(None) })
577 }
578
579 #[overload(fn(event: String, #[args(index, label)] f: Callback<(u32, String)>) -> Instance<Handle>)]
581 pub(crate) fn on(this: Instance<Self>, event: String, cx: CallCx<'_>) -> Instance<Self> {
582 let _ = (event, cx);
583 this
584 }
585 }
586
587 #[test]
588 fn bytes_are_uint8_arrays_tasks_promises_and_the_system_no_parameter() {
589 let mut registry = Registry::ui_set("test/system");
590 registry.module::<Files>().class::<Handle>();
591 let d = declarations(®istry, &[]);
592 assert!(
593 d.contains("function read(path: string): Promise<Uint8Array>;"),
594 "{d}"
595 );
596 assert!(
597 d.contains("function write(bytes: Uint8Array): number;"),
598 "{d}"
599 );
600 assert!(
601 d.contains("next(size?: number | null): Promise<Uint8Array | null>;"),
602 "{d}"
603 );
604 assert!(d.contains("function watch(path: string): void;"), "{d}");
605 assert!(
606 d.contains(" on(event: string, f: (index: number, label: string) => void): Handle;"),
607 "{d}"
608 );
609 assert!(!d.contains("function root"), "{d}");
611 }
612
613 #[test]
614 fn bytes_convert_from_and_to_js() {
615 let host = json_host::JsonHost::default();
616 let raw = host.value(serde_json::json!([0, 7, 255]));
617 let bytes = <Vec<u8>>::from_js(crate::element::JsIn::new(&host, raw)).unwrap();
618 assert_eq!(bytes, [0, 7, 255]);
619 let out = bytes.to_js(&host).unwrap();
620 assert_eq!(host.read(out), Some(serde_json::json!([0, 7, 255])));
621 let bad = host.value(JsonValue::from("x"));
622 assert!(<Vec<u8>>::from_js(crate::element::JsIn::new(&host, bad)).is_err());
623 }
624
625 #[derive(Debug, JsObject)]
626 #[prop(exact)]
627 struct Options {
628 recursive: Option<bool>,
629 #[prop(skip_none)]
630 note: Option<String>,
631 }
632
633 #[test]
634 fn times_are_dates_and_exact_objects_refuse_other_keys() {
635 let host = json_host::JsonHost::default();
636 let time = std::time::UNIX_EPOCH + std::time::Duration::from_millis(1500);
637 let out = time.to_js(&host).unwrap();
638 assert_eq!(host.read(out), Some(serde_json::json!({ "$date": 1500.0 })));
639 let date = host.value(serde_json::json!({ "$date": -250.0 }));
640 let back = std::time::SystemTime::from_js(crate::element::JsIn::new(&host, date)).unwrap();
641 assert_eq!(
642 std::time::UNIX_EPOCH
643 .duration_since(back)
644 .unwrap()
645 .as_millis(),
646 250
647 );
648 let options = host.value(serde_json::json!({ "recursive": true }));
649 let options = Options::from_js(crate::element::JsIn::new(&host, options)).unwrap();
650 assert_eq!(options.recursive, Some(true));
651 let shown = Options {
652 recursive: None,
653 note: None,
654 }
655 .to_js(&host)
656 .unwrap();
657 assert_eq!(
658 host.read(shown),
659 Some(serde_json::json!({ "recursive": null }))
660 );
661 let typo = host.value(serde_json::json!({ "recursive": true, "typo": 1 }));
662 let error = Options::from_js(crate::element::JsIn::new(&host, typo)).unwrap_err();
663 assert_eq!(error.0, "unknown field `typo`");
664 }
665
666 #[test]
667 fn errors_carry_node_s_codes_thrown_and_rejected() {
668 use super::{ErrorClass, JsError, io_code};
669 use crate::element::{IntoThrown, Thrown};
670 let missing = std::io::Error::from(std::io::ErrorKind::NotFound);
671 assert_eq!(io_code(&missing), Some("ENOENT"));
672 #[cfg(unix)]
673 assert_eq!(
674 io_code(&std::io::Error::from_raw_os_error(libc::ELOOP)),
675 Some("ELOOP")
676 );
677 assert_eq!(io_code(&std::io::Error::other("x")), None);
678 let error = JsError::Type("denied".into())
679 .with_code("EPERM")
680 .with_code("EACCES")
681 .with("path", "a.txt");
682 assert_eq!((error.message(), error.code()), ("denied", Some("EACCES")));
683 let Thrown::Fields(fields) = error.clone().into_thrown() else {
684 panic!("fields go with the error");
685 };
686 assert_eq!(fields.class, ErrorClass::Type);
687 assert_eq!(fields.fields.len(), 2);
688 assert_eq!(JsError::from(missing).code(), Some("ENOENT"));
689 let later = super::Later::<u32>::new(async { Err::<u32, _>(error) });
691 let runtime = tokio::runtime::Builder::new_current_thread()
692 .build()
693 .unwrap();
694 let Err(Thrown::Fields(rejected)) = runtime.block_on(later.into_future()) else {
695 panic!("a rejection with fields");
696 };
697 assert_eq!(rejected.field("path"), Some(&serde_json::json!("a.txt")));
698 let later = super::Later::<u32>::new(async { Err::<u32, _>("plain") });
700 assert!(matches!(
701 runtime.block_on(later.into_future()),
702 Err(Thrown::Error(m)) if m == "plain"
703 ));
704 }
705
706 #[test]
707 fn quotas_count_what_is_held() {
708 let quotas = super::Quotas::default();
709 let a = quotas.take("k", 2).unwrap();
710 let _b = quotas.take("k", 2).unwrap();
711 assert!(quotas.take("k", 2).is_none());
712 drop(a);
713 assert_eq!(quotas.held("k"), 1);
714 assert!(quotas.take("other", 1).is_some());
715 }
716
717 #[test]
718 fn quotas_reserve_amounts_up_to_their_limit() {
719 let quotas = super::Quotas::default();
720 let a = quotas.reserve("bytes", 40, 64).unwrap();
721 assert!(quotas.reserve("bytes", 25, 64).is_none());
722 let b = quotas.reserve("bytes", 24, 64).unwrap();
723 assert_eq!((quotas.held("bytes"), a.amount()), (64, 40));
724 assert!(quotas.reserve("bytes", usize::MAX, usize::MAX).is_none());
725 drop(a);
726 assert_eq!(quotas.held("bytes"), 24);
727 drop(b);
728 assert!(quotas.reserve("bytes", 64, 64).is_some());
729 }
730}