zccache 1.12.9

Local-first compiler cache for C/C++/Rust/Emscripten
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
//! Integration tests for rustc compilation caching: basic single-crate paths.
//!
//! Covers single-output link caching, source-content differentiation,
//! `--emit=metadata` (cargo check), multi-output `--emit=dep-info,metadata,link`,
//! and extern-crate invalidation. Split out from
//! `daemon_rustc_cache_test.rs` so each integration-test binary stays small.

use zccache::core::NormalizedPath;
use zccache::daemon::DaemonServer;
use zccache::protocol::{Request, Response};

#[cfg(unix)]
type ClientConn = zccache::ipc::IpcConnection;
#[cfg(windows)]
type ClientConn = zccache::ipc::IpcClientConnection;

async fn start_daemon() -> (
    String,
    tokio::task::JoinHandle<()>,
    std::sync::Arc<tokio::sync::Notify>,
) {
    let endpoint = zccache::ipc::unique_test_endpoint();
    let mut server = DaemonServer::bind(&endpoint).unwrap();
    let shutdown = server.shutdown_handle();
    let handle = tokio::spawn(async move {
        server.run(0).await.unwrap();
    });
    (endpoint, handle, shutdown)
}

/// Helper: start session and return session ID.
async fn start_session(client: &mut ClientConn) -> String {
    client
        .send(&Request::SessionStart {
            client_pid: std::process::id(),
            working_dir: std::env::current_dir().unwrap().into(),
            log_file: None,
            track_stats: false,
            journal_path: None,
            profile: false,
            private_daemon: None,
        })
        .await
        .unwrap();

    match client.recv().await.unwrap() {
        Some(Response::SessionStarted { session_id, .. }) => session_id,
        other => panic!("expected SessionStarted, got: {other:?}"),
    }
}

/// Helper: compile via IPC and return (exit_code, cached).
async fn compile(
    client: &mut ClientConn,
    session_id: &str,
    compiler: &str,
    args: &[&str],
    cwd: &std::path::Path,
) -> (i32, bool) {
    client
        .send(&Request::Compile {
            session_id: session_id.to_string(),
            args: args.iter().map(|s| s.to_string()).collect(),
            cwd: cwd.to_path_buf().into(),
            compiler: NormalizedPath::new(compiler),
            env: None,
            stdin: Vec::new(),
        })
        .await
        .unwrap();

    match client.recv().await.unwrap() {
        Some(Response::CompileResult {
            exit_code, cached, ..
        }) => (exit_code, cached),
        Some(Response::Error { message }) => panic!("compile error: {message}"),
        other => panic!("unexpected response: {other:?}"),
    }
}

/// Simplest possible rustc caching test:
/// 1. Write a trivial lib.rs
/// 2. Compile with rustc --crate-type lib (cache miss)
/// 3. Delete output, compile again (cache hit)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore] // integration-level: starts real daemon with IPC + rustc
async fn test_rustc_lib_compile_cached() {
    let rustc = match zccache::test_support::find_rustc() {
        Some(p) => p,
        None => {
            eprintln!("skipping test: rustc not found");
            return;
        }
    };

    zccache::test_support::test_timeout(async move {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("lib.rs");
        let output = tmp.path().join("libhello.rlib");

        std::fs::write(&src, "pub fn hello() -> i32 { 42 }\n").unwrap();

        let (endpoint, server_handle, shutdown) = start_daemon().await;
        let mut client = zccache::ipc::connect(&endpoint).await.unwrap();
        let session_id = start_session(&mut client).await;

        let rustc_str = rustc.to_string_lossy().to_string();
        let src_str = src.to_string_lossy().to_string();
        let output_str = output.to_string_lossy().to_string();

        // First compile: cache miss
        let (exit_code, cached) = compile(
            &mut client,
            &session_id,
            &rustc_str,
            &[
                "--edition",
                "2021",
                "--crate-type",
                "lib",
                "--crate-name",
                "hello",
                "--emit=link",
                &src_str,
                "-o",
                &output_str,
            ],
            tmp.path(),
        )
        .await;
        assert_eq!(exit_code, 0, "first compile should succeed");
        assert!(!cached, "first compile should be a cache miss");
        assert!(output.exists(), "output file should exist after compile");

        // Delete output file
        std::fs::remove_file(&output).unwrap();
        assert!(!output.exists(), "output should be deleted");

        // Second compile: cache hit
        let (exit_code, cached) = compile(
            &mut client,
            &session_id,
            &rustc_str,
            &[
                "--edition",
                "2021",
                "--crate-type",
                "lib",
                "--crate-name",
                "hello",
                "--emit=link",
                &src_str,
                "-o",
                &output_str,
            ],
            tmp.path(),
        )
        .await;
        assert_eq!(exit_code, 0, "second compile should succeed");
        assert!(cached, "second compile should be a cache hit");
        assert!(output.exists(), "output should be restored from cache");

        shutdown.notify_one();
        server_handle.await.unwrap();
    })
    .await;
}

