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