Skip to main content

scientific_workflow/task/
context.rs

1//! Captured program context and named reproduction inputs.
2use super::dependencies::Dependencies;
3use crate::artifact::{ArtifactSet, RunArchive, StorageLocation};
4use std::{
5    io,
6    path::{Path, PathBuf},
7};
8/// Immutable resolved values and task-local workspace for external Rust programs.
9pub struct TaskContext {
10    parameters: serde_json::Value,
11    dependencies: Dependencies,
12    output: PathBuf,
13}
14impl TaskContext {
15    /// Reads and verifies Workflow's captured task snapshots from the environment.
16    pub fn from_env() -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
17        Ok(Self {
18            parameters: super::project::parameters(None)?,
19            dependencies: Dependencies::from_env()?,
20            output: super::project::output_directory()?,
21        })
22    }
23    /// Writable local task artifacts directory, never the authored input folder.
24    pub fn output_directory(&self) -> &Path {
25        &self.output
26    }
27    /// Resolved parameter section, decoded without another configuration compiler.
28    pub fn parameters<T: serde::de::DeserializeOwned>(
29        &self,
30        section: &str,
31    ) -> Result<T, serde_json::Error> {
32        serde_json::from_value(
33            self.parameters
34                .get(section)
35                .cloned()
36                .unwrap_or(serde_json::Value::Null),
37        )
38    }
39    /// Correlated prerequisite results from declared dependency phases.
40    pub fn dependencies(&self) -> &Dependencies {
41        &self.dependencies
42    }
43    /// A named captured external input, accessed through immutable artifact references.
44    pub fn input(&self, name: &str) -> io::Result<ArtifactSet> {
45        captured_input(name)
46    }
47}
48pub(super) fn captured_input(name: &str) -> io::Result<ArtifactSet> {
49    crate::artifact::validate_key(name)?;
50    let path = std::env::var_os("WORKFLOW_RUN_HANDLE")
51        .ok_or_else(|| io::Error::other("missing WORKFLOW_RUN_HANDLE"))?;
52    let handle: serde_json::Value =
53        serde_json::from_reader(std::fs::File::open(path)?).map_err(io::Error::other)?;
54    let location: StorageLocation =
55        serde_json::from_value(handle["storage"].clone()).map_err(io::Error::other)?;
56    let run = handle["run_id"]
57        .as_str()
58        .ok_or_else(|| io::Error::other("invalid run handle"))?;
59    ArtifactSet::new(
60        RunArchive::open(&location, run)?,
61        format!("reproduction/external-inputs/{name}"),
62    )
63}