/// Test that different source content produces cache misses.
///
/// Uses separate daemon instances to avoid metadata cache state.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore] // integration-level: starts real daemon with IPC + rustc
async fn test_rustc_different_source_different_artifact() {
    let rustc = match zccache::test_support::find_rustc() {
        Some(p) => p,
        None => return,
    };

    zccache::test_support::test_timeout(async move {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("lib.rs");
        let output = tmp.path().join("libhello.rlib");

        let (endpoint, server_handle, shutdown) = start_daemon().await;
        let mut client = zccache::ipc::connect(&endpoint).await.unwrap();
        let session_id = start_session(&mut client).await;

        let rustc_str = rustc.to_string_lossy().to_string();
        let src_str = src.to_string_lossy().to_string();
        let output_str = output.to_string_lossy().to_string();

        // Compile version A
        std::fs::write(&src, "pub fn hello() -> i32 { 42 }\n").unwrap();
        let (exit_code, cached) = compile(
            &mut client,
            &session_id,
            &rustc_str,
            &[
                "--edition",
                "2021",
                "--crate-type",
                "lib",
                "--crate-name",
                "hello",
                "--emit=link",
                &src_str,
                "-o",
                &output_str,
            ],
            tmp.path(),
        )
        .await;
        assert_eq!(exit_code, 0);
        assert!(!cached, "first compile should be miss");
        let data_a = std::fs::read(&output).unwrap();

        // Compile version A again — should hit
        std::fs::remove_file(&output).unwrap();
        let (exit_code, cached) = compile(
            &mut client,
            &session_id,
            &rustc_str,
            &[
                "--edition",
                "2021",
                "--crate-type",
                "lib",
                "--crate-name",
                "hello",
                "--emit=link",
                &src_str,
                "-o",
                &output_str,
            ],
            tmp.path(),
        )
        .await;
        assert_eq!(exit_code, 0);
        assert!(cached, "same source should be cache hit");
        let data_a2 = std::fs::read(&output).unwrap();
        assert_eq!(data_a, data_a2, "cached output should match original");

        shutdown.notify_one();
        server_handle.await.unwrap();
    })
    .await;
}

/// Test --emit=metadata (cargo check) caching.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore] // integration-level: starts real daemon with IPC + rustc
async fn test_rustc_emit_metadata_cached() {
    let rustc = match zccache::test_support::find_rustc() {
        Some(p) => p,
        None => return,
    };

    zccache::test_support::test_timeout(async move {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("lib.rs");
        let output = tmp.path().join("libhello.rmeta");

        std::fs::write(&src, "pub fn hello() -> i32 { 42 }\n").unwrap();

        let (endpoint, server_handle, shutdown) = start_daemon().await;
        let mut client = zccache::ipc::connect(&endpoint).await.unwrap();
        let session_id = start_session(&mut client).await;

        let rustc_str = rustc.to_string_lossy().to_string();
        let src_str = src.to_string_lossy().to_string();
        let output_str = output.to_string_lossy().to_string();

        // Compile with --emit=metadata (cargo check mode)
        let args = &[
            "--edition",
            "2021",
            "--crate-type",
            "lib",
            "--crate-name",
            "hello",
            "--emit=metadata",
            &src_str,
            "-o",
            &output_str,
        ];

        // First compile: miss
        let (exit_code, cached) =
            compile(&mut client, &session_id, &rustc_str, args, tmp.path()).await;
        assert_eq!(exit_code, 0, "metadata compile should succeed");
        assert!(!cached, "first metadata compile should be miss");
        assert!(output.exists(), ".rmeta should exist");

        // Delete output
        std::fs::remove_file(&output).unwrap();

        // Second compile: hit
        let (exit_code, cached) =
            compile(&mut client, &session_id, &rustc_str, args, tmp.path()).await;
        assert_eq!(exit_code, 0);
        assert!(cached, "second metadata compile should be hit");
        assert!(output.exists(), ".rmeta should be restored from cache");

        shutdown.notify_one();
        server_handle.await.unwrap();
    })
    .await;
}

