zccache-core 1.5.0

Shared core types and utilities for zccache
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Configuration types for zccache.

use crate::NormalizedPath;
use std::ffi::OsString;
use std::path::Path;

/// Environment variable used to override the zccache cache root.
pub const CACHE_DIR_ENV: &str = "ZCCACHE_CACHE_DIR";

/// Top-level configuration for zccache.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct Config {
    /// Path to the artifact cache directory.
    pub cache_dir: NormalizedPath,
    /// Maximum artifact cache size in bytes.
    pub max_cache_size: u64,
    /// Daemon idle timeout in seconds before auto-shutdown.
    pub idle_timeout_secs: u64,
    /// Whether to enable the file watcher.
    pub enable_watcher: bool,
    /// Whether to use polling fallback for file watching.
    pub watcher_poll_fallback: bool,
    /// Log level filter (e.g., "info", "debug", "trace").
    pub log_level: String,
    /// Maximum in-memory cache budget in bytes (default: 1 GB).
    pub max_memory_bytes: u64,
    /// How often (in seconds) the memory eviction background task runs (default: 30).
    pub eviction_interval_secs: u64,
    /// How often (in seconds) the disk artifact GC task runs (default: 300).
    pub disk_gc_interval_secs: u64,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            cache_dir: default_cache_dir(),
            max_cache_size: 10 * 1024 * 1024 * 1024, // 10 GB
            idle_timeout_secs: 3600,
            enable_watcher: true,
            watcher_poll_fallback: false,
            log_level: String::from("info"),
            max_memory_bytes: 1_073_741_824, // 1 GB
            eviction_interval_secs: 30,
            disk_gc_interval_secs: 300,
        }
    }
}

/// Returns the configured cache directory path.
///
/// If `ZCCACHE_CACHE_DIR` is set and non-empty, it is used as the cache root.
/// Relative override paths are made absolute against the current working
/// directory so the daemon and CLI derive the same subpaths when spawned
/// together. If unset, this falls back to `~/.zccache` on all platforms.
#[must_use]
pub fn default_cache_dir() -> NormalizedPath {
    default_cache_dir_from_env_value(std::env::var_os(CACHE_DIR_ENV))
}

fn default_cache_dir_from_env_value(value: Option<OsString>) -> NormalizedPath {
    cache_dir_from_env_value(value).unwrap_or_else(|| dirs_fallback().join(".zccache"))
}

/// Returns the cache directory override from `ZCCACHE_CACHE_DIR`, if set.
#[must_use]
pub fn cache_dir_override() -> Option<NormalizedPath> {
    cache_dir_from_env_value(std::env::var_os(CACHE_DIR_ENV))
}

/// Returns the directory for content-addressed compiled outputs.
#[must_use]
pub fn artifacts_dir() -> NormalizedPath {
    artifacts_dir_from_cache_dir(&default_cache_dir())
}

/// Returns the directory for in-progress artifact writes (cleaned on startup).
#[must_use]
pub fn tmp_dir() -> NormalizedPath {
    tmp_dir_from_cache_dir(&default_cache_dir())
}

/// Returns the base directory for compiler-injected depfiles.
///
/// Each daemon instance creates a `{pid}-{instance}` subdirectory here.
/// Stale subdirectories from dead daemon processes are cleaned on startup.
#[must_use]
pub fn depfile_dir() -> NormalizedPath {
    depfile_dir_from_cache_dir(&default_cache_dir())
}

/// Remove legacy zccache state left directly under the OS temp directory.
///
/// Older builds stored the full cache root at `%TEMP%/.zccache` and created
/// depfile directories as `%TEMP%/zccache-depfiles-*`. Those paths are safe to
/// remove only when they are exact legacy matches and do not point at the
/// current cache directory.
pub fn cleanup_legacy_temp_root_state<F>(
    temp_root: &Path,
    current_cache_dir: &Path,
    is_alive: F,
) -> usize
where
    F: Fn(u32) -> bool,
{
    let mut cleaned = cleanup_legacy_temp_cache_dir(temp_root, current_cache_dir);
    cleaned += cleanup_legacy_temp_depfile_dirs(temp_root, is_alive);
    cleaned
}

