Skip to main content

scientific_workflow_protocol/
lib.rs

1//! Versioned local engine protocol. Independent of the execution library.
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::io::{self, Read, Write};
5
6/// Current wire generation. Mismatches are rejected before commands execute.
7pub const VERSION: u32 = 1;
8/// Maximum encoded JSON frame size (8 MiB).
9pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
10/// Stable run identity: UTC nanosecond timestamp, with optional collision suffix.
11#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(try_from = "String", into = "String")]
13pub struct RunId(String);
14impl RunId {
15    /// Returns the validated identifier.
16    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/// A terminal outcome; liveness is a separate property.
75#[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    /// Whether execution has ended.
86    pub fn terminal(self) -> bool {
87        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
88    }
89}
90/// Canonical engine snapshot, also persisted for offline inspection.
91#[derive(Clone, Debug, Serialize, Deserialize)]
92pub struct Status {
93    /// Format generation.
94    pub version: u32,
95    /// Operational run identity.
96    pub run_id: String,
97    /// Last durable lifecycle sequence.
98    pub sequence: u64,
99    /// Last observation time (UTC).
100    pub updated_at: String,
101    /// Engine process identity; does not alone prove current liveness.
102    pub pid: u32,
103    /// Recorded lifecycle outcome.
104    pub outcome: Outcome,
105    /// Current pause reason.
106    pub pause_reason: Option<String>,
107    /// Cooperative control state, including whether active calls have parked.
108    pub control: String,
109    /// Scientific study currently active in a serial campaign.
110    pub study: Option<String>,
111    /// Last observed task facts, keyed by study/replicate/task identity.
112    pub tasks: std::collections::BTreeMap<String, Value>,
113    /// Current thread allocation facts.
114    pub allocations: Value,
115    /// Failure details or final explanation.
116    pub message: Option<String>,
117    /// Wall-clock elapsed milliseconds.
118    pub wall_ms: u64,
119    /// Active execution milliseconds, excluding pauses.
120    pub active_ms: u64,
121}
122/// A durable event with monotonically increasing sequence.
123#[derive(Clone, Debug, Serialize, Deserialize)]
124pub struct Event {
125    /// Sequence within this run.
126    pub sequence: u64,
127    /// UTC observation time.
128    pub at: String,
129    /// Stable event kind.
130    pub kind: String,
131    /// Structured runtime-owned facts.
132    pub data: Value,
133}
134/// One request on a framed connection.
135#[derive(Clone, Debug, Serialize, Deserialize)]
136#[serde(deny_unknown_fields)]
137pub struct Request {
138    /// Required wire version.
139    pub version: u32,
140    /// Client-generated id, echoed in the response.
141    pub id: String,
142    /// Requested operation.
143    pub command: Command,
144}
145/// Read, wait, replay and control operations.
146#[derive(Clone, Debug, Serialize, Deserialize)]
147#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
148pub enum Command {
149    /// Negotiate version and inspect status.
150    Hello,
151    /// Fetch a current snapshot.
152    Status,
153    /// Return a bounded page of durable events after the cursor.
154    Events {
155        /// Exclusive sequence cursor.
156        after: u64,
157    },
158    /// Wait until the actual engine outcome is terminal.
159    Wait,
160    /// Cooperatively pause the active study.
161    Pause,
162    /// Explicitly resume after all safety gates recover.
163    Resume,
164    /// Cooperatively cancel execution.
165    Cancel,
166}
167/// Acknowledgement or structured error. Read-only requests do not mutate the run.
168#[derive(Clone, Debug, Serialize, Deserialize)]
169pub struct Response {
170    /// Server protocol version.
171    pub version: u32,
172    /// Original command id.
173    pub id: String,
174    /// Stable error code, absent for success.
175    pub error: Option<String>,
176    /// Human-readable details.
177    pub message: Option<String>,
178    /// Current canonical snapshot.
179    pub status: Status,
180    /// Bounded event replay page.
181    pub events: Vec<Event>,
182}
183/// Writes one length-prefixed JSON frame without allowing unbounded allocation.
184pub 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}
196/// Reads one frame, rejecting oversize and truncated messages.
197pub 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}