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