Skip to main content

nsh_core/element/
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    /// Refuses the app's connections (`net` sockets and WebSockets, both
55    /// APIs) before they reach the network: a test's, which reaches it
56    /// only when the test asks (`nsh test`'s `network: "live"`). `None`:
57    /// they connect. `fetch` goes through the host's network instead.
58    pub refuse_connections: Option<RefuseConnections>,
59}
60
61/// What a host refuses the app's connections with
62/// ([`System::refuse_connections`]): given what the app connects to (a
63/// WebSocket's URL, a socket's `host:port`), the error its call fails
64/// with.
65pub type RefuseConnections = Arc<dyn Fn(&str) -> JsError + Send + Sync>;
66
67impl System {
68    /// The VM's capabilities and directories.
69    pub fn new(
70        access: Arc<Access>,
71        data_dir: Option<PathBuf>,
72        paths: TrustedPaths,
73        quotas: Quotas,
74    ) -> Self {
75        Self {
76            access,
77            data_dir,
78            paths,
79            quotas,
80            locals: Locals::default(),
81            exit: None,
82            websocket: None,
83            filesystem: None,
84            os: crate::platform::Os::default(),
85            refuse_connections: None,
86        }
87    }
88
89    /// Whether the app may connect to `target` (a WebSocket's URL, a
90    /// socket's `host:port`) as far as the host is concerned: the error
91    /// [`System::refuse_connections`] gives, when the host set one. The
92    /// app's capabilities are checked apart.
93    pub fn check_connection(&self, target: &str) -> Result<(), JsError> {
94        match &self.refuse_connections {
95            Some(refuse) => Err(refuse(target)),
96            None => Ok(()),
97        }
98    }
99
100    /// Refuses the app's connections with what `refuse` gives
101    /// ([`System::refuse_connections`]).
102    pub fn with_refuse_connections(mut self, refuse: Option<RefuseConnections>) -> Self {
103        self.refuse_connections = refuse;
104        self
105    }
106
107    /// Uses the host WebSocket transport instead of the native stack.
108    pub fn with_websocket(
109        mut self,
110        websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
111    ) -> Self {
112        self.websocket = websocket;
113        self
114    }
115
116    /// Uses the host virtual filesystem.
117    pub fn with_filesystem(
118        mut self,
119        filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
120    ) -> Self {
121        self.filesystem = filesystem;
122        self
123    }
124
125    /// The operating system the app runs on.
126    pub fn with_os(mut self, os: crate::platform::Os) -> Self {
127        self.os = os;
128        self
129    }
130
131    /// The VM's state of the runtime modules, kept with it.
132    pub fn with_locals(mut self, locals: Locals) -> Self {
133        self.locals = locals;
134        self
135    }
136
137    /// What the host does with an exit request.
138    pub fn with_exit(mut self, exit: Option<Rc<dyn Fn(i32)>>) -> Self {
139        self.exit = exit;
140        self
141    }
142}
143
144/// One VM's state of a runtime module (a [`Locals`] entry): made on first
145/// use, closed when the VM goes.
146pub trait Local: Default + 'static {
147    /// Ends what the state owns, before the VM's callbacks go (children
148    /// killed, connections closed). Runs once.
149    fn close(&self) {}
150}
151
152type Entry = (TypeId, Rc<dyn Any>, fn(&dyn Any));
153
154/// One VM's states of the runtime modules ([`Local`]), one per type: the
155/// host keeps one per VM, hands it to every [`System`] and closes it when
156/// the VM goes.
157#[derive(Clone, Default)]
158pub struct Locals(Rc<RefCell<Vec<Entry>>>);
159
160impl Locals {
161    /// The VM's `T`, made the first time.
162    pub fn get<T: Local>(&self) -> Rc<T> {
163        let id = TypeId::of::<T>();
164        if let Some((_, local, _)) = self.0.borrow().iter().find(|(t, ..)| *t == id) {
165            return local
166                .clone()
167                .downcast()
168                .expect("the type it is filed under");
169        }
170        let local = Rc::new(T::default());
171        let close: fn(&dyn Any) = |local| {
172            if let Some(local) = local.downcast_ref::<T>() {
173                local.close();
174            }
175        };
176        self.0.borrow_mut().push((id, local.clone(), close));
177        local
178    }
179
180    /// Closes every state, in the order they were made, and forgets them
181    /// (the host, when its VM goes).
182    pub fn close_all(&self) {
183        let locals = std::mem::take(&mut *self.0.borrow_mut());
184        for (_, local, close) in &locals {
185            close(&**local);
186        }
187    }
188}
189
190/// What a call that is not `async` can do beyond computing (a parameter
191/// `cx: CallCx`, filled in by the call): start a task of the core, and tie
192/// work to what owns the call in JS. Only in the call: it borrows it.
193#[derive(Clone, Copy)]
194pub struct CallCx<'a> {
195    host: &'a dyn JsHost,
196}
197
198impl<'a> CallCx<'a> {
199    #[doc(hidden)]
200    pub fn new(host: &'a dyn JsHost) -> Self {
201        Self { host }
202    }
203
204    /// Runs `work` as a task of the core, started in order with what JS
205    /// sent before this call (nothing waits for it).
206    pub fn start(&self, work: impl Future<Output = ()> + 'static) {
207        self.host.start_task(Box::new(move || {
208            Box::pin(async move {
209                work.await;
210                Ok(Box::new(()) as Box<dyn super::ToJs>)
211            })
212        }));
213    }
214
215    /// Runs `f` when what owns the call in JS goes: the reactive owner it
216    /// runs under, or the module's run under hot reload (otherwise when the
217    /// VM goes, as everything else does). [`Cleanup::release`] unregisters
218    /// it once what it undoes ended by itself, so an owner that lives long
219    /// does not collect them.
220    pub fn on_cleanup(&self, f: impl FnOnce() + 'static) -> Cleanup {
221        Cleanup(Some(self.host.on_cleanup(Box::new(f))))
222    }
223}
224
225/// A cleanup [`CallCx::on_cleanup`] registered. Dropping it keeps the
226/// cleanup registered.
227pub struct Cleanup(Option<Box<dyn FnOnce()>>);
228
229impl Cleanup {
230    /// Unregisters the cleanup without running it (a no-op once it ran).
231    pub fn release(mut self) {
232        if let Some(release) = self.0.take() {
233            release();
234        }
235    }
236}
237
238impl fmt::Debug for Cleanup {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        f.write_str("Cleanup")
241    }
242}
243
244/// What stops something JS started, returned to JS as a function that
245/// stops it (`() => void`): what every `on(…)` of Rust returns. It runs
246/// once, when JS calls the function or when what owns the call in JS goes
247/// (the reactive owner it runs under, or the module's run under hot
248/// reload; [`CallCx::on_cleanup`]), whichever comes first, so a listener a
249/// component adds goes with the component. Returned from a synchronous
250/// call: a task's or an op's result reaches JS when nothing owns the call.
251/// What `f` holds stays alive as long as the JS function does, so it holds
252/// instances weakly.
253#[derive(Default)]
254#[non_exhaustive]
255pub struct Stop {
256    run: Rc<StopOnce>,
257}
258
259/// What a [`Stop`] runs, until it ran.
260type StopOnce = RefCell<Option<Box<dyn FnOnce()>>>;
261
262impl Stop {
263    /// Stops with `f`.
264    pub fn new(f: impl FnOnce() + 'static) -> Self {
265        Self {
266            run: Rc::new(RefCell::new(Some(Box::new(f)))),
267        }
268    }
269
270    fn run(run: &StopOnce) {
271        // Taken before it runs: what it does may call the function again.
272        let f = run.borrow_mut().take();
273        if let Some(f) = f {
274            f();
275        }
276    }
277}
278
279impl fmt::Debug for Stop {
280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281        f.write_str("Stop")
282    }
283}
284
285impl Ret for Stop {
286    fn ts_type(_types: &mut super::TsTypes) -> String {
287        "() => void".into()
288    }
289
290    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<super::JsOwned<'a>, super::PropError> {
291        let run = self.run;
292        let release = host.on_cleanup(Box::new({
293            let run = run.clone();
294            move || Self::run(&run)
295        }));
296        let release = RefCell::new(Some(release));
297        let stop = host.new_function(Box::new(move || {
298            // Unregistered first: an owner that lives long does not
299            // collect stopped listeners.
300            let release = release.borrow_mut().take();
301            if let Some(release) = release {
302                release();
303            }
304            Self::run(&run);
305        }))?;
306        Ok(super::JsOwned::new(host, stop))
307    }
308}
309
310impl fmt::Debug for System {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        f.debug_struct("System")
313            .field("data_dir", &self.data_dir)
314            .field("os", &self.os)
315            .finish_non_exhaustive()
316    }
317}
318
319/// One VM's counts of limited resources (open sockets, bytes of file data
320/// in flight, ...), by kind: a host keeps one per VM and hands it to every
321/// [`System`].
322#[derive(Clone, Default)]
323pub struct Quotas(Rc<RefCell<FxHashMap<&'static str, usize>>>);
324
325impl Quotas {
326    /// Takes one `kind` when fewer than `max` are held; dropping the
327    /// [`Held`] gives it back.
328    pub fn take(&self, kind: &'static str, max: usize) -> Option<Held> {
329        self.reserve(kind, 1, max)
330    }
331
332    /// Takes `amount` of `kind` (bytes, ...) when the held total stays at
333    /// most `max`; dropping the [`Held`] gives them back.
334    pub fn reserve(&self, kind: &'static str, amount: usize, max: usize) -> Option<Held> {
335        let mut counts = self.0.borrow_mut();
336        let count = counts.entry(kind).or_default();
337        let total = count.checked_add(amount).filter(|&total| total <= max)?;
338        *count = total;
339        Some(Held {
340            quotas: self.clone(),
341            kind,
342            amount,
343        })
344    }
345
346    /// How many `kind` are held.
347    pub fn held(&self, kind: &'static str) -> usize {
348        self.0.borrow().get(kind).copied().unwrap_or(0)
349    }
350}
351
352/// Resources of a [`Quotas`] kind (one, or an amount), given back when
353/// dropped.
354pub struct Held {
355    quotas: Quotas,
356    kind: &'static str,
357    amount: usize,
358}
359
360impl Held {
361    /// How much it holds.
362    pub fn amount(&self) -> usize {
363        self.amount
364    }
365}
366
367impl Drop for Held {
368    fn drop(&mut self) {
369        if let Some(count) = self.quotas.0.borrow_mut().get_mut(self.kind) {
370            *count -= self.amount;
371        }
372    }
373}
374
375impl fmt::Debug for Held {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        write!(f, "Held({} {})", self.amount, self.kind)
378    }
379}
380
381/// Work a function or member that is not `async` starts in the JS call
382/// and finishes as a task of the core: JS gets a promise of `T`. What the
383/// call refuses before returning it (an argument, a grant, a quota)
384/// rejects the promise, as the task's `Err` does
385/// (a [`JsError`] with its class and properties, any other error as an
386/// `Error` with its message). TS: `Promise<T>`.
387#[must_use = "the work runs only when the call returns it"]
388pub struct Later<T>(Pin<Box<dyn Future<Output = Result<T, Thrown>>>>);
389
390impl<T: Ret + 'static> Later<T> {
391    /// The task's work: its value, or what the promise rejects with.
392    pub fn new<E: IntoThrown>(work: impl Future<Output = Result<T, E>> + 'static) -> Self {
393        Self(Box::pin(async move {
394            work.await.map_err(IntoThrown::into_thrown)
395        }))
396    }
397
398    pub(crate) fn into_future(self) -> ModuleFuture {
399        Box::pin(async move {
400            let result: JsResult = match self.0.await {
401                Ok(v) => Ok(Box::new(v)),
402                Err(e) => Err(e),
403            };
404            result
405        })
406    }
407}
408
409impl<T> fmt::Debug for Later<T> {
410    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411        f.write_str("Later")
412    }
413}
414
415/// An error of a chosen JS class: what `Result<T, JsError>` throws, and
416/// what a [`Later`] task's `Err(JsError)` rejects with (any other error
417/// type is an `Error` with its message). [`JsError::with_code`] and
418/// [`JsError::with`] give it properties, as Node's errors have
419/// (`error.code === "ENOENT"`; TS: `Error & { code?: string }`).
420#[derive(Debug, Clone, PartialEq, Eq)]
421pub enum JsError {
422    /// A `TypeError`: the call was not allowed or its value is wrong.
423    Type(String),
424    /// A `RangeError`: a value past a limit.
425    Range(String),
426    /// An `Error`.
427    Error(String),
428    /// One of those with properties.
429    Fields(Box<ErrorFields>),
430}
431
432/// The JS class of an error.
433#[derive(Debug, Clone, Copy, PartialEq, Eq)]
434pub enum ErrorClass {
435    /// `TypeError`.
436    Type,
437    /// `RangeError`.
438    Range,
439    /// `Error`.
440    Error,
441}
442
443/// An error with properties beside its message ([`JsError::Fields`],
444/// [`Thrown::Fields`]).
445#[derive(Debug, Clone, PartialEq, Eq)]
446pub struct ErrorFields {
447    /// Its class.
448    pub class: ErrorClass,
449    /// Its message.
450    pub message: String,
451    /// Its properties, in order (`code`, `syscall`, `path`, `errno`, ...).
452    pub fields: Vec<(&'static str, JsonValue)>,
453}
454
455impl ErrorFields {
456    fn of(class: ErrorClass, message: String) -> Self {
457        Self {
458            class,
459            message,
460            fields: Vec::new(),
461        }
462    }
463
464    /// Property `key`, if it has one.
465    pub fn field(&self, key: &str) -> Option<&JsonValue> {
466        self.fields.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
467    }
468}
469
470impl JsError {
471    /// The error with property `key` set to `value` (replacing one of the
472    /// same name).
473    pub fn with(self, key: &'static str, value: impl Into<JsonValue>) -> Self {
474        let mut fields = match self {
475            JsError::Type(m) => ErrorFields::of(ErrorClass::Type, m),
476            JsError::Range(m) => ErrorFields::of(ErrorClass::Range, m),
477            JsError::Error(m) => ErrorFields::of(ErrorClass::Error, m),
478            JsError::Fields(f) => *f,
479        };
480        fields.fields.retain(|(k, _)| *k != key);
481        fields.fields.push((key, value.into()));
482        JsError::Fields(Box::new(fields))
483    }
484
485    /// The error with Node's `code` (`"ENOENT"`).
486    pub fn with_code(self, code: &str) -> Self {
487        self.with("code", code)
488    }
489
490    /// What a call the app's capabilities do not grant fails with, as
491    /// Node's permission model: an `Error` with `code`
492    /// [`codes::ACCESS_DENIED`], `permission` (the capability: `"fs"`,
493    /// `"network"`, `"clipboard"`, ...) and `resource` (the path, URL or
494    /// name asked for; `""` when the capability has none).
495    pub fn access_denied(
496        message: impl Into<String>,
497        permission: &str,
498        resource: impl Into<String>,
499    ) -> Self {
500        JsError::Error(message.into())
501            .with_code(codes::ACCESS_DENIED)
502            .with("permission", permission)
503            .with("resource", resource.into())
504    }
505
506    /// Its message.
507    pub fn message(&self) -> &str {
508        match self {
509            JsError::Type(m) | JsError::Range(m) | JsError::Error(m) => m,
510            JsError::Fields(f) => &f.message,
511        }
512    }
513
514    /// Its `code`, if it has one.
515    pub fn code(&self) -> Option<&str> {
516        match self {
517            JsError::Fields(f) => f.field("code").and_then(JsonValue::as_str),
518            _ => None,
519        }
520    }
521}
522
523/// The `code`s of the errors NSH's calls fail with besides an I/O
524/// error's (`ENOENT`, `EACCES`, ...: [`io_code`]). Apps branch on them; the
525/// messages are for people and may change.
526pub mod codes {
527    /// The app's capabilities do not grant the call
528    /// ([`super::JsError::access_denied`]; Node's permission model's).
529    pub const ACCESS_DENIED: &str = "ERR_ACCESS_DENIED";
530    /// The platform the app runs on has no such feature (Node's).
531    pub const UNAVAILABLE: &str = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM";
532    /// A quota of the runtime is used up: calls waiting at once, open
533    /// sockets, storage.
534    pub const QUOTA_EXCEEDED: &str = "ERR_NSH_QUOTA_EXCEEDED";
535    /// The call ran out of time.
536    pub const TIMED_OUT: &str = "ETIMEDOUT";
537    /// The embedding app answered a `host.call` with an error (its handler
538    /// failed, or it handles no such name); the message is the host's.
539    pub const HOST_ERROR: &str = "ERR_NSH_HOST_ERROR";
540}
541
542/// An I/O error as Node reports it: `Error` with the message and the
543/// `code` of its kind or OS error (`ENOENT`, `EACCES`, ...; none when it
544/// has no name).
545impl From<std::io::Error> for JsError {
546    fn from(error: std::io::Error) -> Self {
547        let message = error.to_string();
548        match io_code(&error) {
549            Some(code) => JsError::Error(message).with_code(code),
550            None => JsError::Error(message),
551        }
552    }
553}
554
555/// Node's code of I/O error `error`: its OS error's name when it has one,
556/// else its kind's.
557pub fn io_code(error: &std::io::Error) -> Option<&'static str> {
558    use std::io::ErrorKind as K;
559    #[cfg(unix)]
560    if let Some(code) = error.raw_os_error().and_then(errno_name) {
561        return Some(code);
562    }
563    Some(match error.kind() {
564        K::NotFound => "ENOENT",
565        K::PermissionDenied => "EACCES",
566        K::AlreadyExists => "EEXIST",
567        K::NotADirectory => "ENOTDIR",
568        K::IsADirectory => "EISDIR",
569        K::DirectoryNotEmpty => "ENOTEMPTY",
570        K::InvalidFilename => "ENAMETOOLONG",
571        K::ReadOnlyFilesystem => "EROFS",
572        K::CrossesDevices => "EXDEV",
573        K::StorageFull => "ENOSPC",
574        K::QuotaExceeded => "EDQUOT",
575        K::FileTooLarge => "EFBIG",
576        K::ResourceBusy => "EBUSY",
577        K::ExecutableFileBusy => "ETXTBSY",
578        K::Deadlock => "EDEADLK",
579        K::TooManyLinks => "EMLINK",
580        K::ArgumentListTooLong => "E2BIG",
581        K::Interrupted => "EINTR",
582        K::WouldBlock => "EAGAIN",
583        K::TimedOut => "ETIMEDOUT",
584        K::BrokenPipe => "EPIPE",
585        K::ConnectionRefused => "ECONNREFUSED",
586        K::ConnectionReset => "ECONNRESET",
587        K::ConnectionAborted => "ECONNABORTED",
588        K::NotConnected => "ENOTCONN",
589        K::AddrInUse => "EADDRINUSE",
590        K::AddrNotAvailable => "EADDRNOTAVAIL",
591        K::HostUnreachable => "EHOSTUNREACH",
592        K::NetworkUnreachable => "ENETUNREACH",
593        K::NetworkDown => "ENETDOWN",
594        K::InvalidInput => "EINVAL",
595        K::Unsupported => "ENOTSUP",
596        K::OutOfMemory => "ENOMEM",
597        _ => return None,
598    })
599}
600
601/// The name of Unix error number `errno`, for the ones a file, process or
602/// socket call gives that no [`std::io::ErrorKind`] names (`ELOOP`).
603#[cfg(unix)]
604fn errno_name(errno: i32) -> Option<&'static str> {
605    let names: &[(i32, &str)] = &[
606        (libc::ENOENT, "ENOENT"),
607        (libc::EACCES, "EACCES"),
608        (libc::EPERM, "EPERM"),
609        (libc::EEXIST, "EEXIST"),
610        (libc::ENOTDIR, "ENOTDIR"),
611        (libc::EISDIR, "EISDIR"),
612        (libc::ENOTEMPTY, "ENOTEMPTY"),
613        (libc::ELOOP, "ELOOP"),
614        (libc::ENAMETOOLONG, "ENAMETOOLONG"),
615        (libc::EBADF, "EBADF"),
616        (libc::EBUSY, "EBUSY"),
617        (libc::EINVAL, "EINVAL"),
618        (libc::EMFILE, "EMFILE"),
619        (libc::ENFILE, "ENFILE"),
620        (libc::ENOSPC, "ENOSPC"),
621        (libc::EROFS, "EROFS"),
622        (libc::EXDEV, "EXDEV"),
623        (libc::EAGAIN, "EAGAIN"),
624        (libc::ENXIO, "ENXIO"),
625        (libc::ETXTBSY, "ETXTBSY"),
626        (libc::EFBIG, "EFBIG"),
627        (libc::EMLINK, "EMLINK"),
628        (libc::EPIPE, "EPIPE"),
629        (libc::ENOEXEC, "ENOEXEC"),
630    ];
631    names
632        .iter()
633        .find(|(n, _)| *n == errno)
634        .map(|(_, name)| *name)
635}
636
637/// What an `Err` of a synchronous call throws: an `Error` with its message
638/// for any [`fmt::Display`] error, the chosen class for a [`JsError`].
639pub trait IntoThrown {
640    /// The exception.
641    fn into_thrown(self) -> Thrown;
642}
643
644impl<E: fmt::Display> IntoThrown for E {
645    fn into_thrown(self) -> Thrown {
646        Thrown::Error(self.to_string())
647    }
648}
649
650impl IntoThrown for JsError {
651    fn into_thrown(self) -> Thrown {
652        match self {
653            JsError::Type(m) => Thrown::Type(m),
654            JsError::Range(m) => Thrown::Range(m),
655            JsError::Error(m) => Thrown::Error(m),
656            JsError::Fields(f) => Thrown::Fields(f),
657        }
658    }
659}
660
661#[cfg(test)]
662mod tests {
663    use crate::{
664        JsonValue,
665        element::{JsValue, Registry, declarations, json_host},
666        prelude::*,
667    };
668
669    #[module]
670    struct Files;
671
672    #[module(flat)]
673    impl Files {
674        /// Reads `path` later.
675        pub(crate) fn read(path: String, sys: System) -> Result<Later<Vec<u8>>, JsError> {
676            let _ = (path, sys);
677            Ok(Later::new(async { Ok::<_, String>(vec![1]) }))
678        }
679
680        /// Writes `bytes`, at once.
681        pub(crate) fn write(sys: System, bytes: Vec<u8>) -> u32 {
682            let _ = sys;
683            bytes.len() as u32
684        }
685
686        /// Starts a task, tied to the call's owner.
687        pub(crate) fn watch(path: String, cx: CallCx<'_>) {
688            cx.on_cleanup(move || drop(path));
689            cx.start(async {});
690        }
691
692        /// Listens until the returned function is called.
693        pub(crate) fn listen() -> Stop {
694            Stop::new(|| {})
695        }
696
697        /// Where the files are.
698        #[getter]
699        pub(crate) fn root(sys: System) -> Option<String> {
700            sys.data_dir.map(|d| d.display().to_string())
701        }
702    }
703
704    #[class]
705    struct Handle;
706
707    #[class]
708    impl Handle {
709        /// Its next bytes, later.
710        pub(crate) fn next(&self, sys: System, size: Option<u32>) -> Later<Option<Vec<u8>>> {
711            let _ = (sys, size);
712            Later::new(async { Ok::<_, String>(None) })
713        }
714
715        /// Itself, for chaining.
716        #[overload(fn(event: String, #[args(index, label)] f: Callback<(u32, String)>) -> Instance<Handle>)]
717        pub(crate) fn on(this: Instance<Self>, event: String, cx: CallCx<'_>) -> Instance<Self> {
718            let _ = (event, cx);
719            this
720        }
721    }
722
723    #[test]
724    fn bytes_are_uint8_arrays_tasks_promises_and_the_system_no_parameter() {
725        let mut registry = Registry::ui_set("test/system");
726        registry.module::<Files>().class::<Handle>();
727        let d = declarations(&registry, &[]);
728        assert!(
729            d.contains("function read(path: string): Promise<Uint8Array>;"),
730            "{d}"
731        );
732        assert!(
733            d.contains("function write(bytes: Uint8Array): number;"),
734            "{d}"
735        );
736        assert!(
737            d.contains("next(size?: number | null): Promise<Uint8Array | null>;"),
738            "{d}"
739        );
740        assert!(d.contains("function watch(path: string): void;"), "{d}");
741        assert!(d.contains("function listen(): () => void;"), "{d}");
742        assert!(
743            d.contains("  on(event: string, f: (index: number, label: string) => void): Handle;"),
744            "{d}"
745        );
746        // A getter is no flat export.
747        assert!(!d.contains("function root"), "{d}");
748    }
749
750    #[test]
751    fn bytes_convert_from_and_to_js() {
752        let host = json_host::JsonHost::default();
753        let raw = host.value(serde_json::json!([0, 7, 255]));
754        let bytes = <Vec<u8>>::from_js(crate::element::JsIn::new(&host, raw)).unwrap();
755        assert_eq!(bytes, [0, 7, 255]);
756        let out = bytes.to_js(&host).unwrap();
757        assert_eq!(host.read(out), Some(serde_json::json!([0, 7, 255])));
758        let bad = host.value(JsonValue::from("x"));
759        assert!(<Vec<u8>>::from_js(crate::element::JsIn::new(&host, bad)).is_err());
760    }
761
762    #[test]
763    fn a_stop_is_a_function_that_runs_once() {
764        use crate::element::Ret;
765        let host = json_host::JsonHost::default();
766        let runs = std::rc::Rc::new(std::cell::Cell::new(0));
767        let stop = Stop::new({
768            let runs = runs.clone();
769            move || runs.set(runs.get() + 1)
770        });
771        let f = stop.into_js(&host).unwrap().into_raw();
772        assert_eq!(
773            crate::element::JsHost::kind(&host, f),
774            crate::element::JsKind::Function
775        );
776        assert_eq!(runs.get(), 0);
777        host.call(f);
778        host.call(f);
779        assert_eq!(runs.get(), 1);
780    }
781
782    #[derive(Debug, JsObject)]
783    #[prop(exact)]
784    struct Options {
785        recursive: Option<bool>,
786        #[prop(skip_none)]
787        note: Option<String>,
788    }
789
790    #[test]
791    fn times_are_dates_and_exact_objects_refuse_other_keys() {
792        let host = json_host::JsonHost::default();
793        let time = std::time::UNIX_EPOCH + std::time::Duration::from_millis(1500);
794        let out = time.to_js(&host).unwrap();
795        assert_eq!(host.read(out), Some(serde_json::json!({ "$date": 1500.0 })));
796        let date = host.value(serde_json::json!({ "$date": -250.0 }));
797        let back = std::time::SystemTime::from_js(crate::element::JsIn::new(&host, date)).unwrap();
798        assert_eq!(
799            std::time::UNIX_EPOCH
800                .duration_since(back)
801                .unwrap()
802                .as_millis(),
803            250
804        );
805        let options = host.value(serde_json::json!({ "recursive": true }));
806        let options = Options::from_js(crate::element::JsIn::new(&host, options)).unwrap();
807        assert_eq!(options.recursive, Some(true));
808        let shown = Options {
809            recursive: None,
810            note: None,
811        }
812        .to_js(&host)
813        .unwrap();
814        assert_eq!(
815            host.read(shown),
816            Some(serde_json::json!({ "recursive": null }))
817        );
818        let typo = host.value(serde_json::json!({ "recursive": true, "typo": 1 }));
819        let error = Options::from_js(crate::element::JsIn::new(&host, typo)).unwrap_err();
820        assert_eq!(error.0, "unknown field `typo`");
821    }
822
823    #[test]
824    fn errors_carry_node_s_codes_thrown_and_rejected() {
825        use super::{ErrorClass, JsError, io_code};
826        use crate::element::{IntoThrown, Thrown};
827        let missing = std::io::Error::from(std::io::ErrorKind::NotFound);
828        assert_eq!(io_code(&missing), Some("ENOENT"));
829        #[cfg(unix)]
830        assert_eq!(
831            io_code(&std::io::Error::from_raw_os_error(libc::ELOOP)),
832            Some("ELOOP")
833        );
834        assert_eq!(io_code(&std::io::Error::other("x")), None);
835        let error = JsError::Type("denied".into())
836            .with_code("EPERM")
837            .with_code("EACCES")
838            .with("path", "a.txt");
839        assert_eq!((error.message(), error.code()), ("denied", Some("EACCES")));
840        let Thrown::Fields(fields) = error.clone().into_thrown() else {
841            panic!("fields go with the error");
842        };
843        assert_eq!(fields.class, ErrorClass::Type);
844        assert_eq!(fields.fields.len(), 2);
845        assert_eq!(JsError::from(missing).code(), Some("ENOENT"));
846        // A task's `Err(JsError)` rejects with the same.
847        let later = super::Later::<u32>::new(async { Err::<u32, _>(error) });
848        let runtime = tokio::runtime::Builder::new_current_thread()
849            .build()
850            .unwrap();
851        let Err(Thrown::Fields(rejected)) = runtime.block_on(later.into_future()) else {
852            panic!("a rejection with fields");
853        };
854        assert_eq!(rejected.field("path"), Some(&serde_json::json!("a.txt")));
855        // Any other error rejects with its message.
856        let later = super::Later::<u32>::new(async { Err::<u32, _>("plain") });
857        assert!(matches!(
858            runtime.block_on(later.into_future()),
859            Err(Thrown::Error(m)) if m == "plain"
860        ));
861    }
862
863    #[test]
864    fn quotas_count_what_is_held() {
865        let quotas = super::Quotas::default();
866        let a = quotas.take("k", 2).unwrap();
867        let _b = quotas.take("k", 2).unwrap();
868        assert!(quotas.take("k", 2).is_none());
869        drop(a);
870        assert_eq!(quotas.held("k"), 1);
871        assert!(quotas.take("other", 1).is_some());
872    }
873
874    #[test]
875    fn quotas_reserve_amounts_up_to_their_limit() {
876        let quotas = super::Quotas::default();
877        let a = quotas.reserve("bytes", 40, 64).unwrap();
878        assert!(quotas.reserve("bytes", 25, 64).is_none());
879        let b = quotas.reserve("bytes", 24, 64).unwrap();
880        assert_eq!((quotas.held("bytes"), a.amount()), (64, 40));
881        assert!(quotas.reserve("bytes", usize::MAX, usize::MAX).is_none());
882        drop(a);
883        assert_eq!(quotas.held("bytes"), 24);
884        drop(b);
885        assert!(quotas.reserve("bytes", 64, 64).is_some());
886    }
887}