Skip to main content

scientific_workflow/
protocol.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    /// Input capture or engine startup is still in progress.
79    Starting,
80    /// Execution is active or waiting for its final authoritative commit.
81    Running,
82    /// Execution and the final authoritative commit succeeded.
83    Completed,
84    /// Execution ended with a failure.
85    Failed,
86    /// Cooperative cancellation ended execution.
87    Cancelled,
88}
89impl Outcome {
90    /// Whether execution has ended.
91    pub fn terminal(self) -> bool {
92        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
93    }
94}
95/// Canonical engine snapshot, also persisted for offline inspection.
96#[derive(Clone, Debug, Serialize, Deserialize)]
97pub struct Status {
98    /// Format generation.
99    pub version: u32,
100    /// Operational run identity.
101    pub run_id: String,
102    /// Last durable lifecycle sequence.
103    pub sequence: u64,
104    /// Last observation time (UTC).
105    pub updated_at: String,
106    /// Engine process identity; does not alone prove current liveness.
107    pub pid: u32,
108    /// Recorded lifecycle outcome.
109    pub outcome: Outcome,
110    /// Current pause reason.
111    pub pause_reason: Option<String>,
112    /// Cooperative control state, including whether active calls have parked.
113    pub control: String,
114    /// Scientific study currently active in a serial campaign.
115    pub study: Option<String>,
116    /// Last observed task facts, keyed by study/replicate/task identity.
117    pub tasks: std::collections::BTreeMap<String, Value>,
118    /// Current thread allocation facts.
119    pub allocations: Value,
120    /// Failure details or final explanation.
121    pub message: Option<String>,
122    /// Wall-clock elapsed milliseconds.
123    pub wall_ms: u64,
124    /// Active execution milliseconds, excluding pauses.
125    pub active_ms: u64,
126}
127/// A durable event with monotonically increasing sequence.
128#[derive(Clone, Debug, Serialize, Deserialize)]
129pub struct Event {
130    /// Sequence within this run.
131    pub sequence: u64,
132    /// UTC observation time.
133    pub at: String,
134    /// Stable event kind.
135    pub kind: String,
136    /// Structured runtime-owned facts.
137    pub data: Value,
138}
139/// One request on a framed connection.
140#[derive(Clone, Debug, Serialize, Deserialize)]
141#[serde(deny_unknown_fields)]
142pub struct Request {
143    /// Required wire version.
144    pub version: u32,
145    /// Client-generated id, echoed in the response.
146    pub id: String,
147    /// Requested operation.
148    pub command: Command,
149}
150/// Read, wait, replay and control operations.
151#[derive(Clone, Debug, Serialize, Deserialize)]
152#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
153pub enum Command {
154    /// Negotiate version and inspect status.
155    Hello,
156    /// Fetch a current snapshot.
157    Status,
158    /// Return a bounded page of durable events after the cursor.
159    Events {
160        /// Exclusive sequence cursor.
161        after: u64,
162    },
163    /// Wait until the actual engine outcome is terminal.
164    Wait,
165    /// Cooperatively pause the active study.
166    Pause,
167    /// Explicitly resume after all safety gates recover.
168    Resume,
169    /// Cooperatively cancel execution.
170    Cancel,
171}
172/// Acknowledgement or structured error. Read-only requests do not mutate the run.
173#[derive(Clone, Debug, Serialize, Deserialize)]
174pub struct Response {
175    /// Server protocol version.
176    pub version: u32,
177    /// Original command id.
178    pub id: String,
179    /// Stable error code, absent for success.
180    pub error: Option<String>,
181    /// Human-readable details.
182    pub message: Option<String>,
183    /// Current canonical snapshot.
184    pub status: Status,
185    /// Bounded event replay page.
186    pub events: Vec<Event>,
187}
188/// Writes one length-prefixed JSON frame without allowing unbounded allocation.
189pub 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}
201/// Reads one frame, rejecting oversize and truncated messages.
202pub 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}