forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB8e56ffcTahinli1 month ago262 commits

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