forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiBe910f7eTahinli2 hours ago361 commits

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