Skip to main content

epicenter_cli/
exec.rs

1//! `epicenter exec` — run one command against a fresh per-job build dir
2//! seeded from the vault.
3//!
4//! A job gets its own directory under `{cargo-cache-home}/epicenter/work/<id>/`
5//! that plays the role of Cargo's build dir for the child process
6//! (`CARGO_BUILD_BUILD_DIR` — no config file is written). The vault's unit
7//! groups are hard-linked in first, so the build starts warm; the units the
8//! job produces can be harvested back. Because every job owns its build dir,
9//! jobs never contend on Cargo's per-build-dir lock, and the job dir itself
10//! is a disposable view: deleting it removes no state the vault still holds.
11//!
12//! stdout and stderr of the command pass through untouched; epicenter's own
13//! frame lines go to stderr, and the command's exit code becomes epicenter's
14//! exit code.
15
16use std::io::Write;
17use std::path::{Path, PathBuf};
18use std::process::{Command, ExitStatus};
19use std::time::{Instant, SystemTime, UNIX_EPOCH};
20
21use walkdir::WalkDir;
22
23use anyhow::{Context, Result, bail};
24
25use crate::util::{self, GLYPH_FAIL, GLYPH_INFO, GLYPH_PASS, human_bytes, human_duration};
26use crate::vault;
27
28/// `{cargo-cache-home}/epicenter/work` — the home of per-job working dirs,
29/// a sibling of `build/` and `store/`.
30pub fn work_root(build_root: &Path) -> PathBuf {
31    build_root.parent().unwrap_or(build_root).join("work")
32}
33
34/// One job dir as the read-only summary sees it.
35#[derive(Debug, Clone)]
36pub struct WorkDirInfo {
37    pub name: String,
38    pub files: u64,
39    pub bytes: u64,
40    /// Newest file mtime — the dir's last activity.
41    pub newest: Option<SystemTime>,
42}
43
44/// What the `work/` tier currently holds (read-only summary).
45#[derive(Debug, Default)]
46pub struct WorkTier {
47    pub dirs: usize,
48    pub files: u64,
49    pub bytes: u64,
50    /// Newest file mtime across all job dirs — the tier's last activity.
51    pub newest: Option<SystemTime>,
52    /// Per-dir detail, oldest activity first (the most collectible on top).
53    pub entries: Vec<WorkDirInfo>,
54}
55
56/// Summarize the job dirs under `work/`.
57pub fn work_tier(build_root: &Path) -> Result<WorkTier> {
58    let mut tier = WorkTier::default();
59    let Ok(entries) = std::fs::read_dir(work_root(build_root)) else {
60        return Ok(tier);
61    };
62    for entry in entries.flatten() {
63        if !entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false) {
64            continue;
65        }
66        let name = entry.file_name().to_string_lossy().into_owned();
67        if name.starts_with('.') {
68            continue;
69        }
70        let mut info = WorkDirInfo {
71            name,
72            files: 0,
73            bytes: 0,
74            newest: None,
75        };
76        for file in WalkDir::new(entry.path()).min_depth(1).into_iter().flatten() {
77            if !file.file_type().is_file() {
78                continue;
79            }
80            if let Ok(meta) = file.metadata() {
81                info.files += 1;
82                info.bytes += meta.len();
83                if let Ok(modified) = meta.modified() {
84                    if info.newest.map_or(true, |current| modified > current) {
85                        info.newest = Some(modified);
86                    }
87                }
88            }
89        }
90        tier.dirs += 1;
91        tier.files += info.files;
92        tier.bytes += info.bytes;
93        if let Some(modified) = info.newest {
94            if tier.newest.map_or(true, |current| modified > current) {
95                tier.newest = Some(modified);
96            }
97        }
98        tier.entries.push(info);
99    }
100    tier.entries.sort_by_key(|info| info.newest);
101    Ok(tier)
102}
103
104/// Does a live build hold this build dir? Cargo takes an exclusive advisory
105/// lock on `<build-dir>/<profile>/.cargo-build-lock` for the duration of a
106/// build; the lock file itself survives idle builds, so only lock contention
107/// means "in use". Shared by `exec` (reuse refusal) and `evict` (view guards).
108pub(crate) fn dir_locked(dir: &Path) -> bool {
109    let Ok(entries) = std::fs::read_dir(dir) else {
110        return true;
111    };
112    for entry in entries.flatten() {
113        if !entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false) {
114            continue;
115        }
116        let lock = entry.path().join(".cargo-build-lock");
117        if lock.is_file() && lock_held(&lock) {
118            return true;
119        }
120    }
121    false
122}
123
124/// A lock we cannot take is a lock somebody else holds.
125fn lock_held(lock: &Path) -> bool {
126    let file = std::fs::OpenOptions::new()
127        .write(true)
128        .open(lock)
129        .or_else(|_| std::fs::File::open(lock));
130    let Ok(file) = file else {
131        return true;
132    };
133    match file.try_lock() {
134        Ok(()) => {
135            let _ = file.unlock();
136            false
137        }
138        Err(_) => true,
139    }
140}
141
142/// What the caller wants.
143pub struct Options<'a> {
144    /// Job id / work-dir name; `None` mints one.
145    pub job_id: Option<&'a str>,
146    /// Directory the command runs in (default: the current directory).
147    pub cwd: Option<PathBuf>,
148    /// Store the units the job produced back into the vault.
149    pub harvest_back: bool,
150    /// Remove the work dir after the run — success or failure. Without it
151    /// the dir is kept for inspection.
152    pub remove_on_success: bool,
153    /// Continue in an existing job dir instead of refusing (restore is
154    /// idempotent; a dir a live build holds is still refused).
155    pub reuse: bool,
156    /// The child's `CARGO_TARGET_DIR`: `Some("job")` means `<work dir>/target`
157    /// (per-job finals — the fully parallel case); any other value is a path.
158    pub target_dir: Option<&'a str>,
159    /// The command, argv-style.
160    pub command: &'a [String],
161}
162
163/// Resolve `--target-dir`: the bare flag (`"job"`) picks `<work dir>/target`,
164/// so finals live and die with the job; a value is a path, resolved against
165/// the command's working directory when relative.
166fn resolve_target_dir(raw: &str, work_dir: &Path, cwd: Option<&Path>) -> PathBuf {
167    if raw == "job" {
168        return work_dir.join("target");
169    }
170    let path = PathBuf::from(raw);
171    if path.is_absolute() {
172        return path;
173    }
174    let base = cwd
175        .map(Path::to_path_buf)
176        .or_else(|| std::env::current_dir().ok())
177        .unwrap_or_default();
178    base.join(path)
179}
180
181/// Run the job; returns the command's exit code.
182pub fn run(store_root: &Path, work_root: &Path, opts: &Options<'_>) -> Result<i32> {
183    let Some(program) = opts.command.first() else {
184        bail!("exec needs a command — `epicenter exec -- <cmd>`");
185    };
186    let job_id = match opts.job_id {
187        Some(id) => sanitize_job_id(id)?,
188        None => default_job_id(),
189    };
190    let work_dir = work_root.join(&job_id);
191    let mut reused = false;
192    if work_dir.exists() {
193        if !opts.reuse {
194            bail!(
195                "job dir {} already exists — pick another --id, pass --reuse to continue in it, or remove it",
196                work_dir.display()
197            );
198        }
199        if !work_dir.is_dir() {
200            bail!("{} exists and is not a directory", work_dir.display());
201        }
202        if dir_locked(&work_dir) {
203            bail!(
204                "job dir {} is in use by a live build — wait for it, or use another --id",
205                work_dir.display()
206            );
207        }
208        reused = true;
209    } else {
210        std::fs::create_dir_all(&work_dir)
211            .with_context(|| format!("creating {}", work_dir.display()))?;
212    }
213    let target_dir = opts
214        .target_dir
215        .map(|raw| resolve_target_dir(raw, &work_dir, opts.cwd.as_deref()));
216
217    eprintln!(
218        "{}",
219        util::heading(&format!("epicenter exec — job {job_id}"))
220    );
221    eprintln!(
222        "  {} {}{}",
223        util::dim(&format!("{:<11}", "work dir")),
224        work_dir.display(),
225        if reused {
226            util::dim("  (reused)")
227        } else {
228            String::new()
229        }
230    );
231
232    // Fail-open seeding: an empty vault simply means a cold build. The hint
233    // is about THIS step (before the command) — `--harvest` stores afterwards.
234    let restore = vault::restore(&work_dir, store_root, None, false)?;
235    match &restore.note {
236        Some(_) if opts.harvest_back => eprintln!(
237            "  {} cold start — the vault has nothing for this generation yet; --harvest will store what this job builds",
238            util::info(GLYPH_INFO)
239        ),
240        Some(_) => eprintln!(
241            "  {} cold start — the vault has nothing for this generation yet; pass --harvest to seed it from this job",
242            util::info(GLYPH_INFO)
243        ),
244        None => eprintln!(
245            "  {} {} unit(s) · {} file(s) · {}",
246            util::dim(&format!("{:<11}", "vault")),
247            restore.units_linked,
248            restore.files_linked + restore.files_copied,
249            util::green(&human_bytes(restore.bytes))
250        ),
251    }
252    eprintln!(
253        "  {} CARGO_BUILD_BUILD_DIR (this job only; no config change)",
254        util::dim(&format!("{:<11}", "build-dir"))
255    );
256    if let Some(target) = &target_dir {
257        eprintln!(
258            "  {} {}{}",
259            util::dim(&format!("{:<11}", "target dir")),
260            target.display(),
261            util::dim("  (CARGO_TARGET_DIR — finals live and die with this job)")
262        );
263    }
264    eprintln!("{}", util::dim("  ── command ──"));
265    let _ = std::io::stderr().flush();
266
267    let started = Instant::now();
268    let mut child = Command::new(program);
269    child.args(&opts.command[1..]);
270    child.env("CARGO_BUILD_BUILD_DIR", &work_dir);
271    if let Some(target) = &target_dir {
272        child.env("CARGO_TARGET_DIR", target);
273    }
274    if let Some(dir) = &opts.cwd {
275        child.current_dir(dir);
276    }
277    let status = child
278        .status()
279        .with_context(|| format!("cannot run `{program}` — is it installed and on PATH?"))?;
280    let elapsed = started.elapsed();
281    let code = exit_code(&status);
282
283    let harvested = if opts.harvest_back {
284        Some(vault::harvest(&work_dir, store_root, None, false)?)
285    } else {
286        None
287    };
288    let mut removed = false;
289    let mut remove_error = None;
290    if opts.remove_on_success {
291        match util::force_remove_dir(&work_dir) {
292            Ok(()) => removed = true,
293            Err(err) => remove_error = Some(err),
294        }
295    }
296
297    eprintln!("{}", util::dim("  ── end ──"));
298    let mark = if code == 0 {
299        util::green(GLYPH_PASS)
300    } else {
301        util::fail(GLYPH_FAIL)
302    };
303    eprintln!("  {mark} exit {code} · {}", human_duration(elapsed));
304    if let Some(report) = &harvested {
305        if let Some(note) = &report.note {
306            // Harvest refused wholesale (e.g. the job predates the toolchain).
307            eprintln!("  {} {note}", util::warn(util::GLYPH_WARN));
308        } else {
309            let mut line = format!(
310                "{} newly stored · {} refreshed · {} already in the vault",
311                report.stored, report.refreshed, report.unchanged
312            );
313            let skipped = report.skipped_stale + report.skipped_incomplete;
314            if skipped > 0 {
315                line.push_str(&format!(" · {skipped} skipped"));
316            }
317            eprintln!("  {} {line}", util::dim(&format!("{:<11}", "harvest")));
318        }
319    }
320    if removed {
321        eprintln!(
322            "  {} {} (--rm)",
323            util::dim(&format!("{:<11}", "work dir")),
324            util::dim("removed")
325        );
326    } else if let Some(err) = &remove_error {
327        eprintln!(
328            "  {} {} — could not remove it: {err}",
329            util::dim(&format!("{:<11}", "work dir")),
330            work_dir.display()
331        );
332    } else {
333        eprintln!(
334            "  {} {} {}",
335            util::dim(&format!("{:<11}", "work dir")),
336            work_dir.display(),
337            util::dim("(kept — pass --rm to remove)")
338        );
339    }
340    Ok(code)
341}
342
343/// Signals use the shell convention: 128 + signal number.
344fn exit_code(status: &ExitStatus) -> i32 {
345    if let Some(code) = status.code() {
346        return code;
347    }
348    #[cfg(unix)]
349    {
350        use std::os::unix::process::ExitStatusExt;
351        if let Some(signal) = status.signal() {
352            return 128 + signal;
353        }
354    }
355    1
356}
357
358fn default_job_id() -> String {
359    let secs = SystemTime::now()
360        .duration_since(UNIX_EPOCH)
361        .map(|duration| duration.as_secs())
362        .unwrap_or(0);
363    format!("job-{}-{}", stamp_from_unix(secs), std::process::id())
364}
365
366/// `YYYYMMDD-HHMMSS` in UTC — sortable, readable, filesystem-safe.
367fn stamp_from_unix(secs: u64) -> String {
368    let days = secs / 86_400;
369    let rem = secs % 86_400;
370    let (year, month, day) = civil_from_days(days as i64);
371    format!(
372        "{year:04}{month:02}{day:02}-{:02}{:02}{:02}",
373        rem / 3_600,
374        (rem % 3_600) / 60,
375        rem % 60
376    )
377}
378
379/// Days since the Unix epoch to a civil date — the standard shift-and-correct
380/// integer algorithm, no lookup tables.
381fn civil_from_days(days: i64) -> (i64, u32, u32) {
382    let z = days + 719_468;
383    let era = z.div_euclid(146_097);
384    let doe = z.rem_euclid(146_097) as u64; // [0, 146096]
385    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
386    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
387    let mp = (5 * doy + 2) / 153; // [0, 11]
388    let day = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
389    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12]
390    let year = yoe as i64 + era * 400 + if month <= 2 { 1 } else { 0 };
391    (year, month, day)
392}
393
394/// Job ids become directory names: plain characters only.
395fn sanitize_job_id(id: &str) -> Result<String> {
396    let trimmed = id.trim();
397    if trimmed.is_empty() {
398        bail!("--id must not be empty");
399    }
400    if trimmed == "." || trimmed == ".." || trimmed.starts_with('.') {
401        bail!("--id {id:?} is not a usable directory name");
402    }
403    if !trimmed
404        .chars()
405        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
406    {
407        bail!("--id {id:?}: use letters, digits, `-`, `_` or `.`");
408    }
409    Ok(trimmed.to_string())
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415    use std::fs;
416
417    #[test]
418    fn utc_stamp_is_correct_and_sortable() {
419        assert_eq!(stamp_from_unix(0), "19700101-000000");
420        assert_eq!(stamp_from_unix(86_399), "19700101-235959");
421        assert_eq!(stamp_from_unix(86_400), "19700102-000000");
422        assert_eq!(stamp_from_unix(1_800_000_000), "20270115-080000");
423    }
424
425    #[test]
426    fn job_ids_are_path_safe() {
427        assert_eq!(sanitize_job_id(" ci-1234_ok ").unwrap(), "ci-1234_ok");
428        assert!(sanitize_job_id("").is_err());
429        assert!(sanitize_job_id("..").is_err());
430        assert!(sanitize_job_id("../x").is_err());
431        assert!(sanitize_job_id("a/b").is_err());
432        assert!(sanitize_job_id(".hidden").is_err());
433        assert!(sanitize_job_id("has space").is_err());
434    }
435
436    /// One synthetic unit in a build dir, harvested into a temp vault.
437    fn seeded_store() -> Result<(tempfile::TempDir, tempfile::TempDir)> {
438        let build = tempfile::tempdir()?;
439        let store = tempfile::tempdir()?;
440        let unit = build.path().join("debug/.fingerprint/x-1122334455667788");
441        fs::create_dir_all(&unit)?;
442        fs::write(unit.join("lib-x"), "aaaabbbbccccdddd")?;
443        fs::write(unit.join("dep-lib-x"), [0u8; 4])?;
444        fs::create_dir_all(build.path().join("debug/deps"))?;
445        fs::write(
446            build.path().join("debug/deps/libx-1122334455667788.rlib"),
447            [1u8; 8],
448        )?;
449        vault::harvest(build.path(), store.path(), None, false)?;
450        Ok((build, store))
451    }
452
453    #[cfg(unix)]
454    #[test]
455    fn exec_seeds_the_job_and_propagates_the_exit_code() -> Result<()> {
456        let (_build, store) = seeded_store()?;
457        let work = tempfile::tempdir()?;
458        let job_dir = work.path().join("jobtest");
459        let command = vec![
460            "sh".to_string(),
461            "-c".to_string(),
462            format!(
463                "test \"$CARGO_BUILD_BUILD_DIR\" = '{}' && exit 7",
464                job_dir.display()
465            ),
466        ];
467        let opts = Options {
468            job_id: Some("jobtest"),
469            cwd: None,
470            harvest_back: false,
471            remove_on_success: false,
472            reuse: false,
473            target_dir: None,
474            command: &command,
475        };
476        let code = run(store.path(), work.path(), &opts)?;
477        assert_eq!(code, 7, "the command's exit code is the job's exit code");
478        assert!(
479            job_dir.join("debug/.fingerprint/x-1122334455667788/lib-x").is_file(),
480            "the vault seeded the job"
481        );
482        Ok(())
483    }
484
485    #[cfg(unix)]
486    #[test]
487    fn exec_rm_removes_the_job_dir_either_way() -> Result<()> {
488        let (_build, store) = seeded_store()?;
489        let work = tempfile::tempdir()?;
490
491        let ok: Vec<String> = vec!["true".into()];
492        let opts = Options {
493            job_id: Some("j-ok"),
494            cwd: None,
495            harvest_back: false,
496            remove_on_success: true,
497            reuse: false,
498            target_dir: None,
499            command: &ok,
500        };
501        assert_eq!(run(store.path(), work.path(), &opts)?, 0);
502        assert!(!work.path().join("j-ok").exists(), "success -> removed");
503
504        // `--rm` is explicit: a failing build is removed too (the fixed
505        // rmeta-era failure mode used to leave dirs piling up here).
506        let bad: Vec<String> = vec!["false".into()];
507        let opts = Options {
508            job_id: Some("j-bad"),
509            cwd: None,
510            harvest_back: false,
511            remove_on_success: true,
512            reuse: false,
513            target_dir: None,
514            command: &bad,
515        };
516        assert_eq!(run(store.path(), work.path(), &opts)?, 1);
517        assert!(
518            !work.path().join("j-bad").exists(),
519            "--rm -> removed on failure too"
520        );
521
522        // Without --rm the dir stays for inspection.
523        let kept: Vec<String> = vec!["true".into()];
524        let opts = Options {
525            job_id: Some("j-keep"),
526            cwd: None,
527            harvest_back: false,
528            remove_on_success: false,
529            reuse: false,
530            target_dir: None,
531            command: &kept,
532        };
533        assert_eq!(run(store.path(), work.path(), &opts)?, 0);
534        assert!(
535            work.path().join("j-keep").exists(),
536            "no --rm -> kept for inspection"
537        );
538        Ok(())
539    }
540
541    #[test]
542    fn work_tier_summarizes_job_dirs() -> Result<()> {
543        let home = tempfile::tempdir()?;
544        let build = home.path().join("build");
545        fs::create_dir_all(&build)?;
546        let debug = home.path().join("work/ci-1/debug");
547        fs::create_dir_all(&debug)?;
548        fs::write(debug.join("a.bin"), [0u8; 100])?;
549        fs::write(debug.join("b.bin"), [0u8; 50])?;
550
551        let tier = work_tier(&build)?;
552        assert_eq!(tier.dirs, 1);
553        assert_eq!(tier.files, 2);
554        assert_eq!(tier.bytes, 150);
555        assert!(tier.newest.is_some());
556        assert_eq!(tier.entries.len(), 1);
557        assert_eq!(tier.entries[0].name, "ci-1");
558        assert_eq!(tier.entries[0].bytes, 150);
559        assert_eq!(tier.entries[0].files, 2);
560        Ok(())
561    }
562
563    #[test]
564    fn exec_refuses_a_used_job_dir() -> Result<()> {
565        let (_build, store) = seeded_store()?;
566        let work = tempfile::tempdir()?;
567        fs::create_dir_all(work.path().join("taken"))?;
568        let command: Vec<String> = vec!["true".into()];
569        let opts = Options {
570            job_id: Some("taken"),
571            cwd: None,
572            harvest_back: false,
573            remove_on_success: false,
574            reuse: false,
575            target_dir: None,
576            command: &command,
577        };
578        let err = run(store.path(), work.path(), &opts).unwrap_err();
579        assert!(err.to_string().contains("already exists"), "{err}");
580        assert!(err.to_string().contains("--reuse"), "mentions the way out");
581        Ok(())
582    }
583
584    #[test]
585    fn target_dir_resolution() {
586        let work = Path::new("/cache/work/ci-1");
587        let cwd = Path::new("/project");
588        assert_eq!(
589            resolve_target_dir("job", work, Some(cwd)),
590            PathBuf::from("/cache/work/ci-1/target")
591        );
592        assert_eq!(
593            resolve_target_dir("/abs/finals", work, Some(cwd)),
594            PathBuf::from("/abs/finals")
595        );
596        assert_eq!(
597            resolve_target_dir("rel/finals", work, Some(cwd)),
598            PathBuf::from("/project/rel/finals")
599        );
600    }
601
602    #[cfg(unix)]
603    #[test]
604    fn exec_reuse_continues_in_an_existing_dir() -> Result<()> {
605        let (_build, store) = seeded_store()?;
606        let work = tempfile::tempdir()?;
607        let ok: Vec<String> = vec!["true".into()];
608        let fresh = Options {
609            job_id: Some("j1"),
610            cwd: None,
611            harvest_back: false,
612            remove_on_success: false,
613            reuse: false,
614            target_dir: None,
615            command: &ok,
616        };
617        assert_eq!(run(store.path(), work.path(), &fresh)?, 0);
618
619        let err = run(store.path(), work.path(), &fresh).unwrap_err();
620        assert!(err.to_string().contains("already exists"), "{err}");
621
622        let again = Options {
623            reuse: true,
624            ..fresh
625        };
626        assert_eq!(run(store.path(), work.path(), &again)?, 0);
627        Ok(())
628    }
629
630    #[test]
631    fn exec_reuse_refuses_a_locked_dir() -> Result<()> {
632        let (_build, store) = seeded_store()?;
633        let work = tempfile::tempdir()?;
634        let debug = work.path().join("busy/debug");
635        fs::create_dir_all(&debug)?;
636        let lock = debug.join(".cargo-build-lock");
637        fs::write(&lock, b"")?;
638        let held = fs::OpenOptions::new().write(true).open(&lock)?;
639        held.try_lock().context("test holds the lock")?;
640
641        let cmd: Vec<String> = vec!["true".into()];
642        let opts = Options {
643            job_id: Some("busy"),
644            cwd: None,
645            harvest_back: false,
646            remove_on_success: false,
647            reuse: true,
648            target_dir: None,
649            command: &cmd,
650        };
651        let err = run(store.path(), work.path(), &opts).unwrap_err();
652        assert!(err.to_string().contains("in use"), "{err}");
653        Ok(())
654    }
655
656    #[cfg(unix)]
657    #[test]
658    fn exec_exports_a_per_job_target_dir() -> Result<()> {
659        let (_build, store) = seeded_store()?;
660        let work = tempfile::tempdir()?;
661        let job_dir = work.path().join("t1");
662        let command = vec![
663            "sh".to_string(),
664            "-c".to_string(),
665            format!(
666                "test \"$CARGO_TARGET_DIR\" = '{}'",
667                job_dir.join("target").display()
668            ),
669        ];
670        let opts = Options {
671            job_id: Some("t1"),
672            cwd: None,
673            harvest_back: false,
674            remove_on_success: false,
675            reuse: false,
676            target_dir: Some("job"),
677            command: &command,
678        };
679        assert_eq!(run(store.path(), work.path(), &opts)?, 0);
680        Ok(())
681    }
682}