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#[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#[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 pub replay_of: Option<RunId>,
40 pub state: RunState,
41 pub runner: Option<String>,
43 pub created_at: Timestamp,
45 pub started_at: Option<Timestamp>,
46 pub ended_at: Option<Timestamp>,
47 pub log_bytes: Option<u64>,
50 pub log_outdated: bool,
53 pub verdict: Option<ReplayVerdict>,
55 pub version: u64,
58}
59
60impl Run {
61 pub fn supersedes(&self, shown: &Run) -> bool {
65 self.id == shown.id && self.version >= shown.version
66 }
67
68 pub fn sandbox(&self) -> SandboxId {
70 SandboxId::new(self.replay_of.unwrap_or(self.id).get())
71 }
72
73 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#[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 Same,
109 OtherExit {
110 recorded: i32,
111 replayed: i32,
112 },
113 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#[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 pub fn name(self) -> &'static str {
139 match self {
140 Self::Stdout => "stdout",
141 Self::Stderr => "stderr",
142 }
143 }
144}
145
146#[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#[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#[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 Queued,
205 Running,
206 Paused,
207 Exited {
209 code: i32,
210 },
211 Stopped,
213 Failed {
215 reason: String,
216 },
217}
218
219impl RunState {
220 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 pub fn is_active(&self) -> bool {
234 matches!(self, Self::Queued | Self::Running | Self::Paused)
235 }
236
237 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#[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#[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}