1use std::collections::HashSet;
2use std::fmt;
3use std::ops::RangeInclusive;
4
5use serde::{Deserialize, Serialize};
6
7use crate::{Capacity, ImageReference, Run, RunId, RunState, SandboxNetwork};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
11#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
12#[serde(transparent)]
13pub struct SandboxId(i64);
14
15impl SandboxId {
16 pub fn new(id: i64) -> Self {
17 Self(id)
18 }
19
20 pub fn get(self) -> i64 {
21 self.0
22 }
23
24 pub fn run(self) -> RunId {
25 RunId::new(self.0)
26 }
27}
28
29impl fmt::Display for SandboxId {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 self.0.fmt(f)
32 }
33}
34
35#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
36#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
37#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
38pub struct Sandbox {
39 pub id: SandboxId,
40 pub owner: Option<String>,
41 pub spec: SandboxSpec,
42 pub run: Run,
43}
44
45impl Sandbox {
46 pub fn check_inspectable(&self) -> Result<(), String> {
47 if self.run.inspectable {
48 return Ok(());
49 }
50 if self.run.state.is_active() {
51 return Err(format!("sandbox {} is still running", self.id));
52 }
53 if matches!(self.run.state, RunState::Stopped) {
54 return Err(format!("sandbox {} was stopped before exit", self.id));
55 }
56 if matches!(self.run.state, RunState::Failed { .. }) {
57 return Err(format!("sandbox {} failed before exit", self.id));
58 }
59 if self.run.outdated {
60 return Err(format!(
61 "sandbox {} ran on an older dvm than its runner's now: run it again",
62 self.id
63 ));
64 }
65 Err(format!("sandbox {} has no inspectable state", self.id))
66 }
67
68 pub fn take(&mut self, changed: &Run) -> bool {
69 if changed.id != self.run.id {
70 return false;
71 }
72 if changed.supersedes(&self.run) {
73 self.run = changed.clone();
74 }
75 true
76 }
77}
78
79#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
80#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
81#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
82pub struct SandboxesPage {
83 pub sandboxes: Vec<Sandbox>,
84 pub older: bool,
85}
86
87impl SandboxesPage {
88 pub const SANDBOXES: usize = 50;
89}
90
91#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
92#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
93#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
94pub struct EnvironmentVariable {
95 pub name: String,
96 pub value: String,
97}
98
99impl EnvironmentVariable {
100 pub fn is_name(name: &str) -> bool {
101 let mut chars = name.chars();
102 chars
103 .next()
104 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
105 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
106 }
107}
108
109#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
110#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
111#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
112#[serde(default)]
113pub struct SandboxDraft {
114 pub name: String,
115 pub image: String,
116 pub entrypoint: Option<String>,
117 pub command: Vec<String>,
118 pub environment: Vec<EnvironmentVariable>,
119 pub cpus: u32,
120 pub memory_mib: u32,
121 pub seed: u64,
122 pub network: SandboxNetwork,
123}
124
125impl Default for SandboxDraft {
126 fn default() -> Self {
127 Self {
128 name: String::new(),
129 image: String::new(),
130 entrypoint: None,
131 command: Vec::new(),
132 environment: Vec::new(),
133 cpus: 1,
134 memory_mib: 1024,
135 seed: 0,
136 network: SandboxNetwork::default(),
137 }
138 }
139}
140
141#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
142#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
143#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
144#[serde(try_from = "SandboxDraft", into = "SandboxDraft")]
145#[cfg_attr(feature = "typescript", ts(as = "SandboxDraft"))]
146pub struct SandboxSpec {
147 name: String,
148 image: ImageReference,
149 entrypoint: Option<String>,
150 command: Vec<String>,
151 environment: Vec<EnvironmentVariable>,
152 cpus: u32,
153 memory_mib: u32,
154 seed: u64,
155 network: SandboxNetwork,
156}
157
158impl SandboxSpec {
159 pub const CPUS: RangeInclusive<u32> = 1..=8;
160 pub const MEMORY_MIB: RangeInclusive<u32> = 128..=16384;
161 pub const SEEDS: RangeInclusive<u64> = 0..=(1 << 53) - 1;
163 const NAME_LENGTH: usize = 63;
164 const DVM_OWN_MEMORY_MIB: u64 = 32;
166
167 pub fn name(&self) -> &str {
168 &self.name
169 }
170
171 pub fn image(&self) -> &ImageReference {
172 &self.image
173 }
174
175 pub fn entrypoint(&self) -> Option<&str> {
176 self.entrypoint.as_deref()
177 }
178
179 pub fn command(&self) -> &[String] {
180 &self.command
181 }
182
183 pub fn takes_commands(&self) -> bool {
184 self.command.is_empty() && self.entrypoint.is_none()
185 }
186
187 pub fn environment(&self) -> &[EnvironmentVariable] {
188 &self.environment
189 }
190
191 pub fn cpus(&self) -> u32 {
192 self.cpus
193 }
194
195 pub fn memory_mib(&self) -> u32 {
196 self.memory_mib
197 }
198
199 pub fn seed(&self) -> u64 {
200 self.seed
201 }
202
203 pub fn network(&self) -> &SandboxNetwork {
204 &self.network
205 }
206
207 pub fn with_network(self, network: SandboxNetwork) -> Result<Self, SpecError> {
208 network
209 .check()
210 .map_err(|problem| SpecError::new(SpecField::Network, problem))?;
211 Ok(Self { network, ..self })
212 }
213
214 pub fn footprint(&self) -> Capacity {
215 Capacity {
216 cpus: self.cpus,
217 memory_mib: u64::from(self.memory_mib) + Self::DVM_OWN_MEMORY_MIB,
218 }
219 }
220
221 fn check_name(name: &str) -> Result<(), SpecError> {
222 let valid = !name.is_empty()
223 && name.len() <= Self::NAME_LENGTH
224 && !name.starts_with('-')
225 && !name.ends_with('-')
226 && name
227 .chars()
228 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
229 if valid {
230 Ok(())
231 } else {
232 Err(SpecError::new(
233 SpecField::Name,
234 "up to 63 lowercase letters, digits and '-', not starting or ending with '-'",
235 ))
236 }
237 }
238
239 fn check_environment(environment: &[EnvironmentVariable]) -> Result<(), SpecError> {
240 let mut names = HashSet::new();
241 for variable in environment {
242 if !EnvironmentVariable::is_name(&variable.name) {
243 return Err(SpecError::new(
244 SpecField::Environment,
245 format!(
246 "{:?} isn't a variable name: letters, digits and '_', not starting with a digit",
247 variable.name
248 ),
249 ));
250 }
251 if !names.insert(variable.name.as_str()) {
252 return Err(SpecError::new(
253 SpecField::Environment,
254 format!("{} is given twice", variable.name),
255 ));
256 }
257 Self::check_argument(SpecField::Environment, &variable.value)?;
258 }
259 Ok(())
260 }
261
262 fn check_argument(field: SpecField, argument: &str) -> Result<(), SpecError> {
263 if argument.contains('\0') {
264 Err(SpecError::new(field, "can't contain a NUL character"))
265 } else {
266 Ok(())
267 }
268 }
269
270 fn check_range<T: PartialOrd + fmt::Display>(
271 field: SpecField,
272 value: T,
273 range: RangeInclusive<T>,
274 ) -> Result<(), SpecError> {
275 if range.contains(&value) {
276 Ok(())
277 } else {
278 Err(SpecError::new(
279 field,
280 format!("{value} is outside {}..={}", range.start(), range.end()),
281 ))
282 }
283 }
284}
285
286impl TryFrom<SandboxDraft> for SandboxSpec {
287 type Error = SpecError;
288
289 fn try_from(draft: SandboxDraft) -> Result<Self, Self::Error> {
290 if !draft.name.is_empty() {
291 Self::check_name(&draft.name)?;
292 }
293 let image = ImageReference::try_from(draft.image)
294 .map_err(|error| SpecError::new(SpecField::Image, error.to_string()))?;
295 let name = match draft.name {
296 name if name.is_empty() => image.sandbox_name(),
297 name => name,
298 };
299 if let Some(entrypoint) = &draft.entrypoint {
300 if entrypoint.is_empty() {
301 return Err(SpecError::new(SpecField::Entrypoint, "is empty"));
302 }
303 Self::check_argument(SpecField::Entrypoint, entrypoint)?;
304 }
305 for argument in &draft.command {
306 Self::check_argument(SpecField::Command, argument)?;
307 }
308 Self::check_environment(&draft.environment)?;
309 Self::check_range(SpecField::Cpus, draft.cpus, Self::CPUS)?;
310 Self::check_range(SpecField::Memory, draft.memory_mib, Self::MEMORY_MIB)?;
311 Self::check_range(SpecField::Seed, draft.seed, Self::SEEDS)?;
312 draft
313 .network
314 .check()
315 .map_err(|problem| SpecError::new(SpecField::Network, problem))?;
316 Ok(Self {
317 name,
318 image,
319 entrypoint: draft.entrypoint,
320 command: draft.command,
321 environment: draft.environment,
322 cpus: draft.cpus,
323 memory_mib: draft.memory_mib,
324 seed: draft.seed,
325 network: draft.network,
326 })
327 }
328}
329
330impl From<SandboxSpec> for SandboxDraft {
331 fn from(spec: SandboxSpec) -> Self {
332 Self {
333 name: spec.name,
334 image: spec.image.into(),
335 entrypoint: spec.entrypoint,
336 command: spec.command,
337 environment: spec.environment,
338 cpus: spec.cpus,
339 memory_mib: spec.memory_mib,
340 seed: spec.seed,
341 network: spec.network,
342 }
343 }
344}
345
346#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
347#[error("{field}: {problem}")]
348pub struct SpecError {
349 field: SpecField,
350 problem: String,
351}
352
353impl SpecError {
354 fn new(field: SpecField, problem: impl Into<String>) -> Self {
355 Self {
356 field,
357 problem: problem.into(),
358 }
359 }
360
361 pub fn field(&self) -> SpecField {
362 self.field
363 }
364
365 pub fn problem(&self) -> &str {
366 &self.problem
367 }
368}
369
370#[derive(Clone, Copy, Debug, PartialEq, Eq)]
371pub enum SpecField {
372 Name,
373 Image,
374 Entrypoint,
375 Command,
376 Environment,
377 Cpus,
378 Memory,
379 Seed,
380 Network,
381}
382
383impl fmt::Display for SpecField {
384 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385 f.write_str(match self {
386 Self::Name => "name",
387 Self::Image => "image",
388 Self::Entrypoint => "entrypoint",
389 Self::Command => "command",
390 Self::Environment => "environment",
391 Self::Cpus => "cpus",
392 Self::Memory => "memory",
393 Self::Seed => "seed",
394 Self::Network => "network",
395 })
396 }
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 #[test]
404 fn only_a_spec_without_a_program_takes_commands() {
405 for (command, entrypoint, takes_commands) in [
406 (vec![], None, true),
407 (vec!["echo".to_owned()], None, false),
408 (vec![], Some("/bin/sh".to_owned()), false),
409 (vec!["hi".to_owned()], Some("/bin/echo".to_owned()), false),
410 ] {
411 let spec = SandboxSpec::try_from(SandboxDraft {
412 command,
413 entrypoint,
414 ..draft()
415 })
416 .unwrap();
417 assert_eq!(spec.takes_commands(), takes_commands);
418 }
419 }
420
421 fn draft() -> SandboxDraft {
422 SandboxDraft {
423 name: "hello".to_owned(),
424 image: "alpine:3.20".to_owned(),
425 command: vec!["echo".to_owned(), "hi".to_owned()],
426 environment: vec![EnvironmentVariable {
427 name: "RUST_LOG".to_owned(),
428 value: "debug".to_owned(),
429 }],
430 ..SandboxDraft::default()
431 }
432 }
433
434 fn refused_field(change: impl FnOnce(&mut SandboxDraft)) -> SpecField {
435 let mut draft = draft();
436 change(&mut draft);
437 SandboxSpec::try_from(draft).unwrap_err().field()
438 }
439
440 #[test]
441 fn a_draft_becomes_a_spec_and_back() {
442 let spec = SandboxSpec::try_from(draft()).unwrap();
443 assert_eq!(spec.image().as_str(), "alpine:3.20");
444 assert_eq!(SandboxDraft::from(spec), draft());
445 }
446
447 #[test]
448 fn a_draft_needs_only_its_image() {
449 let draft: SandboxDraft =
450 serde_json::from_str(r#"{"image":"ghcr.io/owner/my_app:1"}"#).unwrap();
451 let spec = SandboxSpec::try_from(draft).unwrap();
452 assert_eq!(
453 SandboxDraft::from(spec.clone()),
454 SandboxDraft {
455 name: "my-app".to_owned(),
456 image: "ghcr.io/owner/my_app:1".to_owned(),
457 ..SandboxDraft::default()
458 }
459 );
460 assert!(spec.command().is_empty() && spec.entrypoint().is_none());
461 }
462
463 #[test]
464 fn each_field_is_checked() {
465 let network = |d: &mut SandboxDraft| {
466 d.network = SandboxNetwork::Allowlist {
467 allow: vec!["::1".into()],
468 }
469 };
470 assert_eq!(refused_field(network), SpecField::Network);
471 assert_eq!(refused_field(|d| d.name = "Hello".into()), SpecField::Name);
472 assert_eq!(refused_field(|d| d.name = "-a".into()), SpecField::Name);
473 assert_eq!(refused_field(|d| d.name = "a".repeat(64)), SpecField::Name);
474 assert_eq!(
475 refused_field(|d| d.image = "--volume=/:/h".into()),
476 SpecField::Image
477 );
478 assert_eq!(
479 refused_field(|d| d.entrypoint = Some(String::new())),
480 SpecField::Entrypoint
481 );
482 assert_eq!(
483 refused_field(|d| d.command.push("a\0b".into())),
484 SpecField::Command
485 );
486 assert_eq!(
487 refused_field(|d| d.environment[0].name = "1A".into()),
488 SpecField::Environment
489 );
490 assert_eq!(
491 refused_field(|d| d.environment.push(d.environment[0].clone())),
492 SpecField::Environment
493 );
494 assert_eq!(refused_field(|d| d.cpus = 0), SpecField::Cpus);
495 assert_eq!(refused_field(|d| d.memory_mib = 64), SpecField::Memory);
496 assert_eq!(refused_field(|d| d.seed = 1 << 53), SpecField::Seed);
497 }
498
499 #[test]
500 fn deserializing_checks() {
501 let json = serde_json::to_string(&draft()).unwrap();
502 let spec: SandboxSpec = serde_json::from_str(&json).unwrap();
503 assert_eq!(spec, SandboxSpec::try_from(draft()).unwrap());
504
505 let invalid = serde_json::to_string(&SandboxDraft {
506 cpus: 64,
507 ..draft()
508 })
509 .unwrap();
510 assert!(serde_json::from_str::<SandboxSpec>(&invalid).is_err());
511 }
512
513 #[test]
514 fn a_sandbox_keeps_the_newer_copy_of_its_run() {
515 use crate::Timestamp;
516 let run = |id: i64, state: RunState, version: u64| Run {
517 id: RunId::new(id),
518 state,
519 runner: None,
520 created_at: Timestamp::from_unix_millis(0),
521 started_at: None,
522 ended_at: None,
523 has_timeline: false,
524 inspectable: false,
525 outdated: false,
526 version,
527 };
528 let mut sandbox = Sandbox {
529 id: SandboxId::new(1),
530 owner: None,
531 spec: SandboxSpec::try_from(draft()).unwrap(),
532 run: run(1, RunState::Queued, 1),
533 };
534 assert!(sandbox.take(&run(1, RunState::Running, 2)));
535 assert_eq!(sandbox.run.state, RunState::Running);
536 assert!(sandbox.take(&run(1, RunState::Queued, 0)));
537 assert_eq!(sandbox.run.state, RunState::Running);
538 assert!(!sandbox.take(&run(2, RunState::Running, 3)));
539 }
540
541 #[test]
542 fn inspectability_reports_why_not() {
543 use crate::Timestamp;
544 let sandbox = |state: RunState, inspectable: bool, outdated: bool| Sandbox {
545 id: SandboxId::new(1),
546 owner: None,
547 spec: SandboxSpec::try_from(draft()).unwrap(),
548 run: Run {
549 id: RunId::new(1),
550 state,
551 runner: Some("test".to_owned()),
552 created_at: Timestamp::from_unix_millis(0),
553 started_at: None,
554 ended_at: None,
555 has_timeline: true,
556 inspectable,
557 outdated,
558 version: 0,
559 },
560 };
561 assert!(
562 sandbox(RunState::Stopped, false, false)
563 .check_inspectable()
564 .unwrap_err()
565 .contains("stopped")
566 );
567 assert!(
568 sandbox(RunState::Exited { code: 0 }, false, true)
569 .check_inspectable()
570 .unwrap_err()
571 .contains("older dvm")
572 );
573 assert_eq!(
574 sandbox(RunState::Exited { code: 3 }, true, false).check_inspectable(),
575 Ok(())
576 );
577 }
578}