Skip to main content

dvm_api/
run.rs

1use std::fmt;
2
3use base64::Engine;
4use base64::engine::general_purpose::STANDARD as BASE64;
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6
7use crate::{SandboxId, Timestamp};
8
9/// A run's id, the controller's.
10#[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 RunId(i64);
15
16impl RunId {
17    pub fn new(id: i64) -> Self {
18        Self(id)
19    }
20
21    pub fn get(self) -> i64 {
22        self.0
23    }
24}
25
26impl fmt::Display for RunId {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        self.0.fmt(f)
29    }
30}
31
32/// A sandbox's run, of its spec, recorded; or a replay of its recording.
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
34#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
35#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
36pub struct Run {
37    pub id: RunId,
38    /// The run whose recording this one replays, if it's a replay.
39    pub replay_of: Option<RunId>,
40    pub state: RunState,
41    /// The runner it was sent to, once it was.
42    pub runner: Option<String>,
43    /// When it was queued.
44    pub created_at: Timestamp,
45    pub started_at: Option<Timestamp>,
46    pub ended_at: Option<Timestamp>,
47    /// The size of its log, which its runner keeps, once it ended; none
48    /// for a replay, or a run that left no log.
49    pub log_bytes: Option<u64>,
50    /// Whether its log was made by another dvm than its runner's now: a log
51    /// replays only on the dvm that made it.
52    pub log_outdated: bool,
53    /// A replay's, once it exited: whether it was the run it replayed.
54    pub verdict: Option<ReplayVerdict>,
55    /// How many times it changed: of two copies of a run, the one with the
56    /// higher version is the newer.
57    pub version: u64,
58}
59
60impl Run {
61    /// Whether this copy is the run as it is in `shown`'s place, or newer:
62    /// the same run, and changed no fewer times. An answer and an event may
63    /// come out of order; the newer stays.
64    pub fn supersedes(&self, shown: &Run) -> bool {
65        self.id == shown.id && self.version >= shown.version
66    }
67
68    /// The sandbox it's of: its own, or the one it replays.
69    pub fn sandbox(&self) -> SandboxId {
70        SandboxId::new(self.replay_of.unwrap_or(self.id).get())
71    }
72
73    /// Whether it may be replayed, and why not: it's no replay itself, its
74    /// log is `whole` (one cut short replays only up to its cut), its runner
75    /// keeps it, and its runner's dvm made it. Its sandbox says
76    /// whether it's whole (`Sandbox::replayable`).
77    pub(crate) fn replayable_if_whole(&self, whole: bool) -> Result<(), String> {
78        if let Some(recorded) = self.replay_of {
79            return Err(format!("run {} is a replay of run {recorded}", self.id));
80        }
81        if !whole {
82            return Err(format!(
83                "run {} didn't exit, so its log is cut short",
84                self.id
85            ));
86        }
87        if self.log_bytes.is_none() {
88            return Err(format!("run {} has no log", self.id));
89        }
90        if self.log_outdated {
91            return Err(format!(
92                "run {}'s log was made by another dvm than its runner's now: run it again",
93                self.id
94            ));
95        }
96        Ok(())
97    }
98}
99
100/// Whether a replay was the run it replayed, as far as can be seen from
101/// outside: its exit code, and its output, byte for byte.
102#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
103#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
104#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
105#[serde(tag = "kind", rename_all = "snake_case")]
106pub enum ReplayVerdict {
107    /// The same exit code, and the same output.
108    Same,
109    OtherExit {
110        recorded: i32,
111        replayed: i32,
112    },
113    /// Another output: the stream it parted in first, and at which byte.
114    OtherOutput {
115        stream: OutputStream,
116        at: u64,
117    },
118}
119
120impl ReplayVerdict {
121    pub fn is_same(&self) -> bool {
122        matches!(self, Self::Same)
123    }
124}
125
126/// One of a program's output streams.
127#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
128#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
129#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
130#[serde(rename_all = "snake_case")]
131pub enum OutputStream {
132    Stdout,
133    Stderr,
134}
135
136impl OutputStream {
137    /// Its name, as a file of a run's output is named.
138    pub fn name(self) -> &'static str {
139        match self {
140            Self::Stdout => "stdout",
141            Self::Stderr => "stderr",
142        }
143    }
144}
145
146/// Bytes as a program wrote them: base64 in JSON, since they needn't be
147/// UTF-8.
148#[derive(Clone, Debug, Default, PartialEq, Eq)]
149#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
150#[cfg_attr(
151    feature = "typescript",
152    ts(export_to = "controller-api.ts", type = "string")
153)]
154pub struct ByteChunk(Vec<u8>);
155
156impl ByteChunk {
157    pub fn new(bytes: Vec<u8>) -> Self {
158        Self(bytes)
159    }
160
161    pub fn bytes(&self) -> &[u8] {
162        &self.0
163    }
164}
165
166impl Serialize for ByteChunk {
167    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
168        serializer.serialize_str(&BASE64.encode(&self.0))
169    }
170}
171
172impl<'de> Deserialize<'de> for ByteChunk {
173    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
174        let encoded = String::deserialize(deserializer)?;
175        BASE64
176            .decode(encoded)
177            .map(Self)
178            .map_err(serde::de::Error::custom)
179    }
180}
181
182/// What a run's program has written so far, as bytes.
183#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
184#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
185#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
186pub struct RunOutput {
187    pub stdout: ByteChunk,
188    pub stderr: ByteChunk,
189}
190
191/// Where a run is:
192///
193/// ```text
194/// Queued → Running ⇄ Paused
195/// Queued | Running | Paused → Exited | Stopped | Failed
196/// ```
197#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
198#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
199#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
200#[serde(tag = "kind", rename_all = "snake_case")]
201pub enum RunState {
202    /// Waiting for a runner to take it, or for the one it was sent to to
203    /// start it.
204    Queued,
205    Running,
206    Paused,
207    /// The program exited, with its code.
208    Exited {
209        code: i32,
210    },
211    /// Stopped by its owner.
212    Stopped,
213    /// Ended by dvm or the platform, not by the program, and why.
214    Failed {
215        reason: String,
216    },
217}
218
219impl RunState {
220    /// The state's name, as the API and the controller's database spell it.
221    pub fn kind(&self) -> &'static str {
222        match self {
223            Self::Queued => "queued",
224            Self::Running => "running",
225            Self::Paused => "paused",
226            Self::Exited { .. } => "exited",
227            Self::Stopped => "stopped",
228            Self::Failed { .. } => "failed",
229        }
230    }
231
232    /// Whether the run hasn't ended.
233    pub fn is_active(&self) -> bool {
234        matches!(self, Self::Queued | Self::Running | Self::Paused)
235    }
236
237    /// The state an owner's action takes the run to, if the action may be
238    /// taken: a queued run can only be stopped, before it starts.
239    pub fn after(&self, action: RunAction) -> Result<Self, InvalidRunAction> {
240        match (self, action) {
241            (Self::Running, RunAction::Pause) => Ok(Self::Paused),
242            (Self::Paused, RunAction::Resume) => Ok(Self::Running),
243            (Self::Queued | Self::Running | Self::Paused, RunAction::Stop) => Ok(Self::Stopped),
244            _ => Err(InvalidRunAction {
245                action,
246                state: self.kind(),
247            }),
248        }
249    }
250
251    pub fn allows(&self, action: RunAction) -> bool {
252        self.after(action).is_ok()
253    }
254}
255
256/// What an owner may do to a sandbox's run, besides starting it, as it's
257/// made: the last segment of its path, `POST /api/sandboxes/{id}/{action}`;
258/// a replay may be stopped, `POST /api/replays/{id}/stop`.
259#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
260#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
261#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
262#[serde(rename_all = "snake_case")]
263pub enum RunAction {
264    Pause,
265    Resume,
266    Stop,
267}
268
269impl fmt::Display for RunAction {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        f.write_str(match self {
272            Self::Pause => "pause",
273            Self::Resume => "resume",
274            Self::Stop => "stop",
275        })
276    }
277}
278
279/// An action the run's state doesn't allow.
280#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
281#[error("can't {action} a run that is {state}")]
282pub struct InvalidRunAction {
283    action: RunAction,
284    state: &'static str,
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn actions_follow_the_state_machine() {
293        use RunAction::*;
294        let exited = RunState::Exited { code: 0 };
295        let failed = RunState::Failed {
296            reason: "unserved syscall".to_owned(),
297        };
298        let cases = [
299            (RunState::Queued, Pause, None),
300            (RunState::Queued, Resume, None),
301            (RunState::Queued, Stop, Some(RunState::Stopped)),
302            (RunState::Running, Pause, Some(RunState::Paused)),
303            (RunState::Running, Resume, None),
304            (RunState::Running, Stop, Some(RunState::Stopped)),
305            (RunState::Paused, Pause, None),
306            (RunState::Paused, Resume, Some(RunState::Running)),
307            (RunState::Paused, Stop, Some(RunState::Stopped)),
308            (exited.clone(), Stop, None),
309            (RunState::Stopped, Stop, None),
310            (failed.clone(), Resume, None),
311        ];
312        for (state, action, after) in cases {
313            assert_eq!(state.after(action).ok(), after, "{action} from {state:?}");
314        }
315        assert!(!exited.is_active() && !failed.is_active());
316    }
317
318    #[test]
319    fn a_refusal_says_why() {
320        let error = RunState::Queued.after(RunAction::Pause).unwrap_err();
321        assert_eq!(error.to_string(), "can't pause a run that is queued");
322    }
323
324    #[test]
325    fn serializes_tagged() {
326        let json = serde_json::to_string(&RunState::Exited { code: 3 }).unwrap();
327        assert_eq!(json, r#"{"kind":"exited","code":3}"#);
328        assert_eq!(
329            serde_json::to_string(&RunAction::Resume).unwrap(),
330            r#""resume""#
331        );
332    }
333}