use crate::campaign::CampaignPlan;
use std::io;
pub(crate) trait StudyExecutor {
fn execute(
&mut self,
id: &str,
input: &std::path::Path,
runner: &std::path::Path,
) -> io::Result<()>;
fn cancelled(&self) -> bool;
}
pub(crate) fn execute_campaign(
plan: &CampaignPlan,
executor: &mut dyn StudyExecutor,
) -> io::Result<()> {
let mut failures = Vec::new();
for member in &plan.declaration.studies {
if executor.cancelled() {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"campaign cancelled",
));
}
let input = plan.root.join(&member.input);
let runner = if member.runner.is_absolute() {
member.runner.clone()
} else {
plan.root.join(&member.runner)
};
if let Err(error) = executor.execute(&member.id, &input, &runner) {
failures.push(format!("{}: {error}", member.id));
if !plan.continue_on_failure() {
break;
}
}
}
if failures.is_empty() {
Ok(())
} else {
Err(io::Error::other(failures.join("; ")))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct Executor {
calls: Vec<String>,
cancel: bool,
}
impl StudyExecutor for Executor {
fn execute(
&mut self,
id: &str,
_: &std::path::Path,
_: &std::path::Path,
) -> io::Result<()> {
self.calls.push(id.into());
if id == "first" {
Err(io::Error::other("scientific failure"))
} else {
Ok(())
}
}
fn cancelled(&self) -> bool {
self.cancel
}
}
#[test]
fn failure_policy_and_cancellation_preserve_serial_admission() {
let root = std::env::temp_dir().join(format!(
"workflow-campaign-policy-{}",
crate::storage::run_id()
));
std::fs::create_dir_all(root.join("input/a")).unwrap();
std::fs::create_dir_all(root.join("input/b")).unwrap();
let input = root.join("input");
std::fs::write(input.join("campaign.json"),r#"{"campaign_schema":1,"studies":[{"id":"first","input":"a","runner":"runner"},{"id":"second","input":"b","runner":"runner"}]}"#).unwrap();
std::fs::write(input.join("runtime.json"),serde_json::to_vec(&serde_json::json!({"interface":"headless","storage":{"backend":"filesystem","root":root.join("store")},"workspace":{"root":root.join("work"),"max_bytes":100_000_000}})).unwrap()).unwrap();
let mut plan = CampaignPlan::load(&input).unwrap();
let mut executor = Executor::default();
assert!(execute_campaign(&plan, &mut executor).is_err());
assert_eq!(executor.calls, vec!["first"]);
plan.declaration.continue_on_failure = true;
let mut executor = Executor::default();
assert!(execute_campaign(&plan, &mut executor).is_err());
assert_eq!(executor.calls, vec!["first", "second"]);
let mut executor = Executor {
cancel: true,
..Default::default()
};
assert_eq!(
execute_campaign(&plan, &mut executor).unwrap_err().kind(),
io::ErrorKind::Interrupted
);
assert!(executor.calls.is_empty());
std::fs::remove_dir_all(root).unwrap();
}
}