scientific-workflow 0.18.0

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
//! Versioned local engine protocol. Independent of the execution library.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io::{self, Read, Write};

/// Current wire generation. Mismatches are rejected before commands execute.
pub const VERSION: u32 = 1;
/// Maximum encoded JSON frame size (8 MiB).
pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
/// Stable run identity: UTC nanosecond timestamp, with optional collision suffix.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct RunId(String);
impl RunId {
    /// Returns the validated identifier.
    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
    }
}
/// A terminal outcome; liveness is a separate property.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
    /// Input capture or engine startup is still in progress.
    Starting,
    /// Execution is active or waiting for its final authoritative commit.
    Running,
    /// Execution and the final authoritative commit succeeded.
    Completed,
    /// Execution ended with a failure.
    Failed,
    /// Cooperative cancellation ended execution.
    Cancelled,
}
impl Outcome {
    /// Whether execution has ended.
    pub fn terminal(self) -> bool {
        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
    }
}
/// Canonical engine snapshot, also persisted for offline inspection.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Status {
    /// Format generation.
    pub version: u32,
    /// Operational run identity.
    pub run_id: String,
    /// Last durable lifecycle sequence.
    pub sequence: u64,
    /// Last observation time (UTC).
    pub updated_at: String,
    /// Engine process identity; does not alone prove current liveness.
    pub pid: u32,
    /// Recorded lifecycle outcome.
    pub outcome: Outcome,
    /// Current pause reason.
    pub pause_reason: Option<String>,
    /// Cooperative control state, including whether active calls have parked.
    pub control: String,
    /// Scientific study currently active in a serial campaign.
    pub study: Option<String>,
    /// Last observed task facts, keyed by study/replicate/task identity.
    pub tasks: std::collections::BTreeMap<String, Value>,
    /// Current thread allocation facts.
    pub allocations: Value,
    /// Failure details or final explanation.
    pub message: Option<String>,
    /// Wall-clock elapsed milliseconds.
    pub wall_ms: u64,
    /// Active execution milliseconds, excluding pauses.
    pub active_ms: u64,
}
/// A durable event with monotonically increasing sequence.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Event {
    /// Sequence within this run.
    pub sequence: u64,
    /// UTC observation time.
    pub at: String,
    /// Stable event kind.
    pub kind: String,
    /// Structured runtime-owned facts.
    pub data: Value,
}
/// One request on a framed connection.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
    /// Required wire version.
    pub version: u32,
    /// Client-generated id, echoed in the response.
    pub id: String,
    /// Requested operation.
    pub command: Command,
}
/// Read, wait, replay and control operations.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum Command {
    /// Negotiate version and inspect status.
    Hello,
    /// Fetch a current snapshot.
    Status,
    /// Return a bounded page of durable events after the cursor.
    Events {
        /// Exclusive sequence cursor.
        after: u64,
    },
    /// Wait until the actual engine outcome is terminal.
    Wait,
    /// Cooperatively pause the active study.
    Pause,
    /// Explicitly resume after all safety gates recover.
    Resume,
    /// Cooperatively cancel execution.
    Cancel,
}
/// Acknowledgement or structured error. Read-only requests do not mutate the run.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Response {
    /// Server protocol version.
    pub version: u32,
    /// Original command id.
    pub id: String,
    /// Stable error code, absent for success.
    pub error: Option<String>,
    /// Human-readable details.
    pub message: Option<String>,
    /// Current canonical snapshot.
    pub status: Status,
    /// Bounded event replay page.
    pub events: Vec<Event>,
}
/// Writes one length-prefixed JSON frame without allowing unbounded allocation.
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()
}
/// Reads one frame, rejecting oversize and truncated messages.
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");
    }
}