/// Test multi-output caching: --emit=dep-info,metadata,link produces 3 files.
/// This is what cargo actually passes to rustc.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore] // integration-level: starts real daemon with IPC + rustc
async fn test_rustc_multi_output_cached() {
    let rustc = match zccache::test_support::find_rustc() {
        Some(p) => p,
        None => return,
    };

    zccache::test_support::test_timeout(async move {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("lib.rs");
        let out_dir = tmp.path().join("deps");
        std::fs::create_dir_all(&out_dir).unwrap();

        std::fs::write(&src, "pub fn add(a: i32, b: i32) -> i32 { a + b }\n").unwrap();

        let (endpoint, server_handle, shutdown) = start_daemon().await;
        let mut client = zccache::ipc::connect(&endpoint).await.unwrap();
        let session_id = start_session(&mut client).await;

        let rustc_str = rustc.to_string_lossy().to_string();
        let src_str = src.to_string_lossy().to_string();
        let out_dir_str = out_dir.to_string_lossy().to_string();

        // Mimic what cargo actually invokes
        let args = &[
            "--edition",
            "2021",
            "--crate-type",
            "lib",
            "--crate-name",
            "hello",
            "--emit=dep-info,metadata,link",
            "-C",
            "embed-bitcode=no",
            "-C",
            "metadata=abc123",
            "-C",
            "extra-filename=-abc123",
            "--out-dir",
            &out_dir_str,
            &src_str,
        ];

        // First compile: miss
        let (exit_code, cached) =
            compile(&mut client, &session_id, &rustc_str, args, tmp.path()).await;
        assert_eq!(exit_code, 0, "first compile should succeed");
        assert!(!cached, "first compile should be miss");

        // Verify all 3 output files exist
        let rlib = out_dir.join("libhello-abc123.rlib");
        let rmeta = out_dir.join("libhello-abc123.rmeta");
        let depinfo = out_dir.join("hello-abc123.d");
        assert!(rlib.exists(), "rlib should exist: {}", rlib.display());
        assert!(rmeta.exists(), "rmeta should exist: {}", rmeta.display());
        assert!(
            depinfo.exists(),
            "dep-info should exist: {}",
            depinfo.display()
        );

        // Save originals for comparison
        let rlib_data = std::fs::read(&rlib).unwrap();
        let rmeta_data = std::fs::read(&rmeta).unwrap();

        // Delete all outputs
        std::fs::remove_file(&rlib).unwrap();
        std::fs::remove_file(&rmeta).unwrap();
        std::fs::remove_file(&depinfo).unwrap();

        // Second compile: should be cache hit with all files restored
        let (exit_code, cached) =
            compile(&mut client, &session_id, &rustc_str, args, tmp.path()).await;
        assert_eq!(exit_code, 0, "second compile should succeed");
        assert!(cached, "second compile should be cache hit");

        // All 3 files should be restored
        assert!(
            rlib.exists(),
            "rlib should be restored from cache: {}",
            rlib.display()
        );
        assert!(
            rmeta.exists(),
            "rmeta should be restored from cache: {}",
            rmeta.display()
        );
        assert!(
            depinfo.exists(),
            "dep-info should be restored from cache: {}",
            depinfo.display()
        );

        // Content should match
        assert_eq!(
            std::fs::read(&rlib).unwrap(),
            rlib_data,
            "rlib content should match"
        );
        assert_eq!(
            std::fs::read(&rmeta).unwrap(),
            rmeta_data,
            "rmeta content should match"
        );

        shutdown.notify_one();
        server_handle.await.unwrap();
    })
    .await;
}

