Skip to main content

scientific_workflow/task/
project.rs

1//! Accessors for Workflow's required project layout and resolved program snapshots.
2use serde::de::DeserializeOwned;
3use std::path::{Path, PathBuf};
4use thiserror::Error;
5
6/// A missing standard path, environment variable, or invalid resolved snapshot.
7#[derive(Debug, Error)]
8#[error("{message}; preserve Workflow's required study layout")]
9pub struct ProjectLayoutError {
10    message: String,
11    #[source]
12    source: Option<Box<dyn std::error::Error + Send + Sync>>,
13}
14fn failure(message: String) -> ProjectLayoutError {
15    ProjectLayoutError {
16        message,
17        source: None,
18    }
19}
20fn environment_path(variable: &str, directory: bool) -> Result<PathBuf, ProjectLayoutError> {
21    let value = std::env::var_os(variable).ok_or_else(|| failure(format!("missing {variable}")))?;
22    let path = PathBuf::from(value);
23    if !path.is_absolute()
24        || !(if directory {
25            path.is_dir()
26        } else {
27            path.is_file()
28        })
29    {
30        return Err(failure(format!(
31            "expected {} at {} from {variable}",
32            if directory { "directory" } else { "file" },
33            path.display()
34        )));
35    }
36    Ok(path)
37}
38/// Returns `WORKFLOW_PROJECT_ROOT` for a launched program; does not change cwd.
39pub fn project_root() -> Result<PathBuf, ProjectLayoutError> {
40    environment_path("WORKFLOW_PROJECT_ROOT", true)
41}
42/// Returns `WORKFLOW_TASK_OUTPUT`, the existing writable artifacts directory.
43pub fn output_directory() -> Result<PathBuf, ProjectLayoutError> {
44    environment_path("WORKFLOW_TASK_OUTPUT", true)
45}
46/// Requires `<root>/wf_configs/study.json` and returns its path without parsing it.
47pub fn study_path(root: &Path) -> Result<PathBuf, ProjectLayoutError> {
48    let path = root.join("wf_configs/study.json");
49    if !path.is_file() {
50        return Err(failure(format!("expected {}", path.display())));
51    }
52    Ok(path)
53}
54/// Loads resolved parameters from `WORKFLOW_CONFIG_PATH` and deserializes `T`.
55///
56/// `section` selects one exact top-level key; `None` selects all parameters.
57/// This does not read unresolved project declarations or repeat Config resolution.
58pub fn parameters<T: DeserializeOwned>(section: Option<&str>) -> Result<T, ProjectLayoutError> {
59    parameters_from_snapshot(&environment_path("WORKFLOW_CONFIG_PATH", false)?, section)
60}
61/// Loads resolved parameters from an explicit standard `workflow-config.json` file.
62///
63/// The file must contain `config["parameters.json"]`. Filesystem/JSON/typed
64/// deserialization errors retain their cause. A failed read returns no value.
65pub fn parameters_from_snapshot<T: DeserializeOwned>(
66    path: &Path,
67    section: Option<&str>,
68) -> Result<T, ProjectLayoutError> {
69    let read = || -> Result<T, Box<dyn std::error::Error + Send + Sync>> {
70        let bytes = std::fs::read(path)?;
71        let snapshot: serde_json::Value = serde_json::from_slice(&bytes)?;
72        let parameters = snapshot
73            .get("config")
74            .and_then(|v| v.get("parameters.json"))
75            .filter(|v| v.is_object())
76            .ok_or("expected config[parameters.json] object")?;
77        let selected = match section {
78            Some(key) => parameters
79                .get(key)
80                .ok_or_else(|| format!("missing parameter section {key:?}"))?,
81            None => parameters,
82        };
83        Ok(serde_json::from_value(selected.clone())?)
84    };
85    read().map_err(|source| ProjectLayoutError {
86        message: format!(
87            "cannot read resolved parameters at {}: {source}",
88            path.display()
89        ),
90        source: Some(source),
91    })
92}