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 pub clipboard_images: Option<bool>,
58 pub refuse_connections: Option<RefuseConnections>,
63 pub updater: Option<Arc<dyn crate::runtime::UpdaterHost>>,
65 #[doc(hidden)]
68 pub app_url: crate::url_scheme::AppUrlCell,
69 pub base_url: Option<Arc<str>>,
72}
73
74pub type RefuseConnections = Arc<dyn Fn(&str) -> JsError + Send + Sync>;
79
80impl System {
81 pub fn new(
83 access: Arc<Access>,
84 data_dir: Option<PathBuf>,
85 paths: TrustedPaths,
86 quotas: Quotas,
87 ) -> Self {
88 Self {
89 access,
90 data_dir,
91 paths,
92 quotas,
93 locals: Locals::default(),
94 exit: None,
95 websocket: None,
96 filesystem: None,
97 os: crate::platform::Os::default(),
98 clipboard_images: None,
99 refuse_connections: None,
100 updater: None,
101 app_url: Default::default(),
102 base_url: None,
103 }
104 }
105
106 pub fn check_connection(&self, target: &str) -> Result<(), JsError> {
111 match &self.refuse_connections {
112 Some(refuse) => Err(refuse(target)),
113 None => Ok(()),
114 }
115 }
116
117 pub fn with_refuse_connections(mut self, refuse: Option<RefuseConnections>) -> Self {
120 self.refuse_connections = refuse;
121 self
122 }
123
124 pub fn with_websocket(
126 mut self,
127 websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
128 ) -> Self {
129 self.websocket = websocket;
130 self
131 }
132
133 pub fn with_updater(mut self, updater: Option<Arc<dyn crate::runtime::UpdaterHost>>) -> Self {
136 self.updater = updater;
137 self
138 }
139
140 #[doc(hidden)]
142 pub fn with_app_url(mut self, app_url: crate::url_scheme::AppUrlCell) -> Self {
143 self.app_url = app_url;
144 self
145 }
146
147 pub fn with_base_url(mut self, base_url: Option<Arc<str>>) -> Self {
149 self.base_url = base_url;
150 self
151 }
152
153 pub fn with_filesystem(
155 mut self,
156 filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
157 ) -> Self {
158 self.filesystem = filesystem;
159 self
160 }
161
162 pub fn with_os(mut self, os: crate::platform::Os) -> Self {
164 self.os = os;
165 self
166 }
167
168 pub fn with_clipboard_images(mut self, clipboard_images: Option<bool>) -> Self {
172 self.clipboard_images = clipboard_images;
173 self
174 }
175
176 pub fn with_locals(mut self, locals: Locals) -> Self {
178 self.locals = locals;
179 self
180 }
181
182 pub fn with_exit(mut self, exit: Option<Rc<dyn Fn(i32)>>) -> Self {
184 self.exit = exit;
185 self
186 }
187}
188
189pub trait Local: Default + 'static {
192 fn close(&self) {}
195}
196
197type Entry = (TypeId, Rc<dyn Any>, fn(&dyn Any));
198
199#[derive(Clone, Default)]
203pub struct Locals(Rc<RefCell<Vec<Entry>>>);
204
205impl Locals {
206 pub fn get<T: Local>(&self) -> Rc<T> {
208 let id = TypeId::of::<T>();
209 if let Some((_, local, _)) = self.0.borrow().iter().find(|(t, ..)| *t == id) {
210 return local
211 .clone()
212 .downcast()
213 .expect("the type it is filed under");
214 }
215 let local = Rc::new(T::default());
216 let close: fn(&dyn Any) = |local| {
217 if let Some(local) = local.downcast_ref::<T>() {
218 local.close();
219 }
220 };
221 self.0.borrow_mut().push((id, local.clone(), close));
222 local
223 }
224
225 pub fn close_all(&self) {
228 let locals = std::mem::take(&mut *self.0.borrow_mut());
229 for (_, local, close) in &locals {
230 close(&**local);
231 }
232 }
233}
234
235#[derive(Clone, Copy)]
239pub struct CallCx<'a> {
240 host: &'a dyn JsHost,
241}
242
243impl<'a> CallCx<'a> {
244 #[doc(hidden)]
245 pub fn new(host: &'a dyn JsHost) -> Self {
246 Self { host }
247 }
248
249 pub fn start(&self, work: impl Future<Output = ()> + 'static) {
252 self.host.start_task(Box::new(move || {
253 Box::pin(async move {
254 work.await;
255 Ok(Box::new(()) as Box<dyn super::ToJs>)
256 })
257 }));
258 }
259
260 pub fn on_cleanup(&self, f: impl FnOnce() + 'static) -> Cleanup {
266 Cleanup(Some(self.host.on_cleanup(Box::new(f))))
267 }
268}
269
270pub struct Cleanup(Option<Box<dyn FnOnce()>>);
273
274impl Cleanup {
275 pub fn release(mut self) {
277 if let Some(release) = self.0.take() {
278 release();
279 }
280 }
281}
282
283impl fmt::Debug for Cleanup {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 f.write_str("Cleanup")
286 }
287}
288
289#[derive(Default)]
299#[non_exhaustive]
300pub struct Stop {
301 run: Rc<StopOnce>,
302}
303
304type StopOnce = RefCell<Option<Box<dyn FnOnce()>>>;
306
307impl Stop {
308 pub fn new(f: impl FnOnce() + 'static) -> Self {
310 Self {
311 run: Rc::new(RefCell::new(Some(Box::new(f)))),
312 }
313 }
314
315 fn run(run: &StopOnce) {
316 let f = run.borrow_mut().take();
318 if let Some(f) = f {
319 f();
320 }
321 }
322}
323
324impl fmt::Debug for Stop {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 f.write_str("Stop")
327 }
328}
329
330impl Ret for Stop {
331 fn ts_type(_types: &mut super::TsTypes) -> String {
332 "() => void".into()
333 }
334
335 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<super::JsOwned<'a>, super::PropError> {
336 let run = self.run;
337 let release = host.on_cleanup(Box::new({
338 let run = run.clone();
339 move || Self::run(&run)
340 }));
341 let release = RefCell::new(Some(release));
342 let stop = host.new_function(Box::new(move || {
343 let release = release.borrow_mut().take();
346 if let Some(release) = release {
347 release();
348 }
349 Self::run(&run);
350 }))?;
351 Ok(super::JsOwned::new(host, stop))
352 }
353}
354
355impl fmt::Debug for System {
356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357 f.debug_struct("System")
358 .field("data_dir", &self.data_dir)
359 .field("os", &self.os)
360 .field("clipboard_images", &self.clipboard_images)
361 .finish_non_exhaustive()
362 }
363}
364
365#[derive(Clone, Default)]
369pub struct Quotas(Rc<RefCell<FxHashMap<&'static str, usize>>>);
370
371impl Quotas {
372 pub fn take(&self, kind: &'static str, max: usize) -> Option<Held> {
375 self.reserve(kind, 1, max)
376 }
377
378 pub fn reserve(&self, kind: &'static str, amount: usize, max: usize) -> Option<Held> {
381 let mut counts = self.0.borrow_mut();
382 let count = counts.entry(kind).or_default();
383 let total = count.checked_add(amount).filter(|&total| total <= max)?;
384 *count = total;
385 Some(Held {
386 quotas: self.clone(),
387 kind,
388 amount,
389 })
390 }
391
392 pub fn held(&self, kind: &'static str) -> usize {
394 self.0.borrow().get(kind).copied().unwrap_or(0)
395 }
396}
397
398pub struct Held {
401 quotas: Quotas,
402 kind: &'static str,
403 amount: usize,
404}
405
406impl Held {
407 pub fn amount(&self) -> usize {
409 self.amount
410 }
411}
412
413impl Drop for Held {
414 fn drop(&mut self) {
415 if let Some(count) = self.quotas.0.borrow_mut().get_mut(self.kind) {
416 *count -= self.amount;
417 }
418 }
419}
420
421impl fmt::Debug for Held {
422 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423 write!(f, "Held({} {})", self.amount, self.kind)
424 }
425}
426
427#[must_use = "the work runs only when the call returns it"]
434pub struct Later<T>(Pin<Box<dyn Future<Output = Result<T, Thrown>>>>);
435
436impl<T: Ret + 'static> Later<T> {
437 pub fn new<E: IntoThrown>(work: impl Future<Output = Result<T, E>> + 'static) -> Self {
439 Self(Box::pin(async move {
440 work.await.map_err(IntoThrown::into_thrown)
441 }))
442 }
443
444 pub(crate) fn into_future(self) -> ModuleFuture {
445 Box::pin(async move {
446 let result: JsResult = match self.0.await {
447 Ok(v) => Ok(Box::new(v)),
448 Err(e) => Err(e),
449 };
450 result
451 })
452 }
453}
454
455impl<T> fmt::Debug for Later<T> {
456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 f.write_str("Later")
458 }
459}
460
461#[derive(Debug, Clone, PartialEq, Eq)]
467pub enum JsError {
468 Type(String),
470 Range(String),
472 Error(String),
474 Fields(Box<ErrorFields>),
476}
477
478#[derive(Debug, Clone, Copy, PartialEq, Eq)]
480pub enum ErrorClass {
481 Type,
483 Range,
485 Error,
487}
488
489#[derive(Debug, Clone, PartialEq, Eq)]
492pub struct ErrorFields {
493 pub class: ErrorClass,
495 pub message: String,
497 pub fields: Vec<(&'static str, JsonValue)>,
499}
500
501impl ErrorFields {
502 fn of(class: ErrorClass, message: String) -> Self {
503 Self {
504 class,
505 message,
506 fields: Vec::new(),
507 }
508 }
509
510 pub fn field(&self, key: &str) -> Option<&JsonValue> {
512 self.fields.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
513 }
514}
515
516impl JsError {
517 pub fn with(self, key: &'static str, value: impl Into<JsonValue>) -> Self {
520 let mut fields = match self {
521 JsError::Type(m) => ErrorFields::of(ErrorClass::Type, m),
522 JsError::Range(m) => ErrorFields::of(ErrorClass::Range, m),
523 JsError::Error(m) => ErrorFields::of(ErrorClass::Error, m),
524 JsError::Fields(f) => *f,
525 };
526 fields.fields.retain(|(k, _)| *k != key);
527 fields.fields.push((key, value.into()));
528 JsError::Fields(Box::new(fields))
529 }
530
531 pub fn with_code(self, code: &str) -> Self {
533 self.with("code", code)
534 }
535
536 pub fn access_denied(
542 message: impl Into<String>,
543 permission: &str,
544 resource: impl Into<String>,
545 ) -> Self {
546 JsError::Error(message.into())
547 .with_code(codes::ACCESS_DENIED)
548 .with("permission", permission)
549 .with("resource", resource.into())
550 }
551
552 pub fn message(&self) -> &str {
554 match self {
555 JsError::Type(m) | JsError::Range(m) | JsError::Error(m) => m,
556 JsError::Fields(f) => &f.message,
557 }
558 }
559
560 pub fn code(&self) -> Option<&str> {
562 match self {
563 JsError::Fields(f) => f.field("code").and_then(JsonValue::as_str),
564 _ => None,
565 }
566 }
567}
568
569pub mod codes {
573 pub const ACCESS_DENIED: &str = "ERR_ACCESS_DENIED";
576 pub const UNAVAILABLE: &str = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM";
578 pub const QUOTA_EXCEEDED: &str = "ERR_NSH_QUOTA_EXCEEDED";
581 pub const TIMED_OUT: &str = "ETIMEDOUT";
583 pub const HOST_ERROR: &str = "ERR_NSH_HOST_ERROR";
586 pub const WEBVIEW_SCRIPT: &str = "ERR_NSH_WEBVIEW_SCRIPT";
589 pub const WEBVIEW_ABORTED: &str = "ERR_NSH_WEBVIEW_ABORTED";
593 pub const WEBVIEW_TERMINATED: &str = "ERR_NSH_WEBVIEW_TERMINATED";
597 pub const DOWNLOAD_DISCARDED: &str = "ERR_NSH_DOWNLOAD_DISCARDED";
601 pub const DOWNLOAD_DESTINATION: &str = "ERR_NSH_DOWNLOAD_DESTINATION";
605 pub const DOWNLOAD_NETWORK: &str = "ERR_NSH_DOWNLOAD_NETWORK";
607 pub const DOWNLOAD_SIZE: &str = "ERR_NSH_DOWNLOAD_SIZE";
610 pub const DOWNLOAD_STATE: &str = "ERR_NSH_DOWNLOAD_STATE";
613}
614
615impl From<std::io::Error> for JsError {
619 fn from(error: std::io::Error) -> Self {
620 let message = error.to_string();
621 match io_code(&error) {
622 Some(code) => JsError::Error(message).with_code(code),
623 None => JsError::Error(message),
624 }
625 }
626}
627
628pub fn io_code(error: &std::io::Error) -> Option<&'static str> {
631 use std::io::ErrorKind as K;
632 #[cfg(unix)]
633 if let Some(code) = error.raw_os_error().and_then(errno_name) {
634 return Some(code);
635 }
636 Some(match error.kind() {
637 K::NotFound => "ENOENT",
638 K::PermissionDenied => "EACCES",
639 K::AlreadyExists => "EEXIST",
640 K::NotADirectory => "ENOTDIR",
641 K::IsADirectory => "EISDIR",
642 K::DirectoryNotEmpty => "ENOTEMPTY",
643 K::InvalidFilename => "ENAMETOOLONG",
644 K::ReadOnlyFilesystem => "EROFS",
645 K::CrossesDevices => "EXDEV",
646 K::StorageFull => "ENOSPC",
647 K::QuotaExceeded => "EDQUOT",
648 K::FileTooLarge => "EFBIG",
649 K::ResourceBusy => "EBUSY",
650 K::ExecutableFileBusy => "ETXTBSY",
651 K::Deadlock => "EDEADLK",
652 K::TooManyLinks => "EMLINK",
653 K::ArgumentListTooLong => "E2BIG",
654 K::Interrupted => "EINTR",
655 K::WouldBlock => "EAGAIN",
656 K::TimedOut => "ETIMEDOUT",
657 K::BrokenPipe => "EPIPE",
658 K::ConnectionRefused => "ECONNREFUSED",
659 K::ConnectionReset => "ECONNRESET",
660 K::ConnectionAborted => "ECONNABORTED",
661 K::NotConnected => "ENOTCONN",
662 K::AddrInUse => "EADDRINUSE",
663 K::AddrNotAvailable => "EADDRNOTAVAIL",
664 K::HostUnreachable => "EHOSTUNREACH",
665 K::NetworkUnreachable => "ENETUNREACH",
666 K::NetworkDown => "ENETDOWN",
667 K::InvalidInput => "EINVAL",
668 K::Unsupported => "ENOTSUP",
669 K::OutOfMemory => "ENOMEM",
670 _ => return None,
671 })
672}
673
674#[cfg(unix)]
677fn errno_name(errno: i32) -> Option<&'static str> {
678 let names: &[(i32, &str)] = &[
679 (libc::ENOENT, "ENOENT"),
680 (libc::EACCES, "EACCES"),
681 (libc::EPERM, "EPERM"),
682 (libc::EEXIST, "EEXIST"),
683 (libc::ENOTDIR, "ENOTDIR"),
684 (libc::EISDIR, "EISDIR"),
685 (libc::ENOTEMPTY, "ENOTEMPTY"),
686 (libc::ELOOP, "ELOOP"),
687 (libc::ENAMETOOLONG, "ENAMETOOLONG"),
688 (libc::EBADF, "EBADF"),
689 (libc::EBUSY, "EBUSY"),
690 (libc::EINVAL, "EINVAL"),
691 (libc::EMFILE, "EMFILE"),
692 (libc::ENFILE, "ENFILE"),
693 (libc::ENOSPC, "ENOSPC"),
694 (libc::EROFS, "EROFS"),
695 (libc::EXDEV, "EXDEV"),
696 (libc::EAGAIN, "EAGAIN"),
697 (libc::ENXIO, "ENXIO"),
698 (libc::ETXTBSY, "ETXTBSY"),
699 (libc::EFBIG, "EFBIG"),
700 (libc::EMLINK, "EMLINK"),
701 (libc::EPIPE, "EPIPE"),
702 (libc::ENOEXEC, "ENOEXEC"),
703 ];
704 names
705 .iter()
706 .find(|(n, _)| *n == errno)
707 .map(|(_, name)| *name)
708}
709
710pub trait IntoThrown {
713 fn into_thrown(self) -> Thrown;
715}
716
717impl<E: fmt::Display> IntoThrown for E {
718 fn into_thrown(self) -> Thrown {
719 Thrown::Error(self.to_string())
720 }
721}
722
723impl IntoThrown for JsError {
724 fn into_thrown(self) -> Thrown {
725 match self {
726 JsError::Type(m) => Thrown::Type(m),
727 JsError::Range(m) => Thrown::Range(m),
728 JsError::Error(m) => Thrown::Error(m),
729 JsError::Fields(f) => Thrown::Fields(f),
730 }
731 }
732}
733
734#[cfg(test)]
735mod tests {
736 use crate::{
737 JsonValue,
738 element::{JsValue, Registry, declarations, json_host},
739 prelude::*,
740 };
741
742 #[module]
743 struct Files;
744
745 #[module(flat)]
746 impl Files {
747 pub(crate) fn read(path: String, sys: System) -> Result<Later<Vec<u8>>, JsError> {
749 let _ = (path, sys);
750 Ok(Later::new(async { Ok::<_, String>(vec![1]) }))
751 }
752
753 pub(crate) fn write(sys: System, bytes: Vec<u8>) -> u32 {
755 let _ = sys;
756 bytes.len() as u32
757 }
758
759 pub(crate) fn watch(path: String, cx: CallCx<'_>) {
761 cx.on_cleanup(move || drop(path));
762 cx.start(async {});
763 }
764
765 pub(crate) fn listen() -> Stop {
767 Stop::new(|| {})
768 }
769
770 #[getter]
772 pub(crate) fn root(sys: System) -> Option<String> {
773 sys.data_dir.map(|d| d.display().to_string())
774 }
775 }
776
777 #[class]
778 struct Handle;
779
780 #[class]
781 impl Handle {
782 pub(crate) fn next(&self, sys: System, size: Option<u32>) -> Later<Option<Vec<u8>>> {
784 let _ = (sys, size);
785 Later::new(async { Ok::<_, String>(None) })
786 }
787
788 #[overload(fn(event: String, #[args(index, label)] f: Callback<(u32, String)>) -> Instance<Handle>)]
790 pub(crate) fn on(this: Instance<Self>, event: String, cx: CallCx<'_>) -> Instance<Self> {
791 let _ = (event, cx);
792 this
793 }
794 }
795
796 #[test]
797 fn bytes_are_uint8_arrays_tasks_promises_and_the_system_no_parameter() {
798 let mut registry = Registry::ui_set("test/system");
799 registry.module::<Files>().class::<Handle>();
800 let d = declarations(®istry, &[]);
801 assert!(
802 d.contains("function read(path: string): Promise<Uint8Array>;"),
803 "{d}"
804 );
805 assert!(
806 d.contains("function write(bytes: Uint8Array): number;"),
807 "{d}"
808 );
809 assert!(
810 d.contains("next(size?: number | null): Promise<Uint8Array | null>;"),
811 "{d}"
812 );
813 assert!(d.contains("function watch(path: string): void;"), "{d}");
814 assert!(d.contains("function listen(): () => void;"), "{d}");
815 assert!(
816 d.contains(" on(event: string, f: (index: number, label: string) => void): Handle;"),
817 "{d}"
818 );
819 assert!(!d.contains("function root"), "{d}");
821 }
822
823 #[test]
824 fn bytes_convert_from_and_to_js() {
825 let host = json_host::JsonHost::default();
826 let raw = host.value(serde_json::json!([0, 7, 255]));
827 let bytes = <Vec<u8>>::from_js(crate::element::JsIn::new(&host, raw)).unwrap();
828 assert_eq!(bytes, [0, 7, 255]);
829 let out = bytes.to_js(&host).unwrap();
830 assert_eq!(host.read(out), Some(serde_json::json!([0, 7, 255])));
831 let bad = host.value(JsonValue::from("x"));
832 assert!(<Vec<u8>>::from_js(crate::element::JsIn::new(&host, bad)).is_err());
833 }
834
835 #[test]
836 fn a_stop_is_a_function_that_runs_once() {
837 use crate::element::Ret;
838 let host = json_host::JsonHost::default();
839 let runs = std::rc::Rc::new(std::cell::Cell::new(0));
840 let stop = Stop::new({
841 let runs = runs.clone();
842 move || runs.set(runs.get() + 1)
843 });
844 let f = stop.into_js(&host).unwrap().into_raw();
845 assert_eq!(
846 crate::element::JsHost::kind(&host, f),
847 crate::element::JsKind::Function
848 );
849 assert_eq!(runs.get(), 0);
850 host.call(f);
851 host.call(f);
852 assert_eq!(runs.get(), 1);
853 }
854
855 #[derive(Debug, JsObject)]
856 #[prop(exact)]
857 struct Options {
858 recursive: Option<bool>,
859 #[prop(skip_none)]
860 note: Option<String>,
861 }
862
863 #[test]
864 fn times_are_dates_and_exact_objects_refuse_other_keys() {
865 let host = json_host::JsonHost::default();
866 let time = std::time::UNIX_EPOCH + std::time::Duration::from_millis(1500);
867 let out = time.to_js(&host).unwrap();
868 assert_eq!(host.read(out), Some(serde_json::json!({ "$date": 1500.0 })));
869 let date = host.value(serde_json::json!({ "$date": -250.0 }));
870 let back = std::time::SystemTime::from_js(crate::element::JsIn::new(&host, date)).unwrap();
871 assert_eq!(
872 std::time::UNIX_EPOCH
873 .duration_since(back)
874 .unwrap()
875 .as_millis(),
876 250
877 );
878 let options = host.value(serde_json::json!({ "recursive": true }));
879 let options = Options::from_js(crate::element::JsIn::new(&host, options)).unwrap();
880 assert_eq!(options.recursive, Some(true));
881 let shown = Options {
882 recursive: None,
883 note: None,
884 }
885 .to_js(&host)
886 .unwrap();
887 assert_eq!(
888 host.read(shown),
889 Some(serde_json::json!({ "recursive": null }))
890 );
891 let typo = host.value(serde_json::json!({ "recursive": true, "typo": 1 }));
892 let error = Options::from_js(crate::element::JsIn::new(&host, typo)).unwrap_err();
893 assert_eq!(error.0, "unknown field `typo`");
894 }
895
896 #[test]
897 fn errors_carry_node_s_codes_thrown_and_rejected() {
898 use super::{ErrorClass, JsError, io_code};
899 use crate::element::{IntoThrown, Thrown};
900 let missing = std::io::Error::from(std::io::ErrorKind::NotFound);
901 assert_eq!(io_code(&missing), Some("ENOENT"));
902 #[cfg(unix)]
903 assert_eq!(
904 io_code(&std::io::Error::from_raw_os_error(libc::ELOOP)),
905 Some("ELOOP")
906 );
907 assert_eq!(io_code(&std::io::Error::other("x")), None);
908 let error = JsError::Type("denied".into())
909 .with_code("EPERM")
910 .with_code("EACCES")
911 .with("path", "a.txt");
912 assert_eq!((error.message(), error.code()), ("denied", Some("EACCES")));
913 let Thrown::Fields(fields) = error.clone().into_thrown() else {
914 panic!("fields go with the error");
915 };
916 assert_eq!(fields.class, ErrorClass::Type);
917 assert_eq!(fields.fields.len(), 2);
918 assert_eq!(JsError::from(missing).code(), Some("ENOENT"));
919 let later = super::Later::<u32>::new(async { Err::<u32, _>(error) });
921 let runtime = tokio::runtime::Builder::new_current_thread()
922 .build()
923 .unwrap();
924 let Err(Thrown::Fields(rejected)) = runtime.block_on(later.into_future()) else {
925 panic!("a rejection with fields");
926 };
927 assert_eq!(rejected.field("path"), Some(&serde_json::json!("a.txt")));
928 let later = super::Later::<u32>::new(async { Err::<u32, _>("plain") });
930 assert!(matches!(
931 runtime.block_on(later.into_future()),
932 Err(Thrown::Error(m)) if m == "plain"
933 ));
934 }
935
936 #[test]
937 fn quotas_count_what_is_held() {
938 let quotas = super::Quotas::default();
939 let a = quotas.take("k", 2).unwrap();
940 let _b = quotas.take("k", 2).unwrap();
941 assert!(quotas.take("k", 2).is_none());
942 drop(a);
943 assert_eq!(quotas.held("k"), 1);
944 assert!(quotas.take("other", 1).is_some());
945 }
946
947 #[test]
948 fn quotas_reserve_amounts_up_to_their_limit() {
949 let quotas = super::Quotas::default();
950 let a = quotas.reserve("bytes", 40, 64).unwrap();
951 assert!(quotas.reserve("bytes", 25, 64).is_none());
952 let b = quotas.reserve("bytes", 24, 64).unwrap();
953 assert_eq!((quotas.held("bytes"), a.amount()), (64, 40));
954 assert!(quotas.reserve("bytes", usize::MAX, usize::MAX).is_none());
955 drop(a);
956 assert_eq!(quotas.held("bytes"), 24);
957 drop(b);
958 assert!(quotas.reserve("bytes", 64, 64).is_some());
959 }
960}