use super::ConfigError;
use super::manifest::{RawFailurePolicy, RawReplicateScheduling};
use serde::{Deserialize, Serialize};
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RuntimeSettings {
#[serde(default)]
pub(crate) npy_environment: Option<PythonSnapshot>,
#[serde(default)]
pub(crate) input_bindings: std::collections::BTreeMap<String, crate::artifact::ArtifactLocator>,
pub(crate) threads: usize,
pub(crate) compute: Compute,
pub(crate) interface: InterfaceMode,
pub(crate) storage: StorageTarget,
pub(crate) workspace: Workspace,
#[serde(default)]
pub(crate) active_phases: Option<Vec<usize>>,
#[serde(default)]
pub(crate) reuse_from: Option<ReuseSource>,
#[serde(default)]
pub(crate) replicate_scheduling: RawReplicateScheduling,
#[serde(default)]
pub(crate) replicate_failure_policy: RawFailurePolicy,
#[serde(default)]
pub(crate) persistence: Persistence,
#[serde(default)]
pub(crate) disk: Disk,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum InterfaceMode {
Headless,
Dashboard,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Compute {
pub(crate) mode: ComputePolicy,
}
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ComputePolicy {
Auto,
Isolated,
}
pub(crate) use crate::artifact::StorageLocation as StorageTarget;
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Workspace {
pub(crate) root: PathBuf,
pub(crate) max_bytes: NonZeroU64,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub(crate) struct Persistence {
pub(crate) chunk_target_mb: NonZeroU64,
pub(crate) queue_capacity_mb: NonZeroU64,
}
impl Default for Persistence {
fn default() -> Self {
Self {
chunk_target_mb: NonZeroU64::new(64).unwrap(),
queue_capacity_mb: NonZeroU64::new(64).unwrap(),
}
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub(crate) struct Disk {
pub(crate) pause_at_percent: Option<f64>,
}
impl Default for Disk {
fn default() -> Self {
Self {
pause_at_percent: Some(95.0),
}
}
}
impl RuntimeSettings {
pub(crate) fn parse(
path: &Path,
value: serde_json::Value,
input: &Path,
) -> Result<Self, ConfigError> {
let settings: Self = serde_json::from_value(value)
.map_err(|e| ConfigError::invalid(path, "/", e.to_string()))?;
validate_locations(path, input, &settings.storage, &settings.workspace)?;
if let Some(ReuseSource::Run {
run_id, execution, ..
}) = &settings.reuse_from
{
let _: scientific_workflow_protocol::RunId = run_id
.clone()
.try_into()
.map_err(|e| ConfigError::invalid(path, "/reuse_from/run_id", e))?;
crate::artifact::validate_key(execution)
.map_err(|e| ConfigError::invalid(path, "/reuse_from/execution", e.to_string()))?;
}
if settings
.persistence
.chunk_target_mb
.get()
.checked_mul(1_000_000)
.is_some_and(|n| n > settings.workspace.max_bytes.get())
{
return Err(ConfigError::invalid(
path,
"/workspace/max_bytes",
"workspace must hold at least one recording chunk",
));
}
Ok(settings)
}
}
pub(crate) fn validate_locations(
path: &Path,
input: &Path,
storage: &StorageTarget,
workspace: &Workspace,
) -> Result<(), ConfigError> {
let external = |p: &Path| -> Result<(), ConfigError> {
if !p.is_absolute()
|| p.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
{
return Err(ConfigError::invalid(
path,
"/",
"storage and workspace paths must be absolute without '..'",
));
}
let mut prefix = p;
while !prefix.exists() {
prefix = prefix
.parent()
.ok_or_else(|| ConfigError::invalid(path, "/", "invalid location"))?;
}
let resolved = prefix
.canonicalize()
.map_err(|e| ConfigError::invalid(path, "/", e.to_string()))?
.join(p.strip_prefix(prefix).unwrap());
if resolved.starts_with(input) || input.starts_with(&resolved) {
return Err(ConfigError::invalid(
path,
"/",
"storage and workspace must be outside the input folder and cannot contain it",
));
}
Ok(())
};
external(&workspace.root)?;
match storage {
StorageTarget::Filesystem { root } => {
external(root)?;
if root.starts_with(&workspace.root) || workspace.root.starts_with(root) {
return Err(ConfigError::invalid(
path,
"/",
"storage and workspace must be disjoint",
));
}
}
StorageTarget::Https {
endpoint,
credential_profile,
} => {
if !endpoint.starts_with("https://") || endpoint.contains(['?', '#']) {
return Err(ConfigError::invalid(
path,
"/storage/endpoint",
"requires an HTTPS Workflow object API base URL",
));
}
external(credential_profile)?;
}
StorageTarget::Gdrive {
folder_id,
credential_profile,
} => {
if folder_id.is_empty()
|| !folder_id
.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
{
return Err(ConfigError::invalid(
path,
"/storage/folder_id",
"invalid Drive folder ID",
));
}
external(credential_profile)?;
}
}
Ok(())
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PythonSnapshot {
pub(crate) executable: PathBuf,
pub(crate) search_paths: Vec<PathBuf>,
pub(crate) home: PathBuf,
}
impl PythonSnapshot {
pub(crate) fn environment(
&self,
) -> Result<std::collections::BTreeMap<std::ffi::OsString, std::ffi::OsString>, std::io::Error>
{
Ok(std::collections::BTreeMap::from([
(
"PYTHONPATH".into(),
std::env::join_paths(&self.search_paths).map_err(std::io::Error::other)?,
),
("PYTHONHOME".into(), self.home.clone().into_os_string()),
("PYTHONNOUSERSITE".into(), "1".into()),
("PYTHONDONTWRITEBYTECODE".into(), "1".into()),
]))
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum ReuseSource {
Local {
execution: PathBuf,
},
Run {
run_id: String,
execution: String,
#[serde(default)]
storage: Option<StorageTarget>,
},
}