kache 0.8.0

Zero-copy, content-addressed build cache for Rust, C/C++ and more. No copies, no wasted disk — just hardlinks locally and S3 for sharing.
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
use std::collections::HashSet;
use std::path::{Path, PathBuf};

use crate::args::RustcArgs;
use guppy::graph::{DependencyDirection, PackageGraph};
use kache_core::BuildIntent;

struct MetadataDiscovery {
    crate_names: Vec<String>,
    workspace_root: Option<PathBuf>,
}

pub fn discover(args: Option<&RustcArgs>) -> Option<BuildIntent> {
    let metadata = discover_metadata(args)?;
    let crate_names = metadata.crate_names;
    if crate_names.is_empty() {
        return None;
    }

    let namespace = std::env::var("KACHE_NAMESPACE")
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty());

    let lock_path = metadata
        .workspace_root
        .as_deref()
        .map(|root| root.join("Cargo.lock"))
        .unwrap_or_else(|| PathBuf::from("Cargo.lock"));
    let cargo_lock_deps = namespace
        .as_ref()
        .and_then(|_| load_cargo_lock_deps(&lock_path))
        .unwrap_or_default();

    Some(BuildIntent {
        crate_names,
        namespace,
        cargo_lock_deps,
    })
}

pub fn into_build_started_request(
    intent: BuildIntent,
    client_epoch: u64,
) -> crate::daemon::BuildStartedRequest {
    crate::daemon::BuildStartedRequest {
        intent,
        client_epoch,
    }
}

fn load_cargo_lock_deps(lock_path: &Path) -> Option<Vec<(String, String)>> {
    crate::shards::parse_cargo_lock(lock_path)
        .map_err(|err| {
            tracing::debug!(
                "build intent: failed to parse {} for shard prefetch: {}",
                lock_path.display(),
                err
            );
            err
        })
        .ok()
}

fn discover_metadata(args: Option<&RustcArgs>) -> Option<MetadataDiscovery> {
    for manifest_path in candidate_manifest_paths(args) {
        if let Some(discovery) = run_cargo_metadata(Some(&manifest_path)) {
            return Some(discovery);
        }
    }

    run_cargo_metadata(None)
}

fn candidate_manifest_paths(args: Option<&RustcArgs>) -> Vec<PathBuf> {
    let mut candidates = Vec::new();

    if let Some(out_dir) = args.and_then(|a| a.out_dir.as_deref())
        && let Some(path) = manifest_from_target_out_dir(out_dir)
        && path.is_file()
    {
        candidates.push(path);
    }

    if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
        let path = PathBuf::from(manifest_dir).join("Cargo.toml");
        if path.is_file() && !candidates.iter().any(|existing| existing == &path) {
            candidates.push(path);
        }
    }

    candidates
}

fn manifest_from_target_out_dir(out_dir: &Path) -> Option<PathBuf> {
    for ancestor in out_dir.ancestors() {
        if ancestor.file_name().and_then(|name| name.to_str()) == Some("target") {
            return ancestor.parent().map(|root| root.join("Cargo.toml"));
        }
    }
    None
}

fn run_cargo_metadata(manifest_path: Option<&Path>) -> Option<MetadataDiscovery> {
    let mut command = std::process::Command::new("cargo");
    command
        .args(["metadata", "--format-version", "1"])
        .env_remove("RUSTC_WRAPPER")
        .env_remove("RUSTC_WORKSPACE_WRAPPER")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null());

    if let Some(path) = manifest_path {
        command.arg("--manifest-path").arg(path);
    }

    let output = command.output().ok()?;

    if !output.status.success() {
        return None;
    }

    parse_metadata_graph(&output.stdout, manifest_path)
}

fn parse_metadata_graph(
    metadata_json: &[u8],
    manifest_path: Option<&Path>,
) -> Option<MetadataDiscovery> {
    let graph = PackageGraph::from_json(std::str::from_utf8(metadata_json).ok()?).ok()?;
    let crate_names = graph_crate_order(&graph, manifest_path)?;
    let workspace_root = Some(graph.workspace().root().as_std_path().to_path_buf());

    Some(MetadataDiscovery {
        crate_names,
        workspace_root,
    })
}

