From fabd8b33292eed0ce5428cb42149fecdf152fa16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 18 Oct 2026 04:14:53 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20perf(ci):=20per-branch=20build=20ca?= =?UTF-8?q?che=20kept=20on=20the=20runner?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Jobs list workspace paths to keep with `cache = ["target"]`. - The runner moves a same-branch entry into the checkout and back after the run; a new branch starts from a copy of its base or default branch entry. - The server picks the scope from the run's trigger: pushes write `ref:`, pull requests only `pr:`, so a PR can never seed the cache a deploy build reuses. - `cache_max_gib` (default 20, 0 = off) evicts the least recently saved entries. 🐛 deploy: exit 75 is a deliberate restart, not a failure. Without SuccessExitStatus the OnFailure rollback ran on every self-update and restored the previous binary. --- crates/forge-ci/src/config.rs | 156 ++++ crates/forge-ci/src/error.rs | 17 + crates/forge-ci/src/proto.rs | 44 ++ crates/forge-runner/src/cache.rs | 1077 ++++++++++++++++++++++++++ crates/forge-runner/src/cli.rs | 30 +- crates/forge-runner/src/config.rs | 24 + crates/forge-runner/src/executor.rs | 3 + crates/forge-runner/src/lib.rs | 1 + crates/forge-runner/src/runner.rs | 22 + crates/forge-runner/tests/builtin.rs | 3 + crates/forge-runner/tests/flow.rs | 4 + crates/forge-web/src/ci/api.rs | 91 +++ crates/forge-web/src/ci/api_tests.rs | 101 ++- crates/forge-web/tests/ci_e2e.rs | 1 + deploy/user/forge-runner.service | 5 +- deploy/user/forge.service | 5 +- docs/ci.md | 54 +- 17 files changed, 1626 insertions(+), 12 deletions(-) create mode 100644 crates/forge-runner/src/cache.rs diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index 0d5cc7a..7f28fa7 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -29,6 +29,10 @@ pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60; pub const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive = 1..=360; /// Longest workflow `name`, in characters, after trimming. pub const MAX_WORKFLOW_NAME_CHARS: usize = 40; +/// Largest number of `cache` entries in one job. +pub const MAX_CACHE_ENTRIES: usize = 8; +/// Longest `cache` entry, in characters. +pub const MAX_CACHE_PATH_CHARS: usize = 200; /// A parsed and validated workflow. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -88,6 +92,9 @@ pub struct JobSpec { /// Runner labels; every label must be present on the runner. #[serde(default)] pub runs_on: Vec, + /// Workspace-relative directories to keep between runs, e.g. `"target"`. See docs/ci.md, Cache. + #[serde(default)] + pub cache: Vec, #[serde(default = "default_timeout_minutes")] pub timeout_minutes: u32, #[serde(default = "default_network")] @@ -296,6 +303,71 @@ fn validate_artifact(job: &str, pattern: &str) -> Result<(), ConfigError> { .map_err(|e| invalid(&e.to_string())) } +/// Checks the `cache` entries of one job: at most [`MAX_CACHE_ENTRIES`], each a valid +/// [`validate_cache_path`], and no duplicates. +fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> { + if entries.len() > MAX_CACHE_ENTRIES { + return Err(ConfigError::TooManyCacheEntries { + job: job.to_string(), + count: entries.len(), + max: MAX_CACHE_ENTRIES, + }); + } + let mut seen = BTreeSet::new(); + for path in entries { + validate_cache_path(job, path)?; + if !seen.insert(path.as_str()) { + return Err(ConfigError::DuplicateCachePath { + job: job.to_string(), + path: path.clone(), + }); + } + } + Ok(()) +} + +/// A cache path is a workspace-relative directory: non-empty, at most [`MAX_CACHE_PATH_CHARS`] +/// characters, no leading `/`, no `\`, no empty, `.` or `..` components, no `.git` component, no +/// glob characters and no control characters. +fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> { + let invalid = |reason: &str| ConfigError::InvalidCachePath { + job: job.to_string(), + path: path.to_string(), + reason: reason.to_string(), + }; + if path.is_empty() { + return Err(invalid("must not be empty")); + } + if path.chars().count() > MAX_CACHE_PATH_CHARS { + return Err(invalid(&format!( + "must be at most {MAX_CACHE_PATH_CHARS} characters" + ))); + } + if path.starts_with('/') { + return Err(invalid("must be relative")); + } + if path.contains('\\') { + return Err(invalid("must not contain a backslash")); + } + if path.chars().any(|c| "*?[]{}".contains(c)) { + return Err(invalid("must not contain glob characters")); + } + if path.chars().any(char::is_control) { + return Err(invalid("must not contain control characters")); + } + for part in path.split('/') { + match part { + "" => return Err(invalid("must not contain empty components")), + "." | ".." => return Err(invalid("must not contain \".\" or \"..\" components")), + _ if part.eq_ignore_ascii_case(".git") => { + return Err(invalid("must not be inside .git")); + } + _ => {} + } + } + Ok(()) +} + fn validate_job( name: &str, job: &JobSpec, @@ -349,6 +421,7 @@ fn validate_job( }); } } + validate_cache(name, &job.cache)?; if !TIMEOUT_RANGE_MINUTES.contains(&job.timeout_minutes) { return Err(ConfigError::InvalidTimeout { job: name.to_string(), @@ -589,6 +662,89 @@ artifacts = ["target/release/forge"] assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. })); } + #[test] + fn cache_defaults_to_empty() { + assert!( + parse_config(&job_toml("")).unwrap().jobs["build"] + .cache + .is_empty() + ); + } + + #[test] + fn cache_accepts_relative_directories() { + let text = job_toml("cache = [\"target\", \".cargo-home\", \"a/b/c\"]"); + assert_eq!( + parse_config(&text).unwrap().jobs["build"].cache, + vec![ + "target".to_string(), + ".cargo-home".to_string(), + "a/b/c".to_string() + ] + ); + let at_limit = "x".repeat(MAX_CACHE_PATH_CHARS); + let text = job_toml(&format!("cache = [{at_limit:?}]")); + assert!(parse_config(&text).is_ok()); + } + + #[test] + fn cache_rejects_bad_paths() { + let long = "x".repeat(MAX_CACHE_PATH_CHARS + 1); + let bad = [ + "".to_string(), + "/abs".to_string(), + "a\\b".to_string(), + "..".to_string(), + "a/../b".to_string(), + "./target".to_string(), + ".".to_string(), + "a//b".to_string(), + "target/".to_string(), + ".git".to_string(), + ".git/objects".to_string(), + "sub/.GIT/x".to_string(), + "target/*".to_string(), + "t?rget".to_string(), + "[t]".to_string(), + "{a,b}".to_string(), + long, + ]; + // A control character, written as a TOML escape. + let text = job_toml(r#"cache = ["a\u0007b"]"#); + assert!(matches!( + err_of(&text), + ConfigError::InvalidCachePath { .. } + )); + for path in bad { + let text = job_toml(&format!("cache = [{path:?}]")); + assert!( + matches!(err_of(&text), ConfigError::InvalidCachePath { .. }), + "cache path {path:?} should be rejected" + ); + } + } + + #[test] + fn cache_rejects_duplicates_and_too_many_entries() { + let text = job_toml("cache = [\"target\", \"target\"]"); + assert!(matches!( + err_of(&text), + ConfigError::DuplicateCachePath { .. } + )); + let entries: Vec = (0..=MAX_CACHE_ENTRIES).map(|i| format!("d{i}")).collect(); + let text = job_toml(&format!("cache = {entries:?}")); + assert_eq!( + err_of(&text), + ConfigError::TooManyCacheEntries { + job: "build".into(), + count: MAX_CACHE_ENTRIES + 1, + max: MAX_CACHE_ENTRIES + } + ); + let text = job_toml(&format!("cache = {:?}", &entries[..MAX_CACHE_ENTRIES])); + assert!(parse_config(&text).is_ok()); + } + #[test] fn timeout_validation() { assert_eq!( diff --git a/crates/forge-ci/src/error.rs b/crates/forge-ci/src/error.rs index 28985b1..5584ed8 100644 --- a/crates/forge-ci/src/error.rs +++ b/crates/forge-ci/src/error.rs @@ -54,6 +54,23 @@ pub enum ConfigError { #[error("job {job:?}: timeout_minutes must be between 1 and 360, got {value}")] InvalidTimeout { job: String, value: u32 }, + #[error("job {job:?}: invalid cache path {path:?}: {reason}")] + InvalidCachePath { + job: String, + path: String, + reason: String, + }, + + #[error("job {job:?}: cache lists {count} entries, the limit is {max}")] + TooManyCacheEntries { + job: String, + count: usize, + max: usize, + }, + + #[error("job {job:?}: duplicate cache path {path:?}")] + DuplicateCachePath { job: String, path: String }, + #[error("invalid {kind} glob {pattern:?}: {reason}")] InvalidTriggerGlob { kind: &'static str, diff --git a/crates/forge-ci/src/proto.rs b/crates/forge-ci/src/proto.rs index fb58ae6..22fc977 100644 --- a/crates/forge-ci/src/proto.rs +++ b/crates/forge-ci/src/proto.rs @@ -72,6 +72,16 @@ pub struct JobAssignment { pub artifacts: Vec, pub timeout_minutes: u32, pub network: bool, + /// Workspace-relative directories to cache, already validated. Empty when the job has no cache. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub cache: Vec, + /// The cache scope this job may write, e.g. `ref:refs/heads/main` or `pr:12`. Empty means the + /// runner neither restores nor saves a cache for this job. The runner namespaces it by repo and job. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub cache_key: String, + /// Read-only fallback scopes, tried in order when `cache_key` has no entry. Never written. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub cache_restore_keys: Vec, } impl fmt::Debug for JobAssignment { @@ -91,6 +101,9 @@ impl fmt::Debug for JobAssignment { .field("artifacts", &self.artifacts) .field("timeout_minutes", &self.timeout_minutes) .field("network", &self.network) + .field("cache", &self.cache) + .field("cache_key", &self.cache_key) + .field("cache_restore_keys", &self.cache_restore_keys) .finish() } } @@ -145,6 +158,34 @@ mod tests { assert_eq!(back, req); } + #[test] + fn cache_fields_are_omitted_when_empty() { + let job = JobAssignment { + job_id: "j1".into(), + job_token: "t".into(), + repo: "o/r".into(), + clone_url: "https://example.test/o/r.git".into(), + commit: "abc".into(), + git_ref: "refs/heads/main".into(), + job_name: "lint".into(), + image: "i".into(), + run: "true".into(), + env: BTreeMap::new(), + secrets: BTreeMap::new(), + artifacts: vec![], + timeout_minutes: 60, + network: true, + cache: vec![], + cache_key: String::new(), + cache_restore_keys: vec![], + }; + let json = serde_json::to_string(&job).unwrap(); + assert!(!json.contains("cache"), "{json}"); + // An older server's reply, without the cache fields, still parses. + let back: JobAssignment = serde_json::from_str(&json).unwrap(); + assert_eq!(back, job); + } + #[test] fn debug_redacts_secrets() { let mut secrets = BTreeMap::new(); @@ -164,6 +205,9 @@ mod tests { artifacts: vec![], timeout_minutes: 60, network: true, + cache: vec![], + cache_key: String::new(), + cache_restore_keys: vec![], }; let dbg = format!("{job:?}"); assert!(!dbg.contains("hunter2-value")); diff --git a/crates/forge-runner/src/cache.rs b/crates/forge-runner/src/cache.rs new file mode 100644 index 0000000..4c5e046 --- /dev/null +++ b/crates/forge-runner/src/cache.rs @@ -0,0 +1,1077 @@ +//! 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 moves them back in. +//! +//! 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`) and `meta.json`. +//! - `.new-`, `.old-` and `.inuse-` are one job's scratch dirs. A crashed job can +//! leave them behind, and [`CacheStore::sweep_stale`] removes them at startup. +//! +//! A restore never fails a job. A failure is logged and the job runs without the cache. + +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 SCRATCH_PREFIXES: [&str; 3] = [".inuse-", ".new-", ".old-"]; + +/// 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), +} + +/// 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, + /// Held while an entry is claimed, installed or evicted, so jobs never race on one. + lock: tokio::sync::Mutex<()>, + /// 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::Mutex::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 entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key); + match self.claim(&job.job_id, &entry).await { + Ok(Some(inuse)) => { + let size = self + .restore_claimed(&inuse, workspace, &wanted, &mut lines) + .await; + lines.push(format!( + "runner: cache hit {} ({})", + job.cache_key, + human(size) + )); + return lines; + } + Ok(None) => {} + Err(e) => lines.push(format!("runner: cache restore failed: {e}")), + } + } + + for key in &job.cache_restore_keys { + if key.is_empty() || key.len() > MAX_KEY_LEN { + continue; + } + if self + .restore_fallback(job, key, workspace, &wanted, &mut lines) + .await + { + return lines; + } + } + lines.push("runner: cache miss".to_owned()); + 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 + } + + /// Moves a claimed entry's wanted paths into the workspace. Returns the entry size. A path + /// that fails is logged and the rest still restore. + async fn restore_claimed( + &self, + inuse: &Path, + workspace: &Path, + wanted: &[PathBuf], + lines: &mut Vec, + ) -> u64 { + let size = match read_meta(inuse) { + Some(meta) => meta.size_bytes, + None => dir_size(inuse).await, + }; + let manifest = match read_manifest(inuse) { + Ok(manifest) => manifest, + Err(e) => { + lines.push(format!("runner: cache restore failed: {e}")); + return size; + } + }; + for (k, rel) in selected(&manifest, wanted, lines) { + let src = inuse.join(format!("p{k}")); + match move_into(workspace, &rel, &src).await { + Ok(true) => {} + Ok(false) => lines.push(skipped(&rel)), + Err(e) => lines.push(format!( + "runner: cache restore failed for {}: {e}", + rel.display() + )), + } + } + size + } + + /// Copies the fallback entry's wanted paths into the workspace. The fallback entry is never + /// moved. Returns true when at least one path was restored. + async fn restore_fallback( + &self, + job: &JobAssignment, + key: &str, + workspace: &Path, + wanted: &[PathBuf], + lines: &mut Vec, + ) -> bool { + let source = self.entry_dir(&job.repo, &job.job_name, key); + if !is_dir(&source) { + return false; + } + let manifest = match read_manifest(&source) { + Ok(manifest) => manifest, + Err(e) => { + lines.push(format!("runner: cache restore failed: {e}")); + return false; + } + }; + 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 false; + } + lines.push(format!("runner: cache restored from fallback {key}")); + true + } + + /// 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; + 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.lock().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(()) + } + + /// Moves the entry to this job's `.inuse` dir, so no other job can take it. `None` means there + /// is no entry, or another job got it first. + async fn claim(&self, job_id: &str, entry: &Path) -> Result, CacheError> { + let _guard = self.lock.lock().await; + if !is_dir(entry) { + return Ok(None); + } + let inuse = self.scratch(".inuse-", job_id); + self.remove(&inuse).await?; + match tokio::fs::rename(entry, &inuse).await { + Ok(()) => Ok(Some(inuse)), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } + } + + /// 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)) +} + +/// Moves `src` to `workspace/rel`. Returns false when the checkout already has something there. +async fn move_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); + } + tokio::fs::rename(src, &dest).await?; + Ok(true) +} + +/// 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() +} + +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(), + } + } + + 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_moves_the_entry_and_hides_it_while_in_use() { + 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"); + assert!( + !entry_of(&store, "ref:refs/heads/main").exists(), + "a hit moves the entry" + ); + assert!(store.root.join(".inuse-job_b").is_dir()); + + // Another job for the same key finds nothing while the first one holds the entry. + let third = job("job_c", "ref:refs/heads/main", &[], &["target"]); + let ws3 = empty_workspace(dir.path(), "ws_c"); + assert_eq!( + store.restore(&third, &ws3).await, + vec!["runner: cache miss".to_owned()] + ); + assert!(!ws3.join("target").exists()); + + // The finished job's scratch dir is gone, and its save puts the entry back. + store.save(&second, Outcome::Success, &ws2).await; + assert!(!store.root.join(".inuse-job_b").exists()); + assert!(entry_of(&store, "ref:refs/heads/main").is_dir()); + } + + #[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"); + } +} diff --git a/crates/forge-runner/src/cli.rs b/crates/forge-runner/src/cli.rs index 400f106..519de2e 100644 --- a/crates/forge-runner/src/cli.rs +++ b/crates/forge-runner/src/cli.rs @@ -14,6 +14,7 @@ use forge_ci::proto::RegisterRequest; use tokio_util::sync::CancellationToken; use tracing_subscriber::EnvFilter; +use crate::cache::CacheStore; use crate::client::ForgeClient; use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode}; use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor}; @@ -207,6 +208,7 @@ async fn run(cli: Cli) -> Result> { sandbox: config::SandboxConfig::default(), registries: Vec::new(), auto_update: true, + cache_max_gib: config::default_cache_max_gib(), }; config::save(&path, &cfg)?; println!( @@ -223,8 +225,14 @@ async fn run(cli: Cli) -> Result> { }; let cfg = config::load(&path)?; let shutdown = CancellationToken::new(); - let executor: Arc = match cfg.executor { - ExecutorKind::Podman => Arc::new(PodmanExecutor::new(cfg.limits.clone())), + let cache_root = cfg.work_dir.join(".cache"); + let cache_cap = cfg.cache_max_gib; + // The id map is what the executor's jobs run under. The cache removes its dirs with it. + let (executor, map): (Arc, IdMap) = match cfg.executor { + ExecutorKind::Podman => ( + Arc::new(PodmanExecutor::new(cfg.limits.clone())), + IdMap::single(), + ), ExecutorKind::Builtin => { // Resolved once. In subuid mode a failure here is a startup error. let map = IdMap::resolve(cfg.sandbox.userns)?; @@ -242,14 +250,22 @@ async fn run(cli: Cli) -> Result> { .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb)) .with_idmap(map.clone(), helper.clone()); let jobs_dir = cfg.work_dir.join("jobs"); - Arc::new( + let executor = BuiltinExecutor::new(images, cfg.limits.clone(), helper, jobs_dir) - .with_idmap(map) - .with_registries(&cfg.registries), - ) + .with_idmap(map.clone()) + .with_registries(&cfg.registries); + (Arc::new(executor), map) } }; - let runner = Runner::new(cfg, executor, RunOptions::default())?; + let mut runner = Runner::new(cfg, executor, RunOptions::default())?; + if cache_cap > 0 { + let cache = + CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?); + if let Err(e) = cache.sweep_stale().await { + tracing::warn!(error = %e, "cannot remove stale cache dirs"); + } + runner = runner.with_cache(cache); + } let stop = shutdown.clone(); tokio::spawn(async move { if tokio::signal::ctrl_c().await.is_ok() { diff --git a/crates/forge-runner/src/config.rs b/crates/forge-runner/src/config.rs index 4b4311c..405f062 100644 --- a/crates/forge-runner/src/config.rs +++ b/crates/forge-runner/src/config.rs @@ -135,6 +135,9 @@ pub struct RunnerConfig { /// 75 and systemd restarts it. Set `auto_update = false` to pin the binary by hand. #[serde(default = "default_auto_update")] pub auto_update: bool, + /// The cap on all build caches together, in GiB. Zero turns the cache off. See `cache`. + #[serde(default = "default_cache_max_gib")] + pub cache_max_gib: u64, } fn default_concurrency() -> usize { @@ -149,6 +152,11 @@ fn default_keep_days() -> u32 { 7 } +/// The default cap on all build caches together, in GiB. +pub fn default_cache_max_gib() -> u64 { + 20 +} + /// The default cap on one unpacked image, in GB. pub fn default_image_max_gb() -> u64 { 20 @@ -169,6 +177,7 @@ impl fmt::Debug for RunnerConfig { .field("images", &self.images) .field("registries", &self.registries) .field("auto_update", &self.auto_update) + .field("cache_max_gib", &self.cache_max_gib) .finish() } } @@ -279,6 +288,7 @@ mod tests { sandbox: SandboxConfig::default(), registries: Vec::new(), auto_update: true, + cache_max_gib: default_cache_max_gib(), } } @@ -352,6 +362,20 @@ mod tests { assert_eq!(config.limits.image_max_gb, 20); assert!(config.registries.is_empty()); assert!(config.auto_update); + assert_eq!(config.cache_max_gib, 20); + } + + #[test] + fn cache_cap_can_be_set_and_turned_off() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("runner.toml"); + std::fs::write( + &path, + "url = \"https://f\"\nrunner_id = \"r\"\nrunner_secret = \"s\"\nname = \"n\"\n\ + work_dir = \"/w\"\ncache_max_gib = 0\n", + ) + .expect("write"); + assert_eq!(load(&path).expect("load").cache_max_gib, 0); } #[test] diff --git a/crates/forge-runner/src/executor.rs b/crates/forge-runner/src/executor.rs index 008367b..dbaca0b 100644 --- a/crates/forge-runner/src/executor.rs +++ b/crates/forge-runner/src/executor.rs @@ -800,6 +800,9 @@ mod tests { artifacts: Vec::new(), timeout_minutes: 5, network: false, + cache: Vec::new(), + cache_key: String::new(), + cache_restore_keys: Vec::new(), } } diff --git a/crates/forge-runner/src/lib.rs b/crates/forge-runner/src/lib.rs index 09dce82..634e597 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -5,6 +5,7 @@ //! forge's end-to-end tests can drive a runner with `HostExecutor`. pub mod artifacts; +pub mod cache; pub mod check; pub mod cli; pub mod client; diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index 1e0fcf2..edb2e9f 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -12,6 +12,7 @@ use tokio::time::Instant; use tokio_util::sync::CancellationToken; use crate::artifacts; +use crate::cache::CacheStore; use crate::client::{ClientError, ForgeClient}; use crate::config::RunnerConfig; use crate::executor::{ExecRequest, ExecResult, Executor}; @@ -63,6 +64,8 @@ pub struct Runner { config: Arc, executor: Arc, options: RunOptions, + /// The build cache, when it is on. See [`CacheStore`]. + cache: Option>, } impl Runner { @@ -77,9 +80,16 @@ impl Runner { config: Arc::new(config), executor, options, + cache: None, }) } + /// Turns on the build cache for every job this runner runs. + pub fn with_cache(mut self, cache: CacheStore) -> Self { + self.cache = Some(Arc::new(cache)); + self + } + pub fn client(&self) -> &ForgeClient { &self.client } @@ -265,6 +275,11 @@ impl Runner { let prepared = workspace::prepare(&self.config.work_dir, &job, &self.config.url).await; let mut result = match prepared { Ok(dir) => { + if let Some(cache) = &self.cache { + for line in cache.restore(&job, &dir).await { + send_line(&tx, line).await; + } + } let result = self .executor .run(ExecRequest { @@ -309,6 +324,13 @@ impl Runner { }; } + // The save decides on the final outcome. It also clears the job's scratch dirs. + if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) { + for line in cache.save(&job, result.outcome, dir).await { + send_line(&tx, line).await; + } + } + if let Some(message) = &result.message { send_line(&tx, format!("runner: {message}")).await; } diff --git a/crates/forge-runner/tests/builtin.rs b/crates/forge-runner/tests/builtin.rs index e16f8f2..a89cd68 100644 --- a/crates/forge-runner/tests/builtin.rs +++ b/crates/forge-runner/tests/builtin.rs @@ -83,6 +83,9 @@ fn job(run: &str) -> JobAssignment { artifacts: Vec::new(), timeout_minutes: 5, network: false, + cache: Vec::new(), + cache_key: String::new(), + cache_restore_keys: Vec::new(), } } diff --git a/crates/forge-runner/tests/flow.rs b/crates/forge-runner/tests/flow.rs index fac0611..52ae108 100644 --- a/crates/forge-runner/tests/flow.rs +++ b/crates/forge-runner/tests/flow.rs @@ -304,6 +304,9 @@ fn job(job_id: &str, commit: &str, clone_url: &str, run: &str) -> JobAssignment artifacts: vec!["dist/**".to_owned()], timeout_minutes: 5, network: false, + cache: Vec::new(), + cache_key: String::new(), + cache_restore_keys: Vec::new(), } } @@ -322,6 +325,7 @@ fn config(url: &str, work_dir: PathBuf) -> RunnerConfig { sandbox: forge_runner::config::SandboxConfig::default(), registries: Vec::new(), auto_update: true, + cache_max_gib: 0, } } diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index e5ca48d..021a7ed 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -270,6 +270,9 @@ async fn try_claim(state: &AppState, runner: &CiRunner) -> Result Result Result<(String, Vec), Refusal> { + if cache.is_empty() { + return Ok((String::new(), Vec::new())); + } + let pull_base = match (run.trigger.as_str(), run.pull_number) { + ("pull_request", Some(number)) => state + .store + .pull_by_number(&run.repo_id, number) + .await + .map_err(api::internal)? + .map(|pull| pull.base_branch), + _ => None, + }; + let scope = cache_scope( + &run.trigger, + &run.git_ref, + run.pull_number, + pull_base.as_deref(), + default_branch, + ); + Ok(match scope { + Some(scope) => (scope.key, scope.restore_keys), + // A run whose scope cannot be derived gets no key, so the runner neither restores nor saves. + None => (String::new(), Vec::new()), + }) +} + +/// The cache scope a run may write, and the read-only scopes it may restore from. +#[derive(Debug, Clone, PartialEq, Eq)] +struct CacheScope { + key: String, + restore_keys: Vec, +} + +/// Derives the cache scopes of a run. Returns `None` when no scope can be derived. +/// +/// Only pull request runs get `pr:` keys and only non-pull-request runs get `ref:` keys. The +/// choice follows the run's trigger, never the ref name, so a pull request from a branch named +/// `main` still writes `pr:N`. A pull request run reads its base branch's cache, a branch or tag +/// run reads the default branch's cache, and both fall back to nothing else. +fn cache_scope( + trigger: &str, + git_ref: &str, + pull_number: Option, + pull_base: Option<&str>, + default_branch: &str, +) -> Option { + let default_ref = format!("ref:refs/heads/{default_branch}"); + match trigger { + "pull_request" => { + let number = pull_number?; + let mut restore_keys = Vec::new(); + if let Some(base) = pull_base { + restore_keys.push(format!("ref:refs/heads/{base}")); + } + if pull_base != Some(default_branch) { + restore_keys.push(default_ref); + } + Some(CacheScope { + key: format!("pr:{number}"), + restore_keys, + }) + } + "push" | "tag" | "manual" | "schedule" => { + let restore_keys = if git_ref == format!("refs/heads/{default_branch}") { + Vec::new() + } else { + vec![default_ref] + }; + Some(CacheScope { + key: format!("ref:{git_ref}"), + restore_keys, + }) + } + _ => None, + } +} + /// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such /// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side. async fn is_fork_run(state: &AppState, run: &CiRun) -> Result { diff --git a/crates/forge-web/src/ci/api_tests.rs b/crates/forge-web/src/ci/api_tests.rs index cfac0b8..bcf07ba 100644 --- a/crates/forge-web/src/ci/api_tests.rs +++ b/crates/forge-web/src/ci/api_tests.rs @@ -11,7 +11,7 @@ use serde_json::{Value, json}; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; -use super::{artifact_key, fit_to_cap, log_path, valid_artifact_name}; +use super::{artifact_key, cache_scope, fit_to_cap, log_path, valid_artifact_name}; use crate::pages::commits::test_support::{Fixture, OWNER, REPO}; use crate::test_support::{app_router, test_state}; @@ -899,3 +899,102 @@ async fn claim_advertises_the_binary_only_to_a_matching_target() { assert!(sent.headers.get("forge-binary-sha256").is_none()); } } + +#[test] +fn cache_scope_for_push_on_default_branch_has_no_restore_keys() { + let scope = cache_scope("push", "refs/heads/main", None, None, "main").unwrap(); + assert_eq!(scope.key, "ref:refs/heads/main"); + assert!(scope.restore_keys.is_empty()); +} + +#[test] +fn cache_scope_for_push_on_branch_restores_default_branch() { + let scope = cache_scope("push", "refs/heads/feature/x", None, None, "main").unwrap(); + assert_eq!(scope.key, "ref:refs/heads/feature/x"); + assert_eq!(scope.restore_keys, vec!["ref:refs/heads/main".to_string()]); +} + +#[test] +fn cache_scope_for_tag_writes_its_ref_and_restores_default_branch() { + let scope = cache_scope("tag", "refs/tags/v1.0", None, None, "main").unwrap(); + assert_eq!(scope.key, "ref:refs/tags/v1.0"); + assert_eq!(scope.restore_keys, vec!["ref:refs/heads/main".to_string()]); +} + +#[test] +fn cache_scope_for_manual_run_uses_the_ref() { + let scope = cache_scope("manual", "refs/heads/main", None, None, "main").unwrap(); + assert_eq!(scope.key, "ref:refs/heads/main"); + assert!(scope.restore_keys.is_empty()); +} + +#[test] +fn cache_scope_for_pull_request_writes_only_its_pr_key() { + let scope = cache_scope( + "pull_request", + "refs/pull/12/head", + Some(12), + Some("release/1.0"), + "main", + ) + .unwrap(); + assert_eq!(scope.key, "pr:12"); + assert_eq!( + scope.restore_keys, + vec![ + "ref:refs/heads/release/1.0".to_string(), + "ref:refs/heads/main".to_string() + ] + ); +} + +#[test] +fn cache_scope_for_pull_request_into_default_branch_restores_it_once() { + let scope = cache_scope( + "pull_request", + "refs/pull/3/head", + Some(3), + Some("main"), + "main", + ) + .unwrap(); + assert_eq!(scope.key, "pr:3"); + assert_eq!(scope.restore_keys, vec!["ref:refs/heads/main".to_string()]); +} + +#[test] +fn cache_scope_for_pull_request_with_head_named_main_still_writes_pr_key() { + // A fork or same-repo PR whose head branch is called `main` must never get a `ref:` write key. + let scope = cache_scope( + "pull_request", + "refs/pull/7/head", + Some(7), + Some("main"), + "main", + ) + .unwrap(); + assert_eq!(scope.key, "pr:7"); + assert!(!scope.key.starts_with("ref:")); +} + +#[test] +fn cache_scope_for_pull_request_without_base_restores_default_only() { + let scope = cache_scope("pull_request", "refs/pull/9/head", Some(9), None, "main").unwrap(); + assert_eq!(scope.key, "pr:9"); + assert_eq!(scope.restore_keys, vec!["ref:refs/heads/main".to_string()]); +} + +#[test] +fn cache_scope_needs_a_pull_number_for_pull_requests_and_a_known_trigger() { + assert!( + cache_scope( + "pull_request", + "refs/pull/1/head", + None, + Some("main"), + "main" + ) + .is_none() + ); + assert!(cache_scope("bogus", "refs/heads/main", None, None, "main").is_none()); +} diff --git a/crates/forge-web/tests/ci_e2e.rs b/crates/forge-web/tests/ci_e2e.rs index b80d9b7..ab2454f 100644 --- a/crates/forge-web/tests/ci_e2e.rs +++ b/crates/forge-web/tests/ci_e2e.rs @@ -474,6 +474,7 @@ async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker registries: Vec::new(), // The e2e runner must not replace the test binary under itself. auto_update: false, + cache_max_gib: 0, }; let runner = Runner::new(config, Arc::new(HostExecutor), RunOptions::default()).expect("runner"); diff --git a/deploy/user/forge-runner.service b/deploy/user/forge-runner.service index 8f3de8b..f894674 100644 --- a/deploy/user/forge-runner.service +++ b/deploy/user/forge-runner.service @@ -9,8 +9,11 @@ OnFailure=forge-runner-rollback.service [Service] ExecStart=%h/bin/forge runner run --config %h/.config/forge-runner/runner.toml -# A self-update exits with code 75, which is non-zero, so Restart=on-failure restarts it into the new binary. +# A self-update exits with code 75. Restart=on-failure +# Exit 75 is a deliberate restart into a new binary, not a failure: no OnFailure rollback. +SuccessExitStatus=75 +RestartForceExitStatus=75 RestartSec=10 TimeoutStopSec=120 diff --git a/deploy/user/forge.service b/deploy/user/forge.service index 0758818..84b2a63 100644 --- a/deploy/user/forge.service +++ b/deploy/user/forge.service @@ -10,8 +10,11 @@ OnFailure=forge-rollback.service WorkingDirectory=%h Environment=FORGE_CONFIG=%h/config/forge.toml ExecStart=%h/bin/forge serve -# A self-update exits with code 75, which is non-zero, so Restart=on-failure restarts it into the new binary. +# A self-update exits with code 75. Restart=on-failure +# Exit 75 is a deliberate restart into a new binary, not a failure: no OnFailure rollback. +SuccessExitStatus=75 +RestartForceExitStatus=75 RestartSec=2 NoNewPrivileges=yes LimitNOFILE=65536 diff --git a/docs/ci.md b/docs/ci.md index 43265e7..1c4278d 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -4,8 +4,8 @@ forge runs CI workflows defined in `.forge/ci.toml` at the root of a repository. separate **runners**, which are `forge runner` on machines you control. The forge never connects to a runner. Runners pull jobs over HTTPS. -What v1 has: jobs with `needs`, secrets, artifacts, live logs, commit statuses, and manual, push, -tag and pull request triggers. What it does not have: a cache, or YAML. The workflow file is TOML. +What v1 has: jobs with `needs`, secrets, artifacts, a build cache, live logs, commit statuses, and +manual, push, tag and pull request triggers. What it does not have: YAML. The workflow file is TOML. Jobs run in a rootless sandbox, with no container tool needed. The runner pulls and unpacks the image itself, and runs each job in its own container built with libcontainer, the crate behind @@ -46,6 +46,7 @@ There must be at least one job, and at most 20. | `env` | table of string | `{}` | Plain env vars. Names match the same pattern. A secret with the same name wins. | | `artifacts` | array of string | `[]` | Relative globs in the workspace. No `..`, no leading `/`. | | `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. | +| `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). | | `timeout_minutes` | integer | `60` | Range 1 to 360. | | `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` shares the runner host's network namespace. Read [the caveats](#builtin-executor-caveats). | @@ -387,6 +388,55 @@ no heartbeat. A job with `runs_on = ["linux", "x86_64"]` is only claimed by a runner that has both labels. Jobs with no `runs_on` can go to any runner. +### Cache + +A job can keep directories between runs, such as a Rust `target` directory: + +```toml +[jobs.test] +image = "docker.io/rust:1" +cache = ["target"] +run = "cargo test --workspace" +``` + +Each entry is a path relative to the workspace (`/workspace`). Rules: + +- At most 8 entries per job, each at most 200 characters, with no duplicates. +- No leading `/`, no `\`, no `..`, no `.` components, no empty components, no glob characters + (`*?[]{}`), no control characters. +- Nothing under `.git`. + +The runner keeps cache entries on its own disk, keyed by repo, job name and scope: a branch, a tag, +or a pull request. Two jobs never share a cache, and two repos never do either. + +- A push, tag or manual run writes the cache of its own ref, such as `refs/heads/main`. It reads + the default branch's cache when its own ref has none, unless it is the default branch. +- A pull request run writes only its own cache, keyed by the pull request number. It reads its + base branch's cache, then the default branch's cache. A pull request never writes a branch cache, + so a change under review cannot leave a cache that a later build of `main` will use. +- When a branch is reused, its cache is moved to the new run, not copied. Only one run owns it at a + time. +- The runner caps the total size of its caches. When the cap is reached, the least recently used + entries are evicted first. The cap is the runner config key `cache_max_gib`, default `20`. + +A cache is a speed-up, not a source of truth. A job must still build correctly from an empty cache. + +#### Rust tip + +Cache the build directory, and optionally the cargo home: + +```toml +[jobs.test] +image = "docker.io/rust:1" +cache = ["target", ".cargo-home"] +run = """ +export CARGO_HOME=/workspace/.cargo-home +cargo test --workspace +""" +``` + +Setting `CARGO_HOME` to a path inside the workspace keeps the downloaded crates in the cache too. + ## Forge limits (`[ci]`) The `[ci]` section of `forge.toml` controls CI on the forge. These are the defaults: