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