scientific-workflow 0.18.0

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
use scientific_workflow::{WorkflowError, artifact::StorageLocation};
use std::{
    io,
    path::{Path, PathBuf},
    process::Command,
};
fn main() {
    if let Err(error) = run() {
        eprintln!("workflow: {error}");
        std::process::exit(1);
    }
}
fn required(args: &[String], index: usize) -> io::Result<&str> {
    args.get(index)
        .map(String::as_str)
        .ok_or_else(|| io::Error::other("missing argument; run workflow help"))
}
fn location(path: &str) -> io::Result<StorageLocation> {
    let value: serde_json::Value =
        serde_json::from_reader(std::fs::File::open(path)?).map_err(io::Error::other)?;
    serde_json::from_value(value.get("storage").unwrap_or(&value).clone()).map_err(io::Error::other)
}
fn run() -> Result<(), WorkflowError> {
    let args = std::env::args().skip(1).collect::<Vec<_>>();
    let command = args.first().map(String::as_str).unwrap_or("help");
    if command.starts_with("--workflow-") {
        return scientific_workflow::run(Path::new("."));
    }
    match command {
        "help" | "--help" => println!(
            "workflow check|start INPUT [--runner BINARY] [--wait]\nworkflow status|watch|pause|resume|cancel|wait SOCKET\nworkflow registry|rebuild STORAGE_JSON [WORKSPACE]\nworkflow artifacts STORAGE_JSON RUN_ID\nworkflow materialize STORAGE_JSON RUN_ID PREFIX CACHE MAX_BYTES\nworkflow seal STORAGE_JSON RUN_ID WORKSPACE [--apply] [--reproduce]\nworkflow reproduce STORAGE_JSON RUN_ID WORKSPACE"
        ),
        "check" | "start" => {
            let input = Path::new(required(&args, 1)?);
            if let Some(position) = args.iter().position(|s| s == "--runner") {
                let status = Command::new(required(&args, position + 1)?)
                    .arg(if command == "check" {
                        "--workflow-check"
                    } else {
                        "--workflow-start"
                    })
                    .arg(input)
                    .args(if args.iter().any(|s| s == "--wait") {
                        vec!["--wait"]
                    } else {
                        vec![]
                    })
                    .status()?;
                if !status.success() {
                    return Err(io::Error::other(format!("model runner exited {status}")).into());
                }
            } else if command == "check" {
                println!(
                    "{}",
                    serde_json::to_string(&scientific_workflow::check(input)?)?
                );
            } else {
                let handle = scientific_workflow::start(input)?;
                println!("{}", serde_json::to_string(&handle)?);
                if args.iter().any(|s| s == "--wait") {
                    let status = handle.wait()?;
                    println!("{}", serde_json::to_string(&status)?);
                    if status.outcome != scientific_workflow::client::Outcome::Completed {
                        return Err(
                            io::Error::other("execution did not complete successfully").into()
                        );
                    }
                }
            }
        }
        "status" | "watch" | "pause" | "resume" | "cancel" | "wait" => {
            let client = scientific_workflow::client::RunClient::connect(required(&args, 1)?)?;
            if command == "watch" {
                let mut cursor = 0;
                loop {
                    let response = client.events(cursor)?;
                    for event in response.events {
                        cursor = event.sequence;
                        println!("{}", serde_json::to_string(&event)?);
                    }
                    if response.status.outcome.terminal() && cursor >= response.status.sequence {
                        break;
                    }
                    std::thread::sleep(std::time::Duration::from_millis(200));
                }
            } else {
                let status = match command {
                    "pause" => client.pause()?,
                    "resume" => client.resume()?,
                    "cancel" => client.cancel()?,
                    "wait" => client.wait()?,
                    _ => client.status()?,
                };
                println!("{}", serde_json::to_string(&status)?);
                if command == "wait"
                    && status.outcome != scientific_workflow::client::Outcome::Completed
                {
                    return Err(io::Error::other("execution did not complete successfully").into());
                }
            }
        }
        "registry" => println!(
            "{}",
            serde_json::to_string_pretty(&scientific_workflow::registry::query(&location(
                required(&args, 1)?
            )?)?)?
        ),
        "rebuild" => println!(
            "{}",
            serde_json::to_string_pretty(&scientific_workflow::registry::rebuild(
                &location(required(&args, 1)?)?,
                Path::new(required(&args, 2)?)
            )?)?
        ),
        "artifacts" => {
            let archive = scientific_workflow::open_run(
                &location(required(&args, 1)?)?,
                required(&args, 2)?,
            )?;
            println!("{}", serde_json::to_string_pretty(archive.manifest())?);
        }
        "materialize" => {
            let archive = scientific_workflow::open_run(
                &location(required(&args, 1)?)?,
                required(&args, 2)?,
            )?;
            let max = required(&args, 5)?.parse().map_err(io::Error::other)?;
            let lease =
                archive.materialize(required(&args, 3)?, Path::new(required(&args, 4)?), max)?;
            println!("{}", lease.path().display());
            println!("Press Enter to release the materialization lease.");
            let mut line = String::new();
            io::stdin().read_line(&mut line)?;
        }
        "reproduce" => {
            println!(
                "{}",
                serde_json::to_string_pretty(&scientific_workflow::reproduce_run(
                    &location(required(&args, 1)?)?,
                    required(&args, 2)?,
                    Path::new(required(&args, 3)?)
                )?)?
            );
        }
        "seal" => {
            let location = location(required(&args, 1)?)?;
            let id = required(&args, 2)?;
            let workspace = PathBuf::from(required(&args, 3)?);
            if args.iter().any(|s| s == "--apply") {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&if args.iter().any(|s| s == "--reproduce") {
                        scientific_workflow::seal_run_with_reproduction(&location, id, &workspace)?
                    } else {
                        scientific_workflow::seal_run(&location, id, &workspace, None)?
                    })?
                );
            } else {
                let archive = scientific_workflow::open_run(&location, id)?;
                println!(
                    "{}",
                    serde_json::to_string_pretty(&scientific_workflow::seal::preview(&archive)?)?
                );
            }
        }
        _ => return Err(io::Error::other("unknown command; run workflow help").into()),
    }
    Ok(())
}