//! The per-repo build cache. A job lists workspace paths to keep between runs (such as `target`). //! When it finishes, those paths move out of its workspace into an entry. The next job for the //! same repo, job name and cache key gets a copy, so the entry stays as it is until a finished //! job replaces it. A cancelled or lost job never touches it. //! //! Layout under `work_dir/.cache`. The leading dot keeps it apart from job dirs, since job ids //! never start with one: //! - `/` is one entry. It holds `p0`, `p1`, ... for the cached //! paths, `manifest.json` (the workspace path of each `pN`), `meta.json` and `stamps.json`. //! - `.new-` and `.old-` are one job's scratch dirs. A crashed job can leave them behind, //! and [`CacheStore::sweep_stale`] removes them at startup. `.inuse-` is swept too: older //! runners moved an entry there while a job used it. //! - `.stamps-` is one job's file of tracked-file stamps, written at restore and copied into //! the entry at save. It sits here, not in the workspace, so the job cannot change it. //! //! A restore never fails a job. A failure is logged and the job runs without the cache. use std::collections::BTreeMap; use std::fs; use std::io; use std::path::{Component, Path, PathBuf}; use std::process::Stdio; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use forge_ci::proto::{JobAssignment, Outcome}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use tokio::process::Command; use crate::sandbox::idmap::{IdMap, remove_tree}; /// Most paths one job may cache. const MAX_PATHS: usize = 32; /// Longest cached path, in bytes. const MAX_PATH_LEN: usize = 512; /// Longest cache key, in bytes. const MAX_KEY_LEN: usize = 256; /// Longest `cp` stderr kept for a log line, in characters. const MAX_STDERR: usize = 500; const MANIFEST: &str = "manifest.json"; const META: &str = "meta.json"; const STAMPS: &str = "stamps.json"; const SCRATCH_PREFIXES: [&str; 4] = [".inuse-", ".new-", ".old-", ".stamps-"]; /// Errors from the build cache. They are logged to the job, never returned to the forge. #[derive(Debug, thiserror::Error)] pub enum CacheError { #[error("cache io: {0}")] Io(#[from] io::Error), #[error("cache path {path:?} refused: {reason}")] Path { path: String, reason: &'static str }, #[error("{} is a symlink, not following it", .0.display())] Symlink(PathBuf), #[error("{} is not a directory", .0.display())] NotDir(PathBuf), #[error("cp failed: {0}")] Copy(String), #[error("git ls-tree failed: {0}")] Git(String), } /// One tracked file's stamp: the blob it had and the mtime it was given, in Unix seconds. #[derive(Debug, Clone, Serialize, Deserialize)] struct Stamp { blob: String, mtime: i64, } /// Tracked file path to its stamp. Read from `stamps.json`, and written to the job's scratch file. type Stamps = BTreeMap; /// What one restored entry gave the job: its size and the stamps it recorded. struct Restored { size: u64, stamps: Stamps, } /// What `meta.json` records about one entry. #[derive(Debug, Serialize, Deserialize)] struct Meta { repo: String, job: String, key: String, /// When the entry was saved, in Unix nanoseconds. Eviction removes the oldest first. saved_at: u64, size_bytes: u64, } /// One entry found while evicting. struct Found { path: PathBuf, size: u64, saved_at: u64, } /// The build cache of one runner. Shared by every job the runner runs. pub struct CacheStore { root: PathBuf, /// The cap on the total size of all entries. Zero means the cache is off. max_bytes: u64, idmap: IdMap, helper: PathBuf, /// Read while an entry is copied into a workspace, written while one is installed or evicted, /// so a copy never sees its entry swapped or removed halfway. lock: tokio::sync::RwLock<()>, /// The last save stamp, so entries saved in the same nanosecond still order by save time. last_stamp: AtomicU64, } impl CacheStore { /// `root` holds the entries and `max_bytes` caps their total size. `idmap` and `helper` remove /// dirs whose files may be owned by subordinate ids (see [`remove_tree`]). pub fn new(root: PathBuf, max_bytes: u64, idmap: IdMap, helper: PathBuf) -> Self { Self { root, max_bytes, idmap, helper, lock: tokio::sync::RwLock::new(()), last_stamp: AtomicU64::new(0), } } /// Removes the scratch dirs of jobs that crashed. Call once at startup, before any job runs. pub async fn sweep_stale(&self) -> Result<(), CacheError> { let mut dir = match tokio::fs::read_dir(&self.root).await { Ok(dir) => dir, Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), Err(e) => return Err(e.into()), }; let mut stale = Vec::new(); while let Some(entry) = dir.next_entry().await? { if is_scratch(&entry.file_name().to_string_lossy()) { stale.push(entry.path()); } } for path in stale { tracing::info!(path = %path.display(), "removing scratch dir of a crashed job"); self.remove(&path).await?; } Ok(()) } /// Puts the job's cached paths into `workspace` before the run. Returns the job log lines. /// Never fails: a failed restore is logged and the job runs uncached. pub async fn restore(&self, job: &JobAssignment, workspace: &Path) -> Vec { let mut lines = Vec::new(); if job.cache.is_empty() || self.max_bytes == 0 { return lines; } let wanted = match validate_paths(&job.cache) { Ok(wanted) => wanted, Err(e) => { lines.push(format!("runner: cache skipped: {e}")); return lines; } }; if !job.cache_key.is_empty() && let Some(restored) = self .restore_from(job, &job.cache_key, workspace, &wanted, &mut lines) .await { lines.push(format!( "runner: cache hit {} ({})", job.cache_key, human(restored.size) )); self.stamp_files(job, workspace, &restored.stamps, &mut lines) .await; return lines; } for key in &job.cache_restore_keys { if key.is_empty() || key.len() > MAX_KEY_LEN { continue; } if let Some(restored) = self .restore_from(job, key, workspace, &wanted, &mut lines) .await { lines.push(format!("runner: cache restored from fallback {key}")); self.stamp_files(job, workspace, &restored.stamps, &mut lines) .await; return lines; } } lines.push("runner: cache miss".to_owned()); self.stamp_files(job, workspace, &Stamps::new(), &mut lines) .await; lines } /// Moves the job's cached paths out of `workspace` into the entry for `job.cache_key`. Only a /// finished job saves, with Success or Failure. Returns the job log lines. Never fails. The /// job's scratch dirs are always removed, whatever happened. pub async fn save( &self, job: &JobAssignment, outcome: Outcome, workspace: &Path, ) -> Vec { let mut lines = Vec::new(); let finished = matches!(outcome, Outcome::Success | Outcome::Failure); if finished && self.max_bytes > 0 && !job.cache.is_empty() && !job.cache_key.is_empty() { match validate_paths(&job.cache) { Ok(paths) => { if let Err(e) = self.save_paths(job, workspace, &paths, &mut lines).await { lines.push(format!("runner: cache not saved: {e}")); } } Err(e) => lines.push(format!("runner: cache not saved: {e}")), } } if let Err(e) = self.remove_scratch(&job.job_id).await { tracing::warn!(job_id = %job.job_id, error = %e, "cannot remove cache scratch dirs"); } lines } /// Copies the entry for `key`'s wanted paths into the workspace. The entry is left as it is. /// Returns the entry size and stamps when at least one path was restored. async fn restore_from( &self, job: &JobAssignment, key: &str, workspace: &Path, wanted: &[PathBuf], lines: &mut Vec, ) -> Option { let _guard = self.lock.read().await; let source = self.entry_dir(&job.repo, &job.job_name, key); if !is_dir(&source) { return None; } let manifest = match read_manifest(&source) { Ok(manifest) => manifest, Err(e) => { lines.push(format!("runner: cache restore failed: {e}")); return None; } }; // Read under the lock, so the stamps belong to the entry copied here. let stamps = read_stamps(&source); let mut restored = 0usize; for (k, rel) in selected(&manifest, wanted, lines) { let src = source.join(format!("p{k}")); match copy_into(workspace, &rel, &src).await { Ok(true) => restored += 1, Ok(false) => lines.push(skipped(&rel)), Err(e) => lines.push(format!( "runner: cache restore failed for {}: {e}", rel.display() )), } } if restored == 0 { return None; } let size = match read_meta(&source) { Some(meta) => meta.size_bytes, None => dir_size(&source).await, }; Some(Restored { size, stamps }) } /// Sets each tracked file's mtime to when its content last changed. A file whose blob matches /// `previous` keeps that stamp, and any other file gets the current time. The new stamps go to /// the job's scratch file for the save. Never fails the job. async fn stamp_files( &self, job: &JobAssignment, workspace: &Path, previous: &Stamps, lines: &mut Vec, ) { match self.try_stamp_files(job, workspace, previous).await { Ok((kept, changed)) => { if !previous.is_empty() { lines.push(format!( "runner: file times restored ({kept} unchanged, {changed} changed)" )); } } Err(e) => lines.push(format!("runner: cache stamps skipped: {e}")), } } /// The work of [`CacheStore::stamp_files`]. Returns how many files kept their stamp and how /// many got the current time. async fn try_stamp_files( &self, job: &JobAssignment, workspace: &Path, previous: &Stamps, ) -> Result<(usize, usize), CacheError> { // The checkout is at the job's commit, so HEAD lists exactly the tracked files. let listing = Command::new("git") .arg("-C") .arg(workspace) .args(["ls-tree", "-r", "-z", "HEAD"]) .stdin(Stdio::null()) .stderr(Stdio::piped()) .kill_on_drop(true) .output() .await?; if !listing.status.success() { let stderr: String = String::from_utf8_lossy(&listing.stderr) .chars() .take(MAX_STDERR) .collect(); return Err(CacheError::Git(stderr.trim().to_owned())); } let now = unix_secs(SystemTime::now()); let mut stamps = Stamps::new(); let mut files = Vec::new(); let (mut kept, mut changed) = (0usize, 0usize); // Records are ` \t`, NUL terminated. Only regular files count. for record in listing.stdout.split(|b| *b == 0).filter(|r| !r.is_empty()) { let Some(tab) = record.iter().position(|b| *b == b'\t') else { continue; }; let (info, path) = (&record[..tab], &record[tab + 1..]); let (Ok(info), Ok(path)) = (std::str::from_utf8(info), std::str::from_utf8(path)) else { continue; }; let mut fields = info.split(' '); let mode = fields.next(); let blob = fields.nth(1); let (Some(mode), Some(blob)) = (mode, blob) else { continue; }; if mode != "100644" && mode != "100755" { continue; } let mtime = match previous.get(path) { Some(old) if old.blob == blob => { kept += 1; old.mtime } _ => { changed += 1; now } }; stamps.insert( path.to_owned(), Stamp { blob: blob.to_owned(), mtime, }, ); files.push((workspace.join(path), mtime)); } tokio::task::spawn_blocking(move || { for (path, secs) in &files { // A file that cannot be stamped keeps its checkout time. That is not a failure. let _ = time_of(*secs).and_then(|time| set_mtime(path, time)); } }) .await .map_err(io::Error::other)?; // A first job on a fresh runner gets here before any save has made the root. tokio::fs::create_dir_all(&self.root).await?; write_json(&self.scratch(".stamps-", &job.job_id), &stamps).await?; Ok((kept, changed)) } /// Builds the new entry in `.new-` and installs it over the old one. Caller has checked /// that the outcome, key and paths allow a save. async fn save_paths( &self, job: &JobAssignment, workspace: &Path, paths: &[PathBuf], lines: &mut Vec, ) -> Result<(), CacheError> { tokio::fs::create_dir_all(&self.root).await?; let new = self.scratch(".new-", &job.job_id); self.remove(&new).await?; tokio::fs::create_dir(&new).await?; let mut manifest: Vec = Vec::new(); for rel in paths { let src = match existing_in_workspace(workspace, rel) { Ok(Some(src)) => src, Ok(None) => continue, Err(e) => { lines.push(format!("runner: cache skipped {}: {e}", rel.display())); continue; } }; let dst = new.join(format!("p{}", manifest.len())); match tokio::fs::rename(&src, &dst).await { Ok(()) => manifest.push(rel.display().to_string()), Err(e) => lines.push(format!("runner: cache skipped {}: {e}", rel.display())), } } if manifest.is_empty() { self.remove(&new).await?; return Ok(()); } // Measured before the metadata files are written, so the size is the cached data only. let size = dir_size(&new).await; // The stamps the job's restore wrote. Missing when the restore did not get that far. let stamps = self.scratch(".stamps-", &job.job_id); if exists_no_follow(&stamps) { tokio::fs::copy(&stamps, new.join(STAMPS)).await?; } write_json(&new.join(MANIFEST), &manifest).await?; let meta = Meta { repo: job.repo.clone(), job: job.job_name.clone(), key: job.cache_key.clone(), saved_at: self.stamp(), size_bytes: size, }; write_json(&new.join(META), &meta).await?; let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key); let old = self.scratch(".old-", &job.job_id); { let _guard = self.lock.write().await; self.remove(&old).await?; let had_old = is_dir(&entry); if had_old { tokio::fs::rename(&entry, &old).await?; } if let Err(e) = tokio::fs::rename(&new, &entry).await { if had_old { // Put the previous entry back, so a failed save loses nothing. let _ = tokio::fs::rename(&old, &entry).await; } return Err(e.into()); } match self.evict().await { Ok(0) => {} Ok(removed) => tracing::info!(removed, "cache entries evicted"), Err(e) => tracing::warn!(error = %e, "cache eviction failed"), } } lines.push(format!("runner: cache saved ({})", human(size))); Ok(()) } /// Removes the least recently saved entries until the total is within the cap. The caller /// holds the lock. Returns how many entries went. async fn evict(&self) -> Result { let mut entries = self.list_entries().await?; let mut total = entries .iter() .fold(0u64, |sum, e| sum.saturating_add(e.size)); entries.sort_by_key(|e| e.saved_at); let mut removed = 0; for entry in entries { if total <= self.max_bytes { break; } self.remove(&entry.path).await?; total = total.saturating_sub(entry.size); removed += 1; } Ok(removed) } /// Every entry under the root. An entry without a readable `meta.json` is sized by walking it, /// and its save time is the dir's mtime. async fn list_entries(&self) -> Result, CacheError> { let mut found = Vec::new(); let mut dir = match tokio::fs::read_dir(&self.root).await { Ok(dir) => dir, Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(found), Err(e) => return Err(e.into()), }; while let Some(item) = dir.next_entry().await? { let name = item.file_name().to_string_lossy().into_owned(); let path = item.path(); if !is_entry_name(&name) || !is_dir(&path) { continue; } let entry = match read_meta(&path) { Some(meta) => Found { path, size: meta.size_bytes, saved_at: meta.saved_at, }, None => { let saved_at = fs::metadata(&path) .and_then(|m| m.modified()) .ok() .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) .map_or(0, nanos); Found { size: dir_size(&path).await, path, saved_at, } } }; found.push(entry); } Ok(found) } /// A save time in Unix nanoseconds, larger than every earlier one from this store. fn stamp(&self) -> u64 { let now = nanos( SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default(), ); let mut prev = self.last_stamp.load(Ordering::SeqCst); loop { let next = now.max(prev.saturating_add(1)); match self .last_stamp .compare_exchange(prev, next, Ordering::SeqCst, Ordering::SeqCst) { Ok(_) => return next, Err(actual) => prev = actual, } } } fn entry_dir(&self, repo: &str, job_name: &str, key: &str) -> PathBuf { self.root.join(entry_name(repo, job_name, key)) } fn scratch(&self, prefix: &str, job_id: &str) -> PathBuf { self.root.join(format!("{prefix}{job_id}")) } /// Removes all of one job's scratch dirs. Missing ones are fine. async fn remove_scratch(&self, job_id: &str) -> Result<(), CacheError> { for prefix in SCRATCH_PREFIXES { self.remove(&self.scratch(prefix, job_id)).await?; } Ok(()) } /// Removes a file or dir tree, through the id map so subuid-owned files go too. Blocking work /// runs off the async runtime. async fn remove(&self, path: &Path) -> Result<(), CacheError> { let (map, helper, path) = (self.idmap.clone(), self.helper.clone(), path.to_owned()); tokio::task::spawn_blocking(move || remove_tree(&map, &path, &helper)) .await .map_err(io::Error::other)??; Ok(()) } } /// Checks one cached path from the forge, and again on the runner. It must be a relative path /// with no empty, `.`, `..` or `.git` parts. pub fn validate_path(path: &str) -> Result { let refuse = |reason: &'static str| CacheError::Path { path: path.to_owned(), reason, }; if path.is_empty() { return Err(refuse("empty")); } if path.len() > MAX_PATH_LEN { return Err(refuse("too long")); } if path.contains(['\0', '\\']) { return Err(refuse("contains NUL or backslash")); } if path.starts_with('/') { return Err(refuse("absolute")); } let mut out = PathBuf::new(); for part in path.split('/') { match part { "" | "." => return Err(refuse("empty or . part")), ".." => return Err(refuse("contains ..")), part if part.eq_ignore_ascii_case(".git") => return Err(refuse(".git is not cached")), part => out.push(part), } } Ok(out) } /// Checks the whole list: at most [`MAX_PATHS`] paths, each valid, and none inside another. pub fn validate_paths(paths: &[String]) -> Result, CacheError> { if paths.len() > MAX_PATHS { return Err(CacheError::Path { path: format!("{} paths", paths.len()), reason: "too many cache paths", }); } let parsed = paths .iter() .map(|p| validate_path(p)) .collect::, _>>()?; for (i, a) in parsed.iter().enumerate() { for b in &parsed[i + 1..] { if a.starts_with(b) || b.starts_with(a) { return Err(CacheError::Path { path: a.display().to_string(), reason: "overlaps another cache path", }); } } } Ok(parsed) } /// The manifest entries the job asked for, as (index, path). An entry that fails validation is /// logged and dropped. fn selected( manifest: &[String], wanted: &[PathBuf], lines: &mut Vec, ) -> Vec<(usize, PathBuf)> { let mut out = Vec::new(); for (k, raw) in manifest.iter().enumerate() { match validate_path(raw) { Ok(rel) if wanted.contains(&rel) => out.push((k, rel)), Ok(_) => {} Err(e) => lines.push(format!("runner: cache skipped: {e}")), } } out } /// The workspace path for `rel`. Missing parent dirs are created when `create` is set. Each parent /// is checked one component at a time, and a symlink there is refused, never followed. Returns /// `None` when a parent is missing and `create` is not set. fn workspace_path( workspace: &Path, rel: &Path, create: bool, ) -> Result, CacheError> { if !fs::symlink_metadata(workspace)?.is_dir() { return Err(CacheError::NotDir(workspace.to_owned())); } let mut cur = workspace.to_owned(); let parent = rel.parent().unwrap_or(Path::new("")); for part in parent.components() { let Component::Normal(name) = part else { return Err(CacheError::Path { path: rel.display().to_string(), reason: "not a plain relative path", }); }; cur.push(name); match fs::symlink_metadata(&cur) { Ok(meta) if meta.file_type().is_symlink() => return Err(CacheError::Symlink(cur)), Ok(meta) if meta.is_dir() => {} Ok(_) => return Err(CacheError::NotDir(cur)), Err(e) if e.kind() == io::ErrorKind::NotFound => { if !create { return Ok(None); } fs::create_dir(&cur)?; } Err(e) => return Err(e.into()), } } let Some(name) = rel.file_name() else { return Err(CacheError::Path { path: rel.display().to_string(), reason: "no file name", }); }; Ok(Some(cur.join(name))) } /// The workspace path of `rel` when something exists there. `None` when nothing does. fn existing_in_workspace(workspace: &Path, rel: &Path) -> Result, CacheError> { let Some(path) = workspace_path(workspace, rel, false)? else { return Ok(None); }; Ok(exists_no_follow(&path).then_some(path)) } /// Copies `src` to `workspace/rel` with `cp -a --reflink=auto`. The source is left in place. /// Returns false when the checkout already has something there. async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result { let Some(dest) = workspace_path(workspace, rel, true)? else { return Ok(false); }; if exists_no_follow(&dest) { return Ok(false); } let output = Command::new("cp") .args(["-a", "--reflink=auto", "--"]) .arg(src) .arg(&dest) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::piped()) .kill_on_drop(true) .output() .await?; if output.status.success() { return Ok(true); } // A partial copy must not stay in the checkout. let _ = plain_remove(&dest).await; let stderr: String = String::from_utf8_lossy(&output.stderr) .chars() .take(MAX_STDERR) .collect(); Err(CacheError::Copy(stderr.trim().to_owned())) } /// Removes a file, symlink or dir tree the runner owns. The checkout is never subuid-owned at /// this point, so no id map is needed. async fn plain_remove(path: &Path) -> io::Result<()> { match fs::symlink_metadata(path) { Ok(meta) if meta.is_dir() => tokio::fs::remove_dir_all(path).await, Ok(_) => tokio::fs::remove_file(path).await, Err(e) => Err(e), } } fn read_meta(dir: &Path) -> Option { let bytes = fs::read(dir.join(META)).ok()?; serde_json::from_slice(&bytes).ok() } /// The stamps an entry recorded. An entry without a readable `stamps.json` has none. fn read_stamps(dir: &Path) -> Stamps { fs::read(dir.join(STAMPS)) .ok() .and_then(|bytes| serde_json::from_slice(&bytes).ok()) .unwrap_or_default() } /// Sets a regular file's modification time. A symlink or other kind is refused, not followed. fn set_mtime(path: &Path, time: SystemTime) -> io::Result<()> { if !fs::symlink_metadata(path)?.is_file() { return Err(io::Error::other("not a regular file")); } fs::File::open(path)?.set_modified(time) } /// A stamp's Unix seconds as a time. Negative or out of range values are refused. fn time_of(secs: i64) -> io::Result { u64::try_from(secs) .ok() .and_then(|s| UNIX_EPOCH.checked_add(Duration::from_secs(s))) .ok_or_else(|| io::Error::other("time out of range")) } /// Unix seconds of `now`, or 0 before the epoch. fn unix_secs(now: SystemTime) -> i64 { now.duration_since(UNIX_EPOCH) .ok() .and_then(|d| i64::try_from(d.as_secs()).ok()) .unwrap_or(0) } fn read_manifest(dir: &Path) -> Result, CacheError> { let bytes = fs::read(dir.join(MANIFEST))?; serde_json::from_slice(&bytes).map_err(|e| CacheError::Io(io::Error::other(e))) } async fn write_json(path: &Path, value: &T) -> Result<(), CacheError> { let bytes = serde_json::to_vec(value).map_err(io::Error::other)?; tokio::fs::write(path, bytes).await?; Ok(()) } /// The total size of the files under `root`. Symlinks count as links and are never followed. /// Unreadable dirs count as empty. Runs off the async runtime. async fn dir_size(root: &Path) -> u64 { let root = root.to_owned(); tokio::task::spawn_blocking(move || tree_size(&root)) .await .unwrap_or(0) } fn tree_size(root: &Path) -> u64 { let mut total = 0u64; let mut stack = vec![root.to_owned()]; while let Some(dir) = stack.pop() { let Ok(entries) = fs::read_dir(&dir) else { continue; }; for entry in entries.flatten() { let Ok(meta) = fs::symlink_metadata(entry.path()) else { continue; }; if meta.is_dir() { stack.push(entry.path()); } else { total = total.saturating_add(meta.len()); } } } total } /// The entry directory name for one job's cache key. Hashing keeps key text out of paths. fn entry_name(repo: &str, job_name: &str, key: &str) -> String { let mut hash = Sha256::new(); hash.update(repo.as_bytes()); hash.update([0u8]); hash.update(job_name.as_bytes()); hash.update([0u8]); hash.update(key.as_bytes()); hex::encode(hash.finalize()) } /// Whether a dir name is an entry: 64 lowercase hex digits. fn is_entry_name(name: &str) -> bool { name.len() == 64 && name .bytes() .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) } fn is_scratch(name: &str) -> bool { SCRATCH_PREFIXES.iter().any(|p| name.starts_with(p)) } fn is_dir(path: &Path) -> bool { fs::symlink_metadata(path).is_ok_and(|m| m.is_dir()) } fn exists_no_follow(path: &Path) -> bool { fs::symlink_metadata(path).is_ok() } fn nanos(d: Duration) -> u64 { u64::try_from(d.as_nanos()).unwrap_or(u64::MAX) } fn skipped(rel: &Path) -> String { format!( "runner: cache skipped {}: already in the checkout", rel.display() ) } /// A size for log lines, such as `3.1 GiB`. fn human(bytes: u64) -> String { const KIB: f64 = 1024.0; let b = bytes as f64; if b >= KIB * KIB * KIB { format!("{:.1} GiB", b / (KIB * KIB * KIB)) } else if b >= KIB * KIB { format!("{:.1} MiB", b / (KIB * KIB)) } else { format!("{:.1} KiB", b / KIB) } } #[cfg(test)] mod tests { use std::collections::BTreeMap; use std::os::unix::fs::symlink; use super::*; fn job(job_id: &str, key: &str, restore: &[&str], cache: &[&str]) -> JobAssignment { JobAssignment { job_id: job_id.to_owned(), job_token: "tok_secret_value".to_owned(), repo: "tahinli/forge".to_owned(), clone_url: "https://forge.example/tahinli/forge.git".to_owned(), commit: "a".repeat(40), git_ref: "refs/heads/main".to_owned(), job_name: "build".to_owned(), image: "docker.io/library/alpine:3".to_owned(), run: "true".to_owned(), env: BTreeMap::new(), secrets: BTreeMap::new(), artifacts: Vec::new(), timeout_minutes: 5, network: false, cache: cache.iter().map(|s| (*s).to_owned()).collect(), cache_key: key.to_owned(), cache_restore_keys: restore.iter().map(|s| (*s).to_owned()).collect(), memory_bytes: None, } } fn store(dir: &Path, max_bytes: u64) -> CacheStore { CacheStore::new( dir.join(".cache"), max_bytes, IdMap::single(), PathBuf::from("/unused-helper"), ) } /// A workspace `dir/` holding `target/a.txt` with `body`. fn workspace(dir: &Path, name: &str, body: &str) -> PathBuf { let ws = dir.join(name); fs::create_dir_all(ws.join("target")).expect("mkdir"); fs::write(ws.join("target/a.txt"), body).expect("write"); ws } fn empty_workspace(dir: &Path, name: &str) -> PathBuf { let ws = dir.join(name); fs::create_dir_all(&ws).expect("mkdir"); ws } fn entry_of(store: &CacheStore, key: &str) -> PathBuf { store.entry_dir("tahinli/forge", "build", key) } fn read(path: &Path) -> String { fs::read_to_string(path).expect("read") } #[tokio::test] async fn hit_copies_and_only_a_finished_job_replaces_the_entry() { let dir = tempfile::tempdir().expect("tempdir"); let store = store(dir.path(), 1 << 30); let first = job("job_a", "ref:refs/heads/main", &[], &["target"]); let ws1 = workspace(dir.path(), "ws_a", "one"); let saved = store.save(&first, Outcome::Success, &ws1).await; assert!( saved.iter().any(|l| l.starts_with("runner: cache saved")), "{saved:?}" ); assert!(!ws1.join("target").exists(), "save moves the path out"); let second = job("job_b", "ref:refs/heads/main", &[], &["target"]); let ws2 = empty_workspace(dir.path(), "ws_b"); let lines = store.restore(&second, &ws2).await; assert!( lines .iter() .any(|l| l.starts_with("runner: cache hit ref:refs/heads/main")), "{lines:?}" ); assert_eq!(read(&ws2.join("target/a.txt")), "one"); // A cancelled job leaves the entry as it was. fs::write(ws2.join("target/a.txt"), "half").expect("write"); store.save(&second, Outcome::Cancelled, &ws2).await; let entry = entry_of(&store, "ref:refs/heads/main"); assert_eq!(read(&entry.join("p0/a.txt")), "one"); // Another job hits the same entry, and its finished save replaces it. let third = job("job_c", "ref:refs/heads/main", &[], &["target"]); let ws3 = empty_workspace(dir.path(), "ws_c"); store.restore(&third, &ws3).await; fs::write(ws3.join("target/a.txt"), "two").expect("write"); store.save(&third, Outcome::Success, &ws3).await; assert_eq!(read(&entry.join("p0/a.txt")), "two"); } #[tokio::test] async fn fallback_copies_and_leaves_the_fallback_entry() { let dir = tempfile::tempdir().expect("tempdir"); let store = store(dir.path(), 1 << 30); let main = job("job_a", "ref:refs/heads/main", &[], &["target"]); store .save( &main, Outcome::Success, &workspace(dir.path(), "ws_a", "main"), ) .await; let pr = job("job_b", "pr:12", &["ref:refs/heads/main"], &["target"]); let ws = empty_workspace(dir.path(), "ws_b"); let lines = store.restore(&pr, &ws).await; assert!( lines.contains(&"runner: cache restored from fallback ref:refs/heads/main".to_owned()), "{lines:?}" ); assert_eq!(read(&ws.join("target/a.txt")), "main"); assert_eq!( read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")), "main" ); } #[tokio::test] async fn save_replaces_the_entry_and_leaves_no_scratch() { let dir = tempfile::tempdir().expect("tempdir"); let store = store(dir.path(), 1 << 30); let first = job("job_1", "ref:refs/heads/main", &[], &["target"]); store .save( &first, Outcome::Success, &workspace(dir.path(), "ws1", "v1"), ) .await; let second = job("job_2", "ref:refs/heads/main", &[], &["target"]); store .save( &second, Outcome::Failure, &workspace(dir.path(), "ws2", "v2"), ) .await; let entry = entry_of(&store, "ref:refs/heads/main"); assert_eq!(read(&entry.join("p0/a.txt")), "v2"); let names: Vec = fs::read_dir(&store.root) .expect("read_dir") .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) .collect(); assert_eq!( names, vec![ entry .file_name() .expect("name") .to_string_lossy() .into_owned() ] ); } #[tokio::test] async fn save_never_writes_restore_keys() { let dir = tempfile::tempdir().expect("tempdir"); let store = store(dir.path(), 1 << 30); let main = job("job_m", "ref:refs/heads/main", &[], &["target"]); store .save( &main, Outcome::Success, &workspace(dir.path(), "ws_m", "main"), ) .await; let pr = job("job_p", "pr:12", &["ref:refs/heads/main"], &["target"]); store .save(&pr, Outcome::Success, &workspace(dir.path(), "ws_p", "pr")) .await; assert_eq!(read(&entry_of(&store, "pr:12").join("p0/a.txt")), "pr"); assert_eq!( read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")), "main" ); // A job whose own key is empty saves nothing, even with restore keys listed. let none = job("job_n", "", &["ref:refs/heads/main"], &["target"]); store .save( &none, Outcome::Success, &workspace(dir.path(), "ws_n", "none"), ) .await; assert_eq!( read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")), "main" ); } #[tokio::test] async fn cancelled_or_errored_runs_do_not_save() { let dir = tempfile::tempdir().expect("tempdir"); let store = store(dir.path(), 1 << 30); let j = job("job_x", "ref:refs/heads/main", &[], &["target"]); for outcome in [Outcome::Cancelled, Outcome::Error] { let ws = workspace(dir.path(), &format!("ws_{outcome:?}"), "x"); let lines = store.save(&j, outcome, &ws).await; assert!(lines.is_empty(), "{lines:?}"); assert!( ws.join("target/a.txt").exists(), "the files stay in the workspace" ); } assert!(!entry_of(&store, "ref:refs/heads/main").exists()); } #[tokio::test] async fn eviction_removes_the_least_recently_saved_entry() { let dir = tempfile::tempdir().expect("tempdir"); // Each entry holds 1000 bytes. The cap fits two of them. let store = store(dir.path(), 2500); for key in ["k1", "k2", "k3"] { let ws = dir.path().join(format!("ws_{key}")); fs::create_dir_all(ws.join("target")).expect("mkdir"); fs::write(ws.join("target/data.bin"), vec![b'x'; 1000]).expect("write"); let j = job(&format!("job_{key}"), key, &[], &["target"]); store.save(&j, Outcome::Success, &ws).await; } assert!(!entry_of(&store, "k1").exists(), "the oldest goes first"); assert!(entry_of(&store, "k2").is_dir()); assert!(entry_of(&store, "k3").is_dir()); } #[test] fn cache_paths_are_checked_again_on_the_runner() { let bad = [ "../x", "a/../b", "/etc", "", ".", "a//b", "target/", ".git", "a/.git/b", "a/./b", "x\\y", "a\0b", ".GIT/config", ]; for path in bad { assert!(validate_path(path).is_err(), "{path:?} must be refused"); } assert_eq!( validate_path("target").expect("ok"), PathBuf::from("target") ); assert_eq!( validate_path("web/node_modules").expect("ok"), PathBuf::from("web/node_modules") ); assert!(validate_paths(&["target".to_owned(), "target/debug".to_owned()]).is_err()); } #[tokio::test] async fn a_symlinked_parent_is_refused_and_not_followed() { let dir = tempfile::tempdir().expect("tempdir"); let store = store(dir.path(), 1 << 30); let outside = dir.path().join("outside"); fs::create_dir_all(&outside).expect("mkdir"); let ws1 = dir.path().join("ws1"); fs::create_dir_all(ws1.join("build/out")).expect("mkdir"); fs::write(ws1.join("build/out/f"), "x").expect("write"); let first = job("job_1", "ref:main", &[], &["build/out"]); store.save(&first, Outcome::Success, &ws1).await; // Restore into a checkout where `build` is a symlink out of the workspace. let ws2 = empty_workspace(dir.path(), "ws2"); symlink(&outside, ws2.join("build")).expect("symlink"); let second = job("job_2", "ref:main", &[], &["build/out"]); let lines = store.restore(&second, &ws2).await; assert!( lines .iter() .any(|l| l.contains("build/out") && l.contains("failed")), "{lines:?}" ); assert!( !outside.join("out").exists(), "restore must not write through the symlink" ); // Save from a checkout with the same symlink: nothing is moved out of `outside`. fs::create_dir_all(outside.join("out")).expect("mkdir"); let ws3 = empty_workspace(dir.path(), "ws3"); symlink(&outside, ws3.join("build")).expect("symlink"); let third = job("job_3", "pr:9", &[], &["build/out"]); let lines = store.save(&third, Outcome::Success, &ws3).await; assert!(lines.iter().any(|l| l.contains("skipped")), "{lines:?}"); assert!( outside.join("out").is_dir(), "save must not move through the symlink" ); } #[tokio::test] async fn stale_scratch_dirs_are_removed_at_startup() { let dir = tempfile::tempdir().expect("tempdir"); let store = store(dir.path(), 1 << 30); for name in [".inuse-crashed", ".new-crashed", ".old-crashed"] { let path = store.root.join(name); fs::create_dir_all(&path).expect("mkdir"); fs::write(path.join("f"), "x").expect("write"); } let keep = entry_of(&store, "ref:main"); fs::create_dir_all(&keep).expect("mkdir"); store.sweep_stale().await.expect("sweep"); for name in [".inuse-crashed", ".new-crashed", ".old-crashed"] { assert!(!store.root.join(name).exists(), "{name} must be removed"); } assert!(keep.is_dir(), "entries are kept"); } /// Runs git in `dir` with a fixed identity. Fails the test when git fails. fn git(dir: &Path, args: &[&str]) { let ok = std::process::Command::new("git") .arg("-C") .arg(dir) .args(args) .env("GIT_AUTHOR_NAME", "ci") .env("GIT_AUTHOR_EMAIL", "ci@example.com") .env("GIT_COMMITTER_NAME", "ci") .env("GIT_COMMITTER_EMAIL", "ci@example.com") .status() .expect("git runs") .success(); assert!(ok, "git {args:?} failed"); } fn mtime_secs(path: &Path) -> u64 { fs::metadata(path) .and_then(|m| m.modified()) .expect("mtime") .duration_since(UNIX_EPOCH) .expect("after the epoch") .as_secs() } #[tokio::test] async fn unchanged_files_keep_their_stamp_and_changed_files_get_a_new_one() { let dir = tempfile::tempdir().expect("tempdir"); let store = store(dir.path(), 1 << 30); let origin = dir.path().join("origin"); let origin_str = origin.to_str().expect("utf8 path").to_owned(); fs::create_dir_all(&origin).expect("mkdir"); git(&origin, &["init", "--quiet"]); fs::write(origin.join("a.txt"), "a").expect("write"); fs::write(origin.join("b.txt"), "b").expect("write"); git(&origin, &["add", "."]); git( &origin, &[ "-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "one", ], ); // The first run is a miss. It saves an entry from its checkout. git(dir.path(), &["clone", "--quiet", &origin_str, "ws1"]); let ws1 = dir.path().join("ws1"); let first = job("job_1", "ref:main", &[], &["target"]); store.restore(&first, &ws1).await; fs::create_dir_all(ws1.join("target")).expect("mkdir"); fs::write(ws1.join("target/out.bin"), "built").expect("write"); store.save(&first, Outcome::Success, &ws1).await; let a_stamp = mtime_secs(&ws1.join("a.txt")); // The next commit changes only b.txt. The sleep makes a new stamp a later second. fs::write(origin.join("b.txt"), "b2").expect("write"); git(&origin, &["add", "."]); git( &origin, &[ "-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "two", ], ); git(dir.path(), &["clone", "--quiet", &origin_str, "ws2"]); tokio::time::sleep(Duration::from_millis(1100)).await; let ws2 = dir.path().join("ws2"); let second = job("job_2", "ref:main", &[], &["target"]); let lines = store.restore(&second, &ws2).await; assert!( lines.contains(&"runner: file times restored (1 unchanged, 1 changed)".to_owned()), "{lines:?}" ); assert_eq!( mtime_secs(&ws2.join("a.txt")), a_stamp, "unchanged keeps its stamp" ); assert!( mtime_secs(&ws2.join("b.txt")) > a_stamp, "a changed file is newer" ); } }