Skip to main content

nsh_core/js/
limits.rs

1//! A VM's resource limits. Only apps embedded in another app have them,
2//! and the embedding app decides them ([`HostLimits`] over
3//! [`Limits::default`]); an app nsh runs on its own is the developer's own
4//! code, as a native app is, and has none ([`Limits::standalone`]).
5
6use std::{fmt, time::Duration};
7
8/// Resource limits of one VM.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Limits {
11    /// QuickJS heap, in bytes (0: no limit). Running out stops the VM.
12    pub memory_bytes: usize,
13    /// Interpreter stack, in bytes: deep recursion becomes a `RangeError`
14    /// rather than a native stack overflow. Must stay below the engine
15    /// thread's stack.
16    pub stack_bytes: usize,
17    /// Evaluating the bundle (`Duration::MAX`: no limit).
18    pub load_budget: Duration,
19    /// Any other call into JS: one event (with the rendering it causes), one
20    /// list bind, one timer, one frame's callbacks, the microtask drain
21    /// (`Duration::MAX`: no limit).
22    pub call_budget: Duration,
23    /// Changes JS may make at once (the op queue's length): they are held in
24    /// Rust memory, which the heap limit does not cover (`usize::MAX`: no
25    /// limit).
26    pub max_op_values: usize,
27    /// Operations one canvas drawing may record (`usize::MAX`: no limit).
28    pub max_canvas_ops: usize,
29    /// Nodes the core keeps (each may have a native view, whose memory the
30    /// heap limit does not cover either; `usize::MAX`: no limit).
31    pub max_nodes: usize,
32}
33
34impl Limits {
35    /// The limits of an app nsh runs on its own (the hosts and runners of
36    /// every platform, a web package, `nsh run` without `--limits`): none
37    /// but the interpreter stack's, which turns deep recursion into a
38    /// `RangeError` instead of a crash of the process.
39    pub fn standalone() -> Self {
40        Self {
41            memory_bytes: 0,
42            stack_bytes: Self::default().stack_bytes,
43            load_budget: Duration::MAX,
44            call_budget: Duration::MAX,
45            max_op_values: usize::MAX,
46            max_canvas_ops: usize::MAX,
47            max_nodes: usize::MAX,
48        }
49    }
50
51    /// The limits of a development host's app: those an embedding app
52    /// would set (`spec`, as [`HostLimits::parse`] reads it: `nsh run
53    /// --limits`, which the dev server passes on), or none
54    /// ([`Limits::standalone`]) without a spec.
55    pub fn development(spec: Option<&str>) -> Result<Self, String> {
56        match spec {
57            None => Ok(Self::standalone()),
58            Some(spec) => Ok(HostLimits::parse(spec)?.limits()),
59        }
60    }
61}
62
63/// The limits of an app embedded in a host app (`NshAppView`, `NshView`,
64/// `AppView`) that sets none: a 256 MB heap, 10 s to load, 2 s per call.
65impl Default for Limits {
66    fn default() -> Self {
67        Self {
68            memory_bytes: 256 << 20,
69            stack_bytes: 4 << 20,
70            load_budget: Duration::from_secs(10),
71            call_budget: Duration::from_secs(2),
72            max_op_values: 8_000_000,
73            max_canvas_ops: 1_000_000,
74            max_nodes: 200_000,
75        }
76    }
77}
78
79/// The limits an embedding app sets for the apps it embeds (`NshLimits`
80/// on iOS, `NshView.setLimits` on Android), and those `nsh run --limits`
81/// runs an app with as such an app would: each one it leaves out keeps
82/// its default ([`Limits::default`]).
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
84pub struct HostLimits {
85    /// The QuickJS heap, in bytes.
86    pub memory_bytes: Option<usize>,
87    /// The interpreter stack, in bytes; at most the default (4 MB), which
88    /// leaves the engine thread's stack room for native frames.
89    pub stack_bytes: Option<usize>,
90    /// Evaluating the bundle.
91    pub load_budget: Option<Duration>,
92    /// Any other call into JS.
93    pub call_budget: Option<Duration>,
94    /// Nodes the core keeps.
95    pub max_nodes: Option<usize>,
96}
97
98const KB: usize = 1 << 10;
99const MB: usize = 1 << 20;
100const GB: usize = 1 << 30;
101
102impl HostLimits {
103    /// The limits these give: the defaults with what is set.
104    pub fn limits(&self) -> Limits {
105        let defaults = Limits::default();
106        Limits {
107            memory_bytes: self.memory_bytes.unwrap_or(defaults.memory_bytes),
108            stack_bytes: self
109                .stack_bytes
110                .map_or(defaults.stack_bytes, |b| b.min(defaults.stack_bytes)),
111            load_budget: self.load_budget.unwrap_or(defaults.load_budget),
112            call_budget: self.call_budget.unwrap_or(defaults.call_budget),
113            max_nodes: self.max_nodes.unwrap_or(defaults.max_nodes),
114            ..defaults
115        }
116    }
117
118    /// Reads limits written as `nsh run --limits` takes them: `key=value`
119    /// pairs separated by commas, of `memory` and `stack` (a size in `KB`,
120    /// `MB` or `GB`), `load` and `call` (a time in `ms` or `s`) and `nodes`
121    /// (a count), say `memory=128MB,call=500ms`. Each value is above zero;
122    /// the empty string sets none.
123    pub fn parse(spec: &str) -> Result<Self, String> {
124        let mut limits = HostLimits::default();
125        for pair in spec.split(',').map(str::trim).filter(|p| !p.is_empty()) {
126            let Some((key, value)) = pair.split_once('=') else {
127                return Err(format!("`{pair}` is not `key=value`"));
128            };
129            let (key, value) = (key.trim(), value.trim());
130            let set = match key {
131                "memory" => limits.memory_bytes.replace(size(key, value)?).is_some(),
132                "stack" => limits.stack_bytes.replace(size(key, value)?).is_some(),
133                "load" => limits.load_budget.replace(time(key, value)?).is_some(),
134                "call" => limits.call_budget.replace(time(key, value)?).is_some(),
135                "nodes" => limits.max_nodes.replace(count(key, value)?).is_some(),
136                _ => {
137                    return Err(format!(
138                        "unknown limit `{key}` (memory, stack, load, call or nodes)"
139                    ));
140                }
141            };
142            if set {
143                return Err(format!("`{key}` is set twice"));
144            }
145        }
146        Ok(limits)
147    }
148}
149
150/// The limits as [`HostLimits::parse`] reads them.
151impl fmt::Display for HostLimits {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        fn bytes(b: usize) -> String {
154            if b.is_multiple_of(MB) {
155                format!("{}MB", b / MB)
156            } else {
157                format!("{}KB", b.div_ceil(KB))
158            }
159        }
160        let pairs = [
161            self.memory_bytes.map(|b| format!("memory={}", bytes(b))),
162            self.stack_bytes.map(|b| format!("stack={}", bytes(b))),
163            self.load_budget
164                .map(|d| format!("load={}ms", d.as_millis())),
165            self.call_budget
166                .map(|d| format!("call={}ms", d.as_millis())),
167            self.max_nodes.map(|n| format!("nodes={n}")),
168        ];
169        let pairs: Vec<String> = pairs.into_iter().flatten().collect();
170        f.write_str(&pairs.join(","))
171    }
172}
173
174/// `value` split into its number (above zero) and its unit.
175fn number<'a>(key: &str, value: &'a str) -> Result<(usize, &'a str), String> {
176    let digits = value
177        .find(|c: char| !c.is_ascii_digit())
178        .unwrap_or(value.len());
179    let n: usize = value[..digits]
180        .parse()
181        .map_err(|_| format!("`{key}`: `{value}` is not a number"))?;
182    if n == 0 {
183        return Err(format!("`{key}`: `{value}` is not above zero"));
184    }
185    Ok((n, value[digits..].trim()))
186}
187
188fn size(key: &str, value: &str) -> Result<usize, String> {
189    let (n, unit) = number(key, value)?;
190    let scale = match unit.to_ascii_uppercase().as_str() {
191        "KB" => KB,
192        "MB" => MB,
193        "GB" => GB,
194        _ => return Err(format!("`{key}`: `{value}` needs a unit: KB, MB or GB")),
195    };
196    n.checked_mul(scale)
197        .ok_or_else(|| format!("`{key}`: `{value}` is too large"))
198}
199
200fn time(key: &str, value: &str) -> Result<Duration, String> {
201    let (n, unit) = number(key, value)?;
202    let ms = match unit.to_ascii_lowercase().as_str() {
203        "ms" => Some(n as u64),
204        "s" => (n as u64).checked_mul(1000),
205        _ => return Err(format!("`{key}`: `{value}` needs a unit: ms or s")),
206    };
207    ms.map(Duration::from_millis)
208        .ok_or_else(|| format!("`{key}`: `{value}` is too large"))
209}
210
211fn count(key: &str, value: &str) -> Result<usize, String> {
212    match number(key, value)? {
213        (n, "") => Ok(n),
214        _ => Err(format!("`{key}`: `{value}` is not a count")),
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn host_limits_set_what_they_name_over_the_defaults() {
224        let limits = HostLimits::parse("memory=128MB, call=500ms,nodes=5000").unwrap();
225        assert_eq!(
226            limits.limits(),
227            Limits {
228                memory_bytes: 128 << 20,
229                call_budget: Duration::from_millis(500),
230                max_nodes: 5000,
231                ..Limits::default()
232            }
233        );
234        assert_eq!(limits.to_string(), "memory=128MB,call=500ms,nodes=5000");
235        assert_eq!(HostLimits::parse(&limits.to_string()), Ok(limits));
236        // None set: an embedding app's defaults.
237        assert_eq!(HostLimits::parse("").unwrap().limits(), Limits::default());
238        let all = HostLimits::parse("memory=1gb,stack=512KB,load=5s,call=2s,nodes=1").unwrap();
239        assert_eq!(
240            all.to_string(),
241            "memory=1024MB,stack=512KB,load=5000ms,call=2000ms,nodes=1"
242        );
243        // The stack stays within the engine thread's.
244        let stack = HostLimits::parse("stack=64MB").unwrap().limits();
245        assert_eq!(stack.stack_bytes, Limits::default().stack_bytes);
246    }
247
248    #[test]
249    fn host_limits_name_what_is_wrong() {
250        for (spec, error) in [
251            ("memory=128", "`memory`: `128` needs a unit: KB, MB or GB"),
252            ("call=2m", "`call`: `2m` needs a unit: ms or s"),
253            ("nodes=10k", "`nodes`: `10k` is not a count"),
254            ("load=0s", "`load`: `0s` is not above zero"),
255            (
256                "heap=1MB",
257                "unknown limit `heap` (memory, stack, load, call or nodes)",
258            ),
259            ("call=1s,call=2s", "`call` is set twice"),
260            ("memory", "`memory` is not `key=value`"),
261            ("memory=MB", "`memory`: `MB` is not a number"),
262        ] {
263            assert_eq!(HostLimits::parse(spec), Err(error.to_owned()), "{spec}");
264        }
265    }
266
267    #[test]
268    fn standalone_apps_and_development_without_limits_have_none() {
269        let none = Limits::standalone();
270        assert_eq!(none.memory_bytes, 0);
271        assert_eq!(none.call_budget, Duration::MAX);
272        assert_eq!(none.max_nodes, usize::MAX);
273        assert_eq!(none.stack_bytes, Limits::default().stack_bytes);
274        assert_eq!(Limits::development(None), Ok(none));
275        assert_eq!(Limits::development(Some("")), Ok(Limits::default()));
276        assert!(Limits::development(Some("call=")).is_err());
277    }
278}