forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

cache.rs1279 lines, 45.4 KiBHistoryRawDownload
1//! The per-repo build cache. A job lists workspace paths to keep between runs (such as `target`).
2//! When it finishes, those paths move out of its workspace into an entry. The next job for the
3//! same repo, job name and cache key gets a copy, so the entry stays as it is until a finished
4//! job replaces it. A cancelled or lost job never touches it.
5//!
6//! Layout under `work_dir/.cache`. The leading dot keeps it apart from job dirs, since job ids
7//! never start with one:
8//! - `<sha256 of repo, job name and key>/` is one entry. It holds `p0`, `p1`, ... for the cached
9//! paths, `manifest.json` (the workspace path of each `pN`), `meta.json` and `stamps.json`.
10//! - `.new-<job>` and `.old-<job>` are one job's scratch dirs. A crashed job can leave them behind,
11//! and [`CacheStore::sweep_stale`] removes them at startup. `.inuse-<job>` is swept too: older
12//! runners moved an entry there while a job used it.
13//! - `.stamps-<job>` is one job's file of tracked-file stamps, written at restore and copied into
14//! the entry at save. It sits here, not in the workspace, so the job cannot change it.
15//!
16//! A restore never fails a job. A failure is logged and the job runs without the cache.
17
18use std::collections::BTreeMap;
19use std::fs;
20use std::io;
21use std::path::{Component, Path, PathBuf};
22use std::process::Stdio;
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::time::{Duration, SystemTime, UNIX_EPOCH};
25
26use forge_ci::proto::{JobAssignment, Outcome};
27use serde::{Deserialize, Serialize};
28use sha2::{Digest, Sha256};
29use tokio::process::Command;
30
31use crate::sandbox::idmap::{IdMap, remove_tree};
32
33/// Most paths one job may cache.
34const MAX_PATHS: usize = 32;
35/// Longest cached path, in bytes.
36const MAX_PATH_LEN: usize = 512;
37/// Longest cache key, in bytes.
38const MAX_KEY_LEN: usize = 256;
39/// Longest `cp` stderr kept for a log line, in characters.
40const MAX_STDERR: usize = 500;
41const MANIFEST: &str = "manifest.json";
42const META: &str = "meta.json";
43const STAMPS: &str = "stamps.json";
44const SCRATCH_PREFIXES: [&str; 4] = [".inuse-", ".new-", ".old-", ".stamps-"];
45
46/// Errors from the build cache. They are logged to the job, never returned to the forge.
47#[derive(Debug, thiserror::Error)]
48pub enum CacheError {
49 #[error("cache io: {0}")]
50 Io(#[from] io::Error),
51 #[error("cache path {path:?} refused: {reason}")]
52 Path { path: String, reason: &'static str },
53 #[error("{} is a symlink, not following it", .0.display())]
54 Symlink(PathBuf),
55 #[error("{} is not a directory", .0.display())]
56 NotDir(PathBuf),
57 #[error("cp failed: {0}")]
58 Copy(String),
59 #[error("git ls-tree failed: {0}")]
60 Git(String),
61}
62
63/// One tracked file's stamp: the blob it had and the mtime it was given, in Unix seconds.
64#[derive(Debug, Clone, Serialize, Deserialize)]
65struct Stamp {
66 blob: String,
67 mtime: i64,
68}
69
70/// Tracked file path to its stamp. Read from `stamps.json`, and written to the job's scratch file.
71type Stamps = BTreeMap<String, Stamp>;
72
73/// What one restored entry gave the job: its size and the stamps it recorded.
74struct Restored {
75 size: u64,
76 stamps: Stamps,
77}
78
79/// What `meta.json` records about one entry.
80#[derive(Debug, Serialize, Deserialize)]
81struct Meta {
82 repo: String,
83 job: String,
84 key: String,
85 /// When the entry was saved, in Unix nanoseconds. Eviction removes the oldest first.
86 saved_at: u64,
87 size_bytes: u64,
88}
89
90/// One entry found while evicting.
91struct Found {
92 path: PathBuf,
93 size: u64,
94 saved_at: u64,
95}
96
97/// The build cache of one runner. Shared by every job the runner runs.
98pub struct CacheStore {
99 root: PathBuf,
100 /// The cap on the total size of all entries. Zero means the cache is off.
101 max_bytes: u64,
102 idmap: IdMap,
103 helper: PathBuf,
104 /// Read while an entry is copied into a workspace, written while one is installed or evicted,
105 /// so a copy never sees its entry swapped or removed halfway.
106 lock: tokio::sync::RwLock<()>,
107 /// The last save stamp, so entries saved in the same nanosecond still order by save time.
108 last_stamp: AtomicU64,
109}
110
111impl CacheStore {
112 /// `root` holds the entries and `max_bytes` caps their total size. `idmap` and `helper` remove
113 /// dirs whose files may be owned by subordinate ids (see [`remove_tree`]).
114 pub fn new(root: PathBuf, max_bytes: u64, idmap: IdMap, helper: PathBuf) -> Self {
115 Self {
116 root,
117 max_bytes,
118 idmap,
119 helper,
120 lock: tokio::sync::RwLock::new(()),
121 last_stamp: AtomicU64::new(0),
122 }
123 }
124
125 /// Removes the scratch dirs of jobs that crashed. Call once at startup, before any job runs.
126 pub async fn sweep_stale(&self) -> Result<(), CacheError> {
127 let mut dir = match tokio::fs::read_dir(&self.root).await {
128 Ok(dir) => dir,
129 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
130 Err(e) => return Err(e.into()),
131 };
132 let mut stale = Vec::new();
133 while let Some(entry) = dir.next_entry().await? {
134 if is_scratch(&entry.file_name().to_string_lossy()) {
135 stale.push(entry.path());
136 }
137 }
138 for path in stale {
139 tracing::info!(path = %path.display(), "removing scratch dir of a crashed job");
140 self.remove(&path).await?;
141 }
142 Ok(())
143 }
144
145 /// Puts the job's cached paths into `workspace` before the run. Returns the job log lines.
146 /// Never fails: a failed restore is logged and the job runs uncached.
147 pub async fn restore(&self, job: &JobAssignment, workspace: &Path) -> Vec<String> {
148 let mut lines = Vec::new();
149 if job.cache.is_empty() || self.max_bytes == 0 {
150 return lines;
151 }
152 let wanted = match validate_paths(&job.cache) {
153 Ok(wanted) => wanted,
154 Err(e) => {
155 lines.push(format!("runner: cache skipped: {e}"));
156 return lines;
157 }
158 };
159
160 if !job.cache_key.is_empty()
161 && let Some(restored) = self
162 .restore_from(job, &job.cache_key, workspace, &wanted, &mut lines)
163 .await
164 {
165 lines.push(format!(
166 "runner: cache hit {} ({})",
167 job.cache_key,
168 human(restored.size)
169 ));
170 self.stamp_files(job, workspace, &restored.stamps, &mut lines)
171 .await;
172 return lines;
173 }
174
175 for key in &job.cache_restore_keys {
176 if key.is_empty() || key.len() > MAX_KEY_LEN {
177 continue;
178 }
179 if let Some(restored) = self
180 .restore_from(job, key, workspace, &wanted, &mut lines)
181 .await
182 {
183 lines.push(format!("runner: cache restored from fallback {key}"));
184 self.stamp_files(job, workspace, &restored.stamps, &mut lines)
185 .await;
186 return lines;
187 }
188 }
189 lines.push("runner: cache miss".to_owned());
190 self.stamp_files(job, workspace, &Stamps::new(), &mut lines)
191 .await;
192 lines
193 }
194
195 /// Moves the job's cached paths out of `workspace` into the entry for `job.cache_key`. Only a
196 /// finished job saves, with Success or Failure. Returns the job log lines. Never fails. The
197 /// job's scratch dirs are always removed, whatever happened.
198 pub async fn save(
199 &self,
200 job: &JobAssignment,
201 outcome: Outcome,
202 workspace: &Path,
203 ) -> Vec<String> {
204 let mut lines = Vec::new();
205 let finished = matches!(outcome, Outcome::Success | Outcome::Failure);
206 if finished && self.max_bytes > 0 && !job.cache.is_empty() && !job.cache_key.is_empty() {
207 match validate_paths(&job.cache) {
208 Ok(paths) => {
209 if let Err(e) = self.save_paths(job, workspace, &paths, &mut lines).await {
210 lines.push(format!("runner: cache not saved: {e}"));
211 }
212 }
213 Err(e) => lines.push(format!("runner: cache not saved: {e}")),
214 }
215 }
216 if let Err(e) = self.remove_scratch(&job.job_id).await {
217 tracing::warn!(job_id = %job.job_id, error = %e, "cannot remove cache scratch dirs");
218 }
219 lines
220 }
221
222 /// Copies the entry for `key`'s wanted paths into the workspace. The entry is left as it is.
223 /// Returns the entry size and stamps when at least one path was restored.
224 async fn restore_from(
225 &self,
226 job: &JobAssignment,
227 key: &str,
228 workspace: &Path,
229 wanted: &[PathBuf],
230 lines: &mut Vec<String>,
231 ) -> Option<Restored> {
232 let _guard = self.lock.read().await;
233 let source = self.entry_dir(&job.repo, &job.job_name, key);
234 if !is_dir(&source) {
235 return None;
236 }
237 let manifest = match read_manifest(&source) {
238 Ok(manifest) => manifest,
239 Err(e) => {
240 lines.push(format!("runner: cache restore failed: {e}"));
241 return None;
242 }
243 };
244 // Read under the lock, so the stamps belong to the entry copied here.
245 let stamps = read_stamps(&source);
246 let mut restored = 0usize;
247 for (k, rel) in selected(&manifest, wanted, lines) {
248 let src = source.join(format!("p{k}"));
249 match copy_into(workspace, &rel, &src).await {
250 Ok(true) => restored += 1,
251 Ok(false) => lines.push(skipped(&rel)),
252 Err(e) => lines.push(format!(
253 "runner: cache restore failed for {}: {e}",
254 rel.display()
255 )),
256 }
257 }
258 if restored == 0 {
259 return None;
260 }
261 let size = match read_meta(&source) {
262 Some(meta) => meta.size_bytes,
263 None => dir_size(&source).await,
264 };
265 Some(Restored { size, stamps })
266 }
267
268 /// Sets each tracked file's mtime to when its content last changed. A file whose blob matches
269 /// `previous` keeps that stamp, and any other file gets the current time. The new stamps go to
270 /// the job's scratch file for the save. Never fails the job.
271 async fn stamp_files(
272 &self,
273 job: &JobAssignment,
274 workspace: &Path,
275 previous: &Stamps,
276 lines: &mut Vec<String>,
277 ) {
278 match self.try_stamp_files(job, workspace, previous).await {
279 Ok((kept, changed)) => {
280 if !previous.is_empty() {
281 lines.push(format!(
282 "runner: file times restored ({kept} unchanged, {changed} changed)"
283 ));
284 }
285 }
286 Err(e) => lines.push(format!("runner: cache stamps skipped: {e}")),
287 }
288 }
289
290 /// The work of [`CacheStore::stamp_files`]. Returns how many files kept their stamp and how
291 /// many got the current time.
292 async fn try_stamp_files(
293 &self,
294 job: &JobAssignment,
295 workspace: &Path,
296 previous: &Stamps,
297 ) -> Result<(usize, usize), CacheError> {
298 // The checkout is at the job's commit, so HEAD lists exactly the tracked files.
299 let listing = Command::new("git")
300 .arg("-C")
301 .arg(workspace)
302 .args(["ls-tree", "-r", "-z", "HEAD"])
303 .stdin(Stdio::null())
304 .stderr(Stdio::piped())
305 .kill_on_drop(true)
306 .output()
307 .await?;
308 if !listing.status.success() {
309 let stderr: String = String::from_utf8_lossy(&listing.stderr)
310 .chars()
311 .take(MAX_STDERR)
312 .collect();
313 return Err(CacheError::Git(stderr.trim().to_owned()));
314 }
315
316 let now = unix_secs(SystemTime::now());
317 let mut stamps = Stamps::new();
318 let mut files = Vec::new();
319 let (mut kept, mut changed) = (0usize, 0usize);
320 // Records are `<mode> <type> <oid>\t<path>`, NUL terminated. Only regular files count.
321 for record in listing.stdout.split(|b| *b == 0).filter(|r| !r.is_empty()) {
322 let Some(tab) = record.iter().position(|b| *b == b'\t') else {
323 continue;
324 };
325 let (info, path) = (&record[..tab], &record[tab + 1..]);
326 let (Ok(info), Ok(path)) = (std::str::from_utf8(info), std::str::from_utf8(path))
327 else {
328 continue;
329 };
330 let mut fields = info.split(' ');
331 let mode = fields.next();
332 let blob = fields.nth(1);
333 let (Some(mode), Some(blob)) = (mode, blob) else {
334 continue;
335 };
336 if mode != "100644" && mode != "100755" {
337 continue;
338 }
339 let mtime = match previous.get(path) {
340 Some(old) if old.blob == blob => {
341 kept += 1;
342 old.mtime
343 }
344 _ => {
345 changed += 1;
346 now
347 }
348 };
349 stamps.insert(
350 path.to_owned(),
351 Stamp {
352 blob: blob.to_owned(),
353 mtime,
354 },
355 );
356 files.push((workspace.join(path), mtime));
357 }
358
359 tokio::task::spawn_blocking(move || {
360 for (path, secs) in &files {
361 // A file that cannot be stamped keeps its checkout time. That is not a failure.
362 let _ = time_of(*secs).and_then(|time| set_mtime(path, time));
363 }
364 })
365 .await
366 .map_err(io::Error::other)?;
367
368 // A first job on a fresh runner gets here before any save has made the root.
369 tokio::fs::create_dir_all(&self.root).await?;
370 write_json(&self.scratch(".stamps-", &job.job_id), &stamps).await?;
371 Ok((kept, changed))
372 }
373
374 /// Builds the new entry in `.new-<job>` and installs it over the old one. Caller has checked
375 /// that the outcome, key and paths allow a save.
376 async fn save_paths(
377 &self,
378 job: &JobAssignment,
379 workspace: &Path,
380 paths: &[PathBuf],
381 lines: &mut Vec<String>,
382 ) -> Result<(), CacheError> {
383 tokio::fs::create_dir_all(&self.root).await?;
384 let new = self.scratch(".new-", &job.job_id);
385 self.remove(&new).await?;
386 tokio::fs::create_dir(&new).await?;
387
388 let mut manifest: Vec<String> = Vec::new();
389 for rel in paths {
390 let src = match existing_in_workspace(workspace, rel) {
391 Ok(Some(src)) => src,
392 Ok(None) => continue,
393 Err(e) => {
394 lines.push(format!("runner: cache skipped {}: {e}", rel.display()));
395 continue;
396 }
397 };
398 let dst = new.join(format!("p{}", manifest.len()));
399 match tokio::fs::rename(&src, &dst).await {
400 Ok(()) => manifest.push(rel.display().to_string()),
401 Err(e) => lines.push(format!("runner: cache skipped {}: {e}", rel.display())),
402 }
403 }
404 if manifest.is_empty() {
405 self.remove(&new).await?;
406 return Ok(());
407 }
408
409 // Measured before the metadata files are written, so the size is the cached data only.
410 let size = dir_size(&new).await;
411 // The stamps the job's restore wrote. Missing when the restore did not get that far.
412 let stamps = self.scratch(".stamps-", &job.job_id);
413 if exists_no_follow(&stamps) {
414 tokio::fs::copy(&stamps, new.join(STAMPS)).await?;
415 }
416 write_json(&new.join(MANIFEST), &manifest).await?;
417 let meta = Meta {
418 repo: job.repo.clone(),
419 job: job.job_name.clone(),
420 key: job.cache_key.clone(),
421 saved_at: self.stamp(),
422 size_bytes: size,
423 };
424 write_json(&new.join(META), &meta).await?;
425
426 let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key);
427 let old = self.scratch(".old-", &job.job_id);
428 {
429 let _guard = self.lock.write().await;
430 self.remove(&old).await?;
431 let had_old = is_dir(&entry);
432 if had_old {
433 tokio::fs::rename(&entry, &old).await?;
434 }
435 if let Err(e) = tokio::fs::rename(&new, &entry).await {
436 if had_old {
437 // Put the previous entry back, so a failed save loses nothing.
438 let _ = tokio::fs::rename(&old, &entry).await;
439 }
440 return Err(e.into());
441 }
442 match self.evict().await {
443 Ok(0) => {}
444 Ok(removed) => tracing::info!(removed, "cache entries evicted"),
445 Err(e) => tracing::warn!(error = %e, "cache eviction failed"),
446 }
447 }
448 lines.push(format!("runner: cache saved ({})", human(size)));
449 Ok(())
450 }
451
452 /// Removes the least recently saved entries until the total is within the cap. The caller
453 /// holds the lock. Returns how many entries went.
454 async fn evict(&self) -> Result<usize, CacheError> {
455 let mut entries = self.list_entries().await?;
456 let mut total = entries
457 .iter()
458 .fold(0u64, |sum, e| sum.saturating_add(e.size));
459 entries.sort_by_key(|e| e.saved_at);
460 let mut removed = 0;
461 for entry in entries {
462 if total <= self.max_bytes {
463 break;
464 }
465 self.remove(&entry.path).await?;
466 total = total.saturating_sub(entry.size);
467 removed += 1;
468 }
469 Ok(removed)
470 }
471
472 /// Every entry under the root. An entry without a readable `meta.json` is sized by walking it,
473 /// and its save time is the dir's mtime.
474 async fn list_entries(&self) -> Result<Vec<Found>, CacheError> {
475 let mut found = Vec::new();
476 let mut dir = match tokio::fs::read_dir(&self.root).await {
477 Ok(dir) => dir,
478 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(found),
479 Err(e) => return Err(e.into()),
480 };
481 while let Some(item) = dir.next_entry().await? {
482 let name = item.file_name().to_string_lossy().into_owned();
483 let path = item.path();
484 if !is_entry_name(&name) || !is_dir(&path) {
485 continue;
486 }
487 let entry = match read_meta(&path) {
488 Some(meta) => Found {
489 path,
490 size: meta.size_bytes,
491 saved_at: meta.saved_at,
492 },
493 None => {
494 let saved_at = fs::metadata(&path)
495 .and_then(|m| m.modified())
496 .ok()
497 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
498 .map_or(0, nanos);
499 Found {
500 size: dir_size(&path).await,
501 path,
502 saved_at,
503 }
504 }
505 };
506 found.push(entry);
507 }
508 Ok(found)
509 }
510
511 /// A save time in Unix nanoseconds, larger than every earlier one from this store.
512 fn stamp(&self) -> u64 {
513 let now = nanos(
514 SystemTime::now()
515 .duration_since(UNIX_EPOCH)
516 .unwrap_or_default(),
517 );
518 let mut prev = self.last_stamp.load(Ordering::SeqCst);
519 loop {
520 let next = now.max(prev.saturating_add(1));
521 match self
522 .last_stamp
523 .compare_exchange(prev, next, Ordering::SeqCst, Ordering::SeqCst)
524 {
525 Ok(_) => return next,
526 Err(actual) => prev = actual,
527 }
528 }
529 }
530
531 fn entry_dir(&self, repo: &str, job_name: &str, key: &str) -> PathBuf {
532 self.root.join(entry_name(repo, job_name, key))
533 }
534
535 fn scratch(&self, prefix: &str, job_id: &str) -> PathBuf {
536 self.root.join(format!("{prefix}{job_id}"))
537 }
538
539 /// Removes all of one job's scratch dirs. Missing ones are fine.
540 async fn remove_scratch(&self, job_id: &str) -> Result<(), CacheError> {
541 for prefix in SCRATCH_PREFIXES {
542 self.remove(&self.scratch(prefix, job_id)).await?;
543 }
544 Ok(())
545 }
546
547 /// Removes a file or dir tree, through the id map so subuid-owned files go too. Blocking work
548 /// runs off the async runtime.
549 async fn remove(&self, path: &Path) -> Result<(), CacheError> {
550 let (map, helper, path) = (self.idmap.clone(), self.helper.clone(), path.to_owned());
551 tokio::task::spawn_blocking(move || remove_tree(&map, &path, &helper))
552 .await
553 .map_err(io::Error::other)??;
554 Ok(())
555 }
556}
557
558/// Checks one cached path from the forge, and again on the runner. It must be a relative path
559/// with no empty, `.`, `..` or `.git` parts.
560pub fn validate_path(path: &str) -> Result<PathBuf, CacheError> {
561 let refuse = |reason: &'static str| CacheError::Path {
562 path: path.to_owned(),
563 reason,
564 };
565 if path.is_empty() {
566 return Err(refuse("empty"));
567 }
568 if path.len() > MAX_PATH_LEN {
569 return Err(refuse("too long"));
570 }
571 if path.contains(['\0', '\\']) {
572 return Err(refuse("contains NUL or backslash"));
573 }
574 if path.starts_with('/') {
575 return Err(refuse("absolute"));
576 }
577 let mut out = PathBuf::new();
578 for part in path.split('/') {
579 match part {
580 "" | "." => return Err(refuse("empty or . part")),
581 ".." => return Err(refuse("contains ..")),
582 part if part.eq_ignore_ascii_case(".git") => return Err(refuse(".git is not cached")),
583 part => out.push(part),
584 }
585 }
586 Ok(out)
587}
588
589/// Checks the whole list: at most [`MAX_PATHS`] paths, each valid, and none inside another.
590pub fn validate_paths(paths: &[String]) -> Result<Vec<PathBuf>, CacheError> {
591 if paths.len() > MAX_PATHS {
592 return Err(CacheError::Path {
593 path: format!("{} paths", paths.len()),
594 reason: "too many cache paths",
595 });
596 }
597 let parsed = paths
598 .iter()
599 .map(|p| validate_path(p))
600 .collect::<Result<Vec<_>, _>>()?;
601 for (i, a) in parsed.iter().enumerate() {
602 for b in &parsed[i + 1..] {
603 if a.starts_with(b) || b.starts_with(a) {
604 return Err(CacheError::Path {
605 path: a.display().to_string(),
606 reason: "overlaps another cache path",
607 });
608 }
609 }
610 }
611 Ok(parsed)
612}
613
614/// The manifest entries the job asked for, as (index, path). An entry that fails validation is
615/// logged and dropped.
616fn selected(
617 manifest: &[String],
618 wanted: &[PathBuf],
619 lines: &mut Vec<String>,
620) -> Vec<(usize, PathBuf)> {
621 let mut out = Vec::new();
622 for (k, raw) in manifest.iter().enumerate() {
623 match validate_path(raw) {
624 Ok(rel) if wanted.contains(&rel) => out.push((k, rel)),
625 Ok(_) => {}
626 Err(e) => lines.push(format!("runner: cache skipped: {e}")),
627 }
628 }
629 out
630}
631
632/// The workspace path for `rel`. Missing parent dirs are created when `create` is set. Each parent
633/// is checked one component at a time, and a symlink there is refused, never followed. Returns
634/// `None` when a parent is missing and `create` is not set.
635fn workspace_path(
636 workspace: &Path,
637 rel: &Path,
638 create: bool,
639) -> Result<Option<PathBuf>, CacheError> {
640 if !fs::symlink_metadata(workspace)?.is_dir() {
641 return Err(CacheError::NotDir(workspace.to_owned()));
642 }
643 let mut cur = workspace.to_owned();
644 let parent = rel.parent().unwrap_or(Path::new(""));
645 for part in parent.components() {
646 let Component::Normal(name) = part else {
647 return Err(CacheError::Path {
648 path: rel.display().to_string(),
649 reason: "not a plain relative path",
650 });
651 };
652 cur.push(name);
653 match fs::symlink_metadata(&cur) {
654 Ok(meta) if meta.file_type().is_symlink() => return Err(CacheError::Symlink(cur)),
655 Ok(meta) if meta.is_dir() => {}
656 Ok(_) => return Err(CacheError::NotDir(cur)),
657 Err(e) if e.kind() == io::ErrorKind::NotFound => {
658 if !create {
659 return Ok(None);
660 }
661 fs::create_dir(&cur)?;
662 }
663 Err(e) => return Err(e.into()),
664 }
665 }
666 let Some(name) = rel.file_name() else {
667 return Err(CacheError::Path {
668 path: rel.display().to_string(),
669 reason: "no file name",
670 });
671 };
672 Ok(Some(cur.join(name)))
673}
674
675/// The workspace path of `rel` when something exists there. `None` when nothing does.
676fn existing_in_workspace(workspace: &Path, rel: &Path) -> Result<Option<PathBuf>, CacheError> {
677 let Some(path) = workspace_path(workspace, rel, false)? else {
678 return Ok(None);
679 };
680 Ok(exists_no_follow(&path).then_some(path))
681}
682
683/// Copies `src` to `workspace/rel` with `cp -a --reflink=auto`. The source is left in place.
684/// Returns false when the checkout already has something there.
685async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, CacheError> {
686 let Some(dest) = workspace_path(workspace, rel, true)? else {
687 return Ok(false);
688 };
689 if exists_no_follow(&dest) {
690 return Ok(false);
691 }
692 let output = Command::new("cp")
693 .args(["-a", "--reflink=auto", "--"])
694 .arg(src)
695 .arg(&dest)
696 .stdin(Stdio::null())
697 .stdout(Stdio::null())
698 .stderr(Stdio::piped())
699 .kill_on_drop(true)
700 .output()
701 .await?;
702 if output.status.success() {
703 return Ok(true);
704 }
705 // A partial copy must not stay in the checkout.
706 let _ = plain_remove(&dest).await;
707 let stderr: String = String::from_utf8_lossy(&output.stderr)
708 .chars()
709 .take(MAX_STDERR)
710 .collect();
711 Err(CacheError::Copy(stderr.trim().to_owned()))
712}
713
714/// Removes a file, symlink or dir tree the runner owns. The checkout is never subuid-owned at
715/// this point, so no id map is needed.
716async fn plain_remove(path: &Path) -> io::Result<()> {
717 match fs::symlink_metadata(path) {
718 Ok(meta) if meta.is_dir() => tokio::fs::remove_dir_all(path).await,
719 Ok(_) => tokio::fs::remove_file(path).await,
720 Err(e) => Err(e),
721 }
722}
723
724fn read_meta(dir: &Path) -> Option<Meta> {
725 let bytes = fs::read(dir.join(META)).ok()?;
726 serde_json::from_slice(&bytes).ok()
727}
728
729/// The stamps an entry recorded. An entry without a readable `stamps.json` has none.
730fn read_stamps(dir: &Path) -> Stamps {
731 fs::read(dir.join(STAMPS))
732 .ok()
733 .and_then(|bytes| serde_json::from_slice(&bytes).ok())
734 .unwrap_or_default()
735}
736
737/// Sets a regular file's modification time. A symlink or other kind is refused, not followed.
738fn set_mtime(path: &Path, time: SystemTime) -> io::Result<()> {
739 if !fs::symlink_metadata(path)?.is_file() {
740 return Err(io::Error::other("not a regular file"));
741 }
742 fs::File::open(path)?.set_modified(time)
743}
744
745/// A stamp's Unix seconds as a time. Negative or out of range values are refused.
746fn time_of(secs: i64) -> io::Result<SystemTime> {
747 u64::try_from(secs)
748 .ok()
749 .and_then(|s| UNIX_EPOCH.checked_add(Duration::from_secs(s)))
750 .ok_or_else(|| io::Error::other("time out of range"))
751}
752
753/// Unix seconds of `now`, or 0 before the epoch.
754fn unix_secs(now: SystemTime) -> i64 {
755 now.duration_since(UNIX_EPOCH)
756 .ok()
757 .and_then(|d| i64::try_from(d.as_secs()).ok())
758 .unwrap_or(0)
759}
760
761fn read_manifest(dir: &Path) -> Result<Vec<String>, CacheError> {
762 let bytes = fs::read(dir.join(MANIFEST))?;
763 serde_json::from_slice(&bytes).map_err(|e| CacheError::Io(io::Error::other(e)))
764}
765
766async fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), CacheError> {
767 let bytes = serde_json::to_vec(value).map_err(io::Error::other)?;
768 tokio::fs::write(path, bytes).await?;
769 Ok(())
770}
771
772/// The total size of the files under `root`. Symlinks count as links and are never followed.
773/// Unreadable dirs count as empty. Runs off the async runtime.
774async fn dir_size(root: &Path) -> u64 {
775 let root = root.to_owned();
776 tokio::task::spawn_blocking(move || tree_size(&root))
777 .await
778 .unwrap_or(0)
779}
780
781fn tree_size(root: &Path) -> u64 {
782 let mut total = 0u64;
783 let mut stack = vec![root.to_owned()];
784 while let Some(dir) = stack.pop() {
785 let Ok(entries) = fs::read_dir(&dir) else {
786 continue;
787 };
788 for entry in entries.flatten() {
789 let Ok(meta) = fs::symlink_metadata(entry.path()) else {
790 continue;
791 };
792 if meta.is_dir() {
793 stack.push(entry.path());
794 } else {
795 total = total.saturating_add(meta.len());
796 }
797 }
798 }
799 total
800}
801
802/// The entry directory name for one job's cache key. Hashing keeps key text out of paths.
803fn entry_name(repo: &str, job_name: &str, key: &str) -> String {
804 let mut hash = Sha256::new();
805 hash.update(repo.as_bytes());
806 hash.update([0u8]);
807 hash.update(job_name.as_bytes());
808 hash.update([0u8]);
809 hash.update(key.as_bytes());
810 hex::encode(hash.finalize())
811}
812
813/// Whether a dir name is an entry: 64 lowercase hex digits.
814fn is_entry_name(name: &str) -> bool {
815 name.len() == 64
816 && name
817 .bytes()
818 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
819}
820
821fn is_scratch(name: &str) -> bool {
822 SCRATCH_PREFIXES.iter().any(|p| name.starts_with(p))
823}
824
825fn is_dir(path: &Path) -> bool {
826 fs::symlink_metadata(path).is_ok_and(|m| m.is_dir())
827}
828
829fn exists_no_follow(path: &Path) -> bool {
830 fs::symlink_metadata(path).is_ok()
831}
832
833fn nanos(d: Duration) -> u64 {
834 u64::try_from(d.as_nanos()).unwrap_or(u64::MAX)
835}
836
837fn skipped(rel: &Path) -> String {
838 format!(
839 "runner: cache skipped {}: already in the checkout",
840 rel.display()
841 )
842}
843
844/// A size for log lines, such as `3.1 GiB`.
845fn human(bytes: u64) -> String {
846 const KIB: f64 = 1024.0;
847 let b = bytes as f64;
848 if b >= KIB * KIB * KIB {
849 format!("{:.1} GiB", b / (KIB * KIB * KIB))
850 } else if b >= KIB * KIB {
851 format!("{:.1} MiB", b / (KIB * KIB))
852 } else {
853 format!("{:.1} KiB", b / KIB)
854 }
855}
856
857#[cfg(test)]
858mod tests {
859 use std::collections::BTreeMap;
860 use std::os::unix::fs::symlink;
861
862 use super::*;
863
864 fn job(job_id: &str, key: &str, restore: &[&str], cache: &[&str]) -> JobAssignment {
865 JobAssignment {
866 job_id: job_id.to_owned(),
867 job_token: "tok_secret_value".to_owned(),
868 repo: "tahinli/forge".to_owned(),
869 clone_url: "https://forge.example/tahinli/forge.git".to_owned(),
870 commit: "a".repeat(40),
871 git_ref: "refs/heads/main".to_owned(),
872 job_name: "build".to_owned(),
873 image: "docker.io/library/alpine:3".to_owned(),
874 run: "true".to_owned(),
875 env: BTreeMap::new(),
876 secrets: BTreeMap::new(),
877 artifacts: Vec::new(),
878 timeout_minutes: 5,
879 network: false,
880 cache: cache.iter().map(|s| (*s).to_owned()).collect(),
881 cache_key: key.to_owned(),
882 cache_restore_keys: restore.iter().map(|s| (*s).to_owned()).collect(),
883 memory_bytes: None,
884 }
885 }
886
887 fn store(dir: &Path, max_bytes: u64) -> CacheStore {
888 CacheStore::new(
889 dir.join(".cache"),
890 max_bytes,
891 IdMap::single(),
892 PathBuf::from("/unused-helper"),
893 )
894 }
895
896 /// A workspace `dir/<name>` holding `target/a.txt` with `body`.
897 fn workspace(dir: &Path, name: &str, body: &str) -> PathBuf {
898 let ws = dir.join(name);
899 fs::create_dir_all(ws.join("target")).expect("mkdir");
900 fs::write(ws.join("target/a.txt"), body).expect("write");
901 ws
902 }
903
904 fn empty_workspace(dir: &Path, name: &str) -> PathBuf {
905 let ws = dir.join(name);
906 fs::create_dir_all(&ws).expect("mkdir");
907 ws
908 }
909
910 fn entry_of(store: &CacheStore, key: &str) -> PathBuf {
911 store.entry_dir("tahinli/forge", "build", key)
912 }
913
914 fn read(path: &Path) -> String {
915 fs::read_to_string(path).expect("read")
916 }
917
918 #[tokio::test]
919 async fn hit_copies_and_only_a_finished_job_replaces_the_entry() {
920 let dir = tempfile::tempdir().expect("tempdir");
921 let store = store(dir.path(), 1 << 30);
922 let first = job("job_a", "ref:refs/heads/main", &[], &["target"]);
923 let ws1 = workspace(dir.path(), "ws_a", "one");
924 let saved = store.save(&first, Outcome::Success, &ws1).await;
925 assert!(
926 saved.iter().any(|l| l.starts_with("runner: cache saved")),
927 "{saved:?}"
928 );
929 assert!(!ws1.join("target").exists(), "save moves the path out");
930
931 let second = job("job_b", "ref:refs/heads/main", &[], &["target"]);
932 let ws2 = empty_workspace(dir.path(), "ws_b");
933 let lines = store.restore(&second, &ws2).await;
934 assert!(
935 lines
936 .iter()
937 .any(|l| l.starts_with("runner: cache hit ref:refs/heads/main")),
938 "{lines:?}"
939 );
940 assert_eq!(read(&ws2.join("target/a.txt")), "one");
941
942 // A cancelled job leaves the entry as it was.
943 fs::write(ws2.join("target/a.txt"), "half").expect("write");
944 store.save(&second, Outcome::Cancelled, &ws2).await;
945 let entry = entry_of(&store, "ref:refs/heads/main");
946 assert_eq!(read(&entry.join("p0/a.txt")), "one");
947
948 // Another job hits the same entry, and its finished save replaces it.
949 let third = job("job_c", "ref:refs/heads/main", &[], &["target"]);
950 let ws3 = empty_workspace(dir.path(), "ws_c");
951 store.restore(&third, &ws3).await;
952 fs::write(ws3.join("target/a.txt"), "two").expect("write");
953 store.save(&third, Outcome::Success, &ws3).await;
954 assert_eq!(read(&entry.join("p0/a.txt")), "two");
955 }
956
957 #[tokio::test]
958 async fn fallback_copies_and_leaves_the_fallback_entry() {
959 let dir = tempfile::tempdir().expect("tempdir");
960 let store = store(dir.path(), 1 << 30);
961 let main = job("job_a", "ref:refs/heads/main", &[], &["target"]);
962 store
963 .save(
964 &main,
965 Outcome::Success,
966 &workspace(dir.path(), "ws_a", "main"),
967 )
968 .await;
969
970 let pr = job("job_b", "pr:12", &["ref:refs/heads/main"], &["target"]);
971 let ws = empty_workspace(dir.path(), "ws_b");
972 let lines = store.restore(&pr, &ws).await;
973 assert!(
974 lines.contains(&"runner: cache restored from fallback ref:refs/heads/main".to_owned()),
975 "{lines:?}"
976 );
977 assert_eq!(read(&ws.join("target/a.txt")), "main");
978 assert_eq!(
979 read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")),
980 "main"
981 );
982 }
983
984 #[tokio::test]
985 async fn save_replaces_the_entry_and_leaves_no_scratch() {
986 let dir = tempfile::tempdir().expect("tempdir");
987 let store = store(dir.path(), 1 << 30);
988 let first = job("job_1", "ref:refs/heads/main", &[], &["target"]);
989 store
990 .save(
991 &first,
992 Outcome::Success,
993 &workspace(dir.path(), "ws1", "v1"),
994 )
995 .await;
996 let second = job("job_2", "ref:refs/heads/main", &[], &["target"]);
997 store
998 .save(
999 &second,
1000 Outcome::Failure,
1001 &workspace(dir.path(), "ws2", "v2"),
1002 )
1003 .await;
1004
1005 let entry = entry_of(&store, "ref:refs/heads/main");
1006 assert_eq!(read(&entry.join("p0/a.txt")), "v2");
1007 let names: Vec<String> = fs::read_dir(&store.root)
1008 .expect("read_dir")
1009 .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
1010 .collect();
1011 assert_eq!(
1012 names,
1013 vec![
1014 entry
1015 .file_name()
1016 .expect("name")
1017 .to_string_lossy()
1018 .into_owned()
1019 ]
1020 );
1021 }
1022
1023 #[tokio::test]
1024 async fn save_never_writes_restore_keys() {
1025 let dir = tempfile::tempdir().expect("tempdir");
1026 let store = store(dir.path(), 1 << 30);
1027 let main = job("job_m", "ref:refs/heads/main", &[], &["target"]);
1028 store
1029 .save(
1030 &main,
1031 Outcome::Success,
1032 &workspace(dir.path(), "ws_m", "main"),
1033 )
1034 .await;
1035
1036 let pr = job("job_p", "pr:12", &["ref:refs/heads/main"], &["target"]);
1037 store
1038 .save(&pr, Outcome::Success, &workspace(dir.path(), "ws_p", "pr"))
1039 .await;
1040 assert_eq!(read(&entry_of(&store, "pr:12").join("p0/a.txt")), "pr");
1041 assert_eq!(
1042 read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")),
1043 "main"
1044 );
1045
1046 // A job whose own key is empty saves nothing, even with restore keys listed.
1047 let none = job("job_n", "", &["ref:refs/heads/main"], &["target"]);
1048 store
1049 .save(
1050 &none,
1051 Outcome::Success,
1052 &workspace(dir.path(), "ws_n", "none"),
1053 )
1054 .await;
1055 assert_eq!(
1056 read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")),
1057 "main"
1058 );
1059 }
1060
1061 #[tokio::test]
1062 async fn cancelled_or_errored_runs_do_not_save() {
1063 let dir = tempfile::tempdir().expect("tempdir");
1064 let store = store(dir.path(), 1 << 30);
1065 let j = job("job_x", "ref:refs/heads/main", &[], &["target"]);
1066 for outcome in [Outcome::Cancelled, Outcome::Error] {
1067 let ws = workspace(dir.path(), &format!("ws_{outcome:?}"), "x");
1068 let lines = store.save(&j, outcome, &ws).await;
1069 assert!(lines.is_empty(), "{lines:?}");
1070 assert!(
1071 ws.join("target/a.txt").exists(),
1072 "the files stay in the workspace"
1073 );
1074 }
1075 assert!(!entry_of(&store, "ref:refs/heads/main").exists());
1076 }
1077
1078 #[tokio::test]
1079 async fn eviction_removes_the_least_recently_saved_entry() {
1080 let dir = tempfile::tempdir().expect("tempdir");
1081 // Each entry holds 1000 bytes. The cap fits two of them.
1082 let store = store(dir.path(), 2500);
1083 for key in ["k1", "k2", "k3"] {
1084 let ws = dir.path().join(format!("ws_{key}"));
1085 fs::create_dir_all(ws.join("target")).expect("mkdir");
1086 fs::write(ws.join("target/data.bin"), vec![b'x'; 1000]).expect("write");
1087 let j = job(&format!("job_{key}"), key, &[], &["target"]);
1088 store.save(&j, Outcome::Success, &ws).await;
1089 }
1090 assert!(!entry_of(&store, "k1").exists(), "the oldest goes first");
1091 assert!(entry_of(&store, "k2").is_dir());
1092 assert!(entry_of(&store, "k3").is_dir());
1093 }
1094
1095 #[test]
1096 fn cache_paths_are_checked_again_on_the_runner() {
1097 let bad = [
1098 "../x",
1099 "a/../b",
1100 "/etc",
1101 "",
1102 ".",
1103 "a//b",
1104 "target/",
1105 ".git",
1106 "a/.git/b",
1107 "a/./b",
1108 "x\\y",
1109 "a\0b",
1110 ".GIT/config",
1111 ];
1112 for path in bad {
1113 assert!(validate_path(path).is_err(), "{path:?} must be refused");
1114 }
1115 assert_eq!(
1116 validate_path("target").expect("ok"),
1117 PathBuf::from("target")
1118 );
1119 assert_eq!(
1120 validate_path("web/node_modules").expect("ok"),
1121 PathBuf::from("web/node_modules")
1122 );
1123 assert!(validate_paths(&["target".to_owned(), "target/debug".to_owned()]).is_err());
1124 }
1125
1126 #[tokio::test]
1127 async fn a_symlinked_parent_is_refused_and_not_followed() {
1128 let dir = tempfile::tempdir().expect("tempdir");
1129 let store = store(dir.path(), 1 << 30);
1130 let outside = dir.path().join("outside");
1131 fs::create_dir_all(&outside).expect("mkdir");
1132
1133 let ws1 = dir.path().join("ws1");
1134 fs::create_dir_all(ws1.join("build/out")).expect("mkdir");
1135 fs::write(ws1.join("build/out/f"), "x").expect("write");
1136 let first = job("job_1", "ref:main", &[], &["build/out"]);
1137 store.save(&first, Outcome::Success, &ws1).await;
1138
1139 // Restore into a checkout where `build` is a symlink out of the workspace.
1140 let ws2 = empty_workspace(dir.path(), "ws2");
1141 symlink(&outside, ws2.join("build")).expect("symlink");
1142 let second = job("job_2", "ref:main", &[], &["build/out"]);
1143 let lines = store.restore(&second, &ws2).await;
1144 assert!(
1145 lines
1146 .iter()
1147 .any(|l| l.contains("build/out") && l.contains("failed")),
1148 "{lines:?}"
1149 );
1150 assert!(
1151 !outside.join("out").exists(),
1152 "restore must not write through the symlink"
1153 );
1154
1155 // Save from a checkout with the same symlink: nothing is moved out of `outside`.
1156 fs::create_dir_all(outside.join("out")).expect("mkdir");
1157 let ws3 = empty_workspace(dir.path(), "ws3");
1158 symlink(&outside, ws3.join("build")).expect("symlink");
1159 let third = job("job_3", "pr:9", &[], &["build/out"]);
1160 let lines = store.save(&third, Outcome::Success, &ws3).await;
1161 assert!(lines.iter().any(|l| l.contains("skipped")), "{lines:?}");
1162 assert!(
1163 outside.join("out").is_dir(),
1164 "save must not move through the symlink"
1165 );
1166 }
1167
1168 #[tokio::test]
1169 async fn stale_scratch_dirs_are_removed_at_startup() {
1170 let dir = tempfile::tempdir().expect("tempdir");
1171 let store = store(dir.path(), 1 << 30);
1172 for name in [".inuse-crashed", ".new-crashed", ".old-crashed"] {
1173 let path = store.root.join(name);
1174 fs::create_dir_all(&path).expect("mkdir");
1175 fs::write(path.join("f"), "x").expect("write");
1176 }
1177 let keep = entry_of(&store, "ref:main");
1178 fs::create_dir_all(&keep).expect("mkdir");
1179
1180 store.sweep_stale().await.expect("sweep");
1181 for name in [".inuse-crashed", ".new-crashed", ".old-crashed"] {
1182 assert!(!store.root.join(name).exists(), "{name} must be removed");
1183 }
1184 assert!(keep.is_dir(), "entries are kept");
1185 }
1186
1187 /// Runs git in `dir` with a fixed identity. Fails the test when git fails.
1188 fn git(dir: &Path, args: &[&str]) {
1189 let ok = std::process::Command::new("git")
1190 .arg("-C")
1191 .arg(dir)
1192 .args(args)
1193 .env("GIT_AUTHOR_NAME", "ci")
1194 .env("GIT_AUTHOR_EMAIL", "ci@example.com")
1195 .env("GIT_COMMITTER_NAME", "ci")
1196 .env("GIT_COMMITTER_EMAIL", "ci@example.com")
1197 .status()
1198 .expect("git runs")
1199 .success();
1200 assert!(ok, "git {args:?} failed");
1201 }
1202
1203 fn mtime_secs(path: &Path) -> u64 {
1204 fs::metadata(path)
1205 .and_then(|m| m.modified())
1206 .expect("mtime")
1207 .duration_since(UNIX_EPOCH)
1208 .expect("after the epoch")
1209 .as_secs()
1210 }
1211
1212 #[tokio::test]
1213 async fn unchanged_files_keep_their_stamp_and_changed_files_get_a_new_one() {
1214 let dir = tempfile::tempdir().expect("tempdir");
1215 let store = store(dir.path(), 1 << 30);
1216 let origin = dir.path().join("origin");
1217 let origin_str = origin.to_str().expect("utf8 path").to_owned();
1218 fs::create_dir_all(&origin).expect("mkdir");
1219 git(&origin, &["init", "--quiet"]);
1220 fs::write(origin.join("a.txt"), "a").expect("write");
1221 fs::write(origin.join("b.txt"), "b").expect("write");
1222 git(&origin, &["add", "."]);
1223 git(
1224 &origin,
1225 &[
1226 "-c",
1227 "commit.gpgsign=false",
1228 "commit",
1229 "--quiet",
1230 "-m",
1231 "one",
1232 ],
1233 );
1234
1235 // The first run is a miss. It saves an entry from its checkout.
1236 git(dir.path(), &["clone", "--quiet", &origin_str, "ws1"]);
1237 let ws1 = dir.path().join("ws1");
1238 let first = job("job_1", "ref:main", &[], &["target"]);
1239 store.restore(&first, &ws1).await;
1240 fs::create_dir_all(ws1.join("target")).expect("mkdir");
1241 fs::write(ws1.join("target/out.bin"), "built").expect("write");
1242 store.save(&first, Outcome::Success, &ws1).await;
1243 let a_stamp = mtime_secs(&ws1.join("a.txt"));
1244
1245 // The next commit changes only b.txt. The sleep makes a new stamp a later second.
1246 fs::write(origin.join("b.txt"), "b2").expect("write");
1247 git(&origin, &["add", "."]);
1248 git(
1249 &origin,
1250 &[
1251 "-c",
1252 "commit.gpgsign=false",
1253 "commit",
1254 "--quiet",
1255 "-m",
1256 "two",
1257 ],
1258 );
1259 git(dir.path(), &["clone", "--quiet", &origin_str, "ws2"]);
1260 tokio::time::sleep(Duration::from_millis(1100)).await;
1261
1262 let ws2 = dir.path().join("ws2");
1263 let second = job("job_2", "ref:main", &[], &["target"]);
1264 let lines = store.restore(&second, &ws2).await;
1265 assert!(
1266 lines.contains(&"runner: file times restored (1 unchanged, 1 changed)".to_owned()),
1267 "{lines:?}"
1268 );
1269 assert_eq!(
1270 mtime_secs(&ws2.join("a.txt")),
1271 a_stamp,
1272 "unchanged keeps its stamp"
1273 );
1274 assert!(
1275 mtime_secs(&ws2.join("b.txt")) > a_stamp,
1276 "a changed file is newer"
1277 );
1278 }
1279}