use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::time::Duration;
use serde_json::Value;
use super::document::{StateSchemaDocument, child_pointer};
use super::error::ConfigError;
use super::expansion;
use super::manifest::{self, FailurePolicy, ParsedTask, StudyManifest};
use super::parameters::ResolvedExecutionUnitParameters;
use super::program::{ResolvedProgramTask, resolve_active_python, resolve_executable};
use super::python;
use super::store::Config;
const PARAMETERS: &str = "parameters.json";
#[derive(Clone, Debug)]
pub(crate) enum ResolvedTask {
ExecutionUnit {
artifacts: crate::artifact::ArtifactDeclarations,
active: bool,
configuration: usize,
snapshot: super::store::ConfigSnapshot,
parameters: ResolvedExecutionUnitParameters,
state: Option<Box<str>>,
threads: Option<usize>,
},
Program {
artifacts: crate::artifact::ArtifactDeclarations,
configuration: usize,
snapshot: super::store::ConfigSnapshot,
program: ResolvedProgramTask,
},
}
impl ResolvedTask {
pub(crate) fn artifacts(&self) -> &crate::artifact::ArtifactDeclarations {
match self {
Self::ExecutionUnit { artifacts, .. } | Self::Program { artifacts, .. } => artifacts,
}
}
pub(crate) const fn configuration(&self) -> usize {
match self {
Self::ExecutionUnit { configuration, .. } | Self::Program { configuration, .. } => {
*configuration
}
}
}
pub(crate) fn snapshot(&self) -> &super::store::ConfigSnapshot {
match self {
Self::ExecutionUnit { snapshot, .. } | Self::Program { snapshot, .. } => snapshot,
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct PhaseSpecification {
pub(crate) auto_name_prefix: Option<Box<str>>,
pub(crate) name: Box<str>,
pub(crate) dependencies: Box<[Box<str>]>,
pub(crate) tasks: Box<[ResolvedTask]>,
pub(crate) max_concurrency: usize,
pub(crate) start_interval: Duration,
pub(crate) timeout: Option<Duration>,
pub(crate) failure_policy: FailurePolicy,
}
impl PhaseSpecification {
pub(crate) fn name(&self) -> &str {
&self.name
}
pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
self.dependencies.iter().map(Box::as_ref)
}
pub(crate) fn tasks(&self) -> &[ResolvedTask] {
&self.tasks
}
pub(crate) const fn max_concurrency(&self) -> usize {
self.max_concurrency
}
pub(crate) const fn start_interval(&self) -> Duration {
self.start_interval
}
pub(crate) const fn timeout(&self) -> Option<Duration> {
self.timeout
}
pub(crate) const fn failure_policy(&self) -> FailurePolicy {
self.failure_policy
}
}
#[derive(Debug)]
pub(crate) struct ProjectSpecification {
config: Config,
manifest: StudyManifest,
state_schemas: BTreeMap<Box<str>, StateSchemaDocument>,
phases: Box<[PhaseSpecification]>,
}
impl ProjectSpecification {
pub(crate) fn load(project_root: &Path) -> Result<Self, ConfigError> {
let config = Config::load(project_root)?;
let parsed = manifest::parse(
config.study_path(),
config.study_value().clone(),
config.runtime(),
)?;
let mut state_schemas = BTreeMap::new();
for (name, authored_path) in &parsed.state_paths {
let (state_path, state_value) = config
.project_document(authored_path)?
.ok_or_else(|| missing_document(config.project_root(), authored_path))?;
state_schemas.insert(
name.clone(),
StateSchemaDocument::new(state_path.to_path_buf(), state_value.clone()),
);
}
let parameters_relative = Path::new(PARAMETERS);
let (parameters_path, parameters_value) =
config
.document(parameters_relative)
.ok_or_else(|| ConfigError::Read {
path: config.config_root().join(parameters_relative),
source: std::io::Error::new(
std::io::ErrorKind::NotFound,
"required project parameters document was not loaded",
),
})?;
let parameter_sections = parameters_value.as_object().ok_or_else(|| {
ConfigError::invalid(
parameters_path,
"/",
"project parameters must be a JSON object keyed by workload",
)
})?;
let execution_units = parsed
.phases
.iter()
.flat_map(|phase| phase.tasks.iter())
.filter_map(|task| match task {
ParsedTask::ExecutionUnit { execution_unit, .. } => {
Some(execution_unit.to_string())
}
ParsedTask::Program { .. } | ParsedTask::Python { .. } | ParsedTask::Npy { .. } => {
None
}
})
.collect::<BTreeSet<_>>();
let shared = parameter_sections
.iter()
.filter(|(key, _)| !execution_units.contains(key.as_str()))
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
let expanded_units = execution_units
.iter()
.map(|key| {
let value = parameter_sections.get(key).ok_or_else(|| {
ConfigError::invalid(
parameters_path,
child_pointer("/", key),
format!("registered execution unit `{key}` has no parameter section"),
)
})?;
Ok((key.clone(), expansion::expand(parameters_path, value)?))
})
.collect::<Result<BTreeMap<_, _>, ConfigError>>()?;
let expanded_shared = expansion::expand(parameters_path, &Value::Object(shared))?;
let mut resolved_snapshots = Vec::with_capacity(expanded_shared.len());
for shared in expanded_shared {
let Value::Object(mut resolved) = shared else {
unreachable!("expanding an object produces objects");
};
for key in &execution_units {
if let Some(value) = parameter_sections.get(key) {
resolved.insert(key.clone(), value.clone());
}
}
let value = Value::Object(resolved);
let snapshot = config.snapshot_with_parameters(&value, parsed.manifest.active_phases());
resolved_snapshots.push(snapshot);
}
let mut phases = Vec::with_capacity(parsed.phases.len());
for phase in parsed.phases {
let mut tasks = Vec::new();
for (task, artifacts) in phase.tasks.into_iter().zip(phase.artifact_roles) {
match task {
ParsedTask::ExecutionUnit {
execution_unit,
active,
state,
timeout,
threads,
} => {
if let Some(state) = state.as_deref()
&& !state_schemas.contains_key(state)
{
return Err(ConfigError::UnknownState {
phase: phase.name.to_string(),
execution_unit: execution_unit.to_string(),
state: state.to_owned(),
});
}
let expanded = &expanded_units[execution_unit.as_ref()];
for (configuration, snapshot) in resolved_snapshots.iter().enumerate() {
tasks.try_reserve(expanded.len()).map_err(|_| {
ConfigError::ExpansionOverflow {
path: parameters_path.to_path_buf(),
}
})?;
for (ordinal, value) in expanded.iter().enumerate() {
let ordinal = u64::try_from(ordinal).map_err(|_| {
ConfigError::ExpansionOverflow {
path: parameters_path.to_path_buf(),
}
})?;
let mut task_parameters = snapshot.parameters().clone();
task_parameters
.as_object_mut()
.expect("resolved project parameters are an object")
.insert(execution_unit.to_string(), value.clone());
let task_snapshot = config.snapshot_with_parameters(
&task_parameters,
parsed.manifest.active_phases(),
);
tasks.push(ResolvedTask::ExecutionUnit {
artifacts: artifacts.clone(),
active,
configuration,
snapshot: task_snapshot,
parameters: ResolvedExecutionUnitParameters::new(
execution_unit.clone(),
parameters_path.to_path_buf(),
ordinal,
value.clone(),
timeout,
),
state: state.clone(),
threads,
});
}
}
}
ParsedTask::Program {
program,
args,
seed_purpose,
timeout,
threads,
} => {
let program = resolve_executable(config.project_root(), &program)?;
let program =
ResolvedProgramTask::new(program, args, seed_purpose, timeout, threads);
for (configuration, snapshot) in resolved_snapshots.iter().enumerate() {
tasks.push(ResolvedTask::Program {
artifacts: artifacts.clone(),
configuration,
snapshot: snapshot.clone(),
program: program.clone(),
});
}
}
ParsedTask::Python {
declaration,
seed_purpose,
timeout,
threads,
} => {
let program = python::resolve(
config.project_root(),
declaration,
seed_purpose,
timeout,
threads,
)?;
for (configuration, snapshot) in resolved_snapshots.iter().enumerate() {
tasks.push(ResolvedTask::Program {
artifacts: artifacts.clone(),
configuration,
snapshot: snapshot.clone(),
program: program.clone(),
});
}
}
ParsedTask::Npy {
exclude_streams,
threads,
auto,
} => {
let program = ResolvedProgramTask::for_npy(
resolve_active_python()?,
&exclude_streams,
threads,
auto,
);
let program = if let Some(snapshot) = &config.runtime().npy_environment {
program.with_python_snapshot(snapshot).map_err(|e| {
ConfigError::invalid(
config.study_path(),
"/npy_environment",
e.to_string(),
)
})?
} else {
program
};
let snapshot = resolved_snapshots
.first()
.expect("parameter expansion always produces one configuration")
.clone();
tasks.push(ResolvedTask::Program {
artifacts: artifacts.clone(),
configuration: 0,
snapshot,
program,
});
}
}
}
phases.push(PhaseSpecification {
auto_name_prefix: phase.auto_name_prefix,
name: phase.name,
dependencies: phase.dependencies,
tasks: tasks.into_boxed_slice(),
max_concurrency: phase.max_concurrency,
start_interval: phase.start_interval,
timeout: phase.timeout,
failure_policy: phase.failure_policy,
});
}
Ok(Self {
config,
manifest: parsed.manifest,
state_schemas,
phases: phases.into_boxed_slice(),
})
}
pub(crate) fn project_root(&self) -> &Path {
self.config.project_root()
}
pub(crate) fn config(&self) -> &Config {
&self.config
}
pub(crate) fn manifest(&self) -> &StudyManifest {
&self.manifest
}
pub(crate) fn state_schemas(&self) -> &BTreeMap<Box<str>, StateSchemaDocument> {
&self.state_schemas
}
pub(crate) fn phases(&self) -> &[PhaseSpecification] {
&self.phases
}
}
fn missing_document(project_root: &Path, authored_path: &Path) -> ConfigError {
let path = if authored_path.is_absolute() {
authored_path.to_path_buf()
} else {
project_root.join(authored_path)
};
ConfigError::Read {
path,
source: std::io::Error::new(
std::io::ErrorKind::NotFound,
"declared state schema was not captured as a JSON config document",
),
}
}