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