/// Remove stale depfile directories from previous (dead) daemon instances.
///
/// Scans [`depfile_dir()`] for subdirectories matching `{pid}-{instance}`.
/// If the PID is no longer alive (per `is_alive`), removes the directory.
/// Returns the number of directories cleaned up.
pub fn cleanup_stale_depfile_dirs<F>(is_alive: F) -> usize
where
    F: Fn(u32) -> bool,
{
    let base = depfile_dir();
    let entries = match std::fs::read_dir(&base) {
        Ok(entries) => entries,
        Err(_) => return 0,
    };

    let mut cleaned = 0;
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let name = match path.file_name().and_then(|n| n.to_str()) {
            Some(n) => n,
            None => continue,
        };
        let pid: u32 = match name.split('-').next().and_then(|s| s.parse().ok()) {
            Some(p) => p,
            None => continue,
        };
        if !is_alive(pid) {
            match std::fs::remove_dir_all(&path) {
                Ok(()) => {
                    cleaned += 1;
                    tracing::info!(path = %path.display(), "removed stale depfile dir");
                }
                Err(e) => {
                    tracing::warn!(
                        path = %path.display(),
                        "failed to remove stale depfile dir: {e}"
                    );
                }
            }
        }
    }
    cleaned
}

fn cleanup_legacy_temp_cache_dir(temp_root: &Path, current_cache_dir: &Path) -> usize {
    let legacy_cache_dir = temp_root.join(".zccache");
    if path_is_or_contains(&legacy_cache_dir, current_cache_dir) {
        return 0;
    }

    if !is_real_dir(&legacy_cache_dir) {
        return 0;
    }

    match std::fs::remove_dir_all(&legacy_cache_dir) {
        Ok(()) => {
            tracing::info!(path = %legacy_cache_dir.display(), "removed legacy temp cache dir");
            1
        }
        Err(e) => {
            tracing::warn!(
                path = %legacy_cache_dir.display(),
                "failed to remove legacy temp cache dir: {e}"
            );
            0
        }
    }
}

fn cleanup_legacy_temp_depfile_dirs<F>(temp_root: &Path, is_alive: F) -> usize
where
    F: Fn(u32) -> bool,
{
    let entries = match std::fs::read_dir(temp_root) {
        Ok(entries) => entries,
        Err(_) => return 0,
    };

    let mut cleaned = 0;
    for entry in entries.flatten() {
        let path = entry.path();
        let file_name = entry.file_name();
        let name = match file_name.to_str() {
            Some(name) if name.starts_with("zccache-depfiles-") => name,
            _ => continue,
        };

        if !is_real_dir(&path) {
            continue;
        }

        let pid = match legacy_temp_depfile_pid(name) {
            Some(pid) => pid,
            None => continue,
        };

        if is_alive(pid) {
            continue;
        }

        match std::fs::remove_dir_all(&path) {
            Ok(()) => {
                cleaned += 1;
                tracing::info!(path = %path.display(), "removed legacy temp depfile dir");
            }
            Err(e) => {
                tracing::warn!(
                    path = %path.display(),
                    "failed to remove legacy temp depfile dir: {e}"
                );
            }
        }
    }
    cleaned
}

fn legacy_temp_depfile_pid(name: &str) -> Option<u32> {
    let suffix = name.strip_prefix("zccache-depfiles-")?;
    suffix.split('-').next()?.parse().ok()
}

fn is_real_dir(path: &Path) -> bool {
    std::fs::symlink_metadata(path)
        .map(|meta| meta.file_type().is_dir())
        .unwrap_or(false)
}

fn path_is_or_contains(parent: &Path, child: &Path) -> bool {
    if child.starts_with(parent) {
        return true;
    }

    let parent = match std::fs::canonicalize(parent) {
        Ok(parent) => parent,
        Err(_) => return false,
    };
    std::fs::canonicalize(child)
        .map(|child| child.starts_with(parent))
        .unwrap_or(false)
}

