1use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::io::{self, Read, Write};
5
6pub const VERSION: u32 = 1;
8pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
10#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(try_from = "String", into = "String")]
13pub struct RunId(String);
14impl RunId {
15 pub fn as_str(&self) -> &str {
17 &self.0
18 }
19}
20impl TryFrom<String> for RunId {
21 type Error = &'static str;
22 fn try_from(value: String) -> Result<Self, Self::Error> {
23 let (base, suffix) = value
24 .split_once('-')
25 .map_or((value.as_str(), None), |(b, s)| (b, Some(s)));
26 let b = base.as_bytes();
27 if b.len() != 26
28 || b[8] != b'T'
29 || b[15] != b'.'
30 || b[25] != b'Z'
31 || !b
32 .iter()
33 .enumerate()
34 .all(|(i, c)| matches!(i, 8 | 15 | 25) || c.is_ascii_digit())
35 || suffix.is_some_and(|s| s.is_empty() || !s.bytes().all(|c| c.is_ascii_digit()))
36 {
37 return Err("invalid UTC run identity");
38 }
39 let number = |range: std::ops::Range<usize>| base[range].parse::<u32>().unwrap();
40 let year = number(0..4);
41 let month = number(4..6);
42 let day = number(6..8);
43 let leap =
44 year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400));
45 let days = match month {
46 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
47 4 | 6 | 9 | 11 => 30,
48 2 => {
49 if leap {
50 29
51 } else {
52 28
53 }
54 }
55 _ => 0,
56 };
57 if year == 0
58 || day == 0
59 || day > days
60 || number(9..11) > 23
61 || number(11..13) > 59
62 || number(13..15) > 59
63 {
64 return Err("invalid UTC calendar time");
65 }
66 Ok(Self(value))
67 }
68}
69impl From<RunId> for String {
70 fn from(id: RunId) -> Self {
71 id.0
72 }
73}
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum Outcome {
78 Starting,
80 Running,
82 Completed,
84 Failed,
86 Cancelled,
88}
89impl Outcome {
90 pub fn terminal(self) -> bool {
92 matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
93 }
94}
95#[derive(Clone, Debug, Serialize, Deserialize)]
97pub struct Status {
98 pub version: u32,
100 pub run_id: String,
102 pub sequence: u64,
104 pub updated_at: String,
106 pub pid: u32,
108 pub outcome: Outcome,
110 pub pause_reason: Option<String>,
112 pub control: String,
114 pub study: Option<String>,
116 pub tasks: std::collections::BTreeMap<String, Value>,
118 pub allocations: Value,
120 pub message: Option<String>,
122 pub wall_ms: u64,
124 pub active_ms: u64,
126}
127#[derive(Clone, Debug, Serialize, Deserialize)]
129pub struct Event {
130 pub sequence: u64,
132 pub at: String,
134 pub kind: String,
136 pub data: Value,
138}
139#[derive(Clone, Debug, Serialize, Deserialize)]
141#[serde(deny_unknown_fields)]
142pub struct Request {
143 pub version: u32,
145 pub id: String,
147 pub command: Command,
149}
150#[derive(Clone, Debug, Serialize, Deserialize)]
152#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
153pub enum Command {
154 Hello,
156 Status,
158 Events {
160 after: u64,
162 },
163 Wait,
165 Pause,
167 Resume,
169 Cancel,
171}
172#[derive(Clone, Debug, Serialize, Deserialize)]
174pub struct Response {
175 pub version: u32,
177 pub id: String,
179 pub error: Option<String>,
181 pub message: Option<String>,
183 pub status: Status,
185 pub events: Vec<Event>,
187}
188pub fn write_frame(w: &mut impl Write, value: &impl Serialize) -> io::Result<()> {
190 let bytes = serde_json::to_vec(value).map_err(io::Error::other)?;
191 if bytes.len() > MAX_FRAME_BYTES {
192 return Err(io::Error::new(
193 io::ErrorKind::InvalidData,
194 "frame too large",
195 ));
196 }
197 w.write_all(&(bytes.len() as u32).to_be_bytes())?;
198 w.write_all(&bytes)?;
199 w.flush()
200}
201pub fn read_frame<T: serde::de::DeserializeOwned>(r: &mut impl Read) -> io::Result<T> {
203 let mut len = [0; 4];
204 r.read_exact(&mut len)?;
205 let len = u32::from_be_bytes(len) as usize;
206 if len == 0 || len > MAX_FRAME_BYTES {
207 return Err(io::Error::new(
208 io::ErrorKind::InvalidData,
209 "invalid frame length",
210 ));
211 }
212 let mut bytes = vec![0; len];
213 r.read_exact(&mut bytes)?;
214 serde_json::from_slice(&bytes).map_err(io::Error::other)
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 #[test]
221 fn utc_id_validates_calendar_and_collision_suffix() {
222 for id in [
223 "20261128T174205.123456789Z",
224 "20240229T235959.000000000Z-0001",
225 ] {
226 assert!(RunId::try_from(id.to_owned()).is_ok());
227 }
228 for id in [
229 "20260229T174205.123456789Z",
230 "20261301T000000.000000000Z",
231 "20261128T240000.000000000Z",
232 "20261128T174205.123456789Z-",
233 "../run",
234 ] {
235 assert!(RunId::try_from(id.to_owned()).is_err());
236 }
237 }
238 #[test]
239 fn frames_reject_limits_truncation_and_invalid_json() {
240 for bytes in [
241 vec![0, 0, 0, 0],
242 ((MAX_FRAME_BYTES + 1) as u32).to_be_bytes().to_vec(),
243 vec![0, 0, 0, 2, b'{'],
244 vec![0, 0, 0, 1, b'?'],
245 ] {
246 assert!(read_frame::<Value>(&mut bytes.as_slice()).is_err());
247 }
248 let mut bytes = Vec::new();
249 let request = Request {
250 version: VERSION,
251 id: "client-1".into(),
252 command: Command::Events { after: 42 },
253 };
254 write_frame(&mut bytes, &request).unwrap();
255 let decoded: Request = read_frame(&mut bytes.as_slice()).unwrap();
256 assert_eq!(decoded.id, "client-1");
257 }
258}