buildl-core 0.3.1

Domain data, ports, and pure pipeline logic for the buildl build system — no I/O, no Lua.
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
//! What a run that succeeded tells the remote cache, and what the cache answers.
//!
//! Its own file because the local content store knows a file by its digest alone, while a remote
//! cache names every file with its size. The sizes are read here, where the bytes are, and the
//! result is handed over as a plain value together with a way to read the bytes it names.
//!
//! Responsibilities: [`upload_of`], which describes a run in the terms a remote cache stores it;
//! [`StoredBlobs`], which lets a remote adapter read the local content store; and [`upload`],
//! which sends the description and says, as a [`Sent`], what the answer means for the build.
//!
//! Non-responsibilities: deciding when to upload, and what a failed call does to the worker that
//! met it, which the worker does; and the order of the calls on the wire, which the remote
//! adapter owns.

use crate::error::{Error, PortName, Result};
use crate::execute::perform::{Kept, Printed, Task};
use crate::ports::{BlobSource, ContentStore, RemoteCache};
use crate::types::{
    Blob, Diagnostic, Digest, Label, OutputManifest, OutputSource, RemoteAction, RemoteCall,
    RemoteContent, RemoteNotice, RemoteOutput, RemoteTree, RemoteTreeFile, RemoteUpload, Uploaded,
};

/// What `task` produced, in the terms a remote cache stores a result.
///
/// `kept` holds one entry per declared output, in declared order, and `printed` what the action
/// wrote. Each output keeps the path it is declared at, and a directory lists its files in path
/// order. The size of every file and of both logs is read from `cas`.
///
/// A target whose output is its standard output sends no output file: its output travels as the
/// digest of `printed.stdout`, which the result always names.
///
/// # Errors
///
/// Returns [`Error::Adapter`] naming [`PortName::ContentStore`] when `kept` does not hold one
/// entry per declared output, or when a file or a log is not held, and whatever `cas` returns
/// when it cannot read one.
pub(crate) fn upload_of<C: ContentStore>(
    task: &Task,
    kept: &[Kept],
    printed: &Printed,
    cas: &C,
) -> Result<RemoteUpload> {
    let declared = &task.action.outputs;
    if kept.len() != declared.len() {
        return Err(Error::Adapter {
            port: PortName::ContentStore,
            diagnostic: Diagnostic::new(format!(
                "{} produced {} outputs but declares {}",
                task.action.label,
                kept.len(),
                declared.len()
            )),
        });
    }
    let sent = match task.action.output_source {
        OutputSource::Command => declared.as_slice(),
        OutputSource::Stdout => &[],
    };
    let outputs = sent
        .iter()
        .zip(kept)
        .map(|(path, kept)| {
            let content = match &kept.manifest {
                OutputManifest::File(file) => RemoteContent::File {
                    blob: blob_of(&file.digest, cas)?,
                    mode: file.mode,
                },
                OutputManifest::Tree(tree) => {
                    let files = tree
                        .entries()
                        .iter()
                        .map(|entry| {
                            Ok(RemoteTreeFile {
                                path: entry.path.clone(),
                                blob: blob_of(&entry.digest, cas)?,
                                mode: entry.mode,
                            })
                        })
                        .collect::<Result<Vec<_>>>()?;
                    RemoteContent::Tree(RemoteTree::new(files))
                }
            };
            Ok(RemoteOutput {
                path: path.clone(),
                content,
            })
        })
        .collect::<Result<Vec<_>>>()?;
    Ok(RemoteUpload {
        outputs,
        stdout: blob_of(&printed.stdout, cas)?,
        stderr: blob_of(&printed.stderr, cas)?,
    })
}

/// The blob that the content held under `digest` is: the digest, and the length of what `cas`
/// holds there.
fn blob_of<C: ContentStore>(digest: &Digest, cas: &C) -> Result<Blob> {
    let bytes = cas.get(digest)?.ok_or_else(|| Error::Adapter {
        port: PortName::ContentStore,
        diagnostic: Diagnostic::new(format!("{digest} is not held, and an upload names it")),
    })?;
    Ok(Blob {
        digest: *digest,
        size: bytes.len() as u64,
    })
}

/// The local content store, as a remote adapter reads the blobs of an upload.
#[derive(Debug, Clone, Copy)]
pub(crate) struct StoredBlobs<'a, C>(pub(crate) &'a C);

