use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io::{self, Read, Write};
pub const VERSION: u32 = 1;
pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct RunId(String);
impl RunId {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for RunId {
type Error = &'static str;
fn try_from(value: String) -> Result<Self, Self::Error> {
let (base, suffix) = value
.split_once('-')
.map_or((value.as_str(), None), |(b, s)| (b, Some(s)));
let b = base.as_bytes();
if b.len() != 26
|| b[8] != b'T'
|| b[15] != b'.'
|| b[25] != b'Z'
|| !b
.iter()
.enumerate()
.all(|(i, c)| matches!(i, 8 | 15 | 25) || c.is_ascii_digit())
|| suffix.is_some_and(|s| s.is_empty() || !s.bytes().all(|c| c.is_ascii_digit()))
{
return Err("invalid UTC run identity");
}
let number = |range: std::ops::Range<usize>| base[range].parse::<u32>().unwrap();
let year = number(0..4);
let month = number(4..6);
let day = number(6..8);
let leap =
year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400));
let days = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
if leap {
29
} else {
28
}
}
_ => 0,
};
if year == 0
|| day == 0
|| day > days
|| number(9..11) > 23
|| number(11..13) > 59
|| number(13..15) > 59
{
return Err("invalid UTC calendar time");
}
Ok(Self(value))
}
}
impl From<RunId> for String {
fn from(id: RunId) -> Self {
id.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
Starting,
Running,
Completed,
Failed,
Cancelled,
}
impl Outcome {
pub fn terminal(self) -> bool {
matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Status {
pub version: u32,
pub run_id: String,
pub sequence: u64,
pub updated_at: String,
pub pid: u32,
pub outcome: Outcome,
pub pause_reason: Option<String>,
pub control: String,
pub study: Option<String>,
pub tasks: std::collections::BTreeMap<String, Value>,
pub allocations: Value,
pub message: Option<String>,
pub wall_ms: u64,
pub active_ms: u64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Event {
pub sequence: u64,
pub at: String,
pub kind: String,
pub data: Value,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
pub version: u32,
pub id: String,
pub command: Command,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum Command {
Hello,
Status,
Events {
after: u64,
},
Wait,
Pause,
Resume,
Cancel,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Response {
pub version: u32,
pub id: String,
pub error: Option<String>,
pub message: Option<String>,
pub status: Status,
pub events: Vec<Event>,
}
pub fn write_frame(w: &mut impl Write, value: &impl Serialize) -> io::Result<()> {
let bytes = serde_json::to_vec(value).map_err(io::Error::other)?;
if bytes.len() > MAX_FRAME_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"frame too large",
));
}
w.write_all(&(bytes.len() as u32).to_be_bytes())?;
w.write_all(&bytes)?;
w.flush()
}
pub fn read_frame<T: serde::de::DeserializeOwned>(r: &mut impl Read) -> io::Result<T> {
let mut len = [0; 4];
r.read_exact(&mut len)?;
let len = u32::from_be_bytes(len) as usize;
if len == 0 || len > MAX_FRAME_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid frame length",
));
}
let mut bytes = vec![0; len];
r.read_exact(&mut bytes)?;
serde_json::from_slice(&bytes).map_err(io::Error::other)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utc_id_validates_calendar_and_collision_suffix() {
for id in [
"20261128T174205.123456789Z",
"20240229T235959.000000000Z-0001",
] {
assert!(RunId::try_from(id.to_owned()).is_ok());
}
for id in [
"20260229T174205.123456789Z",
"20261301T000000.000000000Z",
"20261128T240000.000000000Z",
"20261128T174205.123456789Z-",
"../run",
] {
assert!(RunId::try_from(id.to_owned()).is_err());
}
}
#[test]
fn frames_reject_limits_truncation_and_invalid_json() {
for bytes in [
vec![0, 0, 0, 0],
((MAX_FRAME_BYTES + 1) as u32).to_be_bytes().to_vec(),
vec![0, 0, 0, 2, b'{'],
vec![0, 0, 0, 1, b'?'],
] {
assert!(read_frame::<Value>(&mut bytes.as_slice()).is_err());
}
let mut bytes = Vec::new();
let request = Request {
version: VERSION,
id: "client-1".into(),
command: Command::Events { after: 42 },
};
write_frame(&mut bytes, &request).unwrap();
let decoded: Request = read_frame(&mut bytes.as_slice()).unwrap();
assert_eq!(decoded.id, "client-1");
}
}