rustsy-process 0.2.0-alpha.1

Declared process graphs with verified local artifact caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use crate::{
    artifact::{self, Artifact, Hash, Kind, Tree},
    fs_safety::{self, Scratch, invalid, node_md},
};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::{
    collections::HashSet,
    fs,
    io::{self, Read},
    path::{Path, PathBuf},
};

mod packed;

#[derive(Debug, Deserialize, Serialize)]
struct Envelope {
    action: Hash,
    checksum: Hash,
    outputs: Vec<Tree>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pack: Option<packed::Descriptor>,
}

pub(crate) struct Cache {
    blobs: PathBuf,
    actions: PathBuf,
    packs: PathBuf,
    use_packs: bool,
    verify_local_hit_payload: bool,
}

impl Cache {
    pub(crate) fn new(
        root: &Path,
        use_packs: bool,
        verify_local_hit_payload: bool,
    ) -> io::Result<Self> {
        let parent = fs_safety::absolute(root)?;
        let packs = if use_packs {
            fs_safety::private_dir(&parent, "packs")?
        } else {
            parent.join("packs")
        };
        Ok(Self {
            blobs: fs_safety::private_dir(&parent, "blobs")?,
            actions: fs_safety::private_dir(&parent, "actions")?,
            packs,
            use_packs,
            verify_local_hit_payload,
        })
    }