/// Test that changing an extern crate invalidates the cache.
///
/// 1. Compile crate A → libA.rlib
/// 2. Compile crate B with --extern a=libA.rlib → cache miss
/// 3. Compile crate B again → cache hit
/// 4. Change A's source, recompile A → new libA.rlib
/// 5. Compile crate B again → cache miss (extern content changed)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore] // integration-level: starts real daemon with IPC + rustc
async fn test_rustc_extern_change_invalidates() {
    let rustc = match zccache::test_support::find_rustc() {
        Some(p) => p,
        None => return,
    };

    zccache::test_support::test_timeout(async move {
        let tmp = tempfile::tempdir().unwrap();
        let src_a = tmp.path().join("a.rs");
        let src_b = tmp.path().join("b.rs");
        let lib_a = tmp.path().join("liba.rlib");
        let lib_b = tmp.path().join("libb.rlib");

        // Crate A: a simple lib
        std::fs::write(&src_a, "pub fn value() -> i32 { 42 }\n").unwrap();
        // Crate B: depends on A
        std::fs::write(
            &src_b,
            "extern crate a; pub fn double() -> i32 { a::value() * 2 }\n",
        )
        .unwrap();

        let (endpoint, server_handle, shutdown) = start_daemon().await;
        let mut client = zccache::ipc::connect(&endpoint).await.unwrap();
        let session_id = start_session(&mut client).await;

        let rustc_str = rustc.to_string_lossy().to_string();
        let src_a_str = src_a.to_string_lossy().to_string();
        let src_b_str = src_b.to_string_lossy().to_string();
        let lib_a_str = lib_a.to_string_lossy().to_string();
        let lib_b_str = lib_b.to_string_lossy().to_string();

        // Step 1: Compile crate A
        let (exit_code, _) = compile(
            &mut client,
            &session_id,
            &rustc_str,
            &[
                "--edition",
                "2021",
                "--crate-type",
                "lib",
                "--crate-name",
                "a",
                "--emit=link",
                &src_a_str,
                "-o",
                &lib_a_str,
            ],
            tmp.path(),
        )
        .await;
        assert_eq!(exit_code, 0, "crate A compile should succeed");
        assert!(lib_a.exists());

        // Step 2: Compile crate B with --extern a=libA.rlib (miss)
        let extern_arg = format!("a={lib_a_str}");
        let b_args = &[
            "--edition",
            "2021",
            "--crate-type",
            "lib",
            "--crate-name",
            "b",
            "--emit=link",
            "--extern",
            &extern_arg,
            &src_b_str,
            "-o",
            &lib_b_str,
        ];
        let (exit_code, cached) =
            compile(&mut client, &session_id, &rustc_str, b_args, tmp.path()).await;
        assert_eq!(exit_code, 0, "crate B first compile should succeed");
        assert!(!cached, "crate B first compile should be miss");

        // Step 3: Compile B again (hit)
        std::fs::remove_file(&lib_b).unwrap();
        let (exit_code, cached) =
            compile(&mut client, &session_id, &rustc_str, b_args, tmp.path()).await;
        assert_eq!(exit_code, 0);
        assert!(cached, "crate B second compile should be hit");

        // Step 4: Change A's source, recompile A
        std::thread::sleep(std::time::Duration::from_millis(1100));
        std::fs::write(&src_a, "pub fn value() -> i32 { 99 }\n").unwrap();
        let (exit_code, _) = compile(
            &mut client,
            &session_id,
            &rustc_str,
            &[
                "--edition",
                "2021",
                "--crate-type",
                "lib",
                "--crate-name",
                "a",
                "--emit=link",
                &src_a_str,
                "-o",
                &lib_a_str,
            ],
            tmp.path(),
        )
        .await;
        assert_eq!(exit_code, 0, "crate A recompile should succeed");

        // Step 5: Compile B again — should be miss because extern A changed
        std::fs::remove_file(&lib_b).unwrap();
        let (exit_code, cached) =
            compile(&mut client, &session_id, &rustc_str, b_args, tmp.path()).await;
        assert_eq!(exit_code, 0, "crate B third compile should succeed");
        assert!(
            !cached,
            "crate B should be cache miss after extern A changed"
        );

        shutdown.notify_one();
        server_handle.await.unwrap();
    })
    .await;
}