Skip to main content

artifactize_core/cache/
content.rs

1//! Built-in content fingerprint: the hash of an Artifact's own input files.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    ffi::OsStr,
6    fs::File,
7    io::Read,
8    path::PathBuf,
9};
10
11use ignore::{
12    Match,
13    gitignore::{Gitignore, GitignoreBuilder},
14};
15use sha2::{Digest, Sha256};
16use tokio_util::sync::CancellationToken;
17
18use crate::{
19    config::RepoConfig,
20    platform::{self, FileKind},
21    process, scope,
22    scope::LogicalTarget,
23};
24
25/// Bound input traversal and retained per-file digest metadata for one fingerprint.
26const MAX_ENTRIES: usize = 10_000;
27/// Bound total hashing I/O so one undeclared large input cannot monopolize preparation.
28const MAX_BYTES: u64 = 1024 * 1024 * 1024;
29/// Bound inherited ignore-file parsing while supporting substantial repository rules.
30const GITIGNORE_BYTES: u64 = 1024 * 1024;
31/// Bound user-declared ignore fan-out and compiled matcher work during fingerprinting.
32const MAX_IGNORE_PATTERNS: usize = 64;
33/// Stream hashes in bounded heap memory while amortizing filesystem read calls.
34/// Content fingerprints and executable pins use the same I/O chunk, not a file-size cap.
35pub(crate) const HASH_BUFFER_BYTES: usize = 64 * 1024;
36const BUILTIN_IGNORES: [&str; 5] = [".git", "__pycache__/", "*.pyc", "target/", "node_modules/"];
37
38/// Sorted owner-relative file paths with their SHA-256, and one digest over all of them.
39pub(super) struct Files {
40    pub digest: crate::types::Sha256Digest,
41    pub files: BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
42}
43
44/// Declared `fingerprint.ignore` globs, parsed once from the declaration together with their
45/// matcher, which always excludes the built-ins too.
46#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
47#[serde(try_from = "Vec<String>", into = "Vec<String>")]
48pub struct IgnorePatterns {
49    patterns: Vec<String>,
50    matcher: Gitignore,
51}
52
53impl IgnorePatterns {
54    /// The globs as declared.
55    pub fn patterns(&self) -> &[String] {
56        &self.patterns
57    }
58}
59
60impl Default for IgnorePatterns {
61    /// No declared globs: only the built-ins.
62    fn default() -> Self {
63        Self::try_from(Vec::new()).expect("built-in ignore patterns")
64    }
65}
66
67impl TryFrom<Vec<String>> for IgnorePatterns {
68    type Error = String;
69
70    fn try_from(patterns: Vec<String>) -> Result<Self, String> {
71        let matcher = matcher(&patterns)?;
72        Ok(Self { patterns, matcher })
73    }
74}
75
76impl From<IgnorePatterns> for Vec<String> {
77    fn from(ignore: IgnorePatterns) -> Self {
78        ignore.patterns
79    }
80}
81
82fn matcher(patterns: &[String]) -> Result<Gitignore, String> {
83    if patterns.len() > MAX_IGNORE_PATTERNS
84        || patterns.iter().collect::<BTreeSet<_>>().len() != patterns.len()
85    {
86        return Err("fingerprint.ignore must contain at most 64 unique patterns.".into());
87    }
88    let mut builder = GitignoreBuilder::new(".");
89    // Match actual entry spellings on every volume: a differently cased rule must never
90    // widen the ignored set and silently hide a content change.
91    builder
92        .case_insensitive(false)
93        .expect("case-sensitive ignore matching");
94    for pattern in BUILTIN_IGNORES {
95        builder.add_line(None, pattern).expect("built-in pattern");
96    }
97    for pattern in patterns {
98        if pattern.trim().is_empty()
99            || pattern.starts_with(['!', '#'])
100            || pattern.bytes().any(|byte| byte.is_ascii_control())
101        {
102            return Err(
103                "fingerprint.ignore patterns must be nonblank .gitignore globs without negation or comments."
104                    .into(),
105            );
106        }
107        builder
108            .add_line(None, pattern)
109            .map_err(|error| format!("fingerprint.ignore: {error}"))?;
110    }
111    builder.build().map_err(|error| error.to_string())
112}
113
114/// Hash an Artifact's own inputs off the async runtime.
115pub(super) async fn files(
116    config: &RepoConfig,
117    id: &crate::types::ArtifactName,
118    inputs: &[crate::config::LogicalPath],
119    ignore: &IgnorePatterns,
120    cancellation: &CancellationToken,
121) -> Result<Files, String> {
122    if cancellation.is_cancelled() {
123        return Err(process::Error::Cancelled.to_string());
124    }
125    let walk = Walk::new(config, id, inputs, ignore)?;
126    let token = cancellation.clone();
127    crate::task::joined(tokio::task::spawn_blocking(move || walk.digest(&token)).await)
128        .map_err(|error| error.to_string())?
129}
130
131struct Walk {
132    root: PathBuf,
133    owner: PathBuf,
134    /// The owner folder relative to the repository root, where `.gitignore` bases start.
135    prefix: LogicalTarget,
136    inputs: Vec<LogicalTarget>,
137    file: bool,
138    /// Part-owned paths under this owner, skipped for both walks and explicit inputs.
139    excluded: BTreeSet<PathBuf>,
140    ignore: Gitignore,
141}
142
143#[derive(Default)]
144struct State {
145    files: BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
146    entries: usize,
147    bytes: u64,
148}
149
150impl Walk {
151    fn new(
152        config: &RepoConfig,
153        id: &crate::types::ArtifactName,
154        inputs: &[crate::config::LogicalPath],
155        ignore: &IgnorePatterns,
156    ) -> Result<Self, String> {
157        let artifact = &config.artifacts[id];
158        let owner =
159            scope::scoped_path(&config.root, artifact.folder()).map_err(|e| e.to_string())?;
160        // Preserve the UTF-8 input contract before rendering portable separators.
161        artifact
162            .folder()
163            .to_str()
164            .ok_or("Artifact paths must be UTF-8.")?;
165        let prefix = platform::path_text(artifact.folder())
166            .parse::<LogicalTarget>()
167            .map_err(|error| error.to_string())?;
168        let excluded = config
169            .descendants(id)
170            .into_iter()
171            .flat_map(|name| {
172                let part = &config.artifacts[name];
173                if part.kind() == crate::config::ArtifactKind::Live {
174                    return Vec::new();
175                }
176                if part.kind() == crate::config::ArtifactKind::Aspect {
177                    part.select()
178                        .iter()
179                        .map(|path| part.folder().join(path))
180                        .collect()
181                } else {
182                    part.referenced_path()
183                        .map(std::path::Path::to_path_buf)
184                        .into_iter()
185                        .collect()
186                }
187            })
188            .filter_map(|path| {
189                if artifact.folder().starts_with(&path) {
190                    Some(PathBuf::new())
191                } else {
192                    path.strip_prefix(artifact.folder()).ok().map(PathBuf::from)
193                }
194            })
195            .chain(
196                artifact
197                    .nested
198                    .keys()
199                    .map(|path| PathBuf::from(path.as_str())),
200            )
201            .collect();
202        let inputs = inputs
203            .iter()
204            .map(|input| {
205                if input.as_str() == "." {
206                    Ok(LogicalTarget::Root)
207                } else {
208                    input
209                        .as_str()
210                        .parse::<LogicalTarget>()
211                        .map_err(|error| error.to_string())
212                }
213            })
214            .collect::<Result<Vec<_>, String>>()?;
215        Ok(Self {
216            root: config.root.clone(),
217            owner,
218            prefix,
219            inputs,
220            file: artifact.file_name().is_some(),
221            excluded,
222            ignore: ignore.matcher.clone(),
223        })
224    }
225
226    fn digest(&self, cancellation: &CancellationToken) -> Result<Files, String> {
227        let mut state = State::default();
228        for input in &self.inputs {
229            if self.excluded(input) {
230                continue;
231            }
232            let label = if input.is_empty() {
233                "."
234            } else {
235                input.as_str()
236            };
237            let file =
238                scope::open_scoped(&self.owner, input).map_err(|e| format!("{label}: {e}"))?;
239            if self.file && !file.metadata().map_err(|e| e.to_string())?.is_file() {
240                return Err(format!(
241                    "{label}: File Artifact target must remain a regular file."
242                ));
243            }
244            if file.metadata().map_err(|e| e.to_string())?.is_dir() {
245                let mut gitignores = self.ancestors(input)?;
246                self.directory(&file, input, &mut gitignores, &mut state, cancellation)?;
247            } else {
248                hash_file(file, input, &mut state)?;
249            }
250        }
251        Ok(Files {
252            digest: aggregate(&state.files),
253            files: state.files,
254        })
255    }
256
257    fn excluded(&self, path: &LogicalTarget) -> bool {
258        self.excluded
259            .iter()
260            .any(|part| std::path::Path::new(path.as_str()).starts_with(part))
261    }
262
263    fn directory(
264        &self,
265        directory: &File,
266        path: &LogicalTarget,
267        gitignores: &mut Vec<(LogicalTarget, Gitignore)>,
268        state: &mut State,
269        cancellation: &CancellationToken,
270    ) -> Result<(), String> {
271        let label = if path.is_empty() { "." } else { path.as_str() };
272        // Enumerate the pinned directory, not a path that could have been replaced by a link.
273        let mut entries = platform::read_dir(directory)
274            .map_err(|e| format!("{label}: {e}"))?
275            .map(|entry| {
276                let entry = entry.map_err(|e| format!("{label}: {e}"))?;
277                let kind = entry.file_type().map_err(|e| format!("{label}: {e}"))?;
278                let name = platform::os_text(&entry.file_name())
279                    .map(str::to_owned)
280                    .ok_or("Artifact paths must be UTF-8.")?;
281                Ok((name, kind == FileKind::Directory))
282            })
283            .collect::<Result<Vec<_>, String>>()?;
284        entries.sort();
285        let gitignore =
286            read_gitignore(directory).map_err(|e| format!("{}: {e}", gitignore_name(path)))?;
287        let pushed = gitignore.is_some();
288        if let Some(gitignore) = gitignore {
289            gitignores.push((join(&self.prefix, path)?, gitignore));
290        }
291        for (name, is_dir) in entries {
292            if cancellation.is_cancelled() {
293                return Err(process::Error::Cancelled.to_string());
294            }
295            let child = join(path, &name)?;
296            if self.excluded(&child) || self.ignored(&child, is_dir, gitignores)? {
297                continue;
298            }
299            state.entries += 1;
300            if state.entries > MAX_ENTRIES {
301                return Err(format!(
302                    "Content inputs exceed {MAX_ENTRIES} entries; narrow fingerprint.files or add fingerprint.ignore."
303                ));
304            }
305            let entry = scope::open_child(directory, OsStr::new(&name))
306                .map_err(|e| format!("{child}: {e} Add it to fingerprint.ignore to skip it."))?;
307            if entry.metadata().map_err(|e| e.to_string())?.is_dir() {
308                self.directory(&entry, &child, gitignores, state, cancellation)?;
309            } else {
310                hash_file(entry, &child, state)?;
311            }
312        }
313        if pushed {
314            gitignores.pop();
315        }
316        Ok(())
317    }
318
319    /// `.gitignore` files from the repository root down to a walked input's parent folder.
320    fn ancestors(&self, input: &LogicalTarget) -> Result<Vec<(LogicalTarget, Gitignore)>, String> {
321        let full = join(&self.prefix, input)?;
322        let parts: Vec<_> = full.split('/').filter(|part| !part.is_empty()).collect();
323        let mut gitignores = Vec::new();
324        for depth in 0..parts.len() {
325            let base: LogicalTarget = parts[..depth]
326                .join("/")
327                .parse()
328                .expect("ancestors of a validated logical path");
329            let label = |e: String| format!("{}: {e}", gitignore_name(&base));
330            let directory =
331                scope::open_scoped(&self.root, &base).map_err(|e| label(e.to_string()))?;
332            if let Some(gitignore) = read_gitignore(&directory).map_err(label)? {
333                gitignores.push((base, gitignore));
334            }
335        }
336        Ok(gitignores)
337    }
338
339    /// Built-ins and declared globs always exclude; `.gitignore` files decide the rest,
340    /// each relative to its own folder and the deepest match winning, as in git.
341    fn ignored(
342        &self,
343        path: &LogicalTarget,
344        is_dir: bool,
345        gitignores: &[(LogicalTarget, Gitignore)],
346    ) -> Result<bool, String> {
347        if self.ignore.matched(path, is_dir).is_ignore() {
348            return Ok(true);
349        }
350        let full = join(&self.prefix, path)?;
351        for (base, gitignore) in gitignores.iter().rev() {
352            let relative = if base.is_empty() {
353                full.as_str()
354            } else {
355                &full[base.len() + 1..]
356            };
357            match gitignore.matched(relative, is_dir) {
358                Match::Ignore(_) => return Ok(true),
359                Match::Whitelist(_) => return Ok(false),
360                Match::None => {}
361            }
362        }
363        Ok(false)
364    }
365}
366
367/// A pinned folder's `.gitignore`, if any. Lines git would reject are skipped, as git skips them.
368fn read_gitignore(directory: &File) -> Result<Option<Gitignore>, String> {
369    match platform::entry_kind(directory, OsStr::new(".gitignore")) {
370        Ok(FileKind::Directory) => return Ok(None),
371        Ok(_) => {}
372        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
373        Err(error) => return Err(error.to_string()),
374    }
375    let file = scope::open_child(directory, OsStr::new(".gitignore")).map_err(|e| e.to_string())?;
376    let mut text = Vec::new();
377    file.take(GITIGNORE_BYTES + 1)
378        .read_to_end(&mut text)
379        .map_err(|e| e.to_string())?;
380    if text.len() as u64 > GITIGNORE_BYTES {
381        return Err("A .gitignore file exceeds 1 MiB.".into());
382    }
383    let mut builder = GitignoreBuilder::new(".");
384    // Match actual entry spellings on every volume: a differently cased rule must never
385    // widen the ignored set and silently hide a content change.
386    builder
387        .case_insensitive(false)
388        .expect("case-sensitive ignore matching");
389    for line in String::from_utf8_lossy(&text).lines() {
390        let _ = builder.add_line(None, line);
391    }
392    builder.build().map(Some).map_err(|e| e.to_string())
393}
394
395/// Hash the ordered owner-relative paths and their file digests, without filesystem access.
396fn aggregate(
397    files: &BTreeMap<LogicalTarget, crate::types::Sha256Bytes>,
398) -> crate::types::Sha256Digest {
399    let mut digest = Sha256::new();
400    for (path, file) in files {
401        digest.update(path.as_bytes());
402        digest.update([0]);
403        digest.update(file.as_bytes());
404    }
405    hex(&digest.finalize())
406        .parse()
407        .expect("SHA-256 input digest")
408}
409
410fn hash_file(mut file: File, path: &LogicalTarget, state: &mut State) -> Result<(), String> {
411    if !file.metadata().map_err(|e| e.to_string())?.is_file() {
412        return Err(format!("{path}: Content input must be a regular file."));
413    }
414    let mut digest = Sha256::new();
415    if path.ends_with(".artf") {
416        let remaining = MAX_BYTES.saturating_sub(state.bytes);
417        let mut bytes = Vec::new();
418        file.take(remaining + 1)
419            .read_to_end(&mut bytes)
420            .map_err(|error| format!("{path}: {error}"))?;
421        state.bytes += bytes.len() as u64;
422        if state.bytes > MAX_BYTES {
423            return Err(
424                "Content inputs exceed 1 GiB; narrow fingerprint.files or add fingerprint.ignore."
425                    .into(),
426            );
427        }
428        digest.update(artifactize_tools::artf::definition(&bytes));
429        state.files.insert(
430            path.clone(),
431            crate::types::Sha256Bytes::from_digest(digest.finalize().into()),
432        );
433        return Ok(());
434    }
435    let mut buffer = vec![0; HASH_BUFFER_BYTES];
436    loop {
437        let read = file.read(&mut buffer).map_err(|e| format!("{path}: {e}"))?;
438        if read == 0 {
439            break;
440        }
441        state.bytes += read as u64;
442        if state.bytes > MAX_BYTES {
443            return Err(
444                "Content inputs exceed 1 GiB; narrow fingerprint.files or add fingerprint.ignore."
445                    .into(),
446            );
447        }
448        digest.update(&buffer[..read]);
449    }
450    state.files.insert(
451        path.clone(),
452        crate::types::Sha256Bytes::from_digest(digest.finalize().into()),
453    );
454    Ok(())
455}
456
457/// The `.gitignore` of a folder, for messages: its logical path, or when that would be too
458/// long to be one, the folder and the name as written.
459fn gitignore_name(folder: &LogicalTarget) -> String {
460    join(folder, ".gitignore")
461        .map_or_else(|_| format!("{folder}/.gitignore"), |path| path.to_string())
462}
463
464fn join(base: &LogicalTarget, name: &str) -> Result<LogicalTarget, String> {
465    if name.is_empty() {
466        Ok(base.clone())
467    } else {
468        let path = if base.is_empty() {
469            name.to_owned()
470        } else {
471            format!("{base}/{name}")
472        };
473        path.parse::<LogicalTarget>()
474            .map_err(|error| error.to_string())
475    }
476}
477
478pub(super) fn hex(bytes: &[u8]) -> String {
479    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
480}