    pub(crate) fn capture(
        &self,
        workspace: &Path,
        outputs: &[Artifact],
        action: Hash,
        pool: Option<&rayon::ThreadPool>,
    ) -> io::Result<Vec<Tree>> {
        let (trees, pack) =
            if self.use_packs && outputs.iter().any(|output| output.kind == Kind::Directory) {
                let (trees, descriptor) = packed::capture(self, workspace, outputs)?;
                (trees, Some(descriptor))
            } else {
                let trees = outputs
                    .iter()
                    .map(|out| {
                        artifact::process_tree(workspace, out, pool, |buffer, source| {
                            self.store(source, buffer)
                        })
                    })
                    .collect::<io::Result<Vec<_>>>()?;
                (trees, None)
            };
        let signature = checksum(&trees, pack.as_ref())?;
        let envelope = Envelope {
            action,
            checksum: signature,
            outputs: trees.clone(),
            pack,
        };
        let name = self.actions.join(artifact::text(&action));
        let staged = Scratch::new(&self.actions)?;
        let entry = staged.0.join("manifest");
        let mut file = create(&entry)?;
        serde_json::to_writer(&mut file, &envelope)?;
        file.sync_all()?;
        drop(file);
        match fs::hard_link(&entry, &name) {
            Ok(()) => {}
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
                match self.read(action, outputs) {
                    Ok(previous) if previous.outputs == trees => {}
                    Ok(_) => {
                        return Err(invalid(
                            "deterministic action published conflicting outputs",
                        ));
                    }
                    Err(e) if e.kind() == io::ErrorKind::InvalidData => {
                        replace_regular(&entry, &name)?
                    }
                    Err(e) => return Err(e),
                }
            }
            Err(e) => return Err(e),
        }
        Ok(trees)
    }

    fn read(&self, action: Hash, outputs: &[Artifact]) -> io::Result<Envelope> {
        let path = self.actions.join(artifact::text(&action));
        let md = node_md(&path)?;
        if !md.is_file() || md.len() > 32 * 1024 * 1024 {
            return Err(invalid("invalid or oversized action manifest"));
        }
        let file = fs::File::open(&path)?;
        let envelope: Envelope =
            serde_json::from_reader(io::BufReader::new(file.take(32 * 1024 * 1024)))
                .map_err(invalid)?;
        if envelope.action != action
            || checksum(&envelope.outputs, envelope.pack.as_ref())? != envelope.checksum
            || envelope.outputs.len() != outputs.len()
            || (envelope.pack.is_some() && !self.use_packs)
        {
            return Err(invalid("action manifest does not match the requested key"));
        }
        for (tree, declared) in envelope.outputs.iter().zip(outputs) {
            validate_tree(tree, declared)?;
        }
        Ok(envelope)
    }

    fn store(&self, source: &Path, buffer: &mut [u8]) -> io::Result<Hash> {
        let staged = Scratch::new(&self.blobs)?;
        let entry = staged.0.join("blob");
        let mut writer = create(&entry)?;
        let digest = artifact::copy_hash_buffered(source, &mut writer, buffer)?;
        writer.sync_all()?;
        drop(writer);
        let destination = self.blobs.join(artifact::text(&digest));
        match fs::hard_link(&entry, &destination) {
            Ok(()) => {}
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
                if artifact::copy_hash_buffered(&destination, io::sink(), buffer)? != digest {
                    replace_regular(&entry, &destination)?;
                }
            }
            Err(e) => return Err(e),
        }
        Ok(digest)
    }

    pub(crate) fn restore(
        &self,
        workspace: &Path,
        scratch_root: &Path,
        action: Hash,
        outputs: &[Artifact],
        pool: Option<&rayon::ThreadPool>,
    ) -> io::Result<(Vec<Tree>, Vec<String>, bool)> {
        let Envelope {
            outputs: trees,
            pack,
            ..
        } = self.read(action, outputs)?;
        let checked_local = !self.verify_local_hit_payload && outputs.len() == 1;
        if checked_local {
            match artifact::hash_tree(workspace, &outputs[0], pool) {
                Ok(local) if local == trees[0] => return Ok((trees, Vec::new(), false)),
                Ok(_) => {}
                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
                Err(e) => return Err(e),
            }
        }
        let mut reader = pack
            .as_ref()
            .map(|descriptor| packed::Reader::open(self, descriptor, &trees))
            .transpose()?;
        // Always validate the stored payloads, even when the files in the workspace
        // already match. Otherwise a damaged cache could report a clean hit.
        let mut staged = None;
        let mut restores = Vec::new();
        let mut restored = Vec::new();
        let mut recovery = Vec::new();
        for (index, (tree, declaration)) in trees.iter().zip(outputs).enumerate() {
            let destination = fs_safety::path(workspace, &tree.path, true)?;
            let same = if checked_local {
                false
            } else {
                match artifact::hash_tree(workspace, declaration, pool) {
                    Ok(existing) => existing == *tree,
                    Err(e) if e.kind() == io::ErrorKind::NotFound => false,
                    Err(e) => return Err(e),
                }
            };
            if same {
                if let (Some(reader), Some(descriptor)) = (&mut reader, &pack) {
                    reader.verify(tree, descriptor.sizes(index), None, pool)?;
                } else {
                    self.verify(tree, None, pool)?;
                }
            } else {
                if staged.is_none() {
                    staged = Some(Scratch::new(scratch_root)?);
                }
                let stage = &staged.as_ref().unwrap().0;
                let new = stage.join(format!("new-{index}"));
                for dir in tree.entries.iter().filter(|entry| entry.file.is_none()) {
                    fs::create_dir(if dir.name.is_empty() {
                        new.clone()
                    } else {
                        new.join(&dir.name)
                    })?;
                }
                if let (Some(reader), Some(descriptor)) = (&mut reader, &pack) {
                    reader.verify(tree, descriptor.sizes(index), Some(&new), pool)?;
                } else {
                    self.verify(tree, Some(&new), pool)?;
                }
                for dir in tree
                    .entries
                    .iter()
                    .rev()
                    .filter(|entry| entry.file.is_none())
                {
                    artifact::permissions(&new.join(&dir.name), dir.permissions)?;
                }
                restores.push(Restore {
                    new,
                    destination,
                    backup: stage.join(format!("old-{index}")),
                    has_backup: false,
                    installed: false,
                });
                restored.push(tree.path.clone());
                recovery.push((index, tree.path.as_str()));
            }
        }

        if let Some(stage) = &staged {
            crate::recovery::prepare(&stage.0, workspace, recovery.into_iter())?;
        }
        let result = apply(workspace, &mut restores).and_then(|()| {
            if let Some(stage) = &staged {
                crate::recovery::commit(&stage.0)?;
            }
            Ok(())
        });
        if let Err(primary) = result {
            if let Err(recovery) = rollback(&mut restores) {
                let location = staged.unwrap().persist().display().to_string();
                return Err(io::Error::other(format!(
                    "{primary}; rollback failed: {recovery}. Backups at {location}"
                )));
            }
            return Err(primary);
        }
        Ok((trees, restored, true))
    }

    fn verify(
        &self,
        tree: &Tree,
        target: Option<&Path>,
        pool: Option<&rayon::ThreadPool>,
    ) -> io::Result<()> {
        let run = |buffer: &mut Vec<u8>, entry: &artifact::Entry| {
            let Some(hash) = entry.file else {
                return Ok(());
            };
            let source = self.blobs.join(artifact::text(&hash));
            let actual = match target {
                Some(dir) => {
                    let path = if entry.name.is_empty() {
                        dir.to_owned()
                    } else {
                        dir.join(&entry.name)
                    };
                    let digest = artifact::copy_hash_buffered(&source, create(&path)?, buffer)?;
                    artifact::permissions(&path, entry.permissions)?;
                    Ok(digest)
                }
                None => artifact::copy_hash_buffered(&source, io::sink(), buffer),
            }
            .map_err(|e| {
                if e.kind() == io::ErrorKind::NotFound {
                    invalid(format!("blob {} is missing", artifact::text(&hash)))
                } else {
                    e
                }
            })?;
            if actual != hash {
                return Err(invalid(format!(
                    "blob {} is corrupt",
                    artifact::text(&hash)
                )));
            }
            Ok(())
        };
        if let Some(pool) = pool.filter(|_| tree.entries.len() >= 64) {
            pool.install(|| {
                tree.entries
                    .par_iter()
                    .with_min_len(16)
                    .try_for_each_init(|| vec![0; 128 * 1024], run)
            })
        } else {
            let mut buffer = vec![0; 128 * 1024];
            tree.entries
                .iter()
                .try_for_each(|entry| run(&mut buffer, entry))
        }
    }
}

