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