Skip to main content

nsh_core/ui/
system.rs

1//! What the runtime's system modules (`net`, files, processes) need of the
2//! machinery beyond values: the VM's capabilities ([`System`], a parameter
3//! the call fills in rather than JS), work that starts in the JS call and
4//! finishes as a task ([`Later`]), and errors of a chosen JS class with
5//! Node's properties (`code`, `syscall`, `path`), thrown or rejected
6//! ([`JsError`]).
7
8use 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/// The VM a call comes from, as the host configured it: what the app may
28/// do and where its files are. A parameter `sys: System` of a module
29/// function or a class's member is not one JS passes: the call fills it
30/// in (an `async` one when it is made, as its arguments are converted). A
31/// host that configured nothing gives one that grants nothing.
32#[derive(Clone, Default)]
33#[non_exhaustive]
34pub struct System {
35    /// The capabilities: the app's declaration and the host's grant.
36    pub access: Arc<Access>,
37    /// The app's own data directory (`${dataDir}`), when the host has one.
38    pub data_dir: Option<PathBuf>,
39    /// The host's anchors of `${pluginDir}` and `${homeDir}`.
40    pub paths: TrustedPaths,
41    /// The VM's counts of limited resources.
42    pub quotas: Quotas,
43    /// The VM's own state of the runtime's modules (`process`'s children).
44    pub locals: Locals,
45    /// What the host does when the app asks to exit (`process.exit`);
46    /// `None`: it installed nothing.
47    pub exit: Option<Rc<dyn Fn(i32)>>,
48    /// The host WebSocket transport, when the platform supplies one.
49    pub websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
50    /// The host virtual filesystem, confined to this app’s data directory.
51    pub filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
52    /// The operating system the app runs on, as the host says.
53    pub os: crate::platform::Os,
54}
55
56impl System {
57    /// The VM's capabilities and directories.
58    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    /// Uses the host WebSocket transport instead of the native stack.
78    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    /// Uses the host virtual filesystem.
87    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    /// The operating system the app runs on.
96    pub fn with_os(mut self, os: crate::platform::Os) -> Self {
97        self.os = os;
98        self
99    }
100
101    /// The VM's state of the runtime modules, kept with it.
102    pub fn with_locals(mut self, locals: Locals) -> Self {
103        self.locals = locals;
104        self
105    }
106
107    /// What the host does with an exit request.
108    pub fn with_exit(mut self, exit: Option<Rc<dyn Fn(i32)>>) -> Self {
109        self.exit = exit;
110        self
111    }
112}
113
114/// One VM's state of a runtime module (a [`Locals`] entry): made on first
115/// use, closed when the VM goes.
116pub trait Local: Default + 'static {
117    /// Ends what the state owns, before the VM's callbacks go (children
118    /// killed, connections closed). Runs once.
119    fn close(&self) {}
120}
121
122type Entry = (TypeId, Rc<dyn Any>, fn(&dyn Any));
123
124/// One VM's states of the runtime modules ([`Local`]), one per type: the
125/// host keeps one per VM, hands it to every [`System`] and closes it when
126/// the VM goes.
127#[derive(Clone, Default)]
128pub struct Locals(Rc<RefCell<Vec<Entry>>>);
129
130impl Locals {
131    /// The VM's `T`, made the first time.
132    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    /// Closes every state, in the order they were made, and forgets them
151    /// (the host, when its VM goes).
152    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/// What a call that is not `async` can do beyond computing (a parameter
161/// `cx: CallCx`, filled in by the call): start a task of the core, and tie
162/// work to what owns the call in JS. Only in the call: it borrows it.
163#[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    /// Runs `work` as a task of the core, started in order with what JS
175    /// sent before this call (nothing waits for it).
176    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    /// Runs `f` when what owns the call in JS goes: the reactive owner it
186    /// runs under, or the module's run under hot reload (otherwise when the
187    /// VM goes, as everything else does). [`Cleanup::release`] unregisters
188    /// it once what it undoes ended by itself, so an owner that lives long
189    /// does not collect them.
190    pub fn on_cleanup(&self, f: impl FnOnce() + 'static) -> Cleanup {
191        Cleanup(Some(self.host.on_cleanup(Box::new(f))))
192    }
193}
194
195/// A cleanup [`CallCx::on_cleanup`] registered. Dropping it keeps the
196/// cleanup registered.
197pub struct Cleanup(Option<Box<dyn FnOnce()>>);
198
199impl Cleanup {
200    /// Unregisters the cleanup without running it (a no-op once it ran).
201    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/// One VM's counts of limited resources (open sockets, bytes of file data
224/// in flight, ...), by kind: a host keeps one per VM and hands it to every
225/// [`System`].
226#[derive(Clone, Default)]
227pub struct Quotas(Rc<RefCell<FxHashMap<&'static str, usize>>>);
228
229impl Quotas {
230    /// Takes one `kind` when fewer than `max` are held; dropping the
231    /// [`Held`] gives it back.
232    pub fn take(&self, kind: &'static str, max: usize) -> Option<Held> {
233        self.reserve(kind, 1, max)
234    }
235
236    /// Takes `amount` of `kind` (bytes, ...) when the held total stays at
237    /// most `max`; dropping the [`Held`] gives them back.
238    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    /// How many `kind` are held.
251    pub fn held(&self, kind: &'static str) -> usize {
252        self.0.borrow().get(kind).copied().unwrap_or(0)
253    }
254}
255
256/// Resources of a [`Quotas`] kind (one, or an amount), given back when
257/// dropped.
258pub struct Held {
259    quotas: Quotas,
260    kind: &'static str,
261    amount: usize,
262}
263
264impl Held {
265    /// How much it holds.
266    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/// Work a function or member that is not `async` starts in the JS call
286/// and finishes as a task of the core: JS gets a promise of `T`. What the
287/// call does before returning it (checking its arguments, taking a quota)
288/// throws as a synchronous call's error does; the task's `Err` rejects
289/// (a [`JsError`] with its class and properties, any other error as an
290/// `Error` with its message). TS: `Promise<T>`.
291#[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    /// The task's work: its value, or what the promise rejects with.
296    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/// An error of a chosen JS class: what `Result<T, JsError>` throws, and
320/// what a [`Later`] task's `Err(JsError)` rejects with (any other error
321/// type is an `Error` with its message). [`JsError::with_code`] and
322/// [`JsError::with`] give it properties, as Node's errors have
323/// (`error.code === "ENOENT"`; TS: `Error & { code?: string }`).
324#[derive(Debug, Clone, PartialEq, Eq)]
325pub enum JsError {
326    /// A `TypeError`: the call was not allowed or its value is wrong.
327    Type(String),
328    /// A `RangeError`: a value past a limit.
329    Range(String),
330    /// An `Error`.
331    Error(String),
332    /// One of those with properties.
333    Fields(Box<ErrorFields>),
334}
335
336/// The JS class of an error.
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
338pub enum ErrorClass {
339    /// `TypeError`.
340    Type,
341    /// `RangeError`.
342    Range,
343    /// `Error`.
344    Error,
345}
346
347/// An error with properties beside its message ([`JsError::Fields`],
348/// [`Thrown::Fields`]).
349#[derive(Debug, Clone, PartialEq, Eq)]
350pub struct ErrorFields {
351    /// Its class.
352    pub class: ErrorClass,
353    /// Its message.
354    pub message: String,
355    /// Its properties, in order (`code`, `syscall`, `path`, `errno`, ...).
356    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    /// Property `key`, if it has one.
369    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    /// The error with property `key` set to `value` (replacing one of the
376    /// same name).
377    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    /// The error with Node's `code` (`"ENOENT"`).
390    pub fn with_code(self, code: &str) -> Self {
391        self.with("code", code)
392    }
393
394    /// Its message.
395    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    /// Its `code`, if it has one.
403    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
411/// An I/O error as Node reports it: `Error` with the message and the
412/// `code` of its kind or OS error (`ENOENT`, `EACCES`, ...; none when it
413/// has no name).
414impl 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
424/// Node's code of I/O error `error`: its OS error's name when it has one,
425/// else its kind's.
426pub 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/// The name of Unix error number `errno`, for the ones a file, process or
471/// socket call gives that no [`std::io::ErrorKind`] names (`ELOOP`).
472#[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
506/// What an `Err` of a synchronous call throws: an `Error` with its message
507/// for any [`fmt::Display`] error, the chosen class for a [`JsError`].
508pub trait IntoThrown {
509    /// The exception.
510    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        /// Reads `path` later.
543        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        /// Writes `bytes`, at once.
549        pub(crate) fn write(sys: System, bytes: Vec<u8>) -> u32 {
550            let _ = sys;
551            bytes.len() as u32
552        }
553
554        /// Starts a task, tied to the call's owner.
555        pub(crate) fn watch(path: String, cx: CallCx<'_>) {
556            cx.on_cleanup(move || drop(path));
557            cx.start(async {});
558        }
559
560        /// Where the files are.
561        #[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        /// Its next bytes, later.
573        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        /// Itself, for chaining.
579        #[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(&registry, &[]);
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        // A getter is no flat export.
609        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        // A task's `Err(JsError)` rejects with the same.
689        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        // Any other error rejects with its message.
698        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}