1use std::{fmt, time::Duration};
7
8#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Limits {
11 pub memory_bytes: usize,
13 pub stack_bytes: usize,
17 pub load_budget: Duration,
19 pub call_budget: Duration,
23 pub max_op_values: usize,
27 pub max_canvas_ops: usize,
29 pub max_nodes: usize,
32}
33
34impl Limits {
35 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 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
63impl 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
84pub struct HostLimits {
85 pub memory_bytes: Option<usize>,
87 pub stack_bytes: Option<usize>,
90 pub load_budget: Option<Duration>,
92 pub call_budget: Option<Duration>,
94 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 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 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
150impl 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
174fn 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 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 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}