Skip to main content

scientific_workflow/artifact/
reference.rs

1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256};
3use std::io::{self, Read};
4use std::path::PathBuf;
5/// Configurable authoritative destination. Credentials remain in external profiles.
6#[derive(Clone, Debug, Deserialize, Serialize)]
7#[serde(tag = "backend", rename_all = "snake_case", deny_unknown_fields)]
8pub enum StorageLocation {
9    /// Local drive or mounted network filesystem.
10    Filesystem {
11        /// Absolute destination root.
12        root: PathBuf,
13    },
14    /// Workflow writable object API over HTTPS.
15    Https {
16        /// HTTPS API base URL.
17        endpoint: String,
18        /// External credential JSON path.
19        credential_profile: PathBuf,
20    },
21    /// Native Google Drive blob API.
22    Gdrive {
23        /// Parent folder's native ID.
24        folder_id: String,
25        /// External OAuth credential profile.
26        credential_profile: PathBuf,
27    },
28}
29/// Artifact meaning declared by the producing scientific task.
30#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
31#[serde(rename_all = "snake_case")]
32pub enum ArtifactRole {
33    /// Required to reproduce scientific work.
34    Reproduction,
35    /// Removable original scientific recording.
36    Raw,
37    /// Retained scientific result.
38    Processed,
39    /// Durable lifecycle and commit evidence.
40    Record,
41}
42/// Portable immutable object descriptor. Logical names never imply POSIX access.
43#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
44#[serde(deny_unknown_fields)]
45pub struct ArtifactRef {
46    /// Path in the run's logical tree.
47    pub key: String,
48    /// SHA-256 of exact stored bytes, lowercase hex.
49    pub sha256: String,
50    /// Exact byte length.
51    pub bytes: u64,
52    /// Task-declared retention meaning.
53    pub role: ArtifactRole,
54    /// Whether a captured software file must be executable when materialized.
55    #[serde(default)]
56    pub executable: bool,
57}
58impl ArtifactRef {
59    /// Checks descriptor syntax before resolving a backend object.
60    pub fn validate(&self) -> io::Result<()> {
61        validate_key(&self.key)?;
62        if self.sha256.len() != 64
63            || !self
64                .sha256
65                .bytes()
66                .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
67        {
68            return Err(io::Error::other("invalid artifact digest"));
69        }
70        Ok(())
71    }
72}
73pub(crate) fn validate_key(key: &str) -> io::Result<()> {
74    if key.is_empty()
75        || key.starts_with('/')
76        || key.contains(['\\', '\0'])
77        || key
78            .split('/')
79            .any(|s| s.is_empty() || s == "." || s == "..")
80    {
81        return Err(io::Error::other("invalid logical artifact key"));
82    }
83    Ok(())
84}
85pub(crate) fn digest_bytes(bytes: &[u8]) -> String {
86    hex(&Sha256::digest(bytes))
87}
88pub(crate) fn digest_reader(mut reader: impl Read) -> io::Result<(String, u64)> {
89    let mut hash = Sha256::new();
90    let mut size = 0;
91    let mut buffer = [0; 65536];
92    loop {
93        let n = reader.read(&mut buffer)?;
94        if n == 0 {
95            break;
96        }
97        hash.update(&buffer[..n]);
98        size += n as u64;
99    }
100    Ok((hex(&hash.finalize()), size))
101}
102
103pub(crate) fn hex(bytes: &[u8]) -> String {
104    bytes.iter().map(|b| format!("{b:02x}")).collect()
105}
106
107/// Retention declarations relative to one task's output directory.
108#[derive(Clone, Debug, Default, Serialize, Deserialize)]
109#[serde(default, deny_unknown_fields)]
110pub struct ArtifactDeclarations {
111    /// Produced inputs needed by this or a later scientific task.
112    pub reproduction: Vec<String>,
113    /// Original outputs eligible for sealing.
114    pub raw: Vec<String>,
115    /// Processed products that sealing must retain and verify.
116    pub processed: Vec<String>,
117    /// Named actual-content equality assertions, evaluated on producer commit.
118    pub shared_inputs: std::collections::BTreeMap<String, String>,
119}
120impl ArtifactDeclarations {
121    pub(crate) fn validate(&self) -> io::Result<()> {
122        let mut paths = Vec::new();
123        for p in self
124            .reproduction
125            .iter()
126            .chain(&self.raw)
127            .chain(&self.processed)
128        {
129            validate_key(p)?;
130            if paths.iter().any(|q: &&String| {
131                p == *q || p.starts_with(&format!("{q}/")) || q.starts_with(&format!("{p}/"))
132            }) {
133                return Err(io::Error::other("artifact declarations overlap"));
134            }
135            paths.push(p);
136        }
137        for (name, path) in &self.shared_inputs {
138            if name.trim().is_empty() {
139                return Err(io::Error::other("shared input assertion requires a name"));
140            }
141            validate_key(path)?;
142        }
143        Ok(())
144    }
145}
146
147/// A portable locator for a named subtree of an authoritative run.
148#[derive(Clone, Debug, Serialize, Deserialize)]
149#[serde(deny_unknown_fields)]
150pub struct ArtifactLocator {
151    /// Destination, with an external credential profile reference if needed.
152    pub storage: StorageLocation,
153    /// UTC run namespace.
154    pub run_id: String,
155    /// Explicit logical subtree prefix.
156    pub prefix: String,
157}
158impl ArtifactLocator {
159    /// Resolves the locator through verified backend-independent access.
160    pub fn open(&self) -> io::Result<super::ArtifactSet> {
161        super::ArtifactSet::new(
162            super::RunArchive::open(&self.storage, &self.run_id)?,
163            self.prefix.clone(),
164        )
165    }
166}