rustsy-process 0.2.0-alpha.1

Declared process graphs with verified local artifact caching
Documentation
use crate::fs_safety::{self, Scratch, invalid, node_md};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeSet, fs, io, path::Path};

#[derive(Deserialize, Serialize)]
struct Journal {
    entries: Vec<Entry>,
}

#[derive(Deserialize, Serialize)]
struct Entry {
    index: usize,
    path: String,
    existed: bool,
}

pub(crate) fn prepare<'a>(
    stage: &Path,
    root: &Path,
    entries: impl Iterator<Item = (usize, &'a str)>,
) -> io::Result<()> {
    let entries = entries
        .map(|(index, name)| {
            Ok(Entry {
                index,
                path: name.to_owned(),
                existed: exists(&fs_safety::path(root, name, true)?)?,
            })
        })
        .collect::<io::Result<_>>()?;
    let file = fs::File::create_new(stage.join("journal.tmp"))?;
    serde_json::to_writer(&file, &Journal { entries })?;
    file.sync_all()?;
    drop(file);
    fs::rename(stage.join("journal.tmp"), stage.join("journal.json"))
}

pub(crate) fn commit(stage: &Path) -> io::Result<()> {
    fs::rename(stage.join("journal.json"), stage.join("committed.json"))
}

fn exists(path: &Path) -> io::Result<bool> {
    match node_md(path) {
        Ok(_) => Ok(true),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(e),
    }
}

pub(crate) fn resume(internal: &Path, workspace: &Path, marker: &Path) -> io::Result<usize> {
    if !node_md(marker)?.is_file() {
        return Err(invalid("invalid recovery marker"));
    }
    let record = fs::read_to_string(marker)?;
    let run = record
        .trim()
        .strip_prefix("rustsy-7:")
        .filter(|name| stage_name(name))
        .ok_or_else(|| {
            invalid("legacy or incomplete run marker; inspect the workspace before retrying")
        })?;
    let transactions = internal.join(run).join("transactions");
    if !node_md(&internal.join(run))?.is_dir() || !node_md(&transactions)?.is_dir() {
        return Err(invalid("interrupted run directory is missing"));
    }
    let mut stages = Vec::new();
    for item in fs::read_dir(&transactions)? {
        let item = item?;
        let name = item.file_name();
        let stage = item.path();
        if !name.to_str().is_some_and(stage_name) || !node_md(&stage)?.is_dir() {
            return Err(invalid("invalid interrupted transaction directory"));
        }
        if exists(&stage.join("child-active"))? {
            return Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                format!(
                    "interrupted command may still be running; confirm its process tree has exited before moving {} aside",
                    stage.join("child-active").display()
                ),
            ));
        }
        let journal = stage.join("journal.json");
        if exists(&journal)? {
            let journal: Journal = serde_json::from_reader(fs::File::open(journal)?)?;
            let mut paths = BTreeSet::new();
            let mut indices = BTreeSet::new();
            for entry in &journal.entries {
                fs_safety::relative(&entry.path, false)?;
                if !paths.insert(fs_safety::identity(&entry.path)) || !indices.insert(entry.index) {
                    return Err(invalid("duplicate recovery entry"));
                }
            }
            stages.push((stage, journal));
        }
    }
    let recovered = stages.len();
    for (stage, journal) in stages {
        for entry in journal.entries.iter().rev() {
            let destination = fs_safety::path(workspace, &entry.path, true)?;
            let backup = stage.join(format!("old-{}", entry.index));
            if entry.existed && !exists(&backup)? {
                continue;
            }
            if exists(&destination)? {
                let displaced = Scratch::new(&stage)?.persist();
                fs::rename(&destination, displaced.join("interrupted-output"))?;
            }
            if entry.existed {
                fs::rename(backup, destination)?;
            }
        }
        fs::rename(stage.join("journal.json"), stage.join("recovered.json"))?;
    }
    let archived = Scratch::new(internal)?.persist();
    fs::rename(marker, archived.join("interrupted-run"))?;
    Ok(recovered)
}

pub(crate) fn requires_recovery(transactions: &Path) -> bool {
    let Ok(stages) = fs::read_dir(transactions) else {
        return true;
    };
    stages.into_iter().any(|stage| {
        stage.map_or(true, |stage| {
            ["journal.json", "child-active"]
                .iter()
                .any(|name| exists(&stage.path().join(name)).unwrap_or(true))
        })
    })
}

fn stage_name(name: &str) -> bool {
    name.strip_prefix(".stage-")
        .and_then(|suffix| suffix.split_once('-'))
        .is_some_and(|(pid, sequence)| {
            pid.parse::<u32>().is_ok() && sequence.parse::<u64>().is_ok()
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resumes_interrupted_promotion_and_preserves_commits() -> io::Result<()> {
        let temp = std::env::temp_dir().canonicalize()?;
        let workspace = Scratch::new(&temp)?;
        let internal = fs_safety::private_dir(&workspace.0, ".rustsy-process")?;
        let run = Scratch::new(&internal)?;
        let marker = internal.join("active");
        let label = run.0.file_name().unwrap().to_str().unwrap();
        fs::write(&marker, format!("rustsy-7:{label}\n"))?;
        let transactions = fs_safety::private_dir(&run.0, "transactions")?;
        let stage = Scratch::new(&transactions)?;
        fs::write(workspace.0.join("replaced"), b"old bytes")?;
        fs::write(workspace.0.join("untouched"), b"before first rename")?;
        prepare(
            &stage.0,
            &workspace.0,
            [(0, "replaced"), (1, "absent"), (2, "untouched")].into_iter(),
        )?;
        fs::rename(workspace.0.join("replaced"), stage.0.join("old-0"))?;
        fs::write(workspace.0.join("replaced"), b"partial promotion")?;
        fs::write(workspace.0.join("absent"), b"new partial output")?;
        let committed = Scratch::new(&transactions)?;
        fs::write(workspace.0.join("committed"), b"old")?;
        prepare(&committed.0, &workspace.0, [(0, "committed")].into_iter())?;
        fs::rename(workspace.0.join("committed"), committed.0.join("old-0"))?;
        fs::write(workspace.0.join("committed"), b"published")?;
        commit(&committed.0)?;
        fs::write(stage.0.join("child-active"), b"")?;
        assert_eq!(
            resume(&internal, &workspace.0, &marker).unwrap_err().kind(),
            io::ErrorKind::WouldBlock
        );
        fs::rename(stage.0.join("child-active"), stage.0.join("child-reviewed"))?;
        assert_eq!(resume(&internal, &workspace.0, &marker)?, 1);
        assert_eq!(fs::read(workspace.0.join("replaced"))?, b"old bytes");
        assert!(!workspace.0.join("absent").exists());
        assert_eq!(
            fs::read(workspace.0.join("untouched"))?,
            b"before first rename"
        );
        assert_eq!(fs::read(workspace.0.join("committed"))?, b"published");
        assert!(!marker.exists());
        Ok(())
    }
}