fn graph_crate_order(graph: &PackageGraph, manifest_path: Option<&Path>) -> Option<Vec<String>> {
    let package_ids = if let Some(manifest_path) = manifest_path
        && let Some(package) = graph
            .packages()
            .find(|package| paths_match(package.manifest_path().as_std_path(), manifest_path))
    {
        vec![package.id().clone()]
    } else {
        graph
            .workspace()
            .iter()
            .map(|package| package.id().clone())
            .collect::<Vec<_>>()
    };

    let package_set = graph.query_forward(package_ids.iter()).ok()?.resolve();
    let mut seen = HashSet::new();
    let mut ordered = Vec::new();

    for package in package_set.packages(DependencyDirection::Reverse) {
        let name = package.name().to_string();
        if seen.insert(name.clone()) {
            ordered.push(name);
        }
    }

    Some(ordered)
}

fn paths_match(left: &Path, right: &Path) -> bool {
    if left == right {
        return true;
    }

    match (std::fs::canonicalize(left), std::fs::canonicalize(right)) {
        (Ok(left), Ok(right)) => left == right,
        _ => false,
    }
}

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

    #[test]
    fn test_run_cargo_metadata_uses_guppy_graph_and_workspace_root() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();

        std::fs::write(
            root.join("Cargo.toml"),
            r#"[workspace]
members = ["app", "dep", "unrelated"]
resolver = "2"
"#,
        )
        .unwrap();

        std::fs::create_dir_all(root.join("app/src")).unwrap();
        std::fs::write(
            root.join("app/Cargo.toml"),
            r#"[package]
name = "app"
version = "0.1.0"
edition = "2021"

[dependencies]
dep = { path = "../dep" }
"#,
        )
        .unwrap();
        std::fs::write(root.join("app/src/lib.rs"), "").unwrap();

        std::fs::create_dir_all(root.join("dep/src")).unwrap();
        std::fs::write(
            root.join("dep/Cargo.toml"),
            r#"[package]
name = "dep"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::write(root.join("dep/src/lib.rs"), "").unwrap();

        std::fs::create_dir_all(root.join("unrelated/src")).unwrap();
        std::fs::write(
            root.join("unrelated/Cargo.toml"),
            r#"[package]
name = "unrelated"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::write(root.join("unrelated/src/lib.rs"), "").unwrap();

        let discovery = run_cargo_metadata(Some(&root.join("app/Cargo.toml"))).unwrap();
        assert_eq!(discovery.crate_names, vec!["dep", "app"]);
        assert_eq!(discovery.workspace_root.as_deref(), Some(root));
    }

    #[test]
    fn test_manifest_from_target_out_dir_uses_target_parent() {
        let manifest = manifest_from_target_out_dir(Path::new(
            "/repo/apps/tauri/src-tauri/target/release/deps",
        ))
        .unwrap();

        assert_eq!(manifest, Path::new("/repo/apps/tauri/src-tauri/Cargo.toml"));
    }

    #[test]
    fn test_manifest_from_target_out_dir_without_target_is_none() {
        // No `target` component in the path -> nothing to anchor on.
        assert!(manifest_from_target_out_dir(Path::new("/repo/src/deps")).is_none());
    }

    #[test]
    fn test_manifest_from_target_out_dir_picks_nearest_target() {
        // `ancestors()` walks from the leaf upward, so the *deepest* `target`
        // wins when the path is nested (e.g. a workspace target inside a repo
        // that itself sits under another `target`).
        let manifest =
            manifest_from_target_out_dir(Path::new("/work/target/x/inner/target/release/deps"))
                .unwrap();
        assert_eq!(manifest, Path::new("/work/target/x/inner/Cargo.toml"));
    }

    #[test]
    fn test_paths_match_identical_paths() {
        assert!(paths_match(
            Path::new("/some/where/Cargo.toml"),
            Path::new("/some/where/Cargo.toml"),
        ));
    }

    #[test]
    fn test_paths_match_distinct_nonexistent_paths_do_not_match() {
        // Different paths that can't be canonicalized fall through to false.
        assert!(!paths_match(
            Path::new("/nonexistent/a/Cargo.toml"),
            Path::new("/nonexistent/b/Cargo.toml"),
        ));
    }

    // Unix-only: creating a symlink on Windows needs Developer Mode / admin
    // privileges, which CI runners lack. The canonicalization logic under test
    // is platform-shared and covered here on Linux/macOS.
    #[cfg(unix)]
    #[test]
    fn test_paths_match_canonicalizes_equivalent_paths() {
        // A symlink and its target canonicalize to the same real path.
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("Cargo.toml");
        std::fs::write(&real, "").unwrap();
        let link = dir.path().join("link.toml");
        std::os::unix::fs::symlink(&real, &link).unwrap();
        assert!(paths_match(&link, &real));
    }

    #[test]
    fn test_parse_metadata_graph_rejects_invalid_json() {
        assert!(parse_metadata_graph(b"not json at all", None).is_none());
    }

    #[test]
    fn test_parse_metadata_graph_rejects_invalid_utf8() {
        assert!(parse_metadata_graph(&[0xff, 0xfe, 0x00], None).is_none());
    }

    /// Build a minimal two-member cargo workspace under a temp dir and return
    /// its root. `app` depends on `dep`.
    fn scaffold_workspace() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"app\", \"dep\"]\nresolver = \"2\"\n",
        )
        .unwrap();
        std::fs::create_dir_all(root.join("app/src")).unwrap();
        std::fs::write(
            root.join("app/Cargo.toml"),
            "[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\
             [dependencies]\ndep = { path = \"../dep\" }\n",
        )
        .unwrap();
        std::fs::write(root.join("app/src/lib.rs"), "").unwrap();
        std::fs::create_dir_all(root.join("dep/src")).unwrap();
        std::fs::write(
            root.join("dep/Cargo.toml"),
            "[package]\nname = \"dep\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        std::fs::write(root.join("dep/src/lib.rs"), "").unwrap();
        dir
    }

    #[test]
    fn discover_builds_intent_from_out_dir_args() {
        // `discover` resolves the manifest from a rustc --out-dir that sits under
        // a `target/` tree (candidate_manifest_paths -> manifest_from_target_out_dir),
        // runs cargo metadata, and returns the workspace crate order. Covers
        // discover + discover_metadata + candidate_manifest_paths end-to-end.
        let ws = scaffold_workspace();
        let root = ws.path();
        let out_dir = root.join("target/debug/deps");
        std::fs::create_dir_all(&out_dir).unwrap();

        let args = RustcArgs::parse(&[
            "rustc".to_string(),
            "--out-dir".to_string(),
            out_dir.to_string_lossy().into_owned(),
        ])
        .unwrap();

        let intent = discover(Some(&args)).expect("discover should resolve the workspace");
        // dep is a dependency of app, so reverse topo order lists dep before app.
        assert!(intent.crate_names.contains(&"app".to_string()));
        assert!(intent.crate_names.contains(&"dep".to_string()));
        // No KACHE_NAMESPACE set in the common case -> no namespace, no lock deps.
        assert!(intent.namespace.is_none());
    }

    #[test]
    fn run_cargo_metadata_workspace_manifest_lists_all_members() {
        // Passing the workspace's *virtual* root manifest (no [package]) means no
        // single package matches, so graph_crate_order falls to the workspace-iter
        // branch and returns every member. Covers that else branch.
        let ws = scaffold_workspace();
        let discovery = run_cargo_metadata(Some(&ws.path().join("Cargo.toml")))
            .expect("metadata for workspace");
        let mut names = discovery.crate_names.clone();
        names.sort();
        assert_eq!(names, vec!["app", "dep"]);
    }

    #[test]
    fn load_cargo_lock_deps_parses_a_valid_lockfile() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("Cargo.lock");
        std::fs::write(
            &lock,
            "version = 3\n\n[[package]]\nname = \"serde\"\nversion = \"1.0.0\"\n",
        )
        .unwrap();
        let deps = load_cargo_lock_deps(&lock).expect("valid lock parses");
        assert_eq!(deps, vec![("serde".to_string(), "1.0.0".to_string())]);
    }

    #[test]
    fn load_cargo_lock_deps_returns_none_for_missing_lockfile() {
        // A missing Cargo.lock surfaces the parse-error -> debug-log -> None arm.
        assert!(load_cargo_lock_deps(Path::new("/nonexistent/Cargo.lock")).is_none());
    }

    #[test]
    fn test_build_intent_into_request_preserves_shard_context() {
        let intent = BuildIntent {
            crate_names: vec!["serde".into(), "tokio".into()],
            namespace: Some("x86_64/hash/release".into()),
            cargo_lock_deps: vec![("serde".into(), "1.0.0".into())],
        };

        let req = into_build_started_request(intent, 42);
        assert_eq!(req.intent.crate_names, vec!["serde", "tokio"]);
        assert_eq!(req.intent.namespace.as_deref(), Some("x86_64/hash/release"));
        assert_eq!(req.intent.cargo_lock_deps.len(), 1);
        assert_eq!(req.client_epoch, 42);
    }
}