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)]
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 RunId(i64);
14
15impl RunId {
16 pub fn new(id: i64) -> Self {
17 Self(id)
18 }
19
20 pub fn get(self) -> i64 {
21 self.0
22 }
23}
24
25impl fmt::Display for RunId {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 self.0.fmt(f)
28 }
29}
30
31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
33#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
34pub struct Run {
35 pub id: RunId,
36 pub state: RunState,
37 pub runner: Option<String>,
38 pub created_at: Timestamp,
39 pub started_at: Option<Timestamp>,
40 pub ended_at: Option<Timestamp>,
41 pub has_timeline: bool,
42 pub inspectable: bool,
43 pub outdated: bool,
44 pub version: u64,
45}
46
47impl Run {
48 pub fn supersedes(&self, shown: &Run) -> bool {
49 self.id == shown.id && self.version >= shown.version
50 }
51
52 pub fn sandbox(&self) -> SandboxId {
53 SandboxId::new(self.id.get())
54 }
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
58#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
59#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
60#[serde(rename_all = "snake_case")]
61pub enum OutputStream {
62 Stdout,
63 Stderr,
64}
65
66impl OutputStream {
67 pub fn name(self) -> &'static str {
68 match self {
69 Self::Stdout => "stdout",
70 Self::Stderr => "stderr",
71 }
72 }
73}
74
75#[derive(Clone, Debug, Default, PartialEq, Eq)]
77#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
78#[cfg_attr(
79 feature = "typescript",
80 ts(export_to = "controller-api.ts", type = "string")
81)]
82pub struct ByteChunk(Vec<u8>);
83
84impl ByteChunk {
85 pub fn new(bytes: Vec<u8>) -> Self {
86 Self(bytes)
87 }
88
89 pub fn bytes(&self) -> &[u8] {
90 &self.0
91 }
92}
93
94impl Serialize for ByteChunk {
95 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
96 serializer.serialize_str(&BASE64.encode(&self.0))
97 }
98}
99
100impl<'de> Deserialize<'de> for ByteChunk {
101 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
102 let encoded = String::deserialize(deserializer)?;
103 BASE64
104 .decode(encoded)
105 .map(Self)
106 .map_err(serde::de::Error::custom)
107 }
108}
109
110#[derive(Clone, Debug, Default, 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 RunOutput {
114 pub stdout: ByteChunk,
115 pub stderr: ByteChunk,
116}
117
118#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
119#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
120#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
121#[serde(tag = "kind", rename_all = "snake_case")]
122pub enum RunState {
123 Queued,
124 Running,
125 Paused,
126 Exited { code: i32 },
127 Stopped,
128 Failed { reason: String },
129}
130
131impl RunState {
132 pub fn kind(&self) -> &'static str {
133 match self {
134 Self::Queued => "queued",
135 Self::Running => "running",
136 Self::Paused => "paused",
137 Self::Exited { .. } => "exited",
138 Self::Stopped => "stopped",
139 Self::Failed { .. } => "failed",
140 }
141 }
142
143 pub fn is_active(&self) -> bool {
144 matches!(self, Self::Queued | Self::Running | Self::Paused)
145 }
146
147 pub fn after(&self, action: RunAction) -> Result<Self, InvalidRunAction> {
148 match (self, action) {
149 (Self::Running, RunAction::Pause) => Ok(Self::Paused),
150 (Self::Paused, RunAction::Resume) => Ok(Self::Running),
151 (Self::Queued | Self::Running | Self::Paused, RunAction::Stop) => Ok(Self::Stopped),
152 _ => Err(InvalidRunAction {
153 action,
154 state: self.kind(),
155 }),
156 }
157 }
158
159 pub fn allows(&self, action: RunAction) -> bool {
160 self.after(action).is_ok()
161 }
162}
163
164#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
165#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
166#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
167#[serde(rename_all = "snake_case")]
168pub enum RunAction {
169 Pause,
170 Resume,
171 Stop,
172}
173
174impl fmt::Display for RunAction {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 f.write_str(match self {
177 Self::Pause => "pause",
178 Self::Resume => "resume",
179 Self::Stop => "stop",
180 })
181 }
182}
183
184#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
185#[error("can't {action} a run that is {state}")]
186pub struct InvalidRunAction {
187 action: RunAction,
188 state: &'static str,
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 #[test]
196 fn actions_follow_the_state_machine() {
197 use RunAction::*;
198 let exited = RunState::Exited { code: 0 };
199 let failed = RunState::Failed {
200 reason: "unserved syscall".to_owned(),
201 };
202 let cases = [
203 (RunState::Queued, Pause, None),
204 (RunState::Queued, Resume, None),
205 (RunState::Queued, Stop, Some(RunState::Stopped)),
206 (RunState::Running, Pause, Some(RunState::Paused)),
207 (RunState::Running, Resume, None),
208 (RunState::Running, Stop, Some(RunState::Stopped)),
209 (RunState::Paused, Pause, None),
210 (RunState::Paused, Resume, Some(RunState::Running)),
211 (RunState::Paused, Stop, Some(RunState::Stopped)),
212 (exited.clone(), Stop, None),
213 (RunState::Stopped, Stop, None),
214 (failed.clone(), Resume, None),
215 ];
216 for (state, action, after) in cases {
217 assert_eq!(state.after(action).ok(), after, "{action} from {state:?}");
218 }
219 assert!(!exited.is_active() && !failed.is_active());
220 }
221
222 #[test]
223 fn a_refusal_says_why() {
224 let error = RunState::Queued.after(RunAction::Pause).unwrap_err();
225 assert_eq!(error.to_string(), "can't pause a run that is queued");
226 }
227
228 #[test]
229 fn serializes_tagged() {
230 let json = serde_json::to_string(&RunState::Exited { code: 3 }).unwrap();
231 assert_eq!(json, r#"{"kind":"exited","code":3}"#);
232 assert_eq!(
233 serde_json::to_string(&RunAction::Resume).unwrap(),
234 r#""resume""#
235 );
236 }
237}