impl<C: ContentStore> BlobSource for StoredBlobs<'_, C> {
    fn read(&self, digest: &Digest) -> Result<Option<Vec<u8>>> {
        self.0.get(digest)
    }
}

/// What the remote cache did with an upload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Sent {
    /// The result and everything it names are stored.
    Stored,
    /// Nothing was stored, because an input file changed after its digest was taken. Not a
    /// failure: the notice is a [`RemoteNotice::InputChanged`], and the remote stays on.
    Declined(RemoteNotice),
    /// The call failed: a [`RemoteNotice::Failed`] for [`RemoteCall::Upload`], carrying the
    /// adapter's own message.
    Failed(RemoteNotice),
}

/// Sends what a run produced to the remote cache as the result for `action`, and says what the
/// answer means for the build.
///
/// `label` is the target that ran. The answer is [`Sent`]: whether the result and everything it
/// names are stored, whether an input file changed after its digest was taken so nothing was
/// stored, or whether the call failed.
pub(crate) fn upload<R: RemoteCache, C: ContentStore>(
    remote: &R,
    label: &Label,
    action: &RemoteAction,
    produced: &RemoteUpload,
    cas: &C,
) -> Sent {
    match remote.upload(action, produced, &StoredBlobs(cas)) {
        Ok(Uploaded::Done) => Sent::Stored,
        Ok(Uploaded::InputChanged(path)) => Sent::Declined(RemoteNotice::InputChanged {
            label: label.clone(),
            path,
        }),
        Err(error) => Sent::Failed(RemoteNotice::Failed {
            call: RemoteCall::Upload,
            diagnostic: match error {
                Error::Adapter { diagnostic, .. } => diagnostic,
                other => Diagnostic::new(other.to_string()),
            },
        }),
    }
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::unwrap_used,
        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
    )]

    use std::collections::{BTreeMap, BTreeSet};
    use std::sync::Mutex;

    use super::{Sent, StoredBlobs, upload, upload_of};
    use crate::error::{Error, PortName, Result};
    use crate::execute::fixtures::{command, file, kept, key, label, output_path, tree};
    use crate::execute::perform::{Kept, Printed, Task};
    use crate::ports::{BlobSource, ContentStore, RemoteCache};
    use crate::types::{
        Blob, DecodedTree, Diagnostic, Digest, Executed, FileMode, NetworkAccess, NodeId,
        OutputManifest, OutputPath, OutputSource, Platform, PlatformProperties, ReadyAction,
        RemoteAction, RemoteCall, RemoteContent, RemoteHit, RemoteNotice, RemoteOutput,
        RemotePlatform, RemoteTree, RemoteTreeFile, RemoteUpload, RootPath, SourcePath, StoredFile,
        TargetRole, Timeout, TreePath, Uploaded,
    };

    const TARGET: &str = "//app:app";

    /// A store that keeps what it is given.
    #[derive(Default)]
    struct Store(Mutex<BTreeMap<Digest, Vec<u8>>>);

    impl Store {
        /// A store holding each of `contents`.
        fn holding(contents: &[&str]) -> Self {
            let store = Self::default();
            for content in contents {
                store.put(content.as_bytes()).unwrap();
            }
            store
        }
    }

    impl ContentStore for Store {
        fn put(&self, bytes: &[u8]) -> Result<Digest> {
            let digest = Digest::of(bytes);
            self.0.lock().unwrap().insert(digest, bytes.to_vec());
            Ok(digest)
        }

        fn contains(&self, digest: &Digest) -> bool {
            self.0.lock().unwrap().contains_key(digest)
        }

        fn get(&self, digest: &Digest) -> Result<Option<Vec<u8>>> {
            Ok(self.0.lock().unwrap().get(digest).cloned())
        }

        fn clear(&self, _at: &OutputPath) -> Result<()> {
            Ok(())
        }

        fn place(&self, _digest: &Digest, _mode: FileMode, _at: &OutputPath) -> Result<()> {
            Ok(())
        }
    }

    /// A remote whose upload gives the scripted answer and notes what it was sent and what the
    /// blob source read for it.
    struct Remote {
        answer: Mutex<Option<Result<Uploaded>>>,
        sent: Mutex<Vec<RemoteUpload>>,
        read_back: Mutex<Vec<Option<Vec<u8>>>>,
    }

    impl Remote {
        fn answering(answer: Result<Uploaded>) -> Self {
            Self {
                answer: Mutex::new(Some(answer)),
                sent: Mutex::new(Vec::new()),
                read_back: Mutex::new(Vec::new()),
            }
        }
    }

    impl RemoteCache for Remote {
        fn lookup(&self, _action: &RemoteAction) -> Result<Option<RemoteHit>> {
            unreachable!("an upload asks for no result")
        }

        fn download(&self, _blobs: &[Blob]) -> Result<Vec<Vec<u8>>> {
            unreachable!("an upload downloads nothing")
        }

        fn decode_tree(&self, _bytes: &[u8]) -> Result<DecodedTree> {
            unreachable!("an upload decodes no tree")
        }

        fn upload(
            &self,
            _action: &RemoteAction,
            produced: &RemoteUpload,
            blobs: &dyn BlobSource,
        ) -> Result<Uploaded> {
            self.sent.lock().unwrap().push(produced.clone());
            self.read_back
                .lock()
                .unwrap()
                .push(blobs.read(&produced.stdout.digest)?);
            self.answer.lock().unwrap().take().unwrap()
        }

        fn execute(&self, _action: &RemoteAction) -> Result<Executed> {
            unreachable!("an upload runs nothing")
        }
    }

    /// A task declaring the outputs `names`.
    fn task(names: &[&str]) -> Task {
        Task {
            node: NodeId::new(0),
            role: TargetRole::Build,
            key: key(names),
            action: ReadyAction {
                label: label(TARGET),
                command: command(&["cc"]),
                description: None,
                env: BTreeMap::new(),
                unkeyed: BTreeSet::new(),
                inputs: Vec::new(),
                deps: Vec::new(),
                outputs: names.iter().map(|name| output_path(TARGET, name)).collect(),
                network: NetworkAccess::Sealed,
                output_source: OutputSource::Command,
            },
        }
    }

    fn printed() -> Printed {
        Printed {
            stdout: Digest::of(b"compiling\n"),
            stderr: Digest::of(b"warning: unused\n"),
        }
    }

    fn tree_file(path: &str, content: &str) -> RemoteTreeFile {
        RemoteTreeFile {
            path: TreePath::parse(path).unwrap(),
            blob: Blob::of(content.as_bytes()),
            mode: FileMode::Plain,
        }
    }

    /// A description of nothing in particular, for a remote that does not look at it.
    fn action() -> RemoteAction {
        RemoteAction {
            salt: key(&["app"]).digest(),
            command: command(&["cc"]),
            env: BTreeMap::new(),
            outputs: Vec::new(),
            files: Vec::new(),
            platform: RemotePlatform::of(&Platform::parse("linux/x86_64").unwrap()),
            timeout: Timeout::parse("1m").unwrap(),
            properties: PlatformProperties::default(),
        }
    }

    fn empty_upload() -> RemoteUpload {
        RemoteUpload {
            outputs: Vec::new(),
            stdout: Blob::of(b"compiling\n"),
            stderr: Blob::of(b""),
        }
    }

    #[test]
    fn an_upload_names_every_output_with_sizes() {
        let task = task(&["bin", "inc"]);
        let store = Store::holding(&[
            "binary bytes",
            "a.h body",
            "dir/b.h",
            "compiling\n",
            "warning: unused\n",
        ]);
        let outputs = [
            kept(file("binary bytes")),
            kept(tree(&[("dir/b.h", "dir/b.h"), ("a.h", "a.h body")])),
        ];

        let upload = upload_of(&task, &outputs, &printed(), &store).unwrap();

        assert_eq!(
            upload.outputs,
            [
                RemoteOutput {
                    path: output_path(TARGET, "bin"),
                    content: RemoteContent::File {
                        blob: Blob::of(b"binary bytes"),
                        mode: FileMode::Plain,
                    },
                },
                RemoteOutput {
                    path: output_path(TARGET, "inc"),
                    content: RemoteContent::Tree(RemoteTree::new(vec![
                        tree_file("a.h", "a.h body"),
                        tree_file("dir/b.h", "dir/b.h"),
                    ])),
                },
            ]
        );
        let RemoteContent::File { blob, .. } = &upload.outputs[0].content else {
            unreachable!("the first output was a file");
        };
        assert_eq!(blob.size, "binary bytes".len() as u64);
        let RemoteContent::Tree(files) = &upload.outputs[1].content else {
            unreachable!("the second output was a directory");
        };
        let sizes: Vec<u64> = files.files().iter().map(|f| f.blob.size).collect();
        assert_eq!(sizes, ["a.h body".len() as u64, "dir/b.h".len() as u64]);
    }

    #[test]
    fn an_upload_names_stdout_and_stderr() {
        let store = Store::holding(&["compiling\n", "warning: unused\n"]);

        let upload = upload_of(&task(&[]), &[], &printed(), &store).unwrap();

        assert_eq!(upload.outputs, []);
        assert_eq!(upload.stdout, Blob::of(b"compiling\n"));
        assert_eq!(upload.stdout.size, 10);
        assert_eq!(upload.stderr, Blob::of(b"warning: unused\n"));
        assert_eq!(upload.stderr.size, 16);
    }

    #[test]
    fn a_stdout_upload_carries_no_output_file() {
        let mut task = task(&["pkgs"]);
        task.action.output_source = OutputSource::Stdout;
        let store = Store::holding(&["compiling\n", "warning: unused\n"]);
        let printed = printed();
        let output = Kept {
            digest: Digest::of(b"manifest"),
            manifest: OutputManifest::File(StoredFile {
                digest: printed.stdout,
                mode: FileMode::Plain,
            }),
        };

        let upload = upload_of(&task, &[output], &printed, &store).unwrap();

        assert_eq!(upload.outputs, []);
        assert_eq!(upload.stdout, Blob::of(b"compiling\n"));
    }

    #[test]
    fn a_blob_the_store_does_not_hold_cannot_be_described() {
        let store = Store::holding(&["compiling\n", "warning: unused\n"]);

        let said = upload_of(&task(&["bin"]), &[kept(file("lost"))], &printed(), &store);

        assert!(matches!(
            said,
            Err(Error::Adapter {
                port: PortName::ContentStore,
                ..
            })
        ));
    }

    #[test]
    fn a_different_number_of_outputs_than_declared_is_refused() {
        let store = Store::holding(&["compiling\n", "warning: unused\n", "x"]);

        let said = upload_of(
            &task(&["bin", "inc"]),
            &[kept(file("x"))],
            &printed(),
            &store,
        );

        assert!(matches!(
            said,
            Err(Error::Adapter {
                port: PortName::ContentStore,
                ..
            })
        ));
    }

    #[test]
    fn the_blob_source_reads_the_local_store() {
        let store = Store::holding(&["held bytes"]);
        let source = StoredBlobs(&store);

        assert_eq!(
            source.read(&Digest::of(b"held bytes")).unwrap(),
            Some(b"held bytes".to_vec())
        );
        assert_eq!(source.read(&Digest::of(b"never stored")).unwrap(), None);
    }

    #[test]
    fn a_stored_result_has_nothing_to_say_and_the_remote_reads_the_store() {
        let store = Store::holding(&["compiling\n"]);
        let remote = Remote::answering(Ok(Uploaded::Done));
        let produced = empty_upload();

        let said = upload(&remote, &label(TARGET), &action(), &produced, &store);

        assert_eq!(said, Sent::Stored);
        assert_eq!(*remote.sent.lock().unwrap(), [produced]);
        assert_eq!(
            *remote.read_back.lock().unwrap(),
            [Some(b"compiling\n".to_vec())]
        );
    }

    #[test]
    fn an_input_changed_answer_is_a_notice_not_a_failure() {
        let store = Store::holding(&["compiling\n"]);
        let changed = RootPath::from(&SourcePath::parse("src/main.c").unwrap());
        let remote = Remote::answering(Ok(Uploaded::InputChanged(changed.clone())));

        let said = upload(&remote, &label(TARGET), &action(), &empty_upload(), &store);

        assert_eq!(
            said,
            Sent::Declined(RemoteNotice::InputChanged {
                label: label(TARGET),
                path: changed,
            }),
            "an answer, not an error: the worker leaves the remote on"
        );
    }

    #[test]
    fn a_failed_call_is_a_failure_of_the_upload_call_with_the_adapters_message() {
        let store = Store::holding(&["compiling\n"]);
        let remote = Remote::answering(Err(Error::Adapter {
            port: PortName::RemoteCache,
            diagnostic: Diagnostic::new("the server refused the blob"),
        }));

        let said = upload(&remote, &label(TARGET), &action(), &empty_upload(), &store);

        assert_eq!(
            said,
            Sent::Failed(RemoteNotice::Failed {
                call: RemoteCall::Upload,
                diagnostic: Diagnostic::new("the server refused the blob"),
            })
        );
    }
}