use super::{InterfaceMode, RuntimeSettings, StorageTarget};
use serde::Deserialize;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct CampaignDeclaration {
pub(crate) campaign_schema: u64,
pub(crate) studies: Vec<Member>,
#[serde(default)]
pub(crate) continue_on_failure: bool,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Member {
pub(crate) id: String,
pub(crate) input: PathBuf,
pub(crate) runner: PathBuf,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Policy {
interface: InterfaceMode,
storage: StorageTarget,
workspace: super::runtime::Workspace,
}
pub(crate) fn load_campaign(
input: &Path,
) -> Result<(CampaignDeclaration, RuntimeSettings), super::ConfigError> {
let path = input.join("campaign.json");
let declaration: CampaignDeclaration =
serde_json::from_value(super::document::read_json(&path)?)
.map_err(|e| super::ConfigError::invalid(&path, "/", e.to_string()))?;
if declaration.campaign_schema != 1 || declaration.studies.is_empty() {
return Err(super::ConfigError::invalid(
&path,
"/",
"requires campaign_schema 1 and at least one study",
));
}
let mut ids = std::collections::HashSet::new();
for member in &declaration.studies {
if member.id.is_empty()
|| !member
.id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
|| !ids.insert(&member.id)
{
return Err(super::ConfigError::invalid(
&path,
"/studies",
"study IDs must be distinct path-safe identifiers",
));
}
if member.input.is_absolute()
|| member
.input
.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
{
return Err(super::ConfigError::invalid(
&path,
"/studies/input",
"campaign member input must be a contained relative folder",
));
}
let resolved = input
.join(&member.input)
.canonicalize()
.map_err(|e| super::ConfigError::invalid(&path, "/studies/input", e.to_string()))?;
if !resolved.starts_with(input) {
return Err(super::ConfigError::invalid(
&path,
"/studies/input",
"member escapes campaign input",
));
}
}
let path = input.join("runtime.json");
let runtime: Policy = serde_json::from_value(super::document::read_json(&path)?)
.map_err(|e| super::ConfigError::invalid(&path, "/", e.to_string()))?;
super::runtime::validate_locations(&path, input, &runtime.storage, &runtime.workspace)?;
let settings = RuntimeSettings::parse(
&path,
serde_json::json!({"threads":1,"compute":{"mode":"isolated"},"interface":runtime.interface,"storage":runtime.storage,"workspace":{"root":runtime.workspace.root,"max_bytes":runtime.workspace.max_bytes}}),
input,
)?;
Ok((declaration, settings))
}