fn checksum(trees: &[Tree], pack: Option<&packed::Descriptor>) -> io::Result<Hash> {
    let bytes = match pack {
        Some(pack) => serde_json::to_vec(&(trees, pack))?,
        None => serde_json::to_vec(trees)?,
    };
    Ok(artifact::sha(&bytes))
}

fn validate_tree(tree: &Tree, declaration: &Artifact) -> io::Result<()> {
    if tree.path != declaration.path || tree.entries.is_empty() {
        return Err(invalid("cache manifest names undeclared outputs"));
    }
    let root = &tree.entries[0];
    if !root.name.is_empty() || root.file.is_some() != (declaration.kind == Kind::File) {
        return Err(invalid("cache artifact root has the wrong type"));
    }
    let mut all = HashSet::new();
    all.insert(String::new());
    let mut dirs = HashSet::new();
    if root.file.is_none() {
        dirs.insert(String::new());
    }
    for entry in tree.entries.iter().skip(1) {
        fs_safety::relative(&entry.name, false)?;
        let identity = fs_safety::identity(&entry.name);
        let parent = identity.rsplit_once('/').map_or("", |(parent, _)| parent);
        if !dirs.contains(parent) || !all.insert(identity.clone()) {
            return Err(invalid("cache manifest has a duplicate or missing parent"));
        }
        if entry.file.is_none() {
            dirs.insert(identity);
        }
    }
    Ok(())
}

fn replace_regular(source: &Path, destination: &Path) -> io::Result<()> {
    if !node_md(destination)?.is_file() {
        return Err(invalid("cache entry is not a regular file"));
    }
    fs::rename(source, destination)
}

fn create(path: &Path) -> io::Result<fs::File> {
    fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
}

struct Restore {
    new: PathBuf,
    destination: PathBuf,
    backup: PathBuf,
    has_backup: bool,
    installed: bool,
}