/// Returns the directory for serialized dependency graph storage (future).
#[must_use]
pub fn depgraph_dir() -> NormalizedPath {
    depgraph_dir_from_cache_dir(&default_cache_dir())
}

/// Returns the path to the artifact index database.
#[must_use]
pub fn index_path() -> NormalizedPath {
    index_path_from_cache_dir(&default_cache_dir())
}

/// Returns the directory for crash dump files.
#[must_use]
pub fn crash_dump_dir() -> NormalizedPath {
    crash_dump_dir_from_cache_dir(&default_cache_dir())
}

/// Returns the directory for daemon log files.
#[must_use]
pub fn log_dir() -> NormalizedPath {
    log_dir_from_cache_dir(&default_cache_dir())
}

fn artifacts_dir_from_cache_dir(cache_dir: &NormalizedPath) -> NormalizedPath {
    cache_dir.join("artifacts")
}

fn tmp_dir_from_cache_dir(cache_dir: &NormalizedPath) -> NormalizedPath {
    cache_dir.join("tmp")
}

fn depfile_dir_from_cache_dir(cache_dir: &NormalizedPath) -> NormalizedPath {
    tmp_dir_from_cache_dir(cache_dir).join("depfiles")
}

fn depgraph_dir_from_cache_dir(cache_dir: &NormalizedPath) -> NormalizedPath {
    cache_dir.join("depgraph")
}

fn index_path_from_cache_dir(cache_dir: &NormalizedPath) -> NormalizedPath {
    cache_dir.join("index.redb")
}

fn crash_dump_dir_from_cache_dir(cache_dir: &NormalizedPath) -> NormalizedPath {
    cache_dir.join("crashes")
}

fn log_dir_from_cache_dir(cache_dir: &NormalizedPath) -> NormalizedPath {
    cache_dir.join("logs")
}

fn dirs_fallback() -> NormalizedPath {
    std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .map(NormalizedPath::from)
        .unwrap_or_else(|_| ".".into())
}

fn cache_dir_from_env_value(value: Option<OsString>) -> Option<NormalizedPath> {
    let value = value?;
    if value.is_empty() {
        return None;
    }
    Some(normalize_cache_dir_override(std::path::Path::new(&value)))
}

