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 asset_base: Option<crate::image::AssetBase>,
46 pub paths: TrustedPaths,
48 pub quotas: Quotas,
50 pub locals: Locals,
52 pub exit: Option<Rc<dyn Fn(i32)>>,
55 pub websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
57 pub filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
59 pub os: crate::platform::Os,
61 pub clipboard_images: Option<bool>,
65 pub refuse_connections: Option<RefuseConnections>,
70 pub updater: Option<Arc<dyn crate::runtime::UpdaterHost>>,
72 #[doc(hidden)]
75 pub app_url: crate::url_scheme::AppUrlCell,
76 pub base_url: Option<Arc<str>>,
79}
80
81pub type RefuseConnections = Arc<dyn Fn(&str) -> JsError + Send + Sync>;
86
87impl System {
88 pub fn new(
90 access: Arc<Access>,
91 data_dir: Option<PathBuf>,
92 paths: TrustedPaths,
93 quotas: Quotas,
94 ) -> Self {
95 Self {
96 access,
97 data_dir,
98 asset_base: None,
99 paths,
100 quotas,
101 locals: Locals::default(),
102 exit: None,
103 websocket: None,
104 filesystem: None,
105 os: crate::platform::Os::default(),
106 clipboard_images: None,
107 refuse_connections: None,
108 updater: None,
109 app_url: Default::default(),
110 base_url: None,
111 }
112 }
113
114 pub fn check_connection(&self, target: &str) -> Result<(), JsError> {
119 match &self.refuse_connections {
120 Some(refuse) => Err(refuse(target)),
121 None => Ok(()),
122 }
123 }
124
125 pub fn readable_file(&self, path: &str) -> Result<PathBuf, JsError> {
141 crate::runtime::fs::readable_file(self, path)
142 }
143
144 pub fn with_refuse_connections(mut self, refuse: Option<RefuseConnections>) -> Self {
147 self.refuse_connections = refuse;
148 self
149 }
150
151 pub fn with_websocket(
153 mut self,
154 websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
155 ) -> Self {
156 self.websocket = websocket;
157 self
158 }
159
160 pub fn with_asset_base(mut self, base: Option<crate::image::AssetBase>) -> Self {
164 self.asset_base = base;
165 self
166 }
167
168 pub fn with_updater(mut self, updater: Option<Arc<dyn crate::runtime::UpdaterHost>>) -> Self {
171 self.updater = updater;
172 self
173 }
174
175 #[doc(hidden)]
177 pub fn with_app_url(mut self, app_url: crate::url_scheme::AppUrlCell) -> Self {
178 self.app_url = app_url;
179 self
180 }
181
182 pub fn with_base_url(mut self, base_url: Option<Arc<str>>) -> Self {
184 self.base_url = base_url;
185 self
186 }
187
188 pub fn with_filesystem(
190 mut self,
191 filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
192 ) -> Self {
193 self.filesystem = filesystem;
194 self
195 }
196
197 pub fn with_os(mut self, os: crate::platform::Os) -> Self {
199 self.os = os;
200 self
201 }
202
203 pub fn with_clipboard_images(mut self, clipboard_images: Option<bool>) -> Self {
207 self.clipboard_images = clipboard_images;
208 self
209 }
210
211 pub fn with_locals(mut self, locals: Locals) -> Self {
213 self.locals = locals;
214 self
215 }
216
217 pub fn with_exit(mut self, exit: Option<Rc<dyn Fn(i32)>>) -> Self {
219 self.exit = exit;
220 self
221 }
222}
223
224pub trait Local: Default + 'static {
227 fn close(&self) {}
230}
231
232type Entry = (TypeId, Rc<dyn Any>, fn(&dyn Any));
233
234#[derive(Clone, Default)]
238pub struct Locals(Rc<RefCell<Vec<Entry>>>);
239
240impl Locals {
241 pub fn get<T: Local>(&self) -> Rc<T> {
243 let id = TypeId::of::<T>();
244 if let Some((_, local, _)) = self.0.borrow().iter().find(|(t, ..)| *t == id) {
245 return local
246 .clone()
247 .downcast()
248 .expect("the type it is filed under");
249 }
250 let local = Rc::new(T::default());
251 let close: fn(&dyn Any) = |local| {
252 if let Some(local) = local.downcast_ref::<T>() {
253 local.close();
254 }
255 };
256 self.0.borrow_mut().push((id, local.clone(), close));
257 local
258 }
259
260 pub fn close_all(&self) {
263 let locals = std::mem::take(&mut *self.0.borrow_mut());
264 for (_, local, close) in &locals {
265 close(&**local);
266 }
267 }
268}
269
270#[derive(Clone, Copy)]
274pub struct CallCx<'a> {
275 host: &'a dyn JsHost,
276}
277
278impl<'a> CallCx<'a> {
279 #[doc(hidden)]
280 pub fn new(host: &'a dyn JsHost) -> Self {
281 Self { host }
282 }
283
284 pub fn start(&self, work: impl Future<Output = ()> + 'static) {
287 self.host.start_task(Box::new(move || {
288 Box::pin(async move {
289 work.await;
290 Ok(Box::new(()) as Box<dyn super::ToJs>)
291 })
292 }));
293 }
294
295 pub fn on_cleanup(&self, f: impl FnOnce() + 'static) -> Cleanup {
301 Cleanup(Some(self.host.on_cleanup(Box::new(f))))
302 }
303}
304
305pub struct Cleanup(Option<Box<dyn FnOnce()>>);
308
309impl Cleanup {
310 pub fn release(mut self) {
312 if let Some(release) = self.0.take() {
313 release();
314 }
315 }
316}
317
318impl fmt::Debug for Cleanup {
319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 f.write_str("Cleanup")
321 }
322}
323
324#[derive(Default)]
334#[non_exhaustive]
335pub struct Stop {
336 run: Rc<StopOnce>,
337}
338
339type StopOnce = RefCell<Option<Box<dyn FnOnce()>>>;
341
342impl Stop {
343 pub fn new(f: impl FnOnce() + 'static) -> Self {
345 Self {
346 run: Rc::new(RefCell::new(Some(Box::new(f)))),
347 }
348 }
349
350 fn run(run: &StopOnce) {
351 let f = run.borrow_mut().take();
353 if let Some(f) = f {
354 f();
355 }
356 }
357}
358
359impl fmt::Debug for Stop {
360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 f.write_str("Stop")
362 }
363}
364
365impl Ret for Stop {
366 fn ts_type(_types: &mut super::TsTypes) -> String {
367 "() => void".into()
368 }
369
370 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<super::JsOwned<'a>, super::PropError> {
371 let run = self.run;
372 let release = host.on_cleanup(Box::new({
373 let run = run.clone();
374 move || Self::run(&run)
375 }));
376 let release = RefCell::new(Some(release));
377 let stop = host.new_function(Box::new(move || {
378 let release = release.borrow_mut().take();
381 if let Some(release) = release {
382 release();
383 }
384 Self::run(&run);
385 }))?;
386 Ok(super::JsOwned::new(host, stop))
387 }
388}
389
390impl fmt::Debug for System {
391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392 f.debug_struct("System")
393 .field("data_dir", &self.data_dir)
394 .field("os", &self.os)
395 .field("clipboard_images", &self.clipboard_images)
396 .finish_non_exhaustive()
397 }
398}
399
400#[derive(Clone, Default)]
404pub struct Quotas(Rc<RefCell<FxHashMap<&'static str, usize>>>);
405
406impl Quotas {
407 pub fn take(&self, kind: &'static str, max: usize) -> Option<Held> {
410 self.reserve(kind, 1, max)
411 }
412
413 pub fn reserve(&self, kind: &'static str, amount: usize, max: usize) -> Option<Held> {
416 let mut counts = self.0.borrow_mut();
417 let count = counts.entry(kind).or_default();
418 let total = count.checked_add(amount).filter(|&total| total <= max)?;
419 *count = total;
420 Some(Held {
421 quotas: self.clone(),
422 kind,
423 amount,
424 })
425 }
426
427 pub fn held(&self, kind: &'static str) -> usize {
429 self.0.borrow().get(kind).copied().unwrap_or(0)
430 }
431}
432
433pub struct Held {
436 quotas: Quotas,
437 kind: &'static str,
438 amount: usize,
439}
440
441impl Held {
442 pub fn amount(&self) -> usize {
444 self.amount
445 }
446}
447
448impl Drop for Held {
449 fn drop(&mut self) {
450 if let Some(count) = self.quotas.0.borrow_mut().get_mut(self.kind) {
451 *count -= self.amount;
452 }
453 }
454}
455
456impl fmt::Debug for Held {
457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458 write!(f, "Held({} {})", self.amount, self.kind)
459 }
460}
461
462#[must_use = "the work runs only when the call returns it"]
469pub struct Later<T>(Pin<Box<dyn Future<Output = Result<T, Thrown>>>>);
470
471impl<T: Ret + 'static> Later<T> {
472 pub fn new<E: IntoThrown>(work: impl Future<Output = Result<T, E>> + 'static) -> Self {
474 Self(Box::pin(async move {
475 work.await.map_err(IntoThrown::into_thrown)
476 }))
477 }
478
479 pub(crate) fn into_future(self) -> ModuleFuture {
480 Box::pin(async move {
481 let result: JsResult = match self.0.await {
482 Ok(v) => Ok(v.boxed()),
483 Err(e) => Err(e),
484 };
485 result
486 })
487 }
488}
489
490impl<T> fmt::Debug for Later<T> {
491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492 f.write_str("Later")
493 }
494}
495
496#[derive(Debug, Clone, PartialEq, Eq)]
502pub enum JsError {
503 Type(String),
505 Range(String),
507 Error(String),
509 Fields(Box<ErrorFields>),
511}
512
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
515pub enum ErrorClass {
516 Type,
518 Range,
520 Error,
522}
523
524#[derive(Debug, Clone, PartialEq, Eq)]
527pub struct ErrorFields {
528 pub class: ErrorClass,
530 pub message: String,
532 pub fields: Vec<(&'static str, JsonValue)>,
534}
535
536impl ErrorFields {
537 fn of(class: ErrorClass, message: String) -> Self {
538 Self {
539 class,
540 message,
541 fields: Vec::new(),
542 }
543 }
544
545 pub fn field(&self, key: &str) -> Option<&JsonValue> {
547 self.fields.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
548 }
549}
550
551impl JsError {
552 pub fn with(self, key: &'static str, value: impl Into<JsonValue>) -> Self {
555 let mut fields = match self {
556 JsError::Type(m) => ErrorFields::of(ErrorClass::Type, m),
557 JsError::Range(m) => ErrorFields::of(ErrorClass::Range, m),
558 JsError::Error(m) => ErrorFields::of(ErrorClass::Error, m),
559 JsError::Fields(f) => *f,
560 };
561 fields.fields.retain(|(k, _)| *k != key);
562 fields.fields.push((key, value.into()));
563 JsError::Fields(Box::new(fields))
564 }
565
566 pub fn with_code(self, code: &str) -> Self {
568 self.with("code", code)
569 }
570
571 pub fn access_denied(
577 message: impl Into<String>,
578 permission: &str,
579 resource: impl Into<String>,
580 ) -> Self {
581 JsError::Error(message.into())
582 .with_code(codes::ACCESS_DENIED)
583 .with("permission", permission)
584 .with("resource", resource.into())
585 }
586
587 pub fn message(&self) -> &str {
589 match self {
590 JsError::Type(m) | JsError::Range(m) | JsError::Error(m) => m,
591 JsError::Fields(f) => &f.message,
592 }
593 }
594
595 pub fn code(&self) -> Option<&str> {
597 match self {
598 JsError::Fields(f) => f.field("code").and_then(JsonValue::as_str),
599 _ => None,
600 }
601 }
602}
603
604pub mod codes {
608 pub const ACCESS_DENIED: &str = "ERR_ACCESS_DENIED";
611 pub const UNAVAILABLE: &str = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM";
613 pub const QUOTA_EXCEEDED: &str = "ERR_NSH_QUOTA_EXCEEDED";
616 pub const TIMED_OUT: &str = "ETIMEDOUT";
618 pub const HOST_ERROR: &str = "ERR_NSH_HOST_ERROR";
621 pub const WEBVIEW_SCRIPT: &str = "ERR_NSH_WEBVIEW_SCRIPT";
624 pub const WEBVIEW_ABORTED: &str = "ERR_NSH_WEBVIEW_ABORTED";
628 pub const WEBVIEW_TERMINATED: &str = "ERR_NSH_WEBVIEW_TERMINATED";
632 pub const DOWNLOAD_DISCARDED: &str = "ERR_NSH_DOWNLOAD_DISCARDED";
636 pub const DOWNLOAD_DESTINATION: &str = "ERR_NSH_DOWNLOAD_DESTINATION";
640 pub const DOWNLOAD_NETWORK: &str = "ERR_NSH_DOWNLOAD_NETWORK";
642 pub const DOWNLOAD_SIZE: &str = "ERR_NSH_DOWNLOAD_SIZE";
645 pub const DOWNLOAD_STATE: &str = "ERR_NSH_DOWNLOAD_STATE";
648}
649
650impl From<std::io::Error> for JsError {
654 fn from(error: std::io::Error) -> Self {
655 let message = error.to_string();
656 match io_code(&error) {
657 Some(code) => JsError::Error(message).with_code(code),
658 None => JsError::Error(message),
659 }
660 }
661}
662
663pub fn io_code(error: &std::io::Error) -> Option<&'static str> {
666 use std::io::ErrorKind as K;
667 #[cfg(unix)]
668 if let Some(code) = error.raw_os_error().and_then(errno_name) {
669 return Some(code);
670 }
671 Some(match error.kind() {
672 K::NotFound => "ENOENT",
673 K::PermissionDenied => "EACCES",
674 K::AlreadyExists => "EEXIST",
675 K::NotADirectory => "ENOTDIR",
676 K::IsADirectory => "EISDIR",
677 K::DirectoryNotEmpty => "ENOTEMPTY",
678 K::InvalidFilename => "ENAMETOOLONG",
679 K::ReadOnlyFilesystem => "EROFS",
680 K::CrossesDevices => "EXDEV",
681 K::StorageFull => "ENOSPC",
682 K::QuotaExceeded => "EDQUOT",
683 K::FileTooLarge => "EFBIG",
684 K::ResourceBusy => "EBUSY",
685 K::ExecutableFileBusy => "ETXTBSY",
686 K::Deadlock => "EDEADLK",
687 K::TooManyLinks => "EMLINK",
688 K::ArgumentListTooLong => "E2BIG",
689 K::Interrupted => "EINTR",
690 K::WouldBlock => "EAGAIN",
691 K::TimedOut => "ETIMEDOUT",
692 K::BrokenPipe => "EPIPE",
693 K::ConnectionRefused => "ECONNREFUSED",
694 K::ConnectionReset => "ECONNRESET",
695 K::ConnectionAborted => "ECONNABORTED",
696 K::NotConnected => "ENOTCONN",
697 K::AddrInUse => "EADDRINUSE",
698 K::AddrNotAvailable => "EADDRNOTAVAIL",
699 K::HostUnreachable => "EHOSTUNREACH",
700 K::NetworkUnreachable => "ENETUNREACH",
701 K::NetworkDown => "ENETDOWN",
702 K::InvalidInput => "EINVAL",
703 K::Unsupported => "ENOTSUP",
704 K::OutOfMemory => "ENOMEM",
705 _ => return None,
706 })
707}
708
709#[cfg(unix)]
712fn errno_name(errno: i32) -> Option<&'static str> {
713 let names: &[(i32, &str)] = &[
714 (libc::ENOENT, "ENOENT"),
715 (libc::EACCES, "EACCES"),
716 (libc::EPERM, "EPERM"),
717 (libc::EEXIST, "EEXIST"),
718 (libc::ENOTDIR, "ENOTDIR"),
719 (libc::EISDIR, "EISDIR"),
720 (libc::ENOTEMPTY, "ENOTEMPTY"),
721 (libc::ELOOP, "ELOOP"),
722 (libc::ENAMETOOLONG, "ENAMETOOLONG"),
723 (libc::EBADF, "EBADF"),
724 (libc::EBUSY, "EBUSY"),
725 (libc::EINVAL, "EINVAL"),
726 (libc::EMFILE, "EMFILE"),
727 (libc::ENFILE, "ENFILE"),
728 (libc::ENOSPC, "ENOSPC"),
729 (libc::EROFS, "EROFS"),
730 (libc::EXDEV, "EXDEV"),
731 (libc::EAGAIN, "EAGAIN"),
732 (libc::ENXIO, "ENXIO"),
733 (libc::ETXTBSY, "ETXTBSY"),
734 (libc::EFBIG, "EFBIG"),
735 (libc::EMLINK, "EMLINK"),
736 (libc::EPIPE, "EPIPE"),
737 (libc::ENOEXEC, "ENOEXEC"),
738 ];
739 names
740 .iter()
741 .find(|(n, _)| *n == errno)
742 .map(|(_, name)| *name)
743}
744
745pub trait IntoThrown {
748 fn into_thrown(self) -> Thrown;
750}
751
752impl<E: fmt::Display> IntoThrown for E {
753 fn into_thrown(self) -> Thrown {
754 Thrown::Error(self.to_string())
755 }
756}
757
758impl IntoThrown for JsError {
759 fn into_thrown(self) -> Thrown {
760 match self {
761 JsError::Type(m) => Thrown::Type(m),
762 JsError::Range(m) => Thrown::Range(m),
763 JsError::Error(m) => Thrown::Error(m),
764 JsError::Fields(f) => Thrown::Fields(f),
765 }
766 }
767}
768
769#[cfg(test)]
770mod tests {
771 use crate::{
772 JsonValue,
773 element::{JsValue, Registry, declarations, json_host},
774 prelude::*,
775 };
776
777 #[module]
778 struct Files;
779
780 #[module(flat)]
781 impl Files {
782 pub(crate) fn read(path: String, sys: System) -> Result<Later<Vec<u8>>, JsError> {
784 let _ = (path, sys);
785 Ok(Later::new(async { Ok::<_, String>(vec![1]) }))
786 }
787
788 pub(crate) fn write(sys: System, bytes: Vec<u8>) -> u32 {
790 let _ = sys;
791 bytes.len() as u32
792 }
793
794 pub(crate) fn watch(path: String, cx: CallCx<'_>) {
796 cx.on_cleanup(move || drop(path));
797 cx.start(async {});
798 }
799
800 pub(crate) fn listen() -> Stop {
802 Stop::new(|| {})
803 }
804
805 #[getter]
807 pub(crate) fn root(sys: System) -> Option<String> {
808 sys.data_dir.map(|d| d.display().to_string())
809 }
810 }
811
812 #[class]
813 struct Handle;
814
815 #[class]
816 impl Handle {
817 pub(crate) fn next(&self, sys: System, size: Option<u32>) -> Later<Option<Vec<u8>>> {
819 let _ = (sys, size);
820 Later::new(async { Ok::<_, String>(None) })
821 }
822
823 #[overload(fn(event: String, #[args(index, label)] f: Callback<(u32, String)>) -> Instance<Handle>)]
825 pub(crate) fn on(this: Instance<Self>, event: String, cx: CallCx<'_>) -> Instance<Self> {
826 let _ = (event, cx);
827 this
828 }
829 }
830
831 #[test]
832 fn bytes_are_uint8_arrays_tasks_promises_and_the_system_no_parameter() {
833 let mut registry = Registry::ui_set("test/system");
834 registry.module::<Files>().class::<Handle>();
835 let d = declarations(®istry, &[]);
836 assert!(
837 d.contains("function read(path: string): Promise<Uint8Array>;"),
838 "{d}"
839 );
840 assert!(
841 d.contains("function write(bytes: Uint8Array): number;"),
842 "{d}"
843 );
844 assert!(
845 d.contains("next(size?: number | null): Promise<Uint8Array | null>;"),
846 "{d}"
847 );
848 assert!(d.contains("function watch(path: string): void;"), "{d}");
849 assert!(d.contains("function listen(): () => void;"), "{d}");
850 assert!(
851 d.contains(" on(event: string, f: (index: number, label: string) => void): Handle;"),
852 "{d}"
853 );
854 assert!(!d.contains("function root"), "{d}");
856 }
857
858 #[test]
859 fn bytes_convert_from_and_to_js() {
860 let host = json_host::JsonHost::default();
861 let raw = host.value(serde_json::json!([0, 7, 255]));
862 let bytes = <Vec<u8>>::from_js(crate::element::JsIn::new(&host, raw)).unwrap();
863 assert_eq!(bytes, [0, 7, 255]);
864 let out = bytes.to_js(&host).unwrap();
865 assert_eq!(host.read(out), Some(serde_json::json!([0, 7, 255])));
866 let bad = host.value(JsonValue::from("x"));
867 assert!(<Vec<u8>>::from_js(crate::element::JsIn::new(&host, bad)).is_err());
868 }
869
870 #[test]
871 fn a_stop_is_a_function_that_runs_once() {
872 use crate::element::Ret;
873 let host = json_host::JsonHost::default();
874 let runs = std::rc::Rc::new(std::cell::Cell::new(0));
875 let stop = Stop::new({
876 let runs = runs.clone();
877 move || runs.set(runs.get() + 1)
878 });
879 let f = stop.into_js(&host).unwrap().into_raw();
880 assert_eq!(
881 crate::element::JsHost::kind(&host, f),
882 crate::element::JsKind::Function
883 );
884 assert_eq!(runs.get(), 0);
885 host.call(f);
886 host.call(f);
887 assert_eq!(runs.get(), 1);
888 }
889
890 #[derive(Debug, JsObject)]
891 #[prop(exact)]
892 struct Options {
893 recursive: Option<bool>,
894 #[prop(skip_none)]
895 note: Option<String>,
896 }
897
898 #[test]
899 fn times_are_dates_and_exact_objects_refuse_other_keys() {
900 let host = json_host::JsonHost::default();
901 let time = std::time::UNIX_EPOCH + std::time::Duration::from_millis(1500);
902 let out = time.to_js(&host).unwrap();
903 assert_eq!(host.read(out), Some(serde_json::json!({ "$date": 1500.0 })));
904 let date = host.value(serde_json::json!({ "$date": -250.0 }));
905 let back = std::time::SystemTime::from_js(crate::element::JsIn::new(&host, date)).unwrap();
906 assert_eq!(
907 std::time::UNIX_EPOCH
908 .duration_since(back)
909 .unwrap()
910 .as_millis(),
911 250
912 );
913 let options = host.value(serde_json::json!({ "recursive": true }));
914 let options = Options::from_js(crate::element::JsIn::new(&host, options)).unwrap();
915 assert_eq!(options.recursive, Some(true));
916 let shown = Options {
917 recursive: None,
918 note: None,
919 }
920 .to_js(&host)
921 .unwrap();
922 assert_eq!(
923 host.read(shown),
924 Some(serde_json::json!({ "recursive": null }))
925 );
926 let typo = host.value(serde_json::json!({ "recursive": true, "typo": 1 }));
927 let error = Options::from_js(crate::element::JsIn::new(&host, typo)).unwrap_err();
928 assert_eq!(error.0, "unknown field `typo`");
929 }
930
931 #[test]
932 fn errors_carry_node_s_codes_thrown_and_rejected() {
933 use super::{ErrorClass, JsError, io_code};
934 use crate::element::{IntoThrown, Thrown};
935 let missing = std::io::Error::from(std::io::ErrorKind::NotFound);
936 assert_eq!(io_code(&missing), Some("ENOENT"));
937 #[cfg(unix)]
938 assert_eq!(
939 io_code(&std::io::Error::from_raw_os_error(libc::ELOOP)),
940 Some("ELOOP")
941 );
942 assert_eq!(io_code(&std::io::Error::other("x")), None);
943 let error = JsError::Type("denied".into())
944 .with_code("EPERM")
945 .with_code("EACCES")
946 .with("path", "a.txt");
947 assert_eq!((error.message(), error.code()), ("denied", Some("EACCES")));
948 let Thrown::Fields(fields) = error.clone().into_thrown() else {
949 panic!("fields go with the error");
950 };
951 assert_eq!(fields.class, ErrorClass::Type);
952 assert_eq!(fields.fields.len(), 2);
953 assert_eq!(JsError::from(missing).code(), Some("ENOENT"));
954 let later = super::Later::<u32>::new(async { Err::<u32, _>(error) });
956 let runtime = tokio::runtime::Builder::new_current_thread()
957 .build()
958 .unwrap();
959 let Err(Thrown::Fields(rejected)) = runtime.block_on(later.into_future()) else {
960 panic!("a rejection with fields");
961 };
962 assert_eq!(rejected.field("path"), Some(&serde_json::json!("a.txt")));
963 let later = super::Later::<u32>::new(async { Err::<u32, _>("plain") });
965 assert!(matches!(
966 runtime.block_on(later.into_future()),
967 Err(Thrown::Error(m)) if m == "plain"
968 ));
969 }
970
971 #[test]
972 fn quotas_count_what_is_held() {
973 let quotas = super::Quotas::default();
974 let a = quotas.take("k", 2).unwrap();
975 let _b = quotas.take("k", 2).unwrap();
976 assert!(quotas.take("k", 2).is_none());
977 drop(a);
978 assert_eq!(quotas.held("k"), 1);
979 assert!(quotas.take("other", 1).is_some());
980 }
981
982 #[test]
983 fn quotas_reserve_amounts_up_to_their_limit() {
984 let quotas = super::Quotas::default();
985 let a = quotas.reserve("bytes", 40, 64).unwrap();
986 assert!(quotas.reserve("bytes", 25, 64).is_none());
987 let b = quotas.reserve("bytes", 24, 64).unwrap();
988 assert_eq!((quotas.held("bytes"), a.amount()), (64, 40));
989 assert!(quotas.reserve("bytes", usize::MAX, usize::MAX).is_none());
990 drop(a);
991 assert_eq!(quotas.held("bytes"), 24);
992 drop(b);
993 assert!(quotas.reserve("bytes", 64, 64).is_some());
994 }
995}