scientific_workflow/artifact/
access.rs1use 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#[derive(Clone, Debug, Serialize, Deserialize)]
11#[serde(deny_unknown_fields)]
12pub struct RunManifest {
13 pub format: String,
15 pub run_id: String,
17 pub kind: String,
19 pub scientific_identity: String,
21 pub artifacts: BTreeMap<String, ArtifactRef>,
23 pub capture_complete: bool,
25 pub outcome: crate::protocol::Outcome,
27 pub removed: Vec<String>,
29}
30#[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 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 pub fn manifest(&self) -> &RunManifest {
67 &self.manifest
68 }
69 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 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 pub fn verify(&self, key: &str) -> io::Result<()> {
111 io::copy(&mut self.reader(key)?, &mut io::sink())?;
112 Ok(())
113 }
114 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 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}
238pub struct MaterializationLease {
241 path: PathBuf,
242 root: PathBuf,
243 _consumer: Option<std::sync::Arc<super::lease::ConsumerLease>>,
244}
245impl MaterializationLease {
246 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
257pub 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#[derive(Clone)]
274pub struct ArtifactSet {
275 archive: RunArchive,
276 prefix: String,
277 _consumer: Option<std::sync::Arc<super::lease::ConsumerLease>>,
278}
279impl ArtifactSet {
280 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 pub fn prefix(&self) -> &str {
330 &self.prefix
331 }
332 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 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 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 pub fn verify(&self) -> io::Result<()> {
376 for reference in self.references() {
377 self.archive.verify(&reference.key)?;
378 }
379 Ok(())
380 }
381 pub fn materialize(&self, cache: &Path, max_bytes: u64) -> io::Result<MaterializationLease> {
383 self.archive.materialize(&self.prefix, cache, max_bytes)
384 }
385}