scientific_workflow_protocol/
lib.rs1use 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,
79 Running,
80 Completed,
81 Failed,
82 Cancelled,
83}
84impl Outcome {
85 pub fn terminal(self) -> bool {
87 matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
88 }
89}
90#[derive(Clone, Debug, Serialize, Deserialize)]
92pub struct Status {
93 pub version: u32,
95 pub run_id: String,
97 pub sequence: u64,
99 pub updated_at: String,
101 pub pid: u32,
103 pub outcome: Outcome,
105 pub pause_reason: Option<String>,
107 pub control: String,
109 pub study: Option<String>,
111 pub tasks: std::collections::BTreeMap<String, Value>,
113 pub allocations: Value,
115 pub message: Option<String>,
117 pub wall_ms: u64,
119 pub active_ms: u64,
121}
122#[derive(Clone, Debug, Serialize, Deserialize)]
124pub struct Event {
125 pub sequence: u64,
127 pub at: String,
129 pub kind: String,
131 pub data: Value,
133}
134#[derive(Clone, Debug, Serialize, Deserialize)]
136#[serde(deny_unknown_fields)]
137pub struct Request {
138 pub version: u32,
140 pub id: String,
142 pub command: Command,
144}
145#[derive(Clone, Debug, Serialize, Deserialize)]
147#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
148pub enum Command {
149 Hello,
151 Status,
153 Events {
155 after: u64,
157 },
158 Wait,
160 Pause,
162 Resume,
164 Cancel,
166}
167#[derive(Clone, Debug, Serialize, Deserialize)]
169pub struct Response {
170 pub version: u32,
172 pub id: String,
174 pub error: Option<String>,
176 pub message: Option<String>,
178 pub status: Status,
180 pub events: Vec<Event>,
182}
183pub fn write_frame(w: &mut impl Write, value: &impl Serialize) -> io::Result<()> {
185 let bytes = serde_json::to_vec(value).map_err(io::Error::other)?;
186 if bytes.len() > MAX_FRAME_BYTES {
187 return Err(io::Error::new(
188 io::ErrorKind::InvalidData,
189 "frame too large",
190 ));
191 }
192 w.write_all(&(bytes.len() as u32).to_be_bytes())?;
193 w.write_all(&bytes)?;
194 w.flush()
195}
196pub fn read_frame<T: serde::de::DeserializeOwned>(r: &mut impl Read) -> io::Result<T> {
198 let mut len = [0; 4];
199 r.read_exact(&mut len)?;
200 let len = u32::from_be_bytes(len) as usize;
201 if len == 0 || len > MAX_FRAME_BYTES {
202 return Err(io::Error::new(
203 io::ErrorKind::InvalidData,
204 "invalid frame length",
205 ));
206 }
207 let mut bytes = vec![0; len];
208 r.read_exact(&mut bytes)?;
209 serde_json::from_slice(&bytes).map_err(io::Error::other)
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215 #[test]
216 fn utc_id_validates_calendar_and_collision_suffix() {
217 for id in [
218 "20261128T174205.123456789Z",
219 "20240229T235959.000000000Z-0001",
220 ] {
221 assert!(RunId::try_from(id.to_owned()).is_ok());
222 }
223 for id in [
224 "20260229T174205.123456789Z",
225 "20261301T000000.000000000Z",
226 "20261128T240000.000000000Z",
227 "20261128T174205.123456789Z-",
228 "../run",
229 ] {
230 assert!(RunId::try_from(id.to_owned()).is_err());
231 }
232 }
233 #[test]
234 fn frames_reject_limits_truncation_and_invalid_json() {
235 for bytes in [
236 vec![0, 0, 0, 0],
237 ((MAX_FRAME_BYTES + 1) as u32).to_be_bytes().to_vec(),
238 vec![0, 0, 0, 2, b'{'],
239 vec![0, 0, 0, 1, b'?'],
240 ] {
241 assert!(read_frame::<Value>(&mut bytes.as_slice()).is_err());
242 }
243 let mut bytes = Vec::new();
244 let request = Request {
245 version: VERSION,
246 id: "client-1".into(),
247 command: Command::Events { after: 42 },
248 };
249 write_frame(&mut bytes, &request).unwrap();
250 let decoded: Request = read_frame(&mut bytes.as_slice()).unwrap();
251 assert_eq!(decoded.id, "client-1");
252 }
253}