scientific-workflow 0.18.0

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::io::{self, Read};
use std::path::PathBuf;
/// Configurable authoritative destination. Credentials remain in external profiles.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "backend", rename_all = "snake_case", deny_unknown_fields)]
pub enum StorageLocation {
    /// Local drive or mounted network filesystem.
    Filesystem {
        /// Absolute destination root.
        root: PathBuf,
    },
    /// Workflow writable object API over HTTPS.
    Https {
        /// HTTPS API base URL.
        endpoint: String,
        /// External credential JSON path.
        credential_profile: PathBuf,
    },
    /// Native Google Drive blob API.
    Gdrive {
        /// Parent folder's native ID.
        folder_id: String,
        /// External OAuth credential profile.
        credential_profile: PathBuf,
    },
}
/// Artifact meaning declared by the producing scientific task.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactRole {
    /// Required to reproduce scientific work.
    Reproduction,
    /// Removable original scientific recording.
    Raw,
    /// Retained scientific result.
    Processed,
    /// Durable lifecycle and commit evidence.
    Record,
}
/// Portable immutable object descriptor. Logical names never imply POSIX access.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ArtifactRef {
    /// Path in the run's logical tree.
    pub key: String,
    /// SHA-256 of exact stored bytes, lowercase hex.
    pub sha256: String,
    /// Exact byte length.
    pub bytes: u64,
    /// Task-declared retention meaning.
    pub role: ArtifactRole,
    /// Whether a captured software file must be executable when materialized.
    #[serde(default)]
    pub executable: bool,
}
impl ArtifactRef {
    /// Checks descriptor syntax before resolving a backend object.
    pub fn validate(&self) -> io::Result<()> {
        validate_key(&self.key)?;
        if self.sha256.len() != 64
            || !self
                .sha256
                .bytes()
                .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
        {
            return Err(io::Error::other("invalid artifact digest"));
        }
        Ok(())
    }
}
pub(crate) fn validate_key(key: &str) -> io::Result<()> {
    if key.is_empty()
        || key.starts_with('/')
        || key.contains(['\\', '\0'])
        || key
            .split('/')
            .any(|s| s.is_empty() || s == "." || s == "..")
    {
        return Err(io::Error::other("invalid logical artifact key"));
    }
    Ok(())
}
pub(crate) fn digest_bytes(bytes: &[u8]) -> String {
    hex(&Sha256::digest(bytes))
}
pub(crate) fn digest_reader(mut reader: impl Read) -> io::Result<(String, u64)> {
    let mut hash = Sha256::new();
    let mut size = 0;
    let mut buffer = [0; 65536];
    loop {
        let n = reader.read(&mut buffer)?;
        if n == 0 {
            break;
        }
        hash.update(&buffer[..n]);
        size += n as u64;
    }
    Ok((hex(&hash.finalize()), size))
}

pub(crate) fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// Retention declarations relative to one task's output directory.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ArtifactDeclarations {
    /// Produced inputs needed by this or a later scientific task.
    pub reproduction: Vec<String>,
    /// Original outputs eligible for sealing.
    pub raw: Vec<String>,
    /// Processed products that sealing must retain and verify.
    pub processed: Vec<String>,
    /// Named actual-content equality assertions, evaluated on producer commit.
    pub shared_inputs: std::collections::BTreeMap<String, String>,
}
impl ArtifactDeclarations {
    pub(crate) fn validate(&self) -> io::Result<()> {
        let mut paths = Vec::new();
        for p in self
            .reproduction
            .iter()
            .chain(&self.raw)
            .chain(&self.processed)
        {
            validate_key(p)?;
            if paths.iter().any(|q: &&String| {
                p == *q || p.starts_with(&format!("{q}/")) || q.starts_with(&format!("{p}/"))
            }) {
                return Err(io::Error::other("artifact declarations overlap"));
            }
            paths.push(p);
        }
        for (name, path) in &self.shared_inputs {
            if name.trim().is_empty() {
                return Err(io::Error::other("shared input assertion requires a name"));
            }
            validate_key(path)?;
        }
        Ok(())
    }
}

/// A portable locator for a named subtree of an authoritative run.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ArtifactLocator {
    /// Destination, with an external credential profile reference if needed.
    pub storage: StorageLocation,
    /// UTC run namespace.
    pub run_id: String,
    /// Explicit logical subtree prefix.
    pub prefix: String,
}
impl ArtifactLocator {
    /// Resolves the locator through verified backend-independent access.
    pub fn open(&self) -> io::Result<super::ArtifactSet> {
        super::ArtifactSet::new(
            super::RunArchive::open(&self.storage, &self.run_id)?,
            self.prefix.clone(),
        )
    }
}