fn normalize_cache_dir_override(path: &std::path::Path) -> NormalizedPath {
    if path.is_absolute() {
        path.into()
    } else {
        std::env::current_dir()
            .unwrap_or_default()
            .join(path)
            .into()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_cache_dir_ends_with_zccache() {
        let dir = default_cache_dir_from_env_value(None);
        assert!(dir.ends_with(".zccache"));
    }

    #[test]
    fn cache_dir_override_uses_non_empty_env_value() {
        let root = tempfile::tempdir().unwrap();
        let override_dir = root.path().join("zc");
        let cache_dir =
            default_cache_dir_from_env_value(Some(override_dir.clone().into_os_string()));

        assert_eq!(cache_dir, override_dir);
        assert_eq!(
            artifacts_dir_from_cache_dir(&cache_dir),
            override_dir.join("artifacts")
        );
        assert_eq!(tmp_dir_from_cache_dir(&cache_dir), override_dir.join("tmp"));
        assert_eq!(
            depgraph_dir_from_cache_dir(&cache_dir),
            override_dir.join("depgraph")
        );
        assert_eq!(
            index_path_from_cache_dir(&cache_dir),
            override_dir.join("index.redb")
        );
        assert_eq!(
            crash_dump_dir_from_cache_dir(&cache_dir),
            override_dir.join("crashes")
        );
        assert_eq!(
            log_dir_from_cache_dir(&cache_dir),
            override_dir.join("logs")
        );
    }

    #[test]
    fn cache_dir_override_ignores_empty_env_value() {
        assert!(cache_dir_from_env_value(Some(OsString::new())).is_none());
    }

    #[test]
    fn relative_cache_dir_override_is_made_absolute() {
        let override_dir = cache_dir_from_env_value(Some(OsString::from("target/../zc"))).unwrap();
        assert!(override_dir.is_absolute());
        assert!(override_dir.ends_with("zc"));
    }

    #[test]
    fn crash_dump_dir_ends_with_crashes() {
        let (_temp, cache) = temp_cache_dir();
        let dir = crash_dump_dir_from_cache_dir(&cache);
        assert!(dir.ends_with("crashes"));
    }

    #[test]
    fn crash_dump_dir_is_under_cache_dir() {
        let (_temp, cache) = temp_cache_dir();
        let crashes = crash_dump_dir_from_cache_dir(&cache);
        assert!(crashes.starts_with(&cache));
    }

    #[test]
    fn log_dir_ends_with_logs() {
        let (_temp, cache) = temp_cache_dir();
        let dir = log_dir_from_cache_dir(&cache);
        assert!(dir.ends_with("logs"));
    }

    #[test]
    fn log_dir_is_under_cache_dir() {
        let (_temp, cache) = temp_cache_dir();
        let logs = log_dir_from_cache_dir(&cache);
        assert!(logs.starts_with(&cache));
    }

    #[test]
    fn artifacts_dir_ends_with_artifacts() {
        let (_temp, cache) = temp_cache_dir();
        let dir = artifacts_dir_from_cache_dir(&cache);
        assert!(dir.ends_with("artifacts"));
        assert!(dir.starts_with(cache));
    }

    #[test]
    fn tmp_dir_ends_with_tmp() {
        let (_temp, cache) = temp_cache_dir();
        let dir = tmp_dir_from_cache_dir(&cache);
        assert!(dir.ends_with("tmp"));
        assert!(dir.starts_with(cache));
    }

    #[test]
    fn depgraph_dir_ends_with_depgraph() {
        let (_temp, cache) = temp_cache_dir();
        let dir = depgraph_dir_from_cache_dir(&cache);
        assert!(dir.ends_with("depgraph"));
        assert!(dir.starts_with(cache));
    }

    #[test]
    fn depfile_dir_under_tmp() {
        let (_temp, cache) = temp_cache_dir();
        let tmp = tmp_dir_from_cache_dir(&cache);
        let dir = depfile_dir_from_cache_dir(&cache);
        assert!(dir.ends_with("depfiles"));
        assert!(dir.starts_with(tmp));
    }

    #[test]
    fn cleanup_stale_depfile_dirs_removes_dead() {
        let base = tempfile::tempdir().unwrap();
        let depfiles = base.path().join("depfiles");
        std::fs::create_dir_all(&depfiles).unwrap();

        // Create a "dead" dir (PID 99999999 unlikely alive).
        std::fs::create_dir(depfiles.join("99999999-0")).unwrap();
        // Create a non-matching dir (should be left alone).
        std::fs::create_dir(depfiles.join("not-a-pid")).unwrap();

        let entries = std::fs::read_dir(&depfiles).unwrap();
        let dirs: Vec<_> = entries.flatten().collect();
        assert_eq!(dirs.len(), 2);

        // Use a custom is_alive that says nothing is alive.
        let cleaned = cleanup_stale_with_base(&depfiles, |_| false);
        assert_eq!(cleaned, 1); // only the parseable one removed

        // "not-a-pid" should still exist.
        assert!(depfiles.join("not-a-pid").is_dir());
        assert!(!depfiles.join("99999999-0").exists());
    }

    #[test]
    fn cleanup_stale_depfile_dirs_skips_alive() {
        let base = tempfile::tempdir().unwrap();
        let depfiles = base.path().join("depfiles");
        std::fs::create_dir_all(&depfiles).unwrap();
        std::fs::create_dir(depfiles.join("12345-0")).unwrap();

        let cleaned = cleanup_stale_with_base(&depfiles, |_| true);
        assert_eq!(cleaned, 0);
        assert!(depfiles.join("12345-0").is_dir());
    }

    #[test]
    fn cleanup_stale_depfile_dirs_empty() {
        // Non-existent directory returns 0.
        let cleaned = cleanup_stale_with_base(std::path::Path::new("/nonexistent/path"), |_| false);
        assert_eq!(cleaned, 0);
    }

    #[test]
    fn cleanup_legacy_temp_root_state_removes_legacy_dirs() {
        let temp_root = tempfile::tempdir().unwrap();
        let current_cache_dir = tempfile::tempdir().unwrap();

        let legacy_cache = temp_root.path().join(".zccache");
        std::fs::create_dir_all(&legacy_cache).unwrap();
        std::fs::write(legacy_cache.join("sentinel"), "legacy").unwrap();

        let dead_depfile = temp_root.path().join("zccache-depfiles-1234-0");
        std::fs::create_dir_all(&dead_depfile).unwrap();
        std::fs::write(dead_depfile.join("sentinel"), "dead").unwrap();

        let live_depfile = temp_root.path().join("zccache-depfiles-4321-0");
        std::fs::create_dir_all(&live_depfile).unwrap();

        let unrelated = temp_root.path().join("not-legacy");
        std::fs::create_dir_all(&unrelated).unwrap();

        let cleaned =
            cleanup_legacy_temp_root_state(temp_root.path(), current_cache_dir.path(), |pid| {
                pid != 1234
            });

        assert_eq!(cleaned, 2);
        assert!(!legacy_cache.exists());
        assert!(!dead_depfile.exists());
        assert!(live_depfile.exists());
        assert!(unrelated.exists());
    }

    #[test]
    fn cleanup_legacy_temp_root_state_skips_current_cache_dir() {
        let temp_root = tempfile::tempdir().unwrap();
        let current_cache_dir = temp_root.path().join(".zccache");
        std::fs::create_dir_all(&current_cache_dir).unwrap();
        std::fs::write(current_cache_dir.join("sentinel"), "keep").unwrap();

        let cleaned =
            cleanup_legacy_temp_root_state(temp_root.path(), &current_cache_dir, |_| false);

        assert_eq!(cleaned, 0);
        assert!(current_cache_dir.exists());
        assert_eq!(
            std::fs::read_to_string(current_cache_dir.join("sentinel")).unwrap(),
            "keep"
        );
    }

    #[test]
    fn cleanup_legacy_temp_root_state_skips_parent_of_current_cache_dir() {
        let temp_root = tempfile::tempdir().unwrap();
        let current_cache_dir = temp_root.path().join(".zccache").join("current");
        std::fs::create_dir_all(&current_cache_dir).unwrap();
        std::fs::write(current_cache_dir.join("sentinel"), "keep").unwrap();

        let cleaned =
            cleanup_legacy_temp_root_state(temp_root.path(), &current_cache_dir, |_| false);

        assert_eq!(cleaned, 0);
        assert!(current_cache_dir.exists());
        assert_eq!(
            std::fs::read_to_string(current_cache_dir.join("sentinel")).unwrap(),
            "keep"
        );
    }

    /// Test helper: runs cleanup logic against an arbitrary base dir.
    fn cleanup_stale_with_base<F>(base: &std::path::Path, is_alive: F) -> usize
    where
        F: Fn(u32) -> bool,
    {
        let entries = match std::fs::read_dir(base) {
            Ok(entries) => entries,
            Err(_) => return 0,
        };
        let mut cleaned = 0;
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            let name = match path.file_name().and_then(|n| n.to_str()) {
                Some(n) => n,
                None => continue,
            };
            let pid: u32 = match name.split('-').next().and_then(|s| s.parse().ok()) {
                Some(p) => p,
                None => continue,
            };
            if !is_alive(pid) && std::fs::remove_dir_all(&path).is_ok() {
                cleaned += 1;
            }
        }
        cleaned
    }

    #[test]
    fn disk_gc_interval_default() {
        let config = Config::default();
        assert_eq!(config.disk_gc_interval_secs, 300);
    }

    #[test]
    fn index_path_ends_with_redb() {
        let (_temp, cache) = temp_cache_dir();
        let p = index_path_from_cache_dir(&cache);
        assert!(p.ends_with("index.redb"));
        assert!(p.starts_with(cache));
    }

    fn temp_cache_dir() -> (tempfile::TempDir, NormalizedPath) {
        let temp = tempfile::tempdir().unwrap();
        let cache = NormalizedPath::from(temp.path());
        (temp, cache)
    }
}