Skip to main content

scientific_workflow/artifact/
access.rs

1use super::{ArtifactRef, StorageLocation};
2use crate::storage::{Store, atomic_json};
3use serde::{Deserialize, Serialize};
4use std::{
5    collections::BTreeMap,
6    io::{self, Read, Write},
7    path::{Path, PathBuf},
8};
9/// Authoritative immutable inventory for one run, extended only at commit boundaries.
10#[derive(Clone, Debug, Serialize, Deserialize)]
11#[serde(deny_unknown_fields)]
12pub struct RunManifest {
13    /// Durable bundle format.
14    pub format: String,
15    /// UTC namespace.
16    pub run_id: String,
17    /// StudyPlan or campaign.
18    pub kind: String,
19    /// Input tree content identity, independent of operational configuration.
20    pub scientific_identity: String,
21    /// Captured input and result inventory.
22    pub artifacts: BTreeMap<String, ArtifactRef>,
23    /// Capture finished before the first scientific task starts.
24    pub capture_complete: bool,
25    /// A final outcome, distinct from current engine liveness.
26    pub outcome: scientific_workflow_protocol::Outcome,
27    /// Declared raw keys intentionally removed by sealing.
28    pub removed: Vec<String>,
29}
30/// Read-only access to an authoritative run inventory and verified artifacts.
31#[derive(Clone)]
32pub struct RunArchive {
33    pub(crate) store: Store,
34    pub(crate) manifest: RunManifest,
35    pub(crate) maintenance_owner: Option<String>,
36}
37impl RunArchive {
38    /// Opens a run from a configured backend without consulting the registry.
39    pub fn open(location: &StorageLocation, run_id: &str) -> io::Result<Self> {
40        let _: scientific_workflow_protocol::RunId =
41            run_id.to_owned().try_into().map_err(io::Error::other)?;
42        let store = Store::open(location)?;
43        let manifest: RunManifest = store.json(&format!("{run_id}/manifest.json"))?;
44        if manifest.format != "scientific-workflow-run.v1" || manifest.run_id != run_id {
45            return Err(io::Error::other("unsupported run manifest"));
46        }
47        for (key, reference) in &manifest.artifacts {
48            reference.validate()?;
49            if key != &reference.key {
50                return Err(io::Error::other(
51                    "inventory key differs from artifact reference",
52                ));
53            }
54        }
55        let maintenance_owner = std::env::var("WORKFLOW_MAINTENANCE_OWNER")
56            .ok()
57            .and_then(|v| serde_json::from_str::<serde_json::Value>(&v).ok())
58            .filter(|v| v["run_id"] == run_id)
59            .and_then(|v| v["owner"].as_str().map(str::to_owned));
60        Ok(Self {
61            store,
62            manifest,
63            maintenance_owner,
64        })
65    }
66    /// Returns the authoritative inventory; the registry is never used as evidence.
67    pub fn manifest(&self) -> &RunManifest {
68        &self.manifest
69    }
70    /// Looks up an available logical artifact.
71    pub fn artifact(&self, key: &str) -> io::Result<&ArtifactRef> {
72        if self.manifest.removed.iter().any(|k| k == key) {
73            return Err(io::Error::new(
74                io::ErrorKind::NotFound,
75                "raw artifact was intentionally sealed; regenerate it",
76            ));
77        }
78        self.manifest
79            .artifacts
80            .get(key)
81            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "artifact not in run inventory"))
82    }
83    /// Opens a bounded-memory, checksum-verifying stream. Consume through EOF.
84    pub fn reader(&self, key: &str) -> io::Result<Box<dyn Read + Send>> {
85        let reference = self.artifact(key)?;
86        let lease = if reference.role == super::ArtifactRole::Raw {
87            let current: RunManifest = self
88                .store
89                .json(&format!("{}/manifest.json", self.manifest.run_id))?;
90            if current.removed.iter().any(|k| k == key) {
91                return Err(io::Error::new(
92                    io::ErrorKind::NotFound,
93                    "raw artifact was intentionally sealed; regenerate it",
94                ));
95            }
96            super::lease::ConsumerLease::acquire(
97                &self.store,
98                &self.manifest.run_id,
99                vec![key.into()],
100                self.maintenance_owner.as_deref(),
101            )?
102        } else {
103            None
104        };
105        Ok(Box::new(super::lease::LeasedReader {
106            input: self.store.read_verified(reference)?,
107            lease,
108        }))
109    }
110    /// Verifies one artifact completely without materializing it.
111    pub fn verify(&self, key: &str) -> io::Result<()> {
112        io::copy(&mut self.reader(key)?, &mut io::sink())?;
113        Ok(())
114    }
115    /// Materializes a verified, private local copy for path-only tools and NumPy mmap.
116    /// The caller must keep the returned lease alive while using its path.
117    pub fn materialize(
118        &self,
119        prefix: &str,
120        cache: &Path,
121        max_bytes: u64,
122    ) -> io::Result<MaterializationLease> {
123        super::validate_key(prefix)?;
124        if self
125            .manifest
126            .removed
127            .iter()
128            .any(|k| k == prefix || k.starts_with(&format!("{prefix}/")))
129        {
130            return Err(io::Error::new(
131                io::ErrorKind::NotFound,
132                "selection includes intentionally removed raw data; regenerate it",
133            ));
134        }
135        let keys = self
136            .manifest
137            .artifacts
138            .keys()
139            .filter(|k| {
140                (*k == prefix || k.starts_with(&format!("{prefix}/")))
141                    && !self.manifest.removed.contains(k)
142            })
143            .cloned()
144            .collect::<Vec<_>>();
145        let mut lease = self.materialize_keys(&keys, cache, max_bytes)?;
146        lease.path = lease.path.join(prefix);
147        Ok(lease)
148    }
149    /// Materializes an explicit file selection, preserving logical paths under a
150    /// private lease root. Omitted inputs can remain streamed artifact references.
151    pub fn materialize_keys(
152        &self,
153        keys: &[String],
154        cache: &Path,
155        max_bytes: u64,
156    ) -> io::Result<MaterializationLease> {
157        let keys = keys.iter().collect::<std::collections::BTreeSet<_>>();
158        if keys.is_empty() {
159            return Err(io::Error::new(
160                io::ErrorKind::NotFound,
161                "artifact selection is empty",
162            ));
163        }
164        let size = keys.iter().try_fold(0u64, |n, key| {
165            n.checked_add(self.artifact(key)?.bytes)
166                .ok_or_else(|| io::Error::other("materialization size overflow"))
167        })?;
168        if size > max_bytes {
169            return Err(io::Error::other(
170                "materialization exceeds local lease budget",
171            ));
172        }
173        std::fs::create_dir_all(cache)?;
174        let root = cache.join(format!(
175            "lease-{}-{}",
176            std::process::id(),
177            crate::storage::run_id()
178        ));
179        std::fs::create_dir(&root)?;
180        #[cfg(unix)]
181        {
182            use std::os::unix::fs::PermissionsExt;
183            std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700))?;
184        }
185        let raw_keys = keys
186            .iter()
187            .filter(|key| self.manifest.artifacts[key.as_str()].role == super::ArtifactRole::Raw)
188            .map(|key| (**key).clone())
189            .collect::<Vec<_>>();
190        let consumer = super::lease::ConsumerLease::acquire(
191            &self.store,
192            &self.manifest.run_id,
193            raw_keys,
194            self.maintenance_owner.as_deref(),
195        )?;
196        let lease = MaterializationLease {
197            path: root.join("tree"),
198            root,
199            _consumer: consumer,
200        };
201        for key in keys {
202            let path = lease.path.join(key);
203            std::fs::create_dir_all(path.parent().unwrap())?;
204            let mut output = std::fs::OpenOptions::new()
205                .write(true)
206                .create_new(true)
207                .open(&path)?;
208            let mut input: Box<dyn Read + Send> = if let Some(consumer) = &lease._consumer {
209                Box::new(super::lease::LeasedReader {
210                    input: self.store.read_verified(self.artifact(key)?)?,
211                    lease: Some(consumer.clone()),
212                })
213            } else {
214                self.reader(key)?
215            };
216            io::copy(&mut input, &mut output)?;
217            output.flush()?;
218            output.sync_all()?;
219            #[cfg(unix)]
220            {
221                use std::os::unix::fs::PermissionsExt;
222                std::fs::set_permissions(
223                    &path,
224                    std::fs::Permissions::from_mode(if self.artifact(key)?.executable {
225                        0o500
226                    } else {
227                        0o400
228                    }),
229                )?;
230            }
231        }
232        atomic_json(
233            &lease.root.join("lease.json"),
234            &serde_json::json!({"run":self.manifest.run_id,"bytes":size}),
235        )?;
236        Ok(lease)
237    }
238}
239/// A verified local materialization whose lifetime protects mmap and path consumers.
240/// Dropping it removes the disposable copy, never authoritative stored data.
241pub struct MaterializationLease {
242    path: PathBuf,
243    root: PathBuf,
244    _consumer: Option<std::sync::Arc<super::lease::ConsumerLease>>,
245}
246impl MaterializationLease {
247    /// Path of the requested materialized artifact or subtree.
248    pub fn path(&self) -> &Path {
249        &self.path
250    }
251}
252impl Drop for MaterializationLease {
253    fn drop(&mut self) {
254        let _ = std::fs::remove_dir_all(&self.root);
255    }
256}
257
258/// Opens an immutable reference through the shared verified storage implementation.
259/// Consume through EOF to complete verification.
260pub fn open_reference(
261    locator: &super::ArtifactLocator,
262    reference: &ArtifactRef,
263) -> io::Result<Box<dyn Read + Send>> {
264    let archive = RunArchive::open(&locator.storage, &locator.run_id)?;
265    if archive.artifact(&locator.prefix)? != reference {
266        return Err(io::Error::other(
267            "artifact pointer differs from its authoritative inventory",
268        ));
269    }
270    archive.reader(&locator.prefix)
271}
272
273/// A named, verified subtree, usable without assuming a local filesystem.
274#[derive(Clone)]
275pub struct ArtifactSet {
276    archive: RunArchive,
277    prefix: String,
278    _consumer: Option<std::sync::Arc<super::lease::ConsumerLease>>,
279}
280impl ArtifactSet {
281    /// Selects an explicit subtree of an authoritative run inventory.
282    pub fn new(archive: RunArchive, prefix: impl Into<String>) -> io::Result<Self> {
283        let prefix = prefix.into();
284        super::validate_key(&prefix)?;
285        if !archive
286            .manifest
287            .artifacts
288            .keys()
289            .any(|k| k == &prefix || k.starts_with(&format!("{prefix}/")))
290        {
291            return Err(io::Error::new(
292                io::ErrorKind::NotFound,
293                "artifact subtree is absent",
294            ));
295        }
296        if archive
297            .manifest
298            .removed
299            .iter()
300            .any(|k| k == &prefix || k.starts_with(&format!("{prefix}/")))
301        {
302            return Err(io::Error::new(
303                io::ErrorKind::NotFound,
304                "selection includes intentionally removed raw data; regenerate it",
305            ));
306        }
307        let raw = archive
308            .manifest
309            .artifacts
310            .iter()
311            .filter(|(k, r)| {
312                (**k == prefix || k.starts_with(&format!("{prefix}/")))
313                    && r.role == super::ArtifactRole::Raw
314            })
315            .map(|(k, _)| k.clone())
316            .collect();
317        let consumer = super::lease::ConsumerLease::acquire(
318            &archive.store,
319            &archive.manifest.run_id,
320            raw,
321            archive.maintenance_owner.as_deref(),
322        )?;
323        Ok(Self {
324            archive,
325            prefix,
326            _consumer: consumer,
327        })
328    }
329    /// Exact subtree prefix in the run inventory.
330    pub fn prefix(&self) -> &str {
331        &self.prefix
332    }
333    /// Iterates available immutable descriptors, preserving logical order.
334    pub fn references(&self) -> impl Iterator<Item = &ArtifactRef> {
335        self.archive
336            .manifest
337            .artifacts
338            .iter()
339            .filter(|(k, _)| {
340                (*k == &self.prefix || k.starts_with(&format!("{}/", self.prefix)))
341                    && !self.archive.manifest.removed.contains(k)
342            })
343            .map(|(_, r)| r)
344    }
345    /// Looks up the immutable descriptor for one relative file.
346    pub fn reference(&self, relative: &str) -> io::Result<&ArtifactRef> {
347        let key = if relative.is_empty() {
348            self.prefix.clone()
349        } else {
350            super::validate_key(relative)?;
351            format!("{}/{relative}", self.prefix)
352        };
353        self.archive.artifact(&key)
354    }
355    /// Opens a relative file as a verified bounded-memory stream.
356    pub fn reader(&self, relative: &str) -> io::Result<Box<dyn Read + Send>> {
357        let key = if relative.is_empty() {
358            self.prefix.clone()
359        } else {
360            super::validate_key(relative)?;
361            format!("{}/{relative}", self.prefix)
362        };
363        if let Some(lease) = &self._consumer {
364            lease.check()?;
365            return Ok(Box::new(super::lease::LeasedReader {
366                input: self
367                    .archive
368                    .store
369                    .read_verified(self.archive.artifact(&key)?)?,
370                lease: Some(lease.clone()),
371            }));
372        }
373        self.archive.reader(&key)
374    }
375    /// Verifies every available file in this selection.
376    pub fn verify(&self) -> io::Result<()> {
377        for reference in self.references() {
378            self.archive.verify(&reference.key)?;
379        }
380        Ok(())
381    }
382    /// Materializes a protected local view for tools requiring paths.
383    pub fn materialize(&self, cache: &Path, max_bytes: u64) -> io::Result<MaterializationLease> {
384        self.archive.materialize(&self.prefix, cache, max_bytes)
385    }
386}