forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiB51b2bbfTahinli1 month ago19 commits

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