scientific-workflow 0.18.1

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
use crate::{
    artifact::{ArtifactRef, ArtifactRole, RunArchive},
    storage::Store,
};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, io, path::Path};
/// Verified closure of captured reproduction material.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReproductionReport {
    /// Number of verified reproduction artifacts.
    pub artifacts: usize,
    /// Total verified bytes.
    pub bytes: u64,
}
pub(crate) type CaptureInventory = BTreeMap<String, ArtifactRef>;
pub(crate) fn capture_file(
    store: &Store,
    source: &Path,
    key: &str,
    local: Option<&Path>,
    inventory: &mut CaptureInventory,
    role: ArtifactRole,
) -> io::Result<()> {
    if source.symlink_metadata()?.file_type().is_symlink() {
        return Err(io::Error::other(format!(
            "capture requires explicit ordinary files: {}",
            source.display()
        )));
    }
    let reference = store.publish(key, source, role)?;
    if let Some(path) = local {
        std::fs::create_dir_all(path.parent().unwrap())?;
        crate::workspace::reserve_copy(path, reference.bytes)?;
        std::fs::copy(source, path)?;
        let actual = crate::artifact::digest_reader(std::fs::File::open(path)?)?;
        if actual != (reference.sha256.clone(), reference.bytes) {
            return Err(io::Error::other(format!(
                "input changed during capture: {}",
                source.display()
            )));
        }
    }
    inventory.insert(key.into(), reference);
    Ok(())
}
pub(crate) fn capture_tree(
    store: &Store,
    source: &Path,
    key: &str,
    local: Option<&Path>,
    inventory: &mut CaptureInventory,
) -> io::Result<()> {
    for entry in std::fs::read_dir(source)? {
        let e = entry?;
        let name = e.file_name();
        let name = name
            .to_str()
            .ok_or_else(|| io::Error::other("capture requires UTF-8 paths"))?;
        if [".git", "target", "__pycache__", ".pytest_cache", ".venv"].contains(&name) {
            continue;
        }
        let next = format!("{key}/{name}");
        let path = local.map(|p| p.join(name));
        if e.file_type()?.is_dir() {
            capture_tree(store, &e.path(), &next, path.as_deref(), inventory)?;
        } else {
            capture_file(
                store,
                &e.path(),
                &next,
                path.as_deref(),
                inventory,
                ArtifactRole::Reproduction,
            )?;
        }
    }
    Ok(())
}
/// Verifies every retained reproduction object through the authoritative backend.
pub fn verify_reproduction(archive: &RunArchive) -> io::Result<ReproductionReport> {
    if !archive.manifest().capture_complete {
        return Err(io::Error::other("reproduction capture is incomplete"));
    }
    let mut report = ReproductionReport {
        artifacts: 0,
        bytes: 0,
    };
    for (key, reference) in &archive.manifest().artifacts {
        if reference.role == ArtifactRole::Reproduction {
            archive.verify(key)?;
            report.artifacts += 1;
            report.bytes += reference.bytes;
        }
    }
    if report.artifacts == 0 {
        return Err(io::Error::other("reproduction bundle is empty"));
    }
    Ok(report)
}

/// Software environments explicitly capture symlink targets as ordinary frozen
/// entries. A stack of canonical directories rejects cycles.
pub(crate) fn capture_software_tree(
    store: &Store,
    source: &Path,
    key: &str,
    local: &Path,
    inventory: &mut CaptureInventory,
) -> io::Result<()> {
    fn walk(
        store: &Store,
        source: &Path,
        key: &str,
        local: &Path,
        inventory: &mut CaptureInventory,
        stack: &mut Vec<std::path::PathBuf>,
    ) -> io::Result<()> {
        let source = source.canonicalize()?;
        if stack.contains(&source) {
            return Err(io::Error::other("cycle in software environment"));
        }
        stack.push(source.clone());
        for e in std::fs::read_dir(&source)? {
            let e = e?;
            let name = e
                .file_name()
                .to_str()
                .ok_or_else(|| io::Error::other("non-UTF8 software path"))?
                .to_owned();
            if ["__pycache__", ".git", "target"].contains(&name.as_str()) {
                continue;
            }
            let path = e.path().canonicalize()?;
            let key = format!("{key}/{name}");
            let local = local.join(&name);
            if path.is_dir() {
                walk(store, &path, &key, &local, inventory, stack)?;
            } else if path.is_file() {
                capture_file(
                    store,
                    &path,
                    &key,
                    Some(&local),
                    inventory,
                    ArtifactRole::Reproduction,
                )?;
            }
        }
        stack.pop();
        Ok(())
    }
    walk(store, source, key, local, inventory, &mut Vec::new())
}