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
//! In-memory artifact records and on-disk payload materialization helpers.
//!
//! `CachedArtifact` is the daemon's per-key view of a cached compilation:
//! metadata plus either resident bytes or pointers to on-disk payload files.
//! `ensure_payloads` lazily resolves the payload slice from the artifact dir,
//! and `migrate_meta_files` upgrades legacy `.meta` blobs to the redb-backed
//! `ArtifactStore` on first startup after an upgrade.
use super::*;
#[derive(Clone)]
pub(crate) enum CachedPayload {
/// Payload bytes already resident in memory.
Bytes(Arc<Vec<u8>>),
/// Payload bytes are available in a cache file.
File(NormalizedPath),
/// Payload's cache file is still being written by the async persist
/// spawned at miss-time. Hit handlers should serve from `source_path`
/// (the rustc-output path under `target/` that hardlinks identically
/// to the cache file once persist completes) when the cache file
/// doesn't yet exist. See `store_rustc_outputs` in `miss_store.rs`
/// (issue #632) for the producer side.
PendingFile { source_path: NormalizedPath },
}
#[derive(Clone)]
/// Cached compilation artifact with lazy payload loading.
///
/// Metadata (output names, sizes, stdout, stderr, exit code) is always in
/// memory after startup. Output payloads are either already in memory or are
/// represented by cache files so hits can hardlink without eager reads.
pub(crate) struct CachedArtifact {
pub(crate) meta: ArtifactIndex,
/// Arc-wrapped stdout/stderr for cheap IPC response clones.
pub(crate) stdout: Arc<Vec<u8>>,
pub(crate) stderr: Arc<Vec<u8>>,
/// Lazily-resolved output payloads. `None` = not yet checked on disk.
/// Arc-wrapped so cache-hit clones are O(1) refcount bumps.
pub(crate) payloads: Option<Arc<[CachedPayload]>>,
/// When this artifact was last used (inserted or returned as a hit).
pub(crate) last_used: std::time::Instant,
}
impl CachedArtifact {
/// Create from a freshly compiled `ArtifactData`. Payload mapping is
/// 1:1 between the protocol `ArtifactPayload` enum and the internal
/// `CachedPayload` enum.
pub(super) fn from_artifact_data(artifact: &ArtifactData) -> Self {
let meta = ArtifactIndex::new(
artifact.outputs.iter().map(|o| o.name.clone()).collect(),
artifact
.outputs
.iter()
.map(|o| o.payload.size_bytes())
.collect(),
Arc::clone(&artifact.stdout),
Arc::clone(&artifact.stderr),
artifact.exit_code,
);
Self {
meta,
stdout: Arc::clone(&artifact.stdout),
stderr: Arc::clone(&artifact.stderr),
payloads: Some(Arc::from(
artifact
.outputs
.iter()
.map(|o| match &o.payload {
ArtifactPayload::Bytes(b) => CachedPayload::Bytes(Arc::clone(b)),
ArtifactPayload::Path(p) => CachedPayload::File(p.clone()),
})
.collect::<Vec<_>>(),
)),
last_used: std::time::Instant::now(),
}
}
/// Create from index metadata and already-created payload files.
pub(super) fn from_file_payloads(meta: ArtifactIndex, payloads: Vec<NormalizedPath>) -> Self {
let stdout = Arc::clone(&meta.stdout);
let stderr = Arc::clone(&meta.stderr);
Self {
meta,
stdout,
stderr,
payloads: Some(Arc::from(
payloads
.into_iter()
.map(CachedPayload::File)
.collect::<Vec<_>>(),
)),
last_used: std::time::Instant::now(),
}
}
/// Create from index metadata and rustc-output source paths that an
/// async persist task is in the process of hardlinking into the cache
/// dir. Hits will fall back to the source path until the cache file
/// shows up on disk (after which both paths are the same inode and
/// the fast path takes over). See `store_rustc_outputs` for the
/// producer side and issue #632 for the design rationale.
pub(super) fn from_pending_payloads(
meta: ArtifactIndex,
source_paths: Vec<NormalizedPath>,
) -> Self {
let stdout = Arc::clone(&meta.stdout);
let stderr = Arc::clone(&meta.stderr);
Self {
meta,
stdout,
stderr,
payloads: Some(Arc::from(
source_paths
.into_iter()
.map(|source_path| CachedPayload::PendingFile { source_path })
.collect::<Vec<_>>(),
)),
last_used: std::time::Instant::now(),
}
}
/// Create from index metadata (lazy payloads not loaded yet).
pub(super) fn from_index(meta: ArtifactIndex) -> Self {
let stdout = Arc::clone(&meta.stdout);
let stderr = Arc::clone(&meta.stderr);
Self {
meta,
stdout,
stderr,
payloads: None,
last_used: std::time::Instant::now(),
}
}
}
/// Load output payloads from `{key}_0`, `{key}_1`, ... files on disk.
///
/// Returns the payload slice, or `None` if any data file is missing
/// (indicating corruption or eviction — caller should treat as cache miss).
pub(super) fn ensure_payloads<'a>(
cached: &'a mut CachedArtifact,
artifact_dir: &Path,
key_hex: &str,
) -> Option<&'a [CachedPayload]> {
if cached.payloads.is_none() {
let mut payloads = Vec::with_capacity(cached.meta.output_names.len());
for i in 0..cached.meta.output_names.len() {
let path = artifact_dir.join(format!("{key_hex}_{i}"));
if let Ok(meta) = std::fs::metadata(&path) {
if meta.is_file()
&& cached
.meta
.output_sizes
.get(i)
.is_none_or(|expected| *expected == meta.len())
{
payloads.push(CachedPayload::File(path.into()));
continue;
}
}
// Fallback: artifact may be stored in a `.pack` file (pack mode).
let bytes = try_load_packed_payload(artifact_dir, key_hex, i)?;
if let Some(expected) = cached.meta.output_sizes.get(i) {
if *expected != bytes.len() as u64 {
return None;
}
}
payloads.push(CachedPayload::Bytes(Arc::new(bytes)));
}
cached.payloads = Some(Arc::from(payloads));
}
cached.payloads.as_deref()
}
/// Migrate legacy `.meta` files to the in-memory artifact index.
/// Called once on first startup after upgrade.
pub(super) fn migrate_meta_files(
artifact_dir: &Path,
artifacts: &DashMap<String, CachedArtifact>,
store: &ArtifactStore,
) -> usize {
use rayon::prelude::*;
// Collect .meta file paths first.
let meta_paths: Vec<NormalizedPath> = match std::fs::read_dir(artifact_dir) {
Ok(entries) => entries
.flatten()
.map(|e| e.path().into())
.filter(|p: &NormalizedPath| p.extension().and_then(|e| e.to_str()) == Some("meta"))
.collect(),
Err(_) => return 0,
};
if meta_paths.is_empty() {
return 0;
}
// Parallel phase: read, deserialize, and write data files.
// Each .meta file is fully independent for I/O.
let migrated: Vec<(String, CachedArtifact, NormalizedPath)> = meta_paths
.par_iter()
.filter_map(|path| {
let data = std::fs::read(path).ok()?;
let artifact = bincode::deserialize::<ArtifactData>(&data).ok()?;
let stem: String = path
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
// Write {key}_0, {key}_1, ... data files if missing.
// Legacy `.meta` files only ever stored inline bytes, so we
// only handle the `Bytes` variant here. Any `Path` variant
// would be a forward-compat artefact that legacy migration
// can safely skip — caller treats failures as non-cacheable.
for (i, out) in artifact.outputs.iter().enumerate() {
let data_path = artifact_dir.join(format!("{stem}_{i}"));
if !data_path.exists() {
if let Some(bytes) = out.payload.as_bytes() {
std::fs::write(&data_path, bytes.as_slice()).ok();
}
}
}
let cached = CachedArtifact::from_artifact_data(&artifact);
Some((stem, cached, path.clone()))
})
.collect();
// Sequential phase: insert into the in-memory store and DashMap,
// then delete the legacy .meta files.
let count = migrated.len();
for (stem, cached, meta_path) in migrated {
store.insert(&stem, &cached.meta);
artifacts.insert(stem, cached);
std::fs::remove_file(&meta_path).ok();
}
if count > 0 {
tracing::info!(count, "migrated legacy .meta files to artifact index");
}
count
}