scientific-workflow 0.17.1

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
use super::{ArtifactRef, StorageLocation};
use crate::storage::{Store, atomic_json};
use serde::{Deserialize, Serialize};
use std::{
    collections::BTreeMap,
    io::{self, Read, Write},
    path::{Path, PathBuf},
};
/// Authoritative immutable inventory for one run, extended only at commit boundaries.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RunManifest {
    /// Durable bundle format.
    pub format: String,
    /// UTC namespace.
    pub run_id: String,
    /// StudyPlan or campaign.
    pub kind: String,
    /// Input tree content identity, independent of operational configuration.
    pub scientific_identity: String,
    /// Captured input and result inventory.
    pub artifacts: BTreeMap<String, ArtifactRef>,
    /// Capture finished before the first scientific task starts.
    pub capture_complete: bool,
    /// A final outcome, distinct from current engine liveness.
    pub outcome: scientific_workflow_protocol::Outcome,
    /// Declared raw keys intentionally removed by sealing.
    pub removed: Vec<String>,
}
/// Read-only access to an authoritative run inventory and verified artifacts.
#[derive(Clone)]
pub struct RunArchive {
    pub(crate) store: Store,
    pub(crate) manifest: RunManifest,
    pub(crate) maintenance_owner: Option<String>,
}
impl RunArchive {
    /// Opens a run from a configured backend without consulting the registry.
    pub fn open(location: &StorageLocation, run_id: &str) -> io::Result<Self> {
        let _: scientific_workflow_protocol::RunId =
            run_id.to_owned().try_into().map_err(io::Error::other)?;
        let store = Store::open(location)?;
        let manifest: RunManifest = store.json(&format!("{run_id}/manifest.json"))?;
        if manifest.format != "scientific-workflow-run.v1" || manifest.run_id != run_id {
            return Err(io::Error::other("unsupported run manifest"));
        }
        for (key, reference) in &manifest.artifacts {
            reference.validate()?;
            if key != &reference.key {
                return Err(io::Error::other(
                    "inventory key differs from artifact reference",
                ));
            }
        }
        let maintenance_owner = std::env::var("WORKFLOW_MAINTENANCE_OWNER")
            .ok()
            .and_then(|v| serde_json::from_str::<serde_json::Value>(&v).ok())
            .filter(|v| v["run_id"] == run_id)
            .and_then(|v| v["owner"].as_str().map(str::to_owned));
        Ok(Self {
            store,
            manifest,
            maintenance_owner,
        })
    }
    /// Returns the authoritative inventory; the registry is never used as evidence.
    pub fn manifest(&self) -> &RunManifest {
        &self.manifest
    }
    /// Looks up an available logical artifact.
    pub fn artifact(&self, key: &str) -> io::Result<&ArtifactRef> {
        if self.manifest.removed.iter().any(|k| k == key) {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "raw artifact was intentionally sealed; regenerate it",
            ));
        }
        self.manifest
            .artifacts
            .get(key)
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "artifact not in run inventory"))
    }
    /// Opens a bounded-memory, checksum-verifying stream. Consume through EOF.
    pub fn reader(&self, key: &str) -> io::Result<Box<dyn Read + Send>> {
        let reference = self.artifact(key)?;
        let lease = if reference.role == super::ArtifactRole::Raw {
            let current: RunManifest = self
                .store
                .json(&format!("{}/manifest.json", self.manifest.run_id))?;
            if current.removed.iter().any(|k| k == key) {
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    "raw artifact was intentionally sealed; regenerate it",
                ));
            }
            super::lease::ConsumerLease::acquire(
                &self.store,
                &self.manifest.run_id,
                vec![key.into()],
                self.maintenance_owner.as_deref(),
            )?
        } else {
            None
        };
        Ok(Box::new(super::lease::LeasedReader {
            input: self.store.read_verified(reference)?,
            lease,
        }))
    }
    /// Verifies one artifact completely without materializing it.
    pub fn verify(&self, key: &str) -> io::Result<()> {
        io::copy(&mut self.reader(key)?, &mut io::sink())?;
        Ok(())
    }
    /// Materializes a verified, private local copy for path-only tools and NumPy mmap.
    /// The caller must keep the returned lease alive while using its path.
    pub fn materialize(
        &self,
        prefix: &str,
        cache: &Path,
        max_bytes: u64,
    ) -> io::Result<MaterializationLease> {
        super::validate_key(prefix)?;
        if self
            .manifest
            .removed
            .iter()
            .any(|k| k == prefix || k.starts_with(&format!("{prefix}/")))
        {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "selection includes intentionally removed raw data; regenerate it",
            ));
        }
        let keys = self
            .manifest
            .artifacts
            .keys()
            .filter(|k| {
                (*k == prefix || k.starts_with(&format!("{prefix}/")))
                    && !self.manifest.removed.contains(k)
            })
            .cloned()
            .collect::<Vec<_>>();
        let mut lease = self.materialize_keys(&keys, cache, max_bytes)?;
        lease.path = lease.path.join(prefix);
        Ok(lease)
    }
    /// Materializes an explicit file selection, preserving logical paths under a
    /// private lease root. Omitted inputs can remain streamed artifact references.
    pub fn materialize_keys(
        &self,
        keys: &[String],
        cache: &Path,
        max_bytes: u64,
    ) -> io::Result<MaterializationLease> {
        let keys = keys.iter().collect::<std::collections::BTreeSet<_>>();
        if keys.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "artifact selection is empty",
            ));
        }
        let size = keys.iter().try_fold(0u64, |n, key| {
            n.checked_add(self.artifact(key)?.bytes)
                .ok_or_else(|| io::Error::other("materialization size overflow"))
        })?;
        if size > max_bytes {
            return Err(io::Error::other(
                "materialization exceeds local lease budget",
            ));
        }
        std::fs::create_dir_all(cache)?;
        let root = cache.join(format!(
            "lease-{}-{}",
            std::process::id(),
            crate::storage::run_id()
        ));
        std::fs::create_dir(&root)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700))?;
        }
        let raw_keys = keys
            .iter()
            .filter(|key| self.manifest.artifacts[key.as_str()].role == super::ArtifactRole::Raw)
            .map(|key| (**key).clone())
            .collect::<Vec<_>>();
        let consumer = super::lease::ConsumerLease::acquire(
            &self.store,
            &self.manifest.run_id,
            raw_keys,
            self.maintenance_owner.as_deref(),
        )?;
        let lease = MaterializationLease {
            path: root.join("tree"),
            root,
            _consumer: consumer,
        };
        for key in keys {
            let path = lease.path.join(key);
            std::fs::create_dir_all(path.parent().unwrap())?;
            let mut output = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&path)?;
            let mut input: Box<dyn Read + Send> = if let Some(consumer) = &lease._consumer {
                Box::new(super::lease::LeasedReader {
                    input: self.store.read_verified(self.artifact(key)?)?,
                    lease: Some(consumer.clone()),
                })
            } else {
                self.reader(key)?
            };
            io::copy(&mut input, &mut output)?;
            output.flush()?;
            output.sync_all()?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(
                    &path,
                    std::fs::Permissions::from_mode(if self.artifact(key)?.executable {
                        0o500
                    } else {
                        0o400
                    }),
                )?;
            }
        }
        atomic_json(
            &lease.root.join("lease.json"),
            &serde_json::json!({"run":self.manifest.run_id,"bytes":size}),
        )?;
        Ok(lease)
    }
}
/// A verified local materialization whose lifetime protects mmap and path consumers.
/// Dropping it removes the disposable copy, never authoritative stored data.
pub struct MaterializationLease {
    path: PathBuf,
    root: PathBuf,
    _consumer: Option<std::sync::Arc<super::lease::ConsumerLease>>,
}
impl MaterializationLease {
    /// Path of the requested materialized artifact or subtree.
    pub fn path(&self) -> &Path {
        &self.path
    }
}
impl Drop for MaterializationLease {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

/// Opens an immutable reference through the shared verified storage implementation.
/// Consume through EOF to complete verification.
pub fn open_reference(
    locator: &super::ArtifactLocator,
    reference: &ArtifactRef,
) -> io::Result<Box<dyn Read + Send>> {
    let archive = RunArchive::open(&locator.storage, &locator.run_id)?;
    if archive.artifact(&locator.prefix)? != reference {
        return Err(io::Error::other(
            "artifact pointer differs from its authoritative inventory",
        ));
    }
    archive.reader(&locator.prefix)
}

/// A named, verified subtree, usable without assuming a local filesystem.
#[derive(Clone)]
pub struct ArtifactSet {
    archive: RunArchive,
    prefix: String,
    _consumer: Option<std::sync::Arc<super::lease::ConsumerLease>>,
}
impl ArtifactSet {
    /// Selects an explicit subtree of an authoritative run inventory.
    pub fn new(archive: RunArchive, prefix: impl Into<String>) -> io::Result<Self> {
        let prefix = prefix.into();
        super::validate_key(&prefix)?;
        if !archive
            .manifest
            .artifacts
            .keys()
            .any(|k| k == &prefix || k.starts_with(&format!("{prefix}/")))
        {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "artifact subtree is absent",
            ));
        }
        if archive
            .manifest
            .removed
            .iter()
            .any(|k| k == &prefix || k.starts_with(&format!("{prefix}/")))
        {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "selection includes intentionally removed raw data; regenerate it",
            ));
        }
        let raw = archive
            .manifest
            .artifacts
            .iter()
            .filter(|(k, r)| {
                (**k == prefix || k.starts_with(&format!("{prefix}/")))
                    && r.role == super::ArtifactRole::Raw
            })
            .map(|(k, _)| k.clone())
            .collect();
        let consumer = super::lease::ConsumerLease::acquire(
            &archive.store,
            &archive.manifest.run_id,
            raw,
            archive.maintenance_owner.as_deref(),
        )?;
        Ok(Self {
            archive,
            prefix,
            _consumer: consumer,
        })
    }
    /// Exact subtree prefix in the run inventory.
    pub fn prefix(&self) -> &str {
        &self.prefix
    }
    /// Iterates available immutable descriptors, preserving logical order.
    pub fn references(&self) -> impl Iterator<Item = &ArtifactRef> {
        self.archive
            .manifest
            .artifacts
            .iter()
            .filter(|(k, _)| {
                (*k == &self.prefix || k.starts_with(&format!("{}/", self.prefix)))
                    && !self.archive.manifest.removed.contains(k)
            })
            .map(|(_, r)| r)
    }
    /// Looks up the immutable descriptor for one relative file.
    pub fn reference(&self, relative: &str) -> io::Result<&ArtifactRef> {
        let key = if relative.is_empty() {
            self.prefix.clone()
        } else {
            super::validate_key(relative)?;
            format!("{}/{relative}", self.prefix)
        };
        self.archive.artifact(&key)
    }
    /// Opens a relative file as a verified bounded-memory stream.
    pub fn reader(&self, relative: &str) -> io::Result<Box<dyn Read + Send>> {
        let key = if relative.is_empty() {
            self.prefix.clone()
        } else {
            super::validate_key(relative)?;
            format!("{}/{relative}", self.prefix)
        };
        if let Some(lease) = &self._consumer {
            lease.check()?;
            return Ok(Box::new(super::lease::LeasedReader {
                input: self
                    .archive
                    .store
                    .read_verified(self.archive.artifact(&key)?)?,
                lease: Some(lease.clone()),
            }));
        }
        self.archive.reader(&key)
    }
    /// Verifies every available file in this selection.
    pub fn verify(&self) -> io::Result<()> {
        for reference in self.references() {
            self.archive.verify(&reference.key)?;
        }
        Ok(())
    }
    /// Materializes a protected local view for tools requiring paths.
    pub fn materialize(&self, cache: &Path, max_bytes: u64) -> io::Result<MaterializationLease> {
        self.archive.materialize(&self.prefix, cache, max_bytes)
    }
}