fn apply(workspace: &Path, changes: &mut [Restore]) -> io::Result<()> {
    for item in changes {
        let parent = item
            .destination
            .parent()
            .ok_or_else(|| invalid("missing output parent"))?;
        let local = parent.strip_prefix(workspace).map_err(invalid)?;
        let key = local
            .iter()
            .map(|p| p.to_str().unwrap_or_default())
            .collect::<Vec<_>>()
            .join("/");
        fs_safety::path(workspace, if key.is_empty() { "." } else { &key }, true)?;
        fs::create_dir_all(parent)?;
        match node_md(&item.destination) {
            Ok(_) => {
                fs::rename(&item.destination, &item.backup)?;
                item.has_backup = true;
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
            Err(e) => return Err(e),
        }
        fs::rename(&item.new, &item.destination)?;
        item.installed = true;
    }
    Ok(())
}

fn rollback(changes: &mut [Restore]) -> io::Result<()> {
    for item in changes.iter_mut().rev() {
        if item.installed {
            fs::rename(&item.destination, &item.new)?;
        }
        if item.has_backup {
            fs::rename(&item.backup, &item.destination)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use artifact::Entry;

    fn entry(name: &str, file: bool) -> Entry {
        Entry {
            name: name.into(),
            file: file.then_some([1; 32]),
            permissions: 0o755,
        }
    }

    fn directory() -> Artifact {
        Artifact {
            path: "out/tree".into(),
            kind: Kind::Directory,
        }
    }

    #[test]
    fn reject_paths_and_invalid_manifest_trees() {
        let declaration = directory();
        for entries in [
            vec![entry("", false), entry("../sibling", true)],
            vec![entry("", false), entry("child/leaf", true)],
            vec![
                entry("", false),
                entry("child", true),
                entry("child/leaf", true),
            ],
            vec![entry("", false), entry("child", true), entry("child", true)],
            vec![entry("", true), entry("child", true)],
            vec![entry("", false), entry("alternate:stream", true)],
            vec![entry("", false), entry("COM¹.log", true)],
        ] {
            assert!(
                validate_tree(
                    &Tree {
                        path: declaration.path.clone(),
                        entries
                    },
                    &declaration
                )
                .is_err()
            );
        }
        let foreign = Tree {
            path: "out/foreign".into(),
            entries: vec![entry("", false)],
        };
        assert!(validate_tree(&foreign, &declaration).is_err());
    }

    #[test]
    fn restore_nested_tree_and_repair_missing_blob() -> io::Result<()> {
        let root = Scratch::new(&std::env::temp_dir())?;
        let cache = Cache::new(&fs_safety::private_dir(&root.0, "cas")?, false, true)?;
        let workspace = fs_safety::private_dir(&root.0, "workspace")?;
        let stage = fs_safety::private_dir(&workspace, ".rustsy-process")?;
        let output = workspace.join("out/tree");
        fs::create_dir_all(output.join("empty"))?;
        fs::write(output.join("value"), b"value")?;
        let sibling = workspace.join("out/sibling");
        fs::write(&sibling, b"keep")?;
        let action = artifact::sha(b"tree");
        let outputs = [directory()];
        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(4)
            .build()
            .unwrap();
        cache.capture(&workspace, &outputs, action, Some(&pool))?;
        fs::rename(&output, stage.join("previous"))?;
        assert_eq!(
            cache
                .restore(&workspace, &stage, action, &outputs, Some(&pool))?
                .1,
            ["out/tree"]
        );
        assert_eq!(fs::read(output.join("value"))?, b"value");
        assert!(output.join("empty").is_dir());
        assert_eq!(fs::read(&sibling)?, b"keep");
        fs::remove_file(cache.blobs.join(artifact::text(&artifact::sha(b"value"))))?;
        assert_eq!(
            cache
                .restore(&workspace, &stage, action, &outputs, Some(&pool))
                .unwrap_err()
                .kind(),
            io::ErrorKind::InvalidData
        );
        cache.capture(&workspace, &outputs, action, Some(&pool))?;
        assert!(
            cache
                .restore(&workspace, &stage, action, &outputs, Some(&pool))?
                .1
                .is_empty()
        );
        #[cfg(unix)]
        {
            fs::rename(workspace.join("out"), stage.join("dir"))?;
            std::os::unix::fs::symlink(stage.join("dir"), workspace.join("out"))?;
            assert!(
                cache
                    .restore(&workspace, &stage, action, &outputs, Some(&pool))
                    .is_err()
            );
            assert_eq!(fs::read(stage.join("dir/sibling"))?, b"keep");
        }
        Ok(())
    }

    #[test]
    fn stage_a_parallel_tree_with_one_shared_blob() -> io::Result<()> {
        let root = Scratch::new(&std::env::temp_dir())?;
        let cache = Cache::new(&fs_safety::private_dir(&root.0, "cas")?, false, true)?;
        let work = fs_safety::private_dir(&root.0, "work")?;
        let stage = fs_safety::private_dir(&work, ".rustsy-process")?;
        let dir = work.join("out/tree");
        fs::create_dir_all(&dir)?;
        for n in 0..144 {
            fs::write(dir.join(n.to_string()), b"same")?;
        }
        let key = artifact::sha(b"work");
        let outputs = [directory()];
        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(8)
            .build()
            .unwrap();
        cache.capture(&work, &outputs, key, Some(&pool))?;
        assert_eq!(fs::read_dir(&cache.blobs)?.count(), 1);
        fs::rename(&dir, stage.join("old"))?;
        let restored = cache.restore(&work, &stage, key, &outputs, Some(&pool))?;
        assert_eq!(restored.1, ["out/tree"]);
        assert_eq!(fs::read_dir(&dir)?.count(), 144);
        assert_eq!(fs::read(dir.join("143"))?, b"same");
        Ok(())
    }

    #[test]
    fn packed_tree_preserves_members_and_rejects_corruption_before_promotion() -> io::Result<()> {
        let root = Scratch::new(&std::env::temp_dir())?;
        let path = fs_safety::private_dir(&root.0, "cas")?;
        let cache = Cache::new(&path, true, true)?;
        let work = fs_safety::private_dir(&root.0, "work")?;
        let stage = fs_safety::private_dir(&work, ".rustsy-process")?;
        let dir = work.join("out/tree");
        fs::create_dir_all(dir.join("empty"))?;
        for n in 0..144 {
            fs::write(dir.join(n.to_string()), vec![n as u8; n])?;
        }
        fs::write(work.join("out/extra"), b"outside the declared directory")?;
        let key = artifact::sha(b"packed work");
        let outputs = [directory()];
        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(8)
            .build()
            .unwrap();
        let expected = cache.capture(&work, &outputs, key, Some(&pool))?;
        assert_eq!(fs::read_dir(&cache.blobs)?.count(), 0);
        assert_eq!(fs::read_dir(&cache.packs)?.count(), 1);
        let pack = fs::read_dir(&cache.packs)?.next().unwrap()?.path();
        fs::rename(&dir, stage.join("previous"))?;
        let restored = cache.restore(&work, &stage, key, &outputs, Some(&pool))?;
        assert_eq!(restored.0, expected);
        assert_eq!(restored.1, ["out/tree"]);
        assert_eq!(fs::read(dir.join("143"))?, vec![143; 143]);
        assert!(dir.join("empty").is_dir());
        let mut data = fs::read(&pack)?;
        data[0] ^= 1;
        fs::write(&pack, data)?;
        let verify_local_only = Cache::new(&path, true, false)?;
        assert!(
            !verify_local_only
                .restore(&work, &stage, key, &outputs, Some(&pool))?
                .2
        );
        assert!(
            cache
                .restore(&work, &stage, key, &outputs, Some(&pool))
                .is_err()
        );
        fs::rename(&dir, stage.join("restored"))?;
        assert_eq!(
            verify_local_only
                .restore(&work, &stage, key, &outputs, Some(&pool))
                .unwrap_err()
                .kind(),
            io::ErrorKind::InvalidData
        );
        assert!(!dir.exists());
        assert_eq!(
            fs::read(work.join("out/extra"))?,
            b"outside the declared directory"
        );
        fs::rename(stage.join("previous"), &dir)?;
        cache.capture(&work, &outputs, key, Some(&pool))?;
        assert!(
            cache
                .restore(&work, &stage, key, &outputs, Some(&pool))?
                .1
                .is_empty()
        );
        Ok(())
    }
}