1use std::collections::{BTreeMap, BTreeSet};
21use std::ffi::OsStr;
22use std::fmt;
23use std::fs::{self, File, OpenOptions};
24use std::io::{self, Read, Write};
25use std::path::{Path, PathBuf};
26use std::sync::atomic::{AtomicU64, Ordering};
27
28use rayon::prelude::*;
29use serde::{Deserialize, Serialize};
30use serde_json::Value;
31use sha2::{Digest, Sha256};
32use thiserror::Error;
33
34use crate::rsjs::build::wrapper_control_environment;
35use crate::rsjs::build::{
36 acquire_descriptor_target_lease, classify_dependency_artifact, descriptor_input_content_hash,
37 descriptor_package_source_closure_hash, descriptor_staging_marker_is_valid,
38 descriptor_target_dirty_journal_path, descriptor_target_marker_is_valid,
39 join_cargo_enumerated_descriptor_units, join_descriptor_units_to_cargo_artifacts,
40 managed_paths_overlap, normalize_managed_path_identity, prepare_descriptor_target_directory,
41 run_descriptor_cargo_allow_empty, run_descriptor_cargo_allow_empty_resuming,
42 uplifted_root_lib_hashed_rlib, validate_descriptor_managed_paths,
43 validate_descriptor_observed_inputs, CargoCompilerArtifact, DescriptorCargoOutput,
44 DescriptorCargoRequest, DescriptorCargoRun, DescriptorCargoRunError, DescriptorCargoUnitId,
45 DescriptorSidecarError, DescriptorTargetLease, DescriptorUnitSidecar, UnitArtifactJoinError,
46 ValidatedDescriptorUnit, DESCRIPTOR_OBJECT_HASH_DOMAIN,
47};
48#[cfg(test)]
49use crate::rsjs::build::{
50 descriptor_environment_dependency_value_hash, descriptor_object_content_hash,
51 descriptor_out_dir_dependency_content_hash, descriptor_source_dependency_content_hash,
52 DescriptorEnvironmentDependency, DescriptorOutDirDependency, DescriptorSourceDependency,
53};
54
55pub(crate) const DESCRIPTOR_CACHE_SCHEMA_VERSION: u16 = 5;
56const ARTIFACT_COORDINATE_DOMAIN: &[u8] = b"proa.rsjs.descriptor-cache-coordinate.v2";
57const ARTIFACT_SET_COORDINATE_DOMAIN: &[u8] = b"proa.rsjs.descriptor-cache-coordinate-set.v2";
58const CACHED_SIDECAR_HASH_DOMAIN: &[u8] = b"proa.rsjs.descriptor-cache-sidecar.v1";
59static CACHE_WRITE_NONCE: AtomicU64 = AtomicU64::new(0);
60
61pub fn run_descriptor_cargo_cached(
71 request: &DescriptorCargoRequest,
72 cache_directory: &Path,
73) -> Result<CachedDescriptorCargoLease, DescriptorCacheError> {
74 run_descriptor_cargo_cached_leased(request, cache_directory)
75}
76
77#[must_use = "descriptor cache leases retain filesystem locks until consumed or dropped"]
80pub struct CachedDescriptorCargoLease {
81 output: DescriptorCargoOutput,
82 _cache_lock: CacheGenerationLock,
85 _target_lock: DescriptorTargetLease,
86}
87
88impl fmt::Debug for CachedDescriptorCargoLease {
89 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
90 formatter
91 .debug_struct("CachedDescriptorCargoLease")
92 .field("artifacts", &self.output.cargo_artifacts.len())
93 .field("units", &self.output.units.len())
94 .finish_non_exhaustive()
95 }
96}
97
98impl crate::rsjs::build::descriptor_run_sealed::Sealed for CachedDescriptorCargoLease {
99 fn output(&self) -> &DescriptorCargoOutput {
100 &self.output
101 }
102
103 fn into_output(self) -> DescriptorCargoOutput {
104 self.output
105 }
106}
107
108impl DescriptorCargoRun for CachedDescriptorCargoLease {}
109
110pub(crate) fn run_descriptor_cargo_cached_leased(
111 request: &DescriptorCargoRequest,
112 cache_directory: &Path,
113) -> Result<CachedDescriptorCargoLease, DescriptorCacheError> {
114 validate_descriptor_managed_paths(request).map_err(DescriptorCacheError::DescriptorCargo)?;
115 let cache_directory = validate_cache_directories(
116 cache_directory,
117 &request.staging_directory,
118 &request.target_directory,
119 &request.source_exclusion_directory,
120 &request.working_directory,
121 )?;
122 let target_lock = acquire_descriptor_target_lease(&request.target_directory)
123 .map_err(DescriptorCacheError::DescriptorCargo)?;
124 ensure_plain_directory(&cache_directory)?;
125 let cache_lock = CacheGenerationLock::acquire_path(&cache_directory.join("generation.lock"))?;
126 create_cache_layout(&cache_directory)?;
127 prepare_descriptor_target_directory(&request.target_directory)
128 .map_err(DescriptorCacheError::DescriptorCargo)?;
129 let interrupted_staging = interrupted_cache_generation_staging(&cache_directory, request)?;
130 let mut active_request = request.clone();
131 if let Some(staging) = &interrupted_staging {
132 active_request.staging_directory = staging.clone();
133 eprintln!(
134 "recovering interrupted RSJS descriptor cache transaction from `{}` while preserving Cargo target `{}`",
135 staging.display(),
136 request.target_directory.display(),
137 );
138 } else {
139 mark_cache_generation_dirty(request)?;
140 }
141
142 let result = match run_descriptor_cargo_cached_once(
143 &active_request,
144 &cache_directory,
145 false,
146 interrupted_staging.is_some(),
147 ) {
148 Ok(output) => Ok(output),
149 Err(error)
150 if recoverable_cache_authority_error(&error)
151 || (interrupted_staging.is_some()
152 && recoverable_interrupted_generation_error(&error)) =>
153 {
154 eprintln!(
155 "RSJS descriptor cache recovery could not prove exact reuse ({error}); rebuilding its marker-owned Cargo target once"
156 );
157 reset_descriptor_request_owned_state(
158 &active_request,
159 &active_request.staging_directory,
160 )?;
161 mark_cache_generation_dirty(request)?;
162 run_descriptor_cargo_cached_once(request, &cache_directory, true, false)
163 }
164 Err(error) => Err(error),
165 };
166 match result {
167 Ok(output) => {
168 clear_cache_generation_dirty(request)?;
169 Ok(CachedDescriptorCargoLease {
170 output,
171 _cache_lock: cache_lock,
172 _target_lock: target_lock,
173 })
174 }
175 Err(error) => Err(error),
176 }
177}
178
179#[derive(Debug, Serialize, Deserialize)]
180#[serde(deny_unknown_fields)]
181struct DirtyCacheGeneration {
182 schema_version: u16,
183 target_directory: PathBuf,
184 staging_directory: PathBuf,
185}
186
187fn interrupted_cache_generation_staging(
188 cache_directory: &Path,
189 request: &DescriptorCargoRequest,
190) -> Result<Option<PathBuf>, DescriptorCacheError> {
191 let path = descriptor_target_dirty_journal_path(&request.target_directory)
192 .map_err(DescriptorCacheError::DescriptorCargo)?;
193 let metadata = match fs::symlink_metadata(&path) {
194 Ok(metadata) => metadata,
195 Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(None),
196 Err(source) => return Err(DescriptorCacheError::ReadCacheFile { path, source }),
197 };
198 if !metadata.file_type().is_file() {
199 return Err(DescriptorCacheError::InvalidDirtyMarker(path));
200 }
201 let bytes = fs::read(&path).map_err(|source| DescriptorCacheError::ReadCacheFile {
202 path: path.clone(),
203 source,
204 })?;
205 let marker: DirtyCacheGeneration =
206 serde_json::from_slice(&bytes).map_err(|source| DescriptorCacheError::ParseCacheFile {
207 path: path.clone(),
208 source,
209 })?;
210 if marker.schema_version != DESCRIPTOR_CACHE_SCHEMA_VERSION {
211 return Err(DescriptorCacheError::UnsupportedCacheSchema {
212 path,
213 actual: marker.schema_version,
214 expected: DESCRIPTOR_CACHE_SCHEMA_VERSION,
215 });
216 }
217 let expected = normalize_managed_path(&request.target_directory)?;
218 let actual = normalize_managed_path(&marker.target_directory)?;
219 if actual != expected {
220 return Err(DescriptorCacheError::DirtyTargetMismatch { expected, actual });
221 }
222 validate_cache_directories(
223 cache_directory,
224 &marker.staging_directory,
225 &request.target_directory,
226 &request.source_exclusion_directory,
227 &request.working_directory,
228 )?;
229 let normalized_staging = normalize_managed_path(&marker.staging_directory)?;
230 let normalized_exclusion = normalize_managed_path(&request.source_exclusion_directory)?;
231 let relative = normalized_staging
232 .strip_prefix(&normalized_exclusion)
233 .map_err(
234 |_| DescriptorCacheError::GeneratedStateOutsideSourceExclusion {
235 kind: "staging",
236 path: normalized_staging.clone(),
237 exclusion: normalized_exclusion,
238 },
239 )?;
240 let request_spelling = request.source_exclusion_directory.join(relative);
241 let rebound = normalize_managed_path(&request_spelling)?;
242 if rebound != normalized_staging {
243 return Err(DescriptorCacheError::DirtyStagingMismatch {
244 expected: normalized_staging,
245 actual: rebound,
246 });
247 }
248 Ok(Some(request_spelling))
249}
250
251fn mark_cache_generation_dirty(
252 request: &DescriptorCargoRequest,
253) -> Result<(), DescriptorCacheError> {
254 let marker = DirtyCacheGeneration {
255 schema_version: DESCRIPTOR_CACHE_SCHEMA_VERSION,
256 target_directory: normalize_managed_path(&request.target_directory)?,
257 staging_directory: normalize_managed_path(&request.staging_directory)?,
258 };
259 let bytes =
260 serde_json::to_vec_pretty(&marker).map_err(DescriptorCacheError::SerializeCacheRecord)?;
261 let path = descriptor_target_dirty_journal_path(&request.target_directory)
262 .map_err(DescriptorCacheError::DescriptorCargo)?;
263 atomic_write_replaceable(&path, &bytes)
264}
265
266fn clear_cache_generation_dirty(
267 request: &DescriptorCargoRequest,
268) -> Result<(), DescriptorCacheError> {
269 let path = descriptor_target_dirty_journal_path(&request.target_directory)
270 .map_err(DescriptorCacheError::DescriptorCargo)?;
271 fs::remove_file(&path).map_err(|source| DescriptorCacheError::WriteCacheFile {
272 path: path.clone(),
273 source,
274 })?;
275 let parent = path
276 .parent()
277 .expect("descriptor target journals always have a parent");
278 sync_directory(parent).map_err(|source| DescriptorCacheError::WriteCacheFile {
279 path: parent.to_path_buf(),
280 source,
281 })
282}
283
284fn run_descriptor_cargo_cached_once(
285 request: &DescriptorCargoRequest,
286 cache_directory: &Path,
287 require_complete_rebuild: bool,
288 resume_interrupted_staging: bool,
289) -> Result<DescriptorCargoOutput, DescriptorCacheError> {
290 let mut fresh = if resume_interrupted_staging {
291 run_descriptor_cargo_allow_empty_resuming(request)
292 } else {
293 run_descriptor_cargo_allow_empty(request)
294 }
295 .map_err(DescriptorCacheError::DescriptorCargo)?;
296 if require_complete_rebuild && fresh.cargo_artifacts.iter().any(|artifact| artifact.fresh) {
297 return Err(DescriptorCacheError::RecoveryDidNotFullyRebuild);
298 }
299 if resume_interrupted_staging {
300 retain_current_interrupted_units(&mut fresh, request)?;
301 }
302 let evidence = collect_artifact_evidence(&fresh.cargo_artifacts)?;
303 let artifact_set_coordinate = artifact_set_coordinate(&evidence);
304 if fresh.units.is_empty() {
305 reject_rebuilt_artifact_without_wrapper_units(&evidence)?;
306 }
307
308 let fresh_joined = join_cargo_enumerated_descriptor_units(&fresh.units, &fresh.cargo_artifacts)
309 .map_err(DescriptorCacheError::ArtifactJoin)?;
310 let mut fresh_by_artifact = BTreeMap::<String, DescriptorCargoUnitId>::new();
311 for (unit, artifact) in &fresh_joined {
312 let coordinate = coordinate_for_artifact(artifact, &evidence)?;
313 if let Some(previous) = fresh_by_artifact.insert(coordinate.clone(), *unit) {
314 return Err(DescriptorCacheError::MultipleFreshUnitsForArtifact {
315 coordinate,
316 first: previous,
317 second: *unit,
318 });
319 }
320 }
321
322 let fresh_ids = fresh
323 .units
324 .iter()
325 .map(|unit| unit.unit)
326 .collect::<BTreeSet<_>>();
327 let mut cached_generations = BTreeMap::new();
328 let mut expected_artifact_by_cached_unit = BTreeMap::new();
329
330 if fresh.units.is_empty() && !require_complete_rebuild {
331 let snapshot = load_snapshot(cache_directory, &artifact_set_coordinate, &evidence)?;
332 for generation in snapshot.units {
333 insert_cached_generation(&mut cached_generations, generation)?;
334 }
335 } else {
336 for artifact in &evidence {
337 if fresh_by_artifact.contains_key(&artifact.coordinate) {
338 continue;
339 }
340
341 match load_artifact_index(cache_directory, &artifact.coordinate) {
342 Ok(index) => {
343 if !artifact.artifact.fresh && !index.units.is_empty() {
344 return Err(DescriptorCacheError::RebuiltArtifactMissingFreshUnit {
345 coordinate: artifact.coordinate.clone(),
346 });
347 }
348 for generation in index.units {
349 let unit = generation.unit(Path::new("artifact-index"))?;
350 if let Some(previous) = expected_artifact_by_cached_unit
351 .insert(unit, artifact.coordinate.clone())
352 {
353 if previous != artifact.coordinate {
354 return Err(
355 DescriptorCacheError::CachedUnitClaimedByMultipleArtifacts {
356 unit,
357 first: previous,
358 second: artifact.coordinate.clone(),
359 },
360 );
361 }
362 }
363 insert_cached_generation(&mut cached_generations, generation)?;
364 }
365 }
366 Err(DescriptorCacheError::MissingArtifactIndex { .. })
367 if !artifact.artifact.fresh =>
368 {
369 }
375 Err(error) => return Err(error),
376 }
377 }
378 }
379
380 cached_generations.retain(|unit, _| !fresh_ids.contains(unit));
381 let cached_ids = cached_generations.keys().copied().collect::<BTreeSet<_>>();
382 let fresh_generations = persist_fresh_units(cache_directory, &fresh.units)?;
383 let mut generations = cached_generations;
384 for (_, generation) in fresh_generations {
385 insert_cached_generation(&mut generations, generation)?;
386 }
387 let units = load_cached_units_direct(cache_directory, &generations)?;
391 let units_by_id = units
392 .iter()
393 .map(|unit| (unit.unit, unit))
394 .collect::<BTreeMap<_, _>>();
395 for expected in fresh_ids.iter().chain(cached_ids.iter()) {
396 if !units_by_id.contains_key(expected) {
397 return Err(DescriptorCacheError::MissingMergedUnit(*expected));
398 }
399 }
400
401 let validation_ids = if require_complete_rebuild || resume_interrupted_staging {
402 units_by_id.keys().copied().collect::<BTreeSet<_>>()
403 } else {
404 cached_ids.clone()
405 };
406 validate_cached_unit_inputs(
407 &units_by_id,
408 &validation_ids,
409 &request.target_directory,
410 &fresh.cargo_artifacts,
411 )?;
412 validate_cached_artifact_joins(
413 &units_by_id,
414 &cached_ids,
415 &expected_artifact_by_cached_unit,
416 &fresh.cargo_artifacts,
417 &evidence,
418 fresh.units.is_empty(),
419 )?;
420
421 if let Some(unit) = units_by_id
422 .keys()
423 .find(|unit| !generations.contains_key(unit))
424 {
425 return Err(DescriptorCacheError::MissingCachedGeneration(*unit));
426 }
427 persist_artifact_indexes(
428 cache_directory,
429 &units,
430 &generations,
431 &fresh.cargo_artifacts,
432 &evidence,
433 )?;
434 persist_snapshot(
435 cache_directory,
436 &artifact_set_coordinate,
437 &evidence,
438 units.iter().map(|unit| generations[&unit.unit].clone()),
439 )?;
440 remove_completed_staging(&request.staging_directory)?;
441
442 Ok(DescriptorCargoOutput {
443 cargo_artifacts: fresh.cargo_artifacts,
444 units,
445 })
446}
447
448fn retain_current_interrupted_units(
449 output: &mut DescriptorCargoOutput,
450 request: &DescriptorCargoRequest,
451) -> Result<(), DescriptorCacheError> {
452 let candidates = std::mem::take(&mut output.units);
453 let candidate_count = candidates.len();
454 let mut retained = BTreeMap::<DescriptorCargoUnitId, ValidatedDescriptorUnit>::new();
455 let mut stale = 0usize;
456 for unit in candidates {
457 if interrupted_unit_matches_current_inputs(
458 &unit,
459 &request.target_directory,
460 &request.source_exclusion_directory,
461 &output.cargo_artifacts,
462 )? {
463 if let Some(previous) = retained.get(&unit.unit) {
464 if previous.sidecar != unit.sidecar {
465 return Err(DescriptorCacheError::ConflictingInterruptedUnitCandidates(
466 unit.unit,
467 ));
468 }
469 } else {
470 retained.insert(unit.unit, unit);
471 }
472 } else {
473 stale += 1;
474 }
475 }
476 if stale != 0 {
477 eprintln!(
478 "discarded {stale} stale descriptor recovery candidate{} after current-input validation",
479 if stale == 1 { "" } else { "s" },
480 );
481 }
482 let duplicate_count = candidate_count.saturating_sub(stale + retained.len());
483 if duplicate_count != 0 {
484 eprintln!(
485 "deduplicated {duplicate_count} exact descriptor recovery candidate{}",
486 if duplicate_count == 1 { "" } else { "s" },
487 );
488 }
489 output.units = retained.into_values().collect();
490 Ok(())
491}
492
493fn interrupted_unit_matches_current_inputs(
494 unit: &ValidatedDescriptorUnit,
495 descriptor_target: &Path,
496 source_exclusion: &Path,
497 cargo_artifacts: &[CargoCompilerArtifact],
498) -> Result<bool, DescriptorCacheError> {
499 if !interrupted_unit_matches_local_inputs(unit, descriptor_target, source_exclusion) {
500 return Ok(false);
501 }
502
503 let units_by_id = BTreeMap::from([(unit.unit, unit)]);
504 let unit_ids = BTreeSet::from([unit.unit]);
505 match validate_cached_dependency_artifacts(&units_by_id, &unit_ids, cargo_artifacts) {
506 Ok(()) => {}
507 Err(
508 DescriptorCacheError::CachedDependencyNotEnumerated { .. }
509 | DescriptorCacheError::StaleCachedDependency { .. },
510 ) => return Ok(false),
511 Err(error) => return Err(error),
512 }
513 match join_descriptor_units_to_cargo_artifacts(std::slice::from_ref(unit), cargo_artifacts) {
514 Ok(_) => Ok(true),
515 Err(UnitArtifactJoinError::MissingArtifact(_)) => Err(
516 DescriptorCacheError::InterruptedUnitMissingArtifact(unit.unit),
517 ),
518 Err(error) => Err(DescriptorCacheError::ArtifactJoin(error)),
519 }
520}
521
522fn interrupted_unit_matches_local_inputs(
523 unit: &ValidatedDescriptorUnit,
524 descriptor_target: &Path,
525 source_exclusion: &Path,
526) -> bool {
527 let Some(manifest) = unit.sidecar.cargo_manifest_path.as_deref() else {
528 return false;
529 };
530 let Some(package_root) = manifest.parent() else {
531 return false;
532 };
533 let current_closure =
534 match descriptor_package_source_closure_hash(package_root, source_exclusion) {
535 Ok(hash) => hash,
536 Err(_) => return false,
537 };
538 if current_closure != unit.sidecar.package_source_closure_hash {
539 return false;
540 }
541 validate_descriptor_observed_inputs(descriptor_target, &unit.sidecar).is_ok()
542}
543
544fn reject_rebuilt_artifact_without_wrapper_units(
545 evidence: &[ArtifactEvidence],
546) -> Result<(), DescriptorCacheError> {
547 if let Some(artifact) = evidence.iter().find(|artifact| !artifact.artifact.fresh) {
548 return Err(DescriptorCacheError::RebuiltArtifactMissingFreshUnit {
549 coordinate: artifact.coordinate.clone(),
550 });
551 }
552 Ok(())
553}
554
555fn insert_cached_generation(
556 generations: &mut BTreeMap<DescriptorCargoUnitId, CachedUnitGeneration>,
557 generation: CachedUnitGeneration,
558) -> Result<(), DescriptorCacheError> {
559 let unit = generation.unit(Path::new("cache-generation"))?;
560 if let Some(previous) = generations.insert(unit, generation.clone()) {
561 if previous != generation {
562 return Err(DescriptorCacheError::ConflictingCachedGeneration {
563 unit,
564 first: cached_generation_label(&previous),
565 second: cached_generation_label(&generation),
566 });
567 }
568 }
569 Ok(())
570}
571
572fn validate_cache_directories(
573 cache_directory: &Path,
574 staging_directory: &Path,
575 target_directory: &Path,
576 source_exclusion_directory: &Path,
577 working_directory: &Path,
578) -> Result<PathBuf, DescriptorCacheError> {
579 if !cache_directory.is_absolute() {
580 return Err(DescriptorCacheError::RelativeCacheDirectory(
581 cache_directory.to_path_buf(),
582 ));
583 }
584 for (name, path) in [
585 ("staging", staging_directory),
586 ("target", target_directory),
587 ("source exclusion", source_exclusion_directory),
588 ("working directory", working_directory),
589 ] {
590 if !path.is_absolute() {
591 return Err(DescriptorCacheError::RelativeManagedDirectory {
592 kind: name,
593 path: path.to_path_buf(),
594 });
595 }
596 }
597 let cache = normalize_managed_path(cache_directory)?;
598 let staging = normalize_managed_path(staging_directory)?;
599 let target = normalize_managed_path(target_directory)?;
600 let source_exclusion = normalize_managed_path(source_exclusion_directory)?;
601 let working = normalize_managed_path(working_directory)?;
602
603 for (first_kind, first, second_kind, second) in [
604 ("cache", &cache, "staging", &staging),
605 ("cache", &cache, "target", &target),
606 ("staging", &staging, "target", &target),
607 ] {
608 if managed_paths_overlap(first, second) {
609 return Err(DescriptorCacheError::OverlappingManagedDirectories {
610 first_kind,
611 first: first.clone(),
612 second_kind,
613 second: second.clone(),
614 });
615 }
616 }
617 for (kind, managed) in [("staging", &staging), ("target", &target)] {
618 if working == *managed || working.starts_with(managed) {
619 return Err(DescriptorCacheError::UnsafeManagedDirectory {
620 kind,
621 managed: managed.clone(),
622 working: working.clone(),
623 });
624 }
625 }
626 if target == source_exclusion || !target.starts_with(&source_exclusion) {
627 return Err(DescriptorCacheError::TargetOutsideSourceExclusion {
628 target,
629 exclusion: source_exclusion,
630 });
631 }
632 if source_exclusion == working || working.starts_with(&source_exclusion) {
633 return Err(DescriptorCacheError::UnsafeSourceExclusion {
634 exclusion: source_exclusion,
635 working,
636 });
637 }
638 if source_exclusion.starts_with(&working) {
639 for (kind, managed) in [
640 ("cache", &cache),
641 ("staging", &staging),
642 ("target", &target),
643 ] {
644 if !managed.starts_with(&source_exclusion) {
645 return Err(DescriptorCacheError::GeneratedStateOutsideSourceExclusion {
646 kind,
647 path: managed.clone(),
648 exclusion: source_exclusion.clone(),
649 });
650 }
651 }
652 }
653 Ok(cache)
654}
655
656fn normalize_managed_path(path: &Path) -> Result<PathBuf, DescriptorCacheError> {
657 normalize_managed_path_identity(path).map_err(|source| {
658 DescriptorCacheError::NormalizeManagedDirectory {
659 path: path.to_path_buf(),
660 source,
661 }
662 })
663}
664
665struct CacheGenerationLock {
666 _file: File,
667}
668
669impl CacheGenerationLock {
670 fn acquire_path(path: &Path) -> Result<Self, DescriptorCacheError> {
671 let parent = path
672 .parent()
673 .ok_or_else(|| DescriptorCacheError::CachePathWithoutParent(path.to_path_buf()))?;
674 ensure_plain_directory(parent)?;
675 match fs::symlink_metadata(path) {
676 Ok(metadata) if !metadata.file_type().is_file() => {
677 return Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf()));
678 }
679 Ok(_) => {}
680 Err(source) if source.kind() == io::ErrorKind::NotFound => {}
681 Err(source) => {
682 return Err(DescriptorCacheError::OpenCacheLock {
683 path: path.to_path_buf(),
684 source,
685 });
686 }
687 }
688 let file = OpenOptions::new()
689 .create(true)
690 .read(true)
691 .write(true)
692 .truncate(false)
693 .open(path)
694 .map_err(|source| DescriptorCacheError::OpenCacheLock {
695 path: path.to_path_buf(),
696 source,
697 })?;
698 file.lock()
699 .map_err(|source| DescriptorCacheError::AcquireCacheLock {
700 path: path.to_path_buf(),
701 source,
702 })?;
703 Ok(Self { _file: file })
704 }
705}
706
707fn recoverable_cache_authority_error(error: &DescriptorCacheError) -> bool {
708 matches!(
709 error,
710 DescriptorCacheError::MissingArtifactSetSnapshot { .. }
711 | DescriptorCacheError::MissingArtifactIndex { .. }
712 | DescriptorCacheError::MissingCachedUnitFile { .. }
713 | DescriptorCacheError::CachedOutDirDependencyMismatch { .. }
714 )
715}
716
717fn recoverable_interrupted_generation_error(error: &DescriptorCacheError) -> bool {
718 matches!(
719 error,
720 DescriptorCacheError::MultipleFreshUnitsForArtifact { .. }
721 | DescriptorCacheError::RebuiltArtifactMissingFreshUnit { .. }
722 | DescriptorCacheError::ConflictingInterruptedUnitCandidates(_)
723 | DescriptorCacheError::InterruptedUnitMissingArtifact(_)
724 | DescriptorCacheError::ArtifactJoin(_)
725 )
726}
727
728fn reset_descriptor_request_owned_state(
729 request: &DescriptorCargoRequest,
730 staging_directory: &Path,
731) -> Result<(), DescriptorCacheError> {
732 let marker_valid =
733 descriptor_target_marker_is_valid(&request.target_directory).map_err(|source| {
734 DescriptorCacheError::ReadDescriptorTargetMarker {
735 path: request.target_directory.clone(),
736 source,
737 }
738 })?;
739 if !marker_valid {
740 return Err(DescriptorCacheError::UnownedRecoveryTarget(
741 request.target_directory.clone(),
742 ));
743 }
744 let staging_exists = fs::symlink_metadata(staging_directory)
745 .map(|metadata| metadata.file_type().is_dir())
746 .or_else(|source| {
747 if source.kind() == io::ErrorKind::NotFound {
748 Ok(false)
749 } else {
750 Err(source)
751 }
752 })
753 .map_err(|source| DescriptorCacheError::ReadDescriptorStagingMarker {
754 path: staging_directory.to_path_buf(),
755 source,
756 })?;
757 if staging_exists {
758 let staging_owned =
759 descriptor_staging_marker_is_valid(staging_directory).map_err(|source| {
760 DescriptorCacheError::ReadDescriptorStagingMarker {
761 path: staging_directory.to_path_buf(),
762 source,
763 }
764 })?;
765 if !staging_owned {
766 return Err(DescriptorCacheError::UnownedRecoveryStaging(
767 staging_directory.to_path_buf(),
768 ));
769 }
770 remove_exact_owned_directory(staging_directory, "staging")?;
771 }
772 remove_exact_owned_directory(&request.target_directory, "target")
773}
774
775fn remove_completed_staging(staging_directory: &Path) -> Result<(), DescriptorCacheError> {
776 let staging_owned =
777 descriptor_staging_marker_is_valid(staging_directory).map_err(|source| {
778 DescriptorCacheError::ReadDescriptorStagingMarker {
779 path: staging_directory.to_path_buf(),
780 source,
781 }
782 })?;
783 if !staging_owned {
784 return Err(DescriptorCacheError::UnownedRecoveryStaging(
785 staging_directory.to_path_buf(),
786 ));
787 }
788 remove_exact_owned_directory(staging_directory, "completed staging")
789}
790
791fn remove_exact_owned_directory(
792 path: &Path,
793 kind: &'static str,
794) -> Result<(), DescriptorCacheError> {
795 let metadata = match fs::symlink_metadata(path) {
796 Ok(metadata) => metadata,
797 Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(()),
798 Err(source) => {
799 return Err(DescriptorCacheError::RemoveRecoveryDirectory {
800 kind,
801 path: path.to_path_buf(),
802 source,
803 });
804 }
805 };
806 if !metadata.file_type().is_dir() {
807 return Err(DescriptorCacheError::UnsafeRecoveryDirectory {
808 kind,
809 path: path.to_path_buf(),
810 });
811 }
812 fs::remove_dir_all(path).map_err(|source| DescriptorCacheError::RemoveRecoveryDirectory {
813 kind,
814 path: path.to_path_buf(),
815 source,
816 })
817}
818
819fn create_cache_layout(cache_directory: &Path) -> Result<(), DescriptorCacheError> {
820 for relative in ["units", "objects", "artifacts", "snapshots"] {
821 let path = cache_directory.join(relative);
822 ensure_plain_directory(&path)?;
823 }
824 Ok(())
825}
826
827fn ensure_plain_directory(path: &Path) -> Result<(), DescriptorCacheError> {
828 match fs::symlink_metadata(path) {
829 Ok(metadata) if metadata.file_type().is_dir() => return Ok(()),
830 Ok(_) => return Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf())),
831 Err(source) if source.kind() == io::ErrorKind::NotFound => {}
832 Err(source) => {
833 return Err(DescriptorCacheError::CreateCacheDirectory {
834 path: path.to_path_buf(),
835 source,
836 });
837 }
838 }
839 fs::create_dir_all(path).map_err(|source| DescriptorCacheError::CreateCacheDirectory {
840 path: path.to_path_buf(),
841 source,
842 })?;
843 let metadata = fs::symlink_metadata(path).map_err(|source| {
844 DescriptorCacheError::CreateCacheDirectory {
845 path: path.to_path_buf(),
846 source,
847 }
848 })?;
849 if metadata.file_type().is_dir() {
850 Ok(())
851 } else {
852 Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf()))
853 }
854}
855
856fn require_plain_directory(path: &Path) -> Result<(), DescriptorCacheError> {
857 match fs::symlink_metadata(path) {
858 Ok(metadata) if metadata.file_type().is_dir() => Ok(()),
859 Ok(_) => Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf())),
860 Err(source) => Err(DescriptorCacheError::ReadCacheFile {
861 path: path.to_path_buf(),
862 source,
863 }),
864 }
865}
866
867#[derive(Clone, Debug)]
868struct ArtifactEvidence {
869 artifact: CargoCompilerArtifact,
870 coordinate: String,
871}
872
873fn collect_artifact_evidence(
874 artifacts: &[CargoCompilerArtifact],
875) -> Result<Vec<ArtifactEvidence>, DescriptorCacheError> {
876 let mut evidence = Vec::with_capacity(artifacts.len());
877 let mut seen = BTreeSet::new();
878 for artifact in artifacts {
879 let mut hash = CacheHasher::new(ARTIFACT_COORDINATE_DOMAIN);
880 hash.field("package_id", artifact.package_id.as_bytes());
881 hash.path("manifest_path", &artifact.manifest_path)?;
882 hash.field("target_name", artifact.target.name.as_bytes());
883 hash.set(
884 "target_kind",
885 artifact.target.kind.iter().map(String::as_bytes),
886 );
887 hash.set(
888 "crate_types",
889 artifact.target.crate_types.iter().map(String::as_bytes),
890 );
891 hash.path("source_path", &artifact.target.src_path)?;
892 hash.field("edition", artifact.target.edition.as_bytes());
893 hash.field("profile", &canonical_json(&artifact.profile));
894 hash.set("features", artifact.features.iter().map(String::as_bytes));
895
896 hash.field(
897 "filename_count",
898 &(artifact.filenames.len() as u64).to_be_bytes(),
899 );
900 for path in &artifact.filenames {
901 hash.path("filename", path)?;
902 }
903 match &artifact.executable {
904 Some(path) => {
905 hash.field("executable_present", b"1");
906 hash.path("executable", path)?;
907 }
908 None => hash.field("executable_present", b"0"),
909 }
910
911 let coordinate = hash.finish();
912 if !seen.insert(coordinate.clone()) {
913 return Err(DescriptorCacheError::DuplicateArtifactCoordinate(
914 coordinate,
915 ));
916 }
917 evidence.push(ArtifactEvidence {
918 artifact: artifact.clone(),
919 coordinate,
920 });
921 }
922 evidence.sort_by(|left, right| left.coordinate.cmp(&right.coordinate));
923 Ok(evidence)
924}
925
926fn artifact_set_coordinate(evidence: &[ArtifactEvidence]) -> String {
927 let mut hash = CacheHasher::new(ARTIFACT_SET_COORDINATE_DOMAIN);
928 hash.field("artifact_count", &(evidence.len() as u64).to_be_bytes());
929 for artifact in evidence {
930 hash.field("artifact", artifact.coordinate.as_bytes());
931 }
932 hash.finish()
933}
934
935fn coordinate_for_artifact(
936 artifact: &CargoCompilerArtifact,
937 evidence: &[ArtifactEvidence],
938) -> Result<String, DescriptorCacheError> {
939 let candidates = evidence
940 .iter()
941 .filter(|candidate| candidate.artifact == *artifact)
942 .collect::<Vec<_>>();
943 match candidates.as_slice() {
944 [candidate] => Ok(candidate.coordinate.clone()),
945 [] => Err(DescriptorCacheError::ArtifactMissingFromCurrentEvidence),
946 _ => Err(DescriptorCacheError::AmbiguousCurrentArtifactEvidence),
947 }
948}
949
950#[derive(Debug, Serialize, Deserialize)]
951#[serde(deny_unknown_fields)]
952struct ArtifactCacheIndex {
953 schema_version: u16,
954 artifact_coordinate: String,
955 units: Vec<CachedUnitGeneration>,
956}
957
958#[derive(Debug, Serialize, Deserialize)]
959#[serde(deny_unknown_fields)]
960struct ArtifactSetSnapshot {
961 schema_version: u16,
962 artifact_set_coordinate: String,
963 artifact_coordinates: Vec<String>,
964 units: Vec<CachedUnitGeneration>,
965}
966
967#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
969#[serde(deny_unknown_fields)]
970struct CachedUnitGeneration {
971 cargo_unit_id: String,
972 descriptor_object_hash: String,
973 sidecar_hash: String,
974}
975
976impl CachedUnitGeneration {
977 fn unit(&self, path: &Path) -> Result<DescriptorCargoUnitId, DescriptorCacheError> {
978 DescriptorCargoUnitId::from_hex(&self.cargo_unit_id).map_err(|source| {
979 DescriptorCacheError::InvalidCachedUnitId {
980 path: path.to_path_buf(),
981 source,
982 }
983 })
984 }
985
986 fn validate_hashes(&self, path: &Path) -> Result<(), DescriptorCacheError> {
987 validate_cache_hash(&self.descriptor_object_hash).map_err(|reason| {
988 DescriptorCacheError::InvalidCachedGenerationHash {
989 path: path.to_path_buf(),
990 field: "descriptor_object_hash",
991 value: self.descriptor_object_hash.clone(),
992 reason,
993 }
994 })?;
995 validate_cache_hash(&self.sidecar_hash).map_err(|reason| {
996 DescriptorCacheError::InvalidCachedGenerationHash {
997 path: path.to_path_buf(),
998 field: "sidecar_hash",
999 value: self.sidecar_hash.clone(),
1000 reason,
1001 }
1002 })
1003 }
1004}
1005
1006fn load_artifact_index(
1007 cache_directory: &Path,
1008 coordinate: &str,
1009) -> Result<ParsedArtifactIndex, DescriptorCacheError> {
1010 let path = cache_directory
1011 .join("artifacts")
1012 .join(format!("{coordinate}.json"));
1013 match fs::symlink_metadata(&path) {
1014 Ok(metadata) if !metadata.file_type().is_file() => {
1015 return Err(DescriptorCacheError::UnsafeCacheEntry(path));
1016 }
1017 Ok(_) => {}
1018 Err(source) if source.kind() == io::ErrorKind::NotFound => {
1019 return Err(DescriptorCacheError::MissingArtifactIndex {
1020 coordinate: coordinate.to_string(),
1021 });
1022 }
1023 Err(source) => return Err(DescriptorCacheError::ReadCacheFile { path, source }),
1024 }
1025 let bytes = fs::read(&path).map_err(|source| DescriptorCacheError::ReadCacheFile {
1026 path: path.clone(),
1027 source,
1028 })?;
1029 let index: ArtifactCacheIndex =
1030 serde_json::from_slice(&bytes).map_err(|source| DescriptorCacheError::ParseCacheFile {
1031 path: path.clone(),
1032 source,
1033 })?;
1034 if index.schema_version != DESCRIPTOR_CACHE_SCHEMA_VERSION {
1035 return Err(DescriptorCacheError::UnsupportedCacheSchema {
1036 path,
1037 actual: index.schema_version,
1038 expected: DESCRIPTOR_CACHE_SCHEMA_VERSION,
1039 });
1040 }
1041 if index.artifact_coordinate != coordinate {
1042 return Err(DescriptorCacheError::CacheCoordinateMismatch {
1043 path,
1044 expected: coordinate.to_string(),
1045 actual: index.artifact_coordinate,
1046 });
1047 }
1048 Ok(ParsedArtifactIndex {
1049 units: parse_unique_generations(&path, index.units)?,
1050 })
1051}
1052
1053struct ParsedArtifactIndex {
1054 units: Vec<CachedUnitGeneration>,
1055}
1056
1057fn load_snapshot(
1058 cache_directory: &Path,
1059 coordinate: &str,
1060 evidence: &[ArtifactEvidence],
1061) -> Result<ParsedSnapshot, DescriptorCacheError> {
1062 let path = cache_directory
1063 .join("snapshots")
1064 .join(format!("{coordinate}.json"));
1065 match fs::symlink_metadata(&path) {
1066 Ok(metadata) if !metadata.file_type().is_file() => {
1067 return Err(DescriptorCacheError::UnsafeCacheEntry(path));
1068 }
1069 Ok(_) => {}
1070 Err(source) if source.kind() == io::ErrorKind::NotFound => {
1071 return Err(DescriptorCacheError::MissingArtifactSetSnapshot {
1072 coordinate: coordinate.to_string(),
1073 });
1074 }
1075 Err(source) => return Err(DescriptorCacheError::ReadCacheFile { path, source }),
1076 }
1077 let bytes = fs::read(&path).map_err(|source| DescriptorCacheError::ReadCacheFile {
1078 path: path.clone(),
1079 source,
1080 })?;
1081 let snapshot: ArtifactSetSnapshot =
1082 serde_json::from_slice(&bytes).map_err(|source| DescriptorCacheError::ParseCacheFile {
1083 path: path.clone(),
1084 source,
1085 })?;
1086 if snapshot.schema_version != DESCRIPTOR_CACHE_SCHEMA_VERSION {
1087 return Err(DescriptorCacheError::UnsupportedCacheSchema {
1088 path,
1089 actual: snapshot.schema_version,
1090 expected: DESCRIPTOR_CACHE_SCHEMA_VERSION,
1091 });
1092 }
1093 if snapshot.artifact_set_coordinate != coordinate {
1094 return Err(DescriptorCacheError::CacheCoordinateMismatch {
1095 path,
1096 expected: coordinate.to_string(),
1097 actual: snapshot.artifact_set_coordinate,
1098 });
1099 }
1100 let expected_artifacts = evidence
1101 .iter()
1102 .map(|artifact| artifact.coordinate.clone())
1103 .collect::<Vec<_>>();
1104 if snapshot.artifact_coordinates != expected_artifacts {
1105 return Err(DescriptorCacheError::SnapshotArtifactSetMismatch(path));
1106 }
1107 Ok(ParsedSnapshot {
1108 units: parse_unique_generations(&path, snapshot.units)?,
1109 })
1110}
1111
1112struct ParsedSnapshot {
1113 units: Vec<CachedUnitGeneration>,
1114}
1115
1116fn parse_unique_generations(
1117 path: &Path,
1118 encoded: Vec<CachedUnitGeneration>,
1119) -> Result<Vec<CachedUnitGeneration>, DescriptorCacheError> {
1120 let mut units = Vec::with_capacity(encoded.len());
1121 let mut seen = BTreeSet::new();
1122 for generation in encoded {
1123 generation.validate_hashes(path)?;
1124 let unit = generation.unit(path)?;
1125 if !seen.insert(unit) {
1126 return Err(DescriptorCacheError::DuplicateCachedUnit {
1127 path: path.to_path_buf(),
1128 unit,
1129 });
1130 }
1131 units.push(generation);
1132 }
1133 Ok(units)
1134}
1135
1136fn validate_cache_hash(value: &str) -> Result<(), String> {
1137 if value.len() != 64 {
1138 return Err(format!(
1139 "expected 64 lowercase hexadecimal characters, got {}",
1140 value.len()
1141 ));
1142 }
1143 if let Some((offset, byte)) = value
1144 .bytes()
1145 .enumerate()
1146 .find(|(_, byte)| !matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1147 {
1148 return Err(format!(
1149 "invalid byte `{}` at offset {offset}",
1150 char::from(byte)
1151 ));
1152 }
1153 Ok(())
1154}
1155
1156fn load_cached_units_direct(
1157 cache_directory: &Path,
1158 units: &BTreeMap<DescriptorCargoUnitId, CachedUnitGeneration>,
1159) -> Result<Vec<ValidatedDescriptorUnit>, DescriptorCacheError> {
1160 let mut cached = Vec::with_capacity(units.len());
1161 for (unit, generation) in units {
1162 let sidecar_source = cached_sidecar_path(cache_directory, generation);
1163 let object_source = cached_object_path(cache_directory, generation);
1164 require_plain_directory(sidecar_source.parent().ok_or_else(|| {
1165 DescriptorCacheError::CachePathWithoutParent(sidecar_source.clone())
1166 })?)?;
1167 require_plain_directory(
1168 object_source.parent().ok_or_else(|| {
1169 DescriptorCacheError::CachePathWithoutParent(object_source.clone())
1170 })?,
1171 )?;
1172 require_file(&sidecar_source, *unit, CacheUnitFileKind::Sidecar)?;
1173 require_file(&object_source, *unit, CacheUnitFileKind::Object)?;
1174 let sidecar_bytes =
1175 fs::read(&sidecar_source).map_err(|source| DescriptorCacheError::ReadCacheFile {
1176 path: sidecar_source.clone(),
1177 source,
1178 })?;
1179 let actual_sidecar_hash = cached_sidecar_hash(&sidecar_bytes);
1180 if actual_sidecar_hash != generation.sidecar_hash {
1181 return Err(DescriptorCacheError::CachedSidecarHashMismatch {
1182 unit: *unit,
1183 expected: generation.sidecar_hash.clone(),
1184 actual: actual_sidecar_hash,
1185 });
1186 }
1187 let sidecar: DescriptorUnitSidecar =
1188 serde_json::from_slice(&sidecar_bytes).map_err(|source| {
1189 DescriptorCacheError::ParseCacheFile {
1190 path: sidecar_source.clone(),
1191 source,
1192 }
1193 })?;
1194 if sidecar.schema_version != crate::rsjs::build::DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION {
1195 return Err(DescriptorCacheError::CachedSidecarSchemaMismatch {
1196 path: sidecar_source,
1197 actual: sidecar.schema_version,
1198 expected: crate::rsjs::build::DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION,
1199 });
1200 }
1201 if sidecar.cargo_unit_id != unit.to_string() {
1202 return Err(DescriptorCacheError::CachedSidecarUnitMismatch {
1203 unit: *unit,
1204 actual: sidecar.cargo_unit_id,
1205 });
1206 }
1207 let expected_object = format!("objects/{unit}.o");
1208 if sidecar.descriptor_object != expected_object {
1209 return Err(DescriptorCacheError::CachedSidecarObjectPathMismatch {
1210 unit: *unit,
1211 actual: sidecar.descriptor_object,
1212 expected: expected_object,
1213 });
1214 }
1215 if sidecar.descriptor_object_hash != generation.descriptor_object_hash {
1216 return Err(DescriptorCacheError::CachedGenerationObjectHashMismatch {
1217 unit: *unit,
1218 pointer: generation.descriptor_object_hash.clone(),
1219 sidecar: sidecar.descriptor_object_hash,
1220 });
1221 }
1222 validate_cached_sidecar_semantics(*unit, &sidecar, &sidecar_source)?;
1223 cached.push(CachedUnitCandidate {
1224 unit: *unit,
1225 sidecar,
1226 sidecar_path: sidecar_source,
1227 descriptor_object: object_source,
1228 expected_object_hash: generation.descriptor_object_hash.clone(),
1229 });
1230 }
1231
1232 let actual_hashes = cached
1236 .par_iter()
1237 .map(|unit| hash_cached_descriptor_object(&unit.descriptor_object))
1238 .collect::<Vec<_>>();
1239 let mut validated = Vec::with_capacity(cached.len());
1240 for (unit, actual_hash) in cached.into_iter().zip(actual_hashes) {
1241 let actual_hash = actual_hash.map_err(|source| DescriptorCacheError::ReadCacheSource {
1242 path: unit.descriptor_object.clone(),
1243 source,
1244 })?;
1245 if actual_hash != unit.expected_object_hash {
1246 return Err(DescriptorCacheError::DescriptorObjectHashMismatch {
1247 unit: unit.unit,
1248 expected: unit.expected_object_hash,
1249 actual: actual_hash,
1250 });
1251 }
1252 require_file(
1256 &unit.descriptor_object,
1257 unit.unit,
1258 CacheUnitFileKind::Object,
1259 )?;
1260 validated.push(ValidatedDescriptorUnit {
1261 unit: unit.unit,
1262 sidecar: unit.sidecar,
1263 sidecar_path: unit.sidecar_path,
1264 descriptor_object: unit.descriptor_object,
1265 });
1266 }
1267 Ok(validated)
1268}
1269
1270struct CachedUnitCandidate {
1271 unit: DescriptorCargoUnitId,
1272 sidecar: DescriptorUnitSidecar,
1273 sidecar_path: PathBuf,
1274 descriptor_object: PathBuf,
1275 expected_object_hash: String,
1276}
1277
1278fn hash_cached_descriptor_object(path: &Path) -> io::Result<String> {
1279 let mut input = File::open(path)?;
1280 let mut hash = Sha256::new();
1281 hash.update(DESCRIPTOR_OBJECT_HASH_DOMAIN);
1282 let mut buffer = [0_u8; 64 * 1024];
1283 loop {
1284 let read = input.read(&mut buffer)?;
1285 if read == 0 {
1286 break;
1287 }
1288 hash.update(&buffer[..read]);
1289 }
1290 Ok(encode_digest(&hash.finalize().into()))
1291}
1292
1293fn validate_cached_sidecar_semantics(
1294 unit: DescriptorCargoUnitId,
1295 sidecar: &DescriptorUnitSidecar,
1296 path: &Path,
1297) -> Result<(), DescriptorCacheError> {
1298 let invalid = |reason| DescriptorCacheError::InvalidCachedSidecar {
1299 unit,
1300 path: path.to_path_buf(),
1301 reason,
1302 };
1303
1304 if sidecar.normalized_rustc_inputs_hash != unit.to_string() {
1305 return Err(invalid(format!(
1306 "normalized rustc input hash `{}` does not equal the selected unit",
1307 sidecar.normalized_rustc_inputs_hash
1308 )));
1309 }
1310 for (name, value) in [
1311 (
1312 "logical environment hash",
1313 sidecar.logical_environment_hash.as_str(),
1314 ),
1315 (
1316 "realized environment hash",
1317 sidecar.realized_environment_hash.as_str(),
1318 ),
1319 (
1320 "package source-closure hash",
1321 sidecar.package_source_closure_hash.as_str(),
1322 ),
1323 (
1324 "descriptor object hash",
1325 sidecar.descriptor_object_hash.as_str(),
1326 ),
1327 ] {
1328 validate_cache_hash(value)
1329 .map_err(|reason| invalid(format!("invalid {name} `{value}`: {reason}")))?;
1330 }
1331 validate_cached_relative_path(&sidecar.dep_info_path)
1332 .map_err(|reason| invalid(format!("invalid target-relative dep-info path: {reason}")))?;
1333 if !sidecar.dep_info_working_directory.is_absolute() {
1334 return Err(invalid(
1335 "dep-info working directory is relative".to_string(),
1336 ));
1337 }
1338 match &sidecar.out_dir {
1339 Some(out_dir) => validate_cached_relative_path(out_dir)
1340 .map_err(|reason| invalid(format!("invalid OUT_DIR path `{out_dir}`: {reason}")))?,
1341 None if !sidecar.out_dir_dependencies.is_empty() => {
1342 return Err(invalid(
1343 "OUT_DIR dependencies are present without an OUT_DIR coordinate".to_string(),
1344 ));
1345 }
1346 None => {}
1347 }
1348
1349 let mut previous_out_dir = None::<&str>;
1350 for dependency in &sidecar.out_dir_dependencies {
1351 validate_cached_relative_path(&dependency.relative_path).map_err(|reason| {
1352 invalid(format!(
1353 "invalid OUT_DIR dependency path `{}`: {reason}",
1354 dependency.relative_path
1355 ))
1356 })?;
1357 validate_cache_hash(&dependency.content_hash).map_err(|reason| {
1358 invalid(format!(
1359 "invalid OUT_DIR dependency hash for `{}`: {reason}",
1360 dependency.relative_path
1361 ))
1362 })?;
1363 if previous_out_dir.is_some_and(|previous| previous >= dependency.relative_path.as_str()) {
1364 return Err(invalid(
1365 "OUT_DIR dependencies are not strictly sorted and unique".to_string(),
1366 ));
1367 }
1368 previous_out_dir = Some(&dependency.relative_path);
1369 }
1370
1371 let mut previous_source = None::<&Path>;
1372 for dependency in &sidecar.source_dependencies {
1373 if !dependency.absolute_path.is_absolute() {
1374 return Err(invalid(format!(
1375 "observed source path `{}` is relative",
1376 dependency.absolute_path.display()
1377 )));
1378 }
1379 validate_cache_hash(&dependency.content_hash).map_err(|reason| {
1380 invalid(format!(
1381 "invalid observed source hash for `{}`: {reason}",
1382 dependency.absolute_path.display()
1383 ))
1384 })?;
1385 if previous_source.is_some_and(|previous| previous >= dependency.absolute_path.as_path()) {
1386 return Err(invalid(
1387 "observed source dependencies are not strictly sorted and unique".to_string(),
1388 ));
1389 }
1390 previous_source = Some(&dependency.absolute_path);
1391 }
1392
1393 let mut previous_environment = None::<&str>;
1394 for dependency in &sidecar.environment_dependencies {
1395 if dependency.name.is_empty()
1396 || dependency.name.bytes().any(|byte| byte == 0)
1397 || wrapper_control_environment(&dependency.name)
1398 {
1399 return Err(invalid(format!(
1400 "invalid observed environment dependency name `{}`",
1401 dependency.name
1402 )));
1403 }
1404 if let Some(value_hash) = &dependency.value_hash {
1405 validate_cache_hash(value_hash).map_err(|reason| {
1406 invalid(format!(
1407 "invalid observed environment value hash for `{}`: {reason}",
1408 dependency.name
1409 ))
1410 })?;
1411 }
1412 if previous_environment.is_some_and(|previous| previous >= dependency.name.as_str()) {
1413 return Err(invalid(
1414 "environment dependencies are not strictly sorted and unique".to_string(),
1415 ));
1416 }
1417 previous_environment = Some(&dependency.name);
1418 }
1419 if sidecar.out_dir.is_none()
1420 && sidecar
1421 .environment_dependencies
1422 .iter()
1423 .any(|dependency| dependency.name == "OUT_DIR" && dependency.value_hash.is_some())
1424 {
1425 return Err(invalid(
1426 "present OUT_DIR environment dependency has no OUT_DIR coordinate".to_string(),
1427 ));
1428 }
1429
1430 for (extern_name, artifact) in &sidecar.dependency_artifacts {
1431 if extern_name.is_empty() {
1432 return Err(invalid("dependency name is empty".to_string()));
1433 }
1434 if !artifact.path.is_absolute() {
1435 return Err(invalid(format!(
1436 "dependency `{extern_name}` path `{}` is relative",
1437 artifact.path.display()
1438 )));
1439 }
1440 validate_cache_hash(&artifact.content_hash).map_err(|reason| {
1441 invalid(format!(
1442 "invalid dependency hash for `{extern_name}`: {reason}"
1443 ))
1444 })?;
1445 }
1446 if let Some(extra_filename) = &sidecar.cargo_extra_filename {
1447 validate_cached_extra_filename(extra_filename).map_err(|reason| {
1448 invalid(format!(
1449 "invalid Cargo extra-filename `{extra_filename}`: {reason}"
1450 ))
1451 })?;
1452 }
1453 let codegen = &sidecar.descriptor_codegen;
1454 if codegen.codegen_units != 1
1455 || codegen.incremental
1456 || !codegen.link_dead_code
1457 || codegen.lto != "off"
1458 || codegen.strip != "none"
1459 {
1460 return Err(invalid(
1461 "descriptor retention/codegen policy is incompatible".to_string(),
1462 ));
1463 }
1464 Ok(())
1465}
1466
1467fn validate_cached_relative_path(path: &str) -> Result<(), String> {
1468 if path.is_empty() {
1469 return Err("path is empty".to_string());
1470 }
1471 for component in path.split('/') {
1472 if component.is_empty() || matches!(component, "." | "..") {
1473 return Err(format!("invalid path component `{component}`"));
1474 }
1475 if component.contains('\\')
1476 || component.bytes().any(|byte| byte == 0)
1477 || component
1478 .chars()
1479 .any(|character| character.is_whitespace() && character != ' ')
1480 {
1481 return Err(format!("non-portable path component `{component}`"));
1482 }
1483 }
1484 Ok(())
1485}
1486
1487fn validate_cached_extra_filename(value: &str) -> Result<(), String> {
1488 if value.is_empty() {
1489 return Err("the discriminator is empty".to_string());
1490 }
1491 if value.contains(['/', '\\']) {
1492 return Err("path separators are not allowed".to_string());
1493 }
1494 if let Some((offset, character)) = value
1495 .char_indices()
1496 .find(|(_, character)| character.is_control())
1497 {
1498 return Err(format!(
1499 "control character U+{:04X} at byte offset {offset} is not allowed",
1500 u32::from(character)
1501 ));
1502 }
1503 Ok(())
1504}
1505
1506fn cached_sidecar_path(cache: &Path, generation: &CachedUnitGeneration) -> PathBuf {
1507 cache
1508 .join("units")
1509 .join(&generation.cargo_unit_id)
1510 .join(format!("{}.json", generation.sidecar_hash))
1511}
1512
1513fn cached_object_path(cache: &Path, generation: &CachedUnitGeneration) -> PathBuf {
1514 cache
1515 .join("objects")
1516 .join(&generation.cargo_unit_id)
1517 .join(format!("{}.o", generation.descriptor_object_hash))
1518}
1519
1520fn cached_sidecar_hash(bytes: &[u8]) -> String {
1521 let mut hash = Sha256::new();
1522 hash.update(CACHED_SIDECAR_HASH_DOMAIN);
1523 hash.update(bytes);
1524 encode_digest(&hash.finalize().into())
1525}
1526
1527fn require_file(
1528 path: &Path,
1529 unit: DescriptorCargoUnitId,
1530 kind: CacheUnitFileKind,
1531) -> Result<(), DescriptorCacheError> {
1532 match fs::symlink_metadata(path) {
1533 Ok(metadata) if metadata.file_type().is_file() => Ok(()),
1534 Ok(_) => Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf())),
1535 Err(source) if source.kind() == io::ErrorKind::NotFound => {
1536 Err(DescriptorCacheError::MissingCachedUnitFile {
1537 unit,
1538 kind,
1539 path: path.to_path_buf(),
1540 })
1541 }
1542 Err(source) => Err(DescriptorCacheError::ReadCacheFile {
1543 path: path.to_path_buf(),
1544 source,
1545 }),
1546 }
1547}
1548
1549fn validate_cached_unit_inputs(
1550 units_by_id: &BTreeMap<DescriptorCargoUnitId, &ValidatedDescriptorUnit>,
1551 cached_ids: &BTreeSet<DescriptorCargoUnitId>,
1552 descriptor_target: &Path,
1553 cargo_artifacts: &[CargoCompilerArtifact],
1554) -> Result<(), DescriptorCacheError> {
1555 validate_cached_observed_inputs(units_by_id, cached_ids, descriptor_target)?;
1556 validate_cached_dependency_artifacts(units_by_id, cached_ids, cargo_artifacts)
1557}
1558
1559fn validate_cached_observed_inputs(
1560 units_by_id: &BTreeMap<DescriptorCargoUnitId, &ValidatedDescriptorUnit>,
1561 cached_ids: &BTreeSet<DescriptorCargoUnitId>,
1562 descriptor_target: &Path,
1563) -> Result<(), DescriptorCacheError> {
1564 for unit_id in cached_ids {
1565 let unit = units_by_id
1566 .get(unit_id)
1567 .ok_or(DescriptorCacheError::MissingMergedUnit(*unit_id))?;
1568 validate_descriptor_observed_inputs(descriptor_target, &unit.sidecar).map_err(
1569 |source| DescriptorCacheError::CachedOutDirDependencyMismatch {
1570 unit: *unit_id,
1571 source,
1572 },
1573 )?;
1574 }
1575 Ok(())
1576}
1577
1578fn validate_cached_dependency_artifacts(
1579 units_by_id: &BTreeMap<DescriptorCargoUnitId, &ValidatedDescriptorUnit>,
1580 cached_ids: &BTreeSet<DescriptorCargoUnitId>,
1581 cargo_artifacts: &[CargoCompilerArtifact],
1582) -> Result<(), DescriptorCacheError> {
1583 let mut enumerated = BTreeMap::<PathBuf, BTreeSet<usize>>::new();
1584 for (artifact_index, artifact) in cargo_artifacts.iter().enumerate() {
1585 for path in &artifact.filenames {
1586 if classify_dependency_artifact(artifact, path).is_some() {
1587 enumerated
1588 .entry(path.clone())
1589 .or_default()
1590 .insert(artifact_index);
1591 }
1592 }
1593 if let Some(path) = uplifted_root_lib_hashed_rlib(artifact) {
1598 enumerated.entry(path).or_default().insert(artifact_index);
1599 }
1600 }
1601
1602 let mut expected_by_path = BTreeMap::<PathBuf, (String, DescriptorCargoUnitId, String)>::new();
1603 for unit_id in cached_ids {
1604 let unit = units_by_id
1605 .get(unit_id)
1606 .ok_or(DescriptorCacheError::MissingMergedUnit(*unit_id))?;
1607 for (extern_name, artifact) in &unit.sidecar.dependency_artifacts {
1608 match expected_by_path.entry(artifact.path.clone()) {
1609 std::collections::btree_map::Entry::Vacant(entry) => {
1610 entry.insert((artifact.content_hash.clone(), *unit_id, extern_name.clone()));
1611 }
1612 std::collections::btree_map::Entry::Occupied(entry)
1613 if entry.get().0 != artifact.content_hash =>
1614 {
1615 return Err(DescriptorCacheError::ConflictingSidecarArtifactEvidence {
1616 path: artifact.path.clone(),
1617 first: entry.get().0.clone(),
1618 second: artifact.content_hash.clone(),
1619 unit: *unit_id,
1620 extern_name: extern_name.clone(),
1621 });
1622 }
1623 std::collections::btree_map::Entry::Occupied(_) => {}
1624 }
1625 }
1626 }
1627
1628 let expectations = expected_by_path.into_iter().collect::<Vec<_>>();
1629 for (path, (_, unit, extern_name)) in &expectations {
1630 let matches = enumerated.get(path).map_or(0, BTreeSet::len);
1631 match matches {
1632 0 => {
1633 return Err(DescriptorCacheError::CachedDependencyNotEnumerated {
1634 unit: *unit,
1635 extern_name: extern_name.clone(),
1636 path: path.clone(),
1637 });
1638 }
1639 1 => {}
1640 matches => {
1641 return Err(DescriptorCacheError::AmbiguousCachedDependencyArtifact {
1642 unit: *unit,
1643 extern_name: extern_name.clone(),
1644 path: path.clone(),
1645 matches,
1646 });
1647 }
1648 }
1649 }
1650 let actuals = expectations
1651 .par_iter()
1652 .map(|(path, _)| descriptor_input_content_hash(path))
1653 .collect::<Vec<_>>();
1654 for ((path, (expected, unit, extern_name)), actual) in expectations.into_iter().zip(actuals) {
1655 let actual = actual.map_err(|source| DescriptorCacheError::HashCurrentInput {
1656 path: path.clone(),
1657 source,
1658 })?;
1659 if actual != expected {
1660 return Err(DescriptorCacheError::StaleCachedDependency {
1661 unit,
1662 extern_name,
1663 path,
1664 expected,
1665 actual,
1666 });
1667 }
1668 }
1669 Ok(())
1670}
1671
1672fn validate_cached_artifact_joins(
1673 units_by_id: &BTreeMap<DescriptorCargoUnitId, &ValidatedDescriptorUnit>,
1674 cached_ids: &BTreeSet<DescriptorCargoUnitId>,
1675 expected_artifact_by_cached_unit: &BTreeMap<DescriptorCargoUnitId, String>,
1676 cargo_artifacts: &[CargoCompilerArtifact],
1677 evidence: &[ArtifactEvidence],
1678 exact_snapshot: bool,
1679) -> Result<(), DescriptorCacheError> {
1680 for unit_id in cached_ids {
1681 let unit = *units_by_id
1682 .get(unit_id)
1683 .ok_or(DescriptorCacheError::MissingMergedUnit(*unit_id))?;
1684 match join_descriptor_units_to_cargo_artifacts(std::slice::from_ref(unit), cargo_artifacts)
1685 {
1686 Ok(joined) => {
1687 let artifact = joined
1688 .get(unit_id)
1689 .expect("one-unit join returns the requested unit");
1690 let actual = coordinate_for_artifact(artifact, evidence)?;
1691 if let Some(expected) = expected_artifact_by_cached_unit.get(unit_id) {
1692 if *expected != actual {
1693 return Err(DescriptorCacheError::CachedArtifactJoinMismatch {
1694 unit: *unit_id,
1695 expected: expected.clone(),
1696 actual,
1697 });
1698 }
1699 }
1700 }
1701 Err(UnitArtifactJoinError::MissingArtifact(_)) if exact_snapshot => {
1702 }
1706 Err(source) => return Err(DescriptorCacheError::ArtifactJoin(source)),
1707 }
1708 }
1709 Ok(())
1710}
1711
1712fn persist_fresh_units(
1713 cache_directory: &Path,
1714 units: &[ValidatedDescriptorUnit],
1715) -> Result<BTreeMap<DescriptorCargoUnitId, CachedUnitGeneration>, DescriptorCacheError> {
1716 let mut generations = BTreeMap::new();
1717 for unit in units {
1718 let sidecar_bytes = fs::read(&unit.sidecar_path).map_err(|source| {
1719 DescriptorCacheError::ReadCacheSource {
1720 path: unit.sidecar_path.clone(),
1721 source,
1722 }
1723 })?;
1724 let generation = CachedUnitGeneration {
1725 cargo_unit_id: unit.unit.to_string(),
1726 descriptor_object_hash: unit.sidecar.descriptor_object_hash.clone(),
1727 sidecar_hash: cached_sidecar_hash(&sidecar_bytes),
1728 };
1729 generation.validate_hashes(&unit.sidecar_path)?;
1730 atomic_copy_descriptor_object_verified(
1731 &unit.descriptor_object,
1732 &cached_object_path(cache_directory, &generation),
1733 unit.unit,
1734 &generation.descriptor_object_hash,
1735 )?;
1736 atomic_write_immutable_bytes(
1737 &cached_sidecar_path(cache_directory, &generation),
1738 &sidecar_bytes,
1739 )?;
1740 if let Some(previous) = generations.insert(unit.unit, generation.clone()) {
1741 return Err(DescriptorCacheError::ConflictingCachedGeneration {
1742 unit: unit.unit,
1743 first: cached_generation_label(&previous),
1744 second: cached_generation_label(&generation),
1745 });
1746 }
1747 }
1748 Ok(generations)
1749}
1750
1751fn cached_generation_label(generation: &CachedUnitGeneration) -> String {
1752 format!(
1753 "object={},sidecar={}",
1754 generation.descriptor_object_hash, generation.sidecar_hash
1755 )
1756}
1757
1758fn atomic_copy_descriptor_object_verified(
1759 source: &Path,
1760 destination: &Path,
1761 unit: DescriptorCargoUnitId,
1762 expected: &str,
1763) -> Result<(), DescriptorCacheError> {
1764 let parent = destination
1765 .parent()
1766 .ok_or_else(|| DescriptorCacheError::CachePathWithoutParent(destination.to_path_buf()))?;
1767 ensure_plain_directory(parent)?;
1768 let nonce = CACHE_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
1769 let file_name = destination
1770 .file_name()
1771 .and_then(OsStr::to_str)
1772 .ok_or_else(|| DescriptorCacheError::InvalidCacheFilename(destination.to_path_buf()))?;
1773 let temporary = parent.join(format!(".{file_name}.{}.{}.tmp", std::process::id(), nonce));
1774 let mut input =
1775 File::open(source).map_err(|source_error| DescriptorCacheError::ReadCacheSource {
1776 path: source.to_path_buf(),
1777 source: source_error,
1778 })?;
1779 let mut output = OpenOptions::new()
1780 .create_new(true)
1781 .write(true)
1782 .open(&temporary)
1783 .map_err(|source| DescriptorCacheError::WriteCacheFile {
1784 path: temporary.clone(),
1785 source,
1786 })?;
1787 let mut hash = Sha256::new();
1788 hash.update(DESCRIPTOR_OBJECT_HASH_DOMAIN);
1789 let mut buffer = [0_u8; 64 * 1024];
1790 loop {
1791 let read = input.read(&mut buffer).map_err(|source_error| {
1792 DescriptorCacheError::ReadCacheSource {
1793 path: source.to_path_buf(),
1794 source: source_error,
1795 }
1796 })?;
1797 if read == 0 {
1798 break;
1799 }
1800 hash.update(&buffer[..read]);
1801 output.write_all(&buffer[..read]).map_err(|source| {
1802 DescriptorCacheError::WriteCacheFile {
1803 path: temporary.clone(),
1804 source,
1805 }
1806 })?;
1807 }
1808 output
1809 .sync_all()
1810 .map_err(|source| DescriptorCacheError::WriteCacheFile {
1811 path: temporary.clone(),
1812 source,
1813 })?;
1814 drop(output);
1815 let actual = encode_digest(&hash.finalize().into());
1816 if actual != expected {
1817 let _ = fs::remove_file(&temporary);
1818 return Err(DescriptorCacheError::DescriptorObjectHashMismatch {
1819 unit,
1820 expected: expected.to_string(),
1821 actual,
1822 });
1823 }
1824 install_immutable(&temporary, destination)
1825}
1826
1827fn persist_artifact_indexes(
1828 cache_directory: &Path,
1829 units: &[ValidatedDescriptorUnit],
1830 generations: &BTreeMap<DescriptorCargoUnitId, CachedUnitGeneration>,
1831 cargo_artifacts: &[CargoCompilerArtifact],
1832 evidence: &[ArtifactEvidence],
1833) -> Result<(), DescriptorCacheError> {
1834 let joined = join_cargo_enumerated_descriptor_units(units, cargo_artifacts)
1835 .map_err(DescriptorCacheError::ArtifactJoin)?;
1836 let mut units_by_artifact = BTreeMap::<String, Vec<CachedUnitGeneration>>::new();
1837 for (unit, artifact) in joined {
1838 let coordinate = coordinate_for_artifact(&artifact, evidence)?;
1839 let generation = generations
1840 .get(&unit)
1841 .ok_or(DescriptorCacheError::MissingCachedGeneration(unit))?
1842 .clone();
1843 units_by_artifact
1844 .entry(coordinate)
1845 .or_default()
1846 .push(generation);
1847 }
1848 for artifact in evidence {
1849 let mut units = units_by_artifact
1850 .remove(&artifact.coordinate)
1851 .unwrap_or_default();
1852 units.sort();
1853 let index = ArtifactCacheIndex {
1854 schema_version: DESCRIPTOR_CACHE_SCHEMA_VERSION,
1855 artifact_coordinate: artifact.coordinate.clone(),
1856 units,
1857 };
1858 let bytes = serde_json::to_vec_pretty(&index)
1859 .map_err(DescriptorCacheError::SerializeCacheRecord)?;
1860 atomic_write_replaceable(
1861 &cache_directory
1862 .join("artifacts")
1863 .join(format!("{}.json", artifact.coordinate)),
1864 &bytes,
1865 )?;
1866 }
1867 Ok(())
1868}
1869
1870fn persist_snapshot(
1871 cache_directory: &Path,
1872 artifact_set_coordinate: &str,
1873 evidence: &[ArtifactEvidence],
1874 units: impl IntoIterator<Item = CachedUnitGeneration>,
1875) -> Result<(), DescriptorCacheError> {
1876 let snapshot = ArtifactSetSnapshot {
1877 schema_version: DESCRIPTOR_CACHE_SCHEMA_VERSION,
1878 artifact_set_coordinate: artifact_set_coordinate.to_string(),
1879 artifact_coordinates: evidence
1880 .iter()
1881 .map(|artifact| artifact.coordinate.clone())
1882 .collect(),
1883 units: units.into_iter().collect(),
1884 };
1885 let bytes =
1886 serde_json::to_vec_pretty(&snapshot).map_err(DescriptorCacheError::SerializeCacheRecord)?;
1887 atomic_write_replaceable(
1888 &cache_directory
1889 .join("snapshots")
1890 .join(format!("{artifact_set_coordinate}.json")),
1891 &bytes,
1892 )
1893}
1894
1895fn atomic_write_immutable_bytes(
1896 destination: &Path,
1897 bytes: &[u8],
1898) -> Result<(), DescriptorCacheError> {
1899 let parent = destination
1900 .parent()
1901 .ok_or_else(|| DescriptorCacheError::CachePathWithoutParent(destination.to_path_buf()))?;
1902 ensure_plain_directory(parent)?;
1903 let nonce = CACHE_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
1904 let file_name = destination
1905 .file_name()
1906 .and_then(OsStr::to_str)
1907 .ok_or_else(|| DescriptorCacheError::InvalidCacheFilename(destination.to_path_buf()))?;
1908 let temporary = parent.join(format!(".{file_name}.{}.{}.tmp", std::process::id(), nonce));
1909 let mut output = OpenOptions::new()
1910 .create_new(true)
1911 .write(true)
1912 .open(&temporary)
1913 .map_err(|source| DescriptorCacheError::WriteCacheFile {
1914 path: temporary.clone(),
1915 source,
1916 })?;
1917 output
1918 .write_all(bytes)
1919 .and_then(|()| output.sync_all())
1920 .map_err(|source| DescriptorCacheError::WriteCacheFile {
1921 path: temporary.clone(),
1922 source,
1923 })?;
1924 drop(output);
1925 install_immutable(&temporary, destination)
1926}
1927
1928fn atomic_write_replaceable(path: &Path, bytes: &[u8]) -> Result<(), DescriptorCacheError> {
1929 let parent = path
1930 .parent()
1931 .ok_or_else(|| DescriptorCacheError::CachePathWithoutParent(path.to_path_buf()))?;
1932 ensure_plain_directory(parent)?;
1933 let nonce = CACHE_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
1934 let file_name = path
1935 .file_name()
1936 .and_then(OsStr::to_str)
1937 .ok_or_else(|| DescriptorCacheError::InvalidCacheFilename(path.to_path_buf()))?;
1938 let temporary = parent.join(format!(".{file_name}.{}.{}.tmp", std::process::id(), nonce));
1939 let mut file = OpenOptions::new()
1940 .create_new(true)
1941 .write(true)
1942 .open(&temporary)
1943 .map_err(|source| DescriptorCacheError::WriteCacheFile {
1944 path: temporary.clone(),
1945 source,
1946 })?;
1947 file.write_all(bytes)
1948 .and_then(|()| file.write_all(b"\n"))
1949 .and_then(|()| file.sync_all())
1950 .map_err(|source| DescriptorCacheError::WriteCacheFile {
1951 path: temporary.clone(),
1952 source,
1953 })?;
1954 drop(file);
1955
1956 if let Err(source) = replace_file_atomic(&temporary, path) {
1960 let _ = fs::remove_file(&temporary);
1961 return Err(DescriptorCacheError::WriteCacheFile {
1962 path: path.to_path_buf(),
1963 source,
1964 });
1965 }
1966 sync_directory(parent).map_err(|source| DescriptorCacheError::WriteCacheFile {
1967 path: parent.to_path_buf(),
1968 source,
1969 })
1970}
1971
1972#[cfg(not(windows))]
1973fn replace_file_atomic(temporary: &Path, destination: &Path) -> io::Result<()> {
1974 fs::rename(temporary, destination)
1975}
1976
1977#[cfg(windows)]
1978fn replace_file_atomic(temporary: &Path, destination: &Path) -> io::Result<()> {
1979 use std::iter;
1980 use std::os::windows::ffi::OsStrExt as _;
1981 use windows_sys::Win32::Storage::FileSystem::{
1982 MoveFileExW, MOVE_FILE_REPLACE_EXISTING, MOVE_FILE_WRITE_THROUGH,
1983 };
1984
1985 let temporary = temporary
1986 .as_os_str()
1987 .encode_wide()
1988 .chain(iter::once(0))
1989 .collect::<Vec<_>>();
1990 let destination = destination
1991 .as_os_str()
1992 .encode_wide()
1993 .chain(iter::once(0))
1994 .collect::<Vec<_>>();
1995 let result = unsafe {
1996 MoveFileExW(
1997 temporary.as_ptr(),
1998 destination.as_ptr(),
1999 MOVE_FILE_REPLACE_EXISTING | MOVE_FILE_WRITE_THROUGH,
2000 )
2001 };
2002 if result == 0 {
2003 Err(io::Error::last_os_error())
2004 } else {
2005 Ok(())
2006 }
2007}
2008
2009#[cfg(unix)]
2010fn sync_directory(path: &Path) -> io::Result<()> {
2011 File::open(path)?.sync_all()
2012}
2013
2014#[cfg(not(unix))]
2015fn sync_directory(_path: &Path) -> io::Result<()> {
2016 Ok(())
2019}
2020
2021fn install_immutable(temporary: &Path, destination: &Path) -> Result<(), DescriptorCacheError> {
2022 match fs::symlink_metadata(destination) {
2023 Ok(metadata) if !metadata.file_type().is_file() => {
2024 let _ = fs::remove_file(temporary);
2025 return Err(DescriptorCacheError::UnsafeCacheEntry(
2026 destination.to_path_buf(),
2027 ));
2028 }
2029 Ok(_) => {}
2030 Err(source) if source.kind() == io::ErrorKind::NotFound => {}
2031 Err(source) => {
2032 let _ = fs::remove_file(temporary);
2033 return Err(DescriptorCacheError::ReadCacheFile {
2034 path: destination.to_path_buf(),
2035 source,
2036 });
2037 }
2038 }
2039 match fs::hard_link(temporary, destination) {
2040 Ok(()) => {
2041 fs::remove_file(temporary).map_err(|source| DescriptorCacheError::WriteCacheFile {
2042 path: temporary.to_path_buf(),
2043 source,
2044 })?;
2045 Ok(())
2046 }
2047 Err(source) if source.kind() == io::ErrorKind::AlreadyExists => {
2048 let equal = files_equal(temporary, destination)?;
2049 let _ = fs::remove_file(temporary);
2050 if equal {
2051 Ok(())
2052 } else {
2053 Err(DescriptorCacheError::ConflictingCacheEntry(
2054 destination.to_path_buf(),
2055 ))
2056 }
2057 }
2058 Err(source) => Err(DescriptorCacheError::WriteCacheFile {
2059 path: destination.to_path_buf(),
2060 source,
2061 }),
2062 }
2063}
2064
2065fn files_equal(left: &Path, right: &Path) -> Result<bool, DescriptorCacheError> {
2066 let left_metadata =
2067 fs::metadata(left).map_err(|source| DescriptorCacheError::ReadCacheSource {
2068 path: left.to_path_buf(),
2069 source,
2070 })?;
2071 let right_metadata =
2072 fs::metadata(right).map_err(|source| DescriptorCacheError::ReadCacheSource {
2073 path: right.to_path_buf(),
2074 source,
2075 })?;
2076 if left_metadata.len() != right_metadata.len() {
2077 return Ok(false);
2078 }
2079 let mut left_file =
2080 File::open(left).map_err(|source| DescriptorCacheError::ReadCacheSource {
2081 path: left.to_path_buf(),
2082 source,
2083 })?;
2084 let mut right_file =
2085 File::open(right).map_err(|source| DescriptorCacheError::ReadCacheSource {
2086 path: right.to_path_buf(),
2087 source,
2088 })?;
2089 let mut left_buffer = [0_u8; 64 * 1024];
2090 let mut right_buffer = [0_u8; 64 * 1024];
2091 loop {
2092 let left_read = left_file.read(&mut left_buffer).map_err(|source| {
2093 DescriptorCacheError::ReadCacheSource {
2094 path: left.to_path_buf(),
2095 source,
2096 }
2097 })?;
2098 let right_read = right_file.read(&mut right_buffer).map_err(|source| {
2099 DescriptorCacheError::ReadCacheSource {
2100 path: right.to_path_buf(),
2101 source,
2102 }
2103 })?;
2104 if left_read != right_read || left_buffer[..left_read] != right_buffer[..right_read] {
2105 return Ok(false);
2106 }
2107 if left_read == 0 {
2108 return Ok(true);
2109 }
2110 }
2111}
2112
2113fn canonical_json(value: &Value) -> Vec<u8> {
2114 fn write(value: &Value, output: &mut Vec<u8>) {
2115 match value {
2116 Value::Null => output.extend_from_slice(b"n"),
2117 Value::Bool(value) => {
2118 output.extend_from_slice(if *value { b"t" } else { b"f" });
2119 }
2120 Value::Number(value) => {
2121 output.extend_from_slice(b"d");
2122 output.extend_from_slice(value.to_string().as_bytes());
2123 output.push(0);
2124 }
2125 Value::String(value) => {
2126 output.extend_from_slice(b"s");
2127 output.extend_from_slice(&(value.len() as u64).to_be_bytes());
2128 output.extend_from_slice(value.as_bytes());
2129 }
2130 Value::Array(values) => {
2131 output.extend_from_slice(b"a");
2132 output.extend_from_slice(&(values.len() as u64).to_be_bytes());
2133 for value in values {
2134 write(value, output);
2135 }
2136 }
2137 Value::Object(values) => {
2138 output.extend_from_slice(b"o");
2139 output.extend_from_slice(&(values.len() as u64).to_be_bytes());
2140 let mut keys = values.keys().collect::<Vec<_>>();
2141 keys.sort();
2142 for key in keys {
2143 output.extend_from_slice(&(key.len() as u64).to_be_bytes());
2144 output.extend_from_slice(key.as_bytes());
2145 write(&values[key], output);
2146 }
2147 }
2148 }
2149 }
2150
2151 let mut output = Vec::new();
2152 write(value, &mut output);
2153 output
2154}
2155
2156struct CacheHasher(Sha256);
2157
2158impl CacheHasher {
2159 fn new(domain: &[u8]) -> Self {
2160 let mut hash = Sha256::new();
2161 hash.update((domain.len() as u64).to_be_bytes());
2162 hash.update(domain);
2163 Self(hash)
2164 }
2165
2166 fn field(&mut self, name: &str, value: &[u8]) {
2167 self.0.update((name.len() as u64).to_be_bytes());
2168 self.0.update(name.as_bytes());
2169 self.0.update((value.len() as u64).to_be_bytes());
2170 self.0.update(value);
2171 }
2172
2173 fn set<'a>(&mut self, name: &str, values: impl IntoIterator<Item = &'a [u8]>) {
2174 let values = values.into_iter().collect::<Vec<_>>();
2175 self.field(&format!("{name}:len"), &(values.len() as u64).to_be_bytes());
2176 for value in values {
2177 self.field(name, value);
2178 }
2179 }
2180
2181 fn path(&mut self, name: &str, path: &Path) -> Result<(), DescriptorCacheError> {
2182 let path = path
2183 .to_str()
2184 .ok_or_else(|| DescriptorCacheError::NonUtf8CargoPath(path.to_path_buf()))?;
2185 self.field(name, path.as_bytes());
2186 Ok(())
2187 }
2188
2189 fn finish(self) -> String {
2190 encode_digest(&self.0.finalize().into())
2191 }
2192}
2193
2194fn encode_digest(digest: &[u8; 32]) -> String {
2195 use std::fmt::Write as _;
2196
2197 let mut output = String::with_capacity(64);
2198 for byte in digest {
2199 let _ = write!(output, "{byte:02x}");
2200 }
2201 output
2202}
2203
2204#[derive(Clone, Copy, Debug)]
2206pub enum CacheUnitFileKind {
2207 Sidecar,
2209 Object,
2211}
2212
2213impl std::fmt::Display for CacheUnitFileKind {
2214 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2215 match self {
2216 Self::Sidecar => formatter.write_str("sidecar"),
2217 Self::Object => formatter.write_str("object"),
2218 }
2219 }
2220}
2221
2222#[derive(Debug, Error)]
2224pub enum DescriptorCacheError {
2225 #[error("descriptor cache directory must be absolute: `{0}`")]
2227 RelativeCacheDirectory(PathBuf),
2228 #[error("descriptor {kind} directory must be absolute: `{path}`")]
2230 RelativeManagedDirectory {
2231 kind: &'static str,
2233 path: PathBuf,
2235 },
2236 #[error("failed to normalize descriptor managed directory `{path}`: {source}")]
2238 NormalizeManagedDirectory {
2239 path: PathBuf,
2241 #[source]
2243 source: io::Error,
2244 },
2245 #[error("descriptor {first_kind} `{first}` and {second_kind} `{second}` must not overlap")]
2247 OverlappingManagedDirectories {
2248 first_kind: &'static str,
2250 first: PathBuf,
2252 second_kind: &'static str,
2254 second: PathBuf,
2256 },
2257 #[error(
2259 "descriptor {kind} recovery root `{managed}` would contain working directory `{working}`"
2260 )]
2261 UnsafeManagedDirectory {
2262 kind: &'static str,
2264 managed: PathBuf,
2266 working: PathBuf,
2268 },
2269 #[error("descriptor target `{target}` is outside source exclusion `{exclusion}`")]
2271 TargetOutsideSourceExclusion {
2272 target: PathBuf,
2274 exclusion: PathBuf,
2276 },
2277 #[error(
2279 "descriptor source exclusion `{exclusion}` would contain working directory `{working}`"
2280 )]
2281 UnsafeSourceExclusion {
2282 exclusion: PathBuf,
2284 working: PathBuf,
2286 },
2287 #[error("descriptor {kind} `{path}` must be inside in-package source exclusion `{exclusion}`")]
2289 GeneratedStateOutsideSourceExclusion {
2290 kind: &'static str,
2292 path: PathBuf,
2294 exclusion: PathBuf,
2296 },
2297 #[error("failed to create descriptor cache directory `{path}`: {source}")]
2299 CreateCacheDirectory {
2300 path: PathBuf,
2302 #[source]
2304 source: io::Error,
2305 },
2306 #[error("descriptor cache entry is not a plain regular file/directory: `{0}`")]
2308 UnsafeCacheEntry(PathBuf),
2309 #[error("failed to open descriptor cache lock `{path}`: {source}")]
2311 OpenCacheLock {
2312 path: PathBuf,
2314 #[source]
2316 source: io::Error,
2317 },
2318 #[error("failed to acquire descriptor cache lock `{path}`: {source}")]
2320 AcquireCacheLock {
2321 path: PathBuf,
2323 #[source]
2325 source: io::Error,
2326 },
2327 #[error("descriptor cache dirty marker is not a regular file: `{0}`")]
2329 InvalidDirtyMarker(PathBuf),
2330 #[error(
2332 "descriptor cache dirty marker belongs to target `{actual}`, not requested target `{expected}`"
2333 )]
2334 DirtyTargetMismatch {
2335 expected: PathBuf,
2337 actual: PathBuf,
2339 },
2340 #[error(
2343 "descriptor cache dirty staging path resolves to `{actual}`, not journaled `{expected}`"
2344 )]
2345 DirtyStagingMismatch {
2346 expected: PathBuf,
2348 actual: PathBuf,
2350 },
2351 #[error("descriptor cache recovery did not force every Cargo artifact to rebuild")]
2353 RecoveryDidNotFullyRebuild,
2354 #[error("refusing to reset unowned descriptor target `{0}`")]
2356 UnownedRecoveryTarget(PathBuf),
2357 #[error("refusing to reset unowned descriptor staging directory `{0}`")]
2359 UnownedRecoveryStaging(PathBuf),
2360 #[error("failed to read descriptor target ownership marker in `{path}`: {source}")]
2362 ReadDescriptorTargetMarker {
2363 path: PathBuf,
2365 #[source]
2367 source: io::Error,
2368 },
2369 #[error("failed to read descriptor staging ownership marker in `{path}`: {source}")]
2371 ReadDescriptorStagingMarker {
2372 path: PathBuf,
2374 #[source]
2376 source: io::Error,
2377 },
2378 #[error("refusing to remove non-directory descriptor {kind} recovery path `{path}`")]
2380 UnsafeRecoveryDirectory {
2381 kind: &'static str,
2383 path: PathBuf,
2385 },
2386 #[error("failed to remove descriptor {kind} recovery directory `{path}`: {source}")]
2388 RemoveRecoveryDirectory {
2389 kind: &'static str,
2391 path: PathBuf,
2393 #[source]
2395 source: io::Error,
2396 },
2397 #[error(transparent)]
2399 DescriptorCargo(DescriptorCargoRunError),
2400 #[error("failed to hash current Cargo input `{path}`: {source}")]
2402 HashCurrentInput {
2403 path: PathBuf,
2405 #[source]
2407 source: io::Error,
2408 },
2409 #[error(
2412 "descriptor sidecars disagree about Cargo artifact `{path}`: unit {unit} extern `{extern_name}` reports `{second}`, but another unit reports `{first}`"
2413 )]
2414 ConflictingSidecarArtifactEvidence {
2415 path: PathBuf,
2417 first: String,
2419 second: String,
2421 unit: DescriptorCargoUnitId,
2423 extern_name: String,
2425 },
2426 #[error("current Cargo artifact path is not UTF-8: `{0}`")]
2428 NonUtf8CargoPath(PathBuf),
2429 #[error("current Cargo artifacts have duplicate coordinate `{0}`")]
2431 DuplicateArtifactCoordinate(String),
2432 #[error("joined Cargo artifact is absent from current artifact evidence")]
2434 ArtifactMissingFromCurrentEvidence,
2435 #[error("joined Cargo artifact has ambiguous current evidence")]
2437 AmbiguousCurrentArtifactEvidence,
2438 #[error("current artifact `{coordinate}` joined fresh units {first} and {second}")]
2440 MultipleFreshUnitsForArtifact {
2441 coordinate: String,
2443 first: DescriptorCargoUnitId,
2445 second: DescriptorCargoUnitId,
2447 },
2448 #[error("descriptor cache has no exact snapshot for current artifact set `{coordinate}`")]
2450 MissingArtifactSetSnapshot {
2451 coordinate: String,
2453 },
2454 #[error("descriptor cache has no index for fresh Cargo artifact `{coordinate}`")]
2456 MissingArtifactIndex {
2457 coordinate: String,
2459 },
2460 #[error("rebuilt Cargo artifact `{coordinate}` emitted no fresh descriptor wrapper unit")]
2462 RebuiltArtifactMissingFreshUnit {
2463 coordinate: String,
2465 },
2466 #[error("interrupted descriptor recovery unit {0} has no exact current Cargo artifact")]
2469 InterruptedUnitMissingArtifact(DescriptorCargoUnitId),
2470 #[error("interrupted descriptor recovery has conflicting candidates for unit {0}")]
2473 ConflictingInterruptedUnitCandidates(DescriptorCargoUnitId),
2474 #[error("failed to parse descriptor cache file `{path}`: {source}")]
2476 ParseCacheFile {
2477 path: PathBuf,
2479 #[source]
2481 source: serde_json::Error,
2482 },
2483 #[error("failed to read descriptor cache file `{path}`: {source}")]
2485 ReadCacheFile {
2486 path: PathBuf,
2488 #[source]
2490 source: io::Error,
2491 },
2492 #[error("descriptor cache file `{path}` uses schema {actual}; expected {expected}")]
2494 UnsupportedCacheSchema {
2495 path: PathBuf,
2497 actual: u16,
2499 expected: u16,
2501 },
2502 #[error("cached descriptor sidecar `{path}` uses schema {actual}; expected {expected}")]
2504 CachedSidecarSchemaMismatch {
2505 path: PathBuf,
2507 actual: u16,
2509 expected: u16,
2511 },
2512 #[error("cached descriptor sidecar for unit {unit} reports unit `{actual}`")]
2514 CachedSidecarUnitMismatch {
2515 unit: DescriptorCargoUnitId,
2517 actual: String,
2519 },
2520 #[error(
2522 "cached descriptor sidecar for unit {unit} reports object `{actual}`; expected `{expected}`"
2523 )]
2524 CachedSidecarObjectPathMismatch {
2525 unit: DescriptorCargoUnitId,
2527 actual: String,
2529 expected: String,
2531 },
2532 #[error("descriptor cache file `{path}` reports coordinate `{actual}`; expected `{expected}`")]
2534 CacheCoordinateMismatch {
2535 path: PathBuf,
2537 expected: String,
2539 actual: String,
2541 },
2542 #[error("descriptor cache snapshot `{0}` does not list the current artifact set")]
2544 SnapshotArtifactSetMismatch(PathBuf),
2545 #[error("descriptor cache file `{path}` has an invalid unit ID: {source}")]
2547 InvalidCachedUnitId {
2548 path: PathBuf,
2550 #[source]
2552 source: crate::rsjs::build::WrapperError,
2553 },
2554 #[error("descriptor cache file `{path}` has invalid {field} `{value}`: {reason}")]
2556 InvalidCachedGenerationHash {
2557 path: PathBuf,
2559 field: &'static str,
2561 value: String,
2563 reason: String,
2565 },
2566 #[error("descriptor cache file `{path}` repeats unit {unit}")]
2568 DuplicateCachedUnit {
2569 path: PathBuf,
2571 unit: DescriptorCargoUnitId,
2573 },
2574 #[error("cached unit {unit} is claimed by current artifacts `{first}` and `{second}`")]
2576 CachedUnitClaimedByMultipleArtifacts {
2577 unit: DescriptorCargoUnitId,
2579 first: String,
2581 second: String,
2583 },
2584 #[error("cached unit {unit} {kind} is missing at `{path}`")]
2586 MissingCachedUnitFile {
2587 unit: DescriptorCargoUnitId,
2589 kind: CacheUnitFileKind,
2591 path: PathBuf,
2593 },
2594 #[error("merged descriptor staging omitted authorized unit {0}")]
2596 MissingMergedUnit(DescriptorCargoUnitId),
2597 #[error(
2599 "descriptor unit {unit} has conflicting prevalidated object hashes `{first}` and `{second}`"
2600 )]
2601 ConflictingPrevalidatedObjectHash {
2602 unit: DescriptorCargoUnitId,
2604 first: String,
2606 second: String,
2608 },
2609 #[error("descriptor unit {unit} has conflicting cache generations `{first}` and `{second}`")]
2611 ConflictingCachedGeneration {
2612 unit: DescriptorCargoUnitId,
2614 first: String,
2616 second: String,
2618 },
2619 #[error("descriptor unit {0} has no committed cache generation")]
2621 MissingCachedGeneration(DescriptorCargoUnitId),
2622 #[error(
2624 "cached descriptor unit {unit} pointer requires object hash `{pointer}`, but sidecar reports `{sidecar}`"
2625 )]
2626 CachedGenerationObjectHashMismatch {
2627 unit: DescriptorCargoUnitId,
2629 pointer: String,
2631 sidecar: String,
2633 },
2634 #[error(
2636 "cached descriptor sidecar for unit {unit} has hash `{actual}`; expected `{expected}`"
2637 )]
2638 CachedSidecarHashMismatch {
2639 unit: DescriptorCargoUnitId,
2641 expected: String,
2643 actual: String,
2645 },
2646 #[error("cached descriptor sidecar for unit {unit} at `{path}` is invalid: {reason}")]
2649 InvalidCachedSidecar {
2650 unit: DescriptorCargoUnitId,
2652 path: PathBuf,
2654 reason: String,
2656 },
2657 #[error("cached descriptor unit {unit} OUT_DIR dependency validation failed: {source}")]
2660 CachedOutDirDependencyMismatch {
2661 unit: DescriptorCargoUnitId,
2663 #[source]
2665 source: crate::rsjs::build::WrapperError,
2666 },
2667 #[error(
2669 "cached descriptor unit {unit} extern `{extern_name}` path `{path}` is absent from current Cargo artifacts"
2670 )]
2671 CachedDependencyNotEnumerated {
2672 unit: DescriptorCargoUnitId,
2674 extern_name: String,
2676 path: PathBuf,
2678 },
2679 #[error(
2681 "cached descriptor unit {unit} extern `{extern_name}` path `{path}` matches {matches} current Cargo artifacts"
2682 )]
2683 AmbiguousCachedDependencyArtifact {
2684 unit: DescriptorCargoUnitId,
2686 extern_name: String,
2688 path: PathBuf,
2690 matches: usize,
2692 },
2693 #[error(
2695 "cached descriptor unit {unit} extern `{extern_name}` path `{path}` has hash `{actual}`; expected `{expected}`"
2696 )]
2697 StaleCachedDependency {
2698 unit: DescriptorCargoUnitId,
2700 extern_name: String,
2702 path: PathBuf,
2704 expected: String,
2706 actual: String,
2708 },
2709 #[error(
2711 "cached unit {unit} joined current artifact `{actual}` instead of indexed artifact `{expected}`"
2712 )]
2713 CachedArtifactJoinMismatch {
2714 unit: DescriptorCargoUnitId,
2716 expected: String,
2718 actual: String,
2720 },
2721 #[error(transparent)]
2723 MergedSidecars(DescriptorSidecarError),
2724 #[error(transparent)]
2726 ArtifactJoin(UnitArtifactJoinError),
2727 #[error("failed to serialize descriptor cache record: {0}")]
2729 SerializeCacheRecord(serde_json::Error),
2730 #[error("descriptor object for unit {unit} has hash `{actual}`; expected `{expected}`")]
2732 DescriptorObjectHashMismatch {
2733 unit: DescriptorCargoUnitId,
2735 expected: String,
2737 actual: String,
2739 },
2740 #[error("descriptor cache path has no parent: `{0}`")]
2742 CachePathWithoutParent(PathBuf),
2743 #[error("descriptor cache path has an invalid filename: `{0}`")]
2745 InvalidCacheFilename(PathBuf),
2746 #[error("failed to read descriptor cache source `{path}`: {source}")]
2748 ReadCacheSource {
2749 path: PathBuf,
2751 #[source]
2753 source: io::Error,
2754 },
2755 #[error("failed to atomically write descriptor cache file `{path}`: {source}")]
2757 WriteCacheFile {
2758 path: PathBuf,
2760 #[source]
2762 source: io::Error,
2763 },
2764 #[error("descriptor cache content address already contains different bytes: `{0}`")]
2766 ConflictingCacheEntry(PathBuf),
2767}
2768
2769#[cfg(test)]
2770mod tests;