Skip to main content

supercov_engine/
build_cache.rs

1//! Exact-fingerprint reuse of instrumented JavaScript build outputs.
2
3use std::{
4    collections::BTreeMap,
5    fs,
6    path::{Component, Path, PathBuf},
7    process::Command,
8};
9
10use serde::{Deserialize, Serialize};
11use sha2::{Digest, Sha256};
12
13use crate::{lifecycle::atomic_write, project_discovery::CoverageProject, run_store::RunIntegrity};
14
15pub const BUILD_CACHE_SCHEMA_VERSION: u32 = 1;
16const OUTPUT_CANDIDATES: &[&str] = &["build", "dist", ".next", ".nuxt", ".output"];
17const SCAN_EXCLUSIONS: &[&str] = &[".git", ".supercov", "node_modules"];
18const SCAN_DEPTH_LIMIT: usize = 6;
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "camelCase", deny_unknown_fields)]
22pub struct BuildCacheMetadata {
23    pub schema_version: u32,
24    pub key: String,
25    pub created_at: String,
26    pub artifact_paths: Vec<String>,
27}
28
29#[derive(Serialize)]
30#[serde(rename_all = "camelCase")]
31struct CacheIdentity<'a> {
32    schema_version: u32,
33    execution_fingerprint: &'a str,
34    adapter: crate::project_discovery::BuildAdapter,
35    command: &'a [String],
36    environment: &'a BTreeMap<String, String>,
37    node: String,
38    platform: &'static str,
39    architecture: &'static str,
40}
41
42fn safe_relative(path: &Path) -> bool {
43    path.components().next().is_some()
44        && path
45            .components()
46            .all(|component| matches!(component, Component::Normal(_)))
47}
48
49fn regular_artifact(workspace: &Path, relative: &Path) -> bool {
50    safe_relative(relative)
51        && fs::symlink_metadata(workspace.join(relative))
52            .is_ok_and(|metadata| metadata.file_type().is_file() || metadata.file_type().is_dir())
53}
54
55fn node_version() -> String {
56    std::env::var("SUPERCOV_NODE_VERSION").unwrap_or_else(|_| {
57        Command::new("node")
58            .args(["--print", "process.versions.node"])
59            .output()
60            .ok()
61            .filter(|output| output.status.success())
62            .and_then(|output| String::from_utf8(output.stdout).ok())
63            .map(|value| value.trim().to_owned())
64            .filter(|value| !value.is_empty())
65            .unwrap_or_else(|| "unavailable".into())
66    })
67}
68
69pub fn build_cache_key(
70    integrity: &RunIntegrity,
71    project: &CoverageProject,
72) -> Result<String, String> {
73    let identity = CacheIdentity {
74        schema_version: BUILD_CACHE_SCHEMA_VERSION,
75        execution_fingerprint: &integrity.fingerprint.execution,
76        adapter: project.build_adapter,
77        command: &project.build_command,
78        environment: &project.build_environment,
79        node: node_version(),
80        platform: std::env::consts::OS,
81        architecture: std::env::consts::ARCH,
82    };
83    let bytes = serde_json::to_vec(&identity)
84        .map_err(|error| format!("failed to serialize build-cache identity: {error}"))?;
85    Ok(format!("{:x}", Sha256::digest(bytes)))
86}
87
88pub fn read_build_cache(workspace: &Path, key: &str) -> Option<BuildCacheMetadata> {
89    let path = workspace.join(".supercov/build-cache.json");
90    if !fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.file_type().is_file()) {
91        return None;
92    }
93    let metadata: BuildCacheMetadata = serde_json::from_slice(&fs::read(path).ok()?).ok()?;
94    if metadata.schema_version != BUILD_CACHE_SCHEMA_VERSION
95        || metadata.key != key
96        || metadata.artifact_paths.is_empty()
97        || metadata
98            .artifact_paths
99            .iter()
100            .any(|path| !regular_artifact(workspace, Path::new(path)))
101    {
102        return None;
103    }
104    Some(metadata)
105}
106
107pub fn reuse_paths(metadata: &BuildCacheMetadata) -> Vec<PathBuf> {
108    metadata
109        .artifact_paths
110        .iter()
111        .map(PathBuf::from)
112        .chain([PathBuf::from(".supercov/build-cache.json")])
113        .collect()
114}
115
116#[derive(Deserialize, Default)]
117struct DeclaredOutputs {
118    #[serde(default)]
119    paths: Vec<String>,
120}
121
122/// Monorepo build outputs live at package roots (`packages/*/dist`), not the
123/// workspace root, so candidates come from a depth-limited scan of the whole
124/// mirror rather than a root-only check.
125fn workspace_output_directories(workspace: &Path) -> Vec<String> {
126    let mut found = Vec::new();
127    let mut pending = vec![(workspace.to_owned(), 0usize)];
128    while let Some((directory, depth)) = pending.pop() {
129        let Ok(entries) = fs::read_dir(&directory) else {
130            continue;
131        };
132        for entry in entries.flatten() {
133            if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
134                continue;
135            }
136            let name = entry.file_name();
137            let Some(name) = name.to_str() else {
138                continue;
139            };
140            if SCAN_EXCLUSIONS.contains(&name) {
141                continue;
142            }
143            if OUTPUT_CANDIDATES.contains(&name) {
144                if let Ok(relative) = entry.path().strip_prefix(workspace) {
145                    found.push(slash_path(relative));
146                }
147            } else if depth < SCAN_DEPTH_LIMIT {
148                pending.push((entry.path(), depth + 1));
149            }
150        }
151    }
152    found
153}
154
155/// Cache metadata is read back through `Path::new`, which accepts `/` on
156/// every host; a path spelled with `\\` would only ever be right on the host
157/// that wrote it.
158fn slash_path(path: &Path) -> String {
159    path.components()
160        .map(|component| component.as_os_str().to_string_lossy().into_owned())
161        .collect::<Vec<_>>()
162        .join("/")
163}
164
165pub fn write_build_cache(
166    project_root: &Path,
167    workspace: &Path,
168    key: &str,
169    created_at: &str,
170) -> Result<Option<BuildCacheMetadata>, String> {
171    let declared = fs::read(workspace.join(".supercov/build-outputs.json"))
172        .ok()
173        .and_then(|bytes| serde_json::from_slice::<DeclaredOutputs>(&bytes).ok())
174        .unwrap_or_default();
175    let mut candidates = workspace_output_directories(workspace)
176        .into_iter()
177        .chain(
178            declared
179                .paths
180                .into_iter()
181                .filter(|path| safe_relative(Path::new(path))),
182        )
183        .collect::<Vec<_>>();
184    candidates.sort();
185    candidates.dedup();
186    candidates.retain(|path| regular_artifact(workspace, Path::new(path)));
187    let existing = candidates.clone();
188    candidates.retain(|path| {
189        !existing.iter().any(|parent| {
190            parent != path
191                && Path::new(path)
192                    .strip_prefix(Path::new(parent))
193                    .is_ok_and(|local| local.components().next().is_some())
194        })
195    });
196    if candidates.is_empty() || !regular_artifact(workspace, Path::new(".supercov/manifest.json")) {
197        return Ok(None);
198    }
199    candidates.push(".supercov/manifest.json".into());
200    let metadata = BuildCacheMetadata {
201        schema_version: BUILD_CACHE_SCHEMA_VERSION,
202        key: key.into(),
203        created_at: created_at.into(),
204        artifact_paths: candidates,
205    };
206    let mut bytes = serde_json::to_vec_pretty(&metadata)
207        .map_err(|error| format!("failed to serialize build-cache metadata: {error}"))?;
208    bytes.push(b'\n');
209    atomic_write(
210        project_root,
211        &workspace.join(".supercov/build-cache.json"),
212        &bytes,
213    )
214    .map_err(|error| error.to_string())?;
215    Ok(Some(metadata))
216}
217
218#[cfg(test)]
219mod tests {
220    use std::time::{SystemTime, UNIX_EPOCH};
221
222    use super::*;
223
224    fn temporary() -> PathBuf {
225        // Two tests starting on the same nanosecond drew the same directory
226        // and polluted each other's artifact scans; the counter breaks ties.
227        static UNIQUE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
228        let nonce = SystemTime::now()
229            .duration_since(UNIX_EPOCH)
230            .unwrap()
231            .as_nanos();
232        let root = std::env::temp_dir().join(format!(
233            "supercov-build-cache-{}-{nonce}-{}",
234            std::process::id(),
235            UNIQUE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
236        ));
237        fs::create_dir_all(&root).unwrap();
238        root
239    }
240
241    #[test]
242    fn writes_reads_and_rejects_incomplete_exact_cache_metadata() {
243        let root = temporary();
244        let workspace = root.join(".supercov/cache/workspace/project");
245        fs::create_dir_all(workspace.join(".supercov")).unwrap();
246        fs::create_dir_all(workspace.join("dist")).unwrap();
247        fs::write(workspace.join("dist/app.js"), "built").unwrap();
248        fs::write(workspace.join(".supercov/manifest.json"), "{}").unwrap();
249        let written = write_build_cache(&root, &workspace, "key", "time")
250            .unwrap()
251            .unwrap();
252        assert_eq!(written.artifact_paths, ["dist", ".supercov/manifest.json"]);
253        assert_eq!(read_build_cache(&workspace, "key"), Some(written.clone()));
254        assert_eq!(
255            reuse_paths(&written),
256            [
257                PathBuf::from("dist"),
258                PathBuf::from(".supercov/manifest.json"),
259                PathBuf::from(".supercov/build-cache.json"),
260            ]
261        );
262        fs::remove_dir_all(workspace.join("dist")).unwrap();
263        assert_eq!(read_build_cache(&workspace, "key"), None);
264        fs::remove_dir_all(root).unwrap();
265    }
266
267    #[test]
268    fn records_package_level_outputs_and_skips_dependency_trees() {
269        let root = temporary();
270        let workspace = root.join(".supercov/cache/workspace/project");
271        fs::create_dir_all(workspace.join(".supercov")).unwrap();
272        fs::write(workspace.join(".supercov/manifest.json"), "{}").unwrap();
273        fs::create_dir_all(workspace.join("packages/app/dist/assets")).unwrap();
274        fs::write(workspace.join("packages/app/dist/app.js"), "built").unwrap();
275        fs::create_dir_all(workspace.join("packages/site/.next")).unwrap();
276        fs::create_dir_all(workspace.join("node_modules/library/dist")).unwrap();
277        fs::create_dir_all(workspace.join("packages/app/node_modules/local/dist")).unwrap();
278        let written = write_build_cache(&root, &workspace, "key", "time")
279            .unwrap()
280            .unwrap();
281        assert_eq!(
282            written.artifact_paths,
283            [
284                "packages/app/dist",
285                "packages/site/.next",
286                ".supercov/manifest.json"
287            ]
288        );
289        assert_eq!(read_build_cache(&workspace, "key"), Some(written));
290        fs::remove_dir_all(root).unwrap();
291    }
292}