1use std::{
2 collections::{BTreeMap, BTreeSet},
3 ffi::{OsStr, OsString},
4 fmt::Write as _,
5 fs::{self, File},
6 io,
7 path::{Path, PathBuf},
8 sync::atomic::{AtomicU64, Ordering},
9 time::{Duration, Instant},
10};
11
12use super::{
13 cache_fs::{
14 ArtifactCacheMaintenance, ArtifactCachePrunePolicy, ArtifactCachePruneReport, CacheFsError,
15 LAST_USED_FILE, RetainedCacheEntry, canonicalize_allow_missing, directory_logical_size,
16 ensure_cache_directory_tag, is_sha256_directory, lock_cache_file,
17 perform_scheduled_cache_maintenance, prune_direct_child_directories,
18 record_cache_entry_use, remove_path_if_present, remove_unretained_entry,
19 try_lock_cache_file,
20 },
21 digest::{
22 FileDigest, InputDigest, InputHasher, copy_file_atomic, digest_bytes, digest_file,
23 digest_labeled_paths, materialize_verified_output, os_bytes, read_file_with_limit,
24 },
25 staging::OwnedDirectory,
26 wasm_cache::{
27 ResolvedCargoBuildInputs, WasmBuildError, WasmBuildSpec, resolve_cargo_build_inputs,
28 },
29};
30
31const ARTIFACT_CACHE_FORMAT: &str = "ic-testkit-artifact-set-v1";
32const MANIFEST_FILE: &str = "manifest.ic-testkit";
33const OUTPUT_FILE_SUFFIX: &str = ".artifact";
34const MAX_PREPARATION_RETRIES: usize = 3;
35static STAGING_SEQUENCE: AtomicU64 = AtomicU64::new(0);
36
37#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
39pub enum ArtifactOutputValidation {
40 RegularFile,
42 #[default]
44 NonEmptyFile,
45}
46
47#[derive(Clone, Eq, PartialEq)]
55pub struct ArtifactCacheSpec {
56 cache_root: PathBuf,
57 namespace: String,
58 recipe_id: String,
59 coordination_scope: String,
60 inputs: Vec<LabeledPath>,
61 tools: Vec<LabeledPath>,
62 arguments: Vec<OsString>,
63 environment: BTreeMap<OsString, Option<OsString>>,
64 identities: Vec<LabeledIdentity>,
66 cargo_build_inputs: Vec<CargoBuildInputSet>,
67 outputs: Vec<OutputSpec>,
68 prune_policy: Option<ArtifactCachePrunePolicy>,
69 prune_interval: Option<Duration>,
70}
71
72pub enum ArtifactCachePreparation {
74 Reused(ArtifactCacheRecord),
76 Build(ArtifactBuildTransaction),
78}
79
80#[derive(Clone, Debug, Eq, PartialEq)]
82pub enum ArtifactCacheOutcome {
83 Built(ArtifactCacheRecord),
85 Reused(ArtifactCacheRecord),
87}
88
89#[derive(Clone, Debug, Eq, PartialEq)]
91pub struct ArtifactCacheRecord {
92 key: InputDigest,
93 input_digest: InputDigest,
94 artifacts: Vec<ArtifactCacheArtifact>,
95 _retention: RetainedCacheEntry,
96 timings: ArtifactCacheTimings,
97 maintenance: Option<ArtifactCacheMaintenance>,
98}
99
100#[derive(Clone, Debug, Eq, PartialEq)]
102pub struct ArtifactCacheArtifact {
103 name: String,
104 path: PathBuf,
105}
106
107#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
109pub struct ArtifactCacheTimings {
110 coordination_lock_wait: Duration,
111 content_lock_wait: Duration,
112 namespace_lock_wait: Duration,
113 input_capture: Duration,
114 cache_lookup: Duration,
115 caller_build: Option<Duration>,
116 output_validation: Duration,
117 publication: Duration,
118 materialization: Duration,
119 maintenance: Option<Duration>,
120 total: Duration,
121}
122
123pub struct ArtifactBuildTransaction {
125 spec: Box<ArtifactCacheSpec>,
126 resolved: ResolvedKey,
127 staging_directory: OwnedDirectory,
129 entry_directory: PathBuf,
130 namespace_directory: PathBuf,
131 _coordination_lock: File,
132 _content_lock: File,
133 timings: ArtifactCacheTimings,
134 total_started: Instant,
135 caller_build_started: Instant,
136}
137
138#[non_exhaustive]
140#[derive(Debug)]
141pub enum ArtifactCacheError {
142 InvalidSpec {
144 message: String,
146 },
147 Io {
149 operation: &'static str,
151 path: PathBuf,
153 source: io::Error,
155 },
156 InputsChangedDuringPreparation {
158 before: InputDigest,
160 after: InputDigest,
162 },
163 InputsChangedDuringAcquisition {
165 before: InputDigest,
167 after: InputDigest,
169 },
170 CargoBuildInputsChanged {
172 label: String,
174 before: InputDigest,
176 after: InputDigest,
178 },
179 CargoBuildInputRevalidation {
181 label: String,
183 source: WasmBuildError,
185 },
186 InvalidOutputs {
188 outputs: Vec<(String, PathBuf)>,
190 },
191 UnknownOutput {
193 name: String,
195 },
196 FailedTransactionCleanup {
198 transaction_error: Box<Self>,
200 path: PathBuf,
202 source: io::Error,
204 },
205}
206
207#[derive(Clone, Debug, Eq, PartialEq)]
208struct LabeledPath {
209 label: String,
210 path: PathBuf,
211}
212
213#[derive(Clone, Eq, PartialEq)]
214struct LabeledIdentity {
215 label: String,
216 value: Vec<u8>,
217}
218
219#[derive(Clone, Eq, PartialEq)]
220struct CargoBuildInputSet {
221 label: String,
222 build_spec: WasmBuildSpec,
223 resolved: ResolvedCargoBuildInputs,
224}
225
226#[derive(Clone, Debug, Eq, PartialEq)]
227struct OutputSpec {
228 name: String,
229 destination: PathBuf,
230 validation: ArtifactOutputValidation,
231}
232
233#[derive(Clone, Copy)]
234struct ResolvedKey {
235 key: InputDigest,
236 input_digest: InputDigest,
237}
238
239impl ArtifactCacheSpec {
240 #[must_use]
246 pub fn new(cache_root: &Path, namespace: &str, recipe_id: &str) -> Self {
247 Self {
248 cache_root: cache_root.to_owned(),
249 namespace: namespace.to_owned(),
250 recipe_id: recipe_id.to_owned(),
251 coordination_scope: namespace.to_owned(),
252 inputs: Vec::new(),
253 tools: Vec::new(),
254 arguments: Vec::new(),
255 environment: BTreeMap::new(),
256 identities: Vec::new(),
257 cargo_build_inputs: Vec::new(),
258 outputs: Vec::new(),
259 prune_policy: None,
260 prune_interval: None,
261 }
262 }
263
264 #[must_use]
266 pub fn with_coordination_scope(mut self, coordination_scope: &str) -> Self {
267 coordination_scope.clone_into(&mut self.coordination_scope);
268 self
269 }
270
271 #[must_use]
273 pub fn with_input(mut self, label: &str, path: &Path) -> Self {
274 self.inputs.push(LabeledPath {
275 label: label.to_owned(),
276 path: path.to_owned(),
277 });
278 self
279 }
280
281 #[must_use]
283 pub fn with_tool(mut self, label: &str, path: &Path) -> Self {
284 self.tools.push(LabeledPath {
285 label: label.to_owned(),
286 path: path.to_owned(),
287 });
288 self
289 }
290
291 #[must_use]
293 pub fn with_arguments<I, S>(mut self, arguments: I) -> Self
294 where
295 I: IntoIterator<Item = S>,
296 S: AsRef<OsStr>,
297 {
298 self.arguments = arguments
299 .into_iter()
300 .map(|argument| argument.as_ref().to_owned())
301 .collect();
302 self
303 }
304
305 #[must_use]
310 pub fn with_environment<I, K, V>(mut self, environment: I) -> Self
311 where
312 I: IntoIterator<Item = (K, V)>,
313 K: Into<OsString>,
314 V: Into<OsString>,
315 {
316 self.environment.extend(
317 environment
318 .into_iter()
319 .map(|(name, value)| (name.into(), Some(value.into()))),
320 );
321 self
322 }
323
324 #[must_use]
329 pub fn with_unset_environment<I, S>(mut self, names: I) -> Self
330 where
331 I: IntoIterator<Item = S>,
332 S: Into<OsString>,
333 {
334 self.environment
335 .extend(names.into_iter().map(|name| (name.into(), None)));
336 self
337 }
338
339 #[must_use]
343 pub fn with_identity_bytes(mut self, label: &str, value: &[u8]) -> Self {
344 self.identities.push(LabeledIdentity {
345 label: label.to_owned(),
346 value: value.to_vec(),
347 });
348 self.identities
349 .sort_by(|left, right| left.label.cmp(&right.label));
350 self
351 }
352
353 #[must_use]
361 pub fn with_cargo_build_inputs(
362 mut self,
363 label: &str,
364 build_spec: &WasmBuildSpec,
365 resolved: &ResolvedCargoBuildInputs,
366 ) -> Self {
367 self.cargo_build_inputs.push(CargoBuildInputSet {
368 label: label.to_owned(),
369 build_spec: build_spec.clone(),
370 resolved: resolved.clone(),
371 });
372 self.cargo_build_inputs
373 .sort_by(|left, right| left.label.cmp(&right.label));
374 self
375 }
376
377 #[must_use]
379 pub fn with_output(self, name: &str, destination: &Path) -> Self {
380 self.with_output_validation(name, destination, ArtifactOutputValidation::NonEmptyFile)
381 }
382
383 #[must_use]
385 pub fn with_output_validation(
386 mut self,
387 name: &str,
388 destination: &Path,
389 validation: ArtifactOutputValidation,
390 ) -> Self {
391 self.outputs.push(OutputSpec {
392 name: name.to_owned(),
393 destination: destination.to_owned(),
394 validation,
395 });
396 self.outputs
397 .sort_by(|left, right| left.name.cmp(&right.name));
398 self
399 }
400
401 #[must_use]
403 pub const fn with_prune_policy(mut self, policy: ArtifactCachePrunePolicy) -> Self {
404 self.prune_policy = Some(policy);
405 self.prune_interval = None;
406 self
407 }
408
409 #[must_use]
417 pub const fn with_prune_policy_at_most_every(
418 mut self,
419 policy: ArtifactCachePrunePolicy,
420 minimum_interval: Duration,
421 ) -> Self {
422 self.prune_policy = Some(policy);
423 self.prune_interval = Some(minimum_interval);
424 self
425 }
426
427 #[must_use]
429 pub fn cache_root(&self) -> &Path {
430 &self.cache_root
431 }
432
433 #[must_use]
435 pub fn namespace(&self) -> &str {
436 &self.namespace
437 }
438
439 #[must_use]
441 pub fn recipe_id(&self) -> &str {
442 &self.recipe_id
443 }
444}
445
446impl std::fmt::Debug for ArtifactCacheSpec {
447 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448 formatter
449 .debug_struct("ArtifactCacheSpec")
450 .field("cache_root", &self.cache_root)
451 .field("namespace", &self.namespace)
452 .field("recipe_id", &self.recipe_id)
453 .field("coordination_scope", &self.coordination_scope)
454 .field("inputs", &self.inputs)
455 .field("tools", &self.tools)
456 .field("argument_count", &self.arguments.len())
457 .field(
458 "environment_names",
459 &self.environment.keys().collect::<Vec<_>>(),
460 )
461 .field(
462 "identity_labels",
463 &self
464 .identities
465 .iter()
466 .map(|identity| identity.label.as_str())
467 .collect::<Vec<_>>(),
468 )
469 .field(
470 "cargo_build_input_labels",
471 &self
472 .cargo_build_inputs
473 .iter()
474 .map(|input| input.label.as_str())
475 .collect::<Vec<_>>(),
476 )
477 .field("outputs", &self.outputs)
478 .field("prune_policy", &self.prune_policy)
479 .field("prune_interval", &self.prune_interval)
480 .finish()
481 }
482}
483
484impl ArtifactCachePreparation {
485 #[must_use]
487 pub const fn reused_record(&self) -> Option<&ArtifactCacheRecord> {
488 match self {
489 Self::Reused(record) => Some(record),
490 Self::Build(_) => None,
491 }
492 }
493}
494
495impl ArtifactCacheOutcome {
496 #[must_use]
498 pub const fn record(&self) -> &ArtifactCacheRecord {
499 match self {
500 Self::Built(record) | Self::Reused(record) => record,
501 }
502 }
503
504 #[must_use]
506 pub const fn is_reused(&self) -> bool {
507 matches!(self, Self::Reused(_))
508 }
509}
510
511impl ArtifactCacheRecord {
512 #[must_use]
514 pub const fn key(&self) -> InputDigest {
515 self.key
516 }
517
518 #[must_use]
520 pub const fn input_digest(&self) -> InputDigest {
521 self.input_digest
522 }
523
524 #[must_use]
530 pub fn artifacts(&self) -> &[ArtifactCacheArtifact] {
531 &self.artifacts
532 }
533
534 #[must_use]
536 pub const fn timings(&self) -> ArtifactCacheTimings {
537 self.timings
538 }
539
540 #[must_use]
542 pub const fn maintenance(&self) -> Option<&ArtifactCacheMaintenance> {
543 self.maintenance.as_ref()
544 }
545}
546
547impl ArtifactCacheArtifact {
548 #[must_use]
550 pub fn name(&self) -> &str {
551 &self.name
552 }
553
554 #[must_use]
556 pub fn path(&self) -> &Path {
557 &self.path
558 }
559}
560
561impl ArtifactCacheTimings {
562 #[must_use]
564 pub const fn coordination_lock_wait(self) -> Duration {
565 self.coordination_lock_wait
566 }
567
568 #[must_use]
570 pub const fn content_lock_wait(self) -> Duration {
571 self.content_lock_wait
572 }
573
574 #[must_use]
576 pub const fn namespace_lock_wait(self) -> Duration {
577 self.namespace_lock_wait
578 }
579
580 #[must_use]
582 pub const fn input_capture(self) -> Duration {
583 self.input_capture
584 }
585
586 #[must_use]
588 pub const fn cache_lookup(self) -> Duration {
589 self.cache_lookup
590 }
591
592 #[must_use]
594 pub const fn caller_build(self) -> Option<Duration> {
595 self.caller_build
596 }
597
598 #[must_use]
600 pub const fn output_validation(self) -> Duration {
601 self.output_validation
602 }
603
604 #[must_use]
606 pub const fn publication(self) -> Duration {
607 self.publication
608 }
609
610 #[must_use]
612 pub const fn materialization(self) -> Duration {
613 self.materialization
614 }
615
616 #[must_use]
618 pub const fn maintenance(self) -> Option<Duration> {
619 self.maintenance
620 }
621
622 #[must_use]
624 pub const fn total(self) -> Duration {
625 self.total
626 }
627
628 pub(super) fn saturating_add(self, other: Self) -> Self {
629 Self {
630 coordination_lock_wait: self
631 .coordination_lock_wait
632 .saturating_add(other.coordination_lock_wait),
633 content_lock_wait: self
634 .content_lock_wait
635 .saturating_add(other.content_lock_wait),
636 namespace_lock_wait: self
637 .namespace_lock_wait
638 .saturating_add(other.namespace_lock_wait),
639 input_capture: self.input_capture.saturating_add(other.input_capture),
640 cache_lookup: self.cache_lookup.saturating_add(other.cache_lookup),
641 caller_build: [self.caller_build, other.caller_build]
642 .into_iter()
643 .flatten()
644 .reduce(Duration::saturating_add),
645 output_validation: self
646 .output_validation
647 .saturating_add(other.output_validation),
648 publication: self.publication.saturating_add(other.publication),
649 materialization: self.materialization.saturating_add(other.materialization),
650 maintenance: [self.maintenance, other.maintenance]
651 .into_iter()
652 .flatten()
653 .reduce(Duration::saturating_add),
654 total: self.total.saturating_add(other.total),
655 }
656 }
657}
658
659impl std::fmt::Display for ArtifactCacheTimings {
660 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
661 write!(
662 formatter,
663 "total={:?} coordination_lock={:?} content_lock={:?} namespace_lock={:?} inputs={:?} lookup={:?} build={:?} validation={:?} publication={:?} materialization={:?} maintenance={:?}",
664 self.total,
665 self.coordination_lock_wait,
666 self.content_lock_wait,
667 self.namespace_lock_wait,
668 self.input_capture,
669 self.cache_lookup,
670 self.caller_build,
671 self.output_validation,
672 self.publication,
673 self.materialization,
674 self.maintenance,
675 )
676 }
677}
678
679impl std::fmt::Display for ArtifactCacheOutcome {
680 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
681 let state = if self.is_reused() { "reused" } else { "built" };
682 write!(
683 formatter,
684 "{state} key={} artifacts={} {}",
685 self.record().key,
686 self.record().artifacts.len(),
687 self.record().timings,
688 )
689 }
690}
691
692impl ArtifactBuildTransaction {
693 #[must_use]
698 pub fn staging_directory(&self) -> &Path {
699 self.staging_directory.path()
700 }
701
702 pub fn output_path(&self, name: &str) -> Result<PathBuf, ArtifactCacheError> {
707 self.output_index(name)
708 .map(|index| staged_output_path(self.staging_directory.path(), index))
709 .ok_or_else(|| ArtifactCacheError::UnknownOutput {
710 name: name.to_owned(),
711 })
712 }
713
714 pub fn import_output(&self, name: &str, source: &Path) -> Result<(), ArtifactCacheError> {
719 let destination = self.output_path(name)?;
720 copy_file_atomic(source, &destination).map_err(|source_error| ArtifactCacheError::Io {
721 operation: "import artifact output into staging",
722 path: destination,
723 source: source_error,
724 })?;
725 Ok(())
726 }
727
728 pub fn commit(mut self) -> Result<ArtifactCacheOutcome, ArtifactCacheError> {
734 let result = self.commit_inner();
735 match result {
736 Ok(outcome) => Ok(outcome),
737 Err(transaction_error) if self.staging_directory.is_armed() => {
738 let path = self.staging_directory.path().to_owned();
739 match self.staging_directory.try_cleanup() {
740 Ok(()) => Err(transaction_error),
741 Err(source) => Err(ArtifactCacheError::FailedTransactionCleanup {
742 transaction_error: Box::new(transaction_error),
743 path,
744 source,
745 }),
746 }
747 }
748 Err(transaction_error) => Err(transaction_error),
749 }
750 }
751
752 pub fn abort(mut self) -> Result<(), ArtifactCacheError> {
757 self.staging_directory
758 .try_cleanup()
759 .map_err(|source| ArtifactCacheError::Io {
760 operation: "abort artifact cache transaction",
761 path: self.staging_directory.path().to_owned(),
762 source,
763 })?;
764 Ok(())
765 }
766
767 fn output_index(&self, name: &str) -> Option<usize> {
768 self.spec
769 .outputs
770 .iter()
771 .position(|output| output.name == name)
772 }
773
774 fn commit_inner(&mut self) -> Result<ArtifactCacheOutcome, ArtifactCacheError> {
775 self.timings.caller_build = Some(self.caller_build_started.elapsed());
776
777 let validation_started = Instant::now();
778 let output_info = inspect_complete_output_set(&self.spec, self.staging_directory.path())?;
779 self.timings.output_validation = validation_started.elapsed();
780
781 let capture_started = Instant::now();
782 revalidate_cargo_build_input_fingerprints(&self.spec)?;
783 let verified = resolve_key(&self.spec)?;
784 self.timings.input_capture = self
785 .timings
786 .input_capture
787 .saturating_add(capture_started.elapsed());
788 if verified.input_digest != self.resolved.input_digest {
789 return Err(ArtifactCacheError::InputsChangedDuringAcquisition {
790 before: self.resolved.input_digest,
791 after: verified.input_digest,
792 });
793 }
794
795 let publication_started = Instant::now();
796 let manifest =
797 manifest_contents(self.resolved.key, &self.spec, output_info.iter().copied());
798 ic_host_fs::durable::write_bytes(
799 &self.staging_directory.path().join(MANIFEST_FILE),
800 manifest.as_bytes(),
801 )
802 .map_err(|source| ArtifactCacheError::Io {
803 operation: "write artifact cache manifest",
804 path: self.staging_directory.path().join(MANIFEST_FILE),
805 source: io::Error::other(source),
806 })?;
807 let namespace_lock_path = namespace_lock_path(&self.spec);
808 let (_namespace_lock, namespace_wait) =
809 lock_cache_file(&namespace_lock_path).map_err(artifact_cache_fs_error)?;
810 self.timings.namespace_lock_wait = self
811 .timings
812 .namespace_lock_wait
813 .saturating_add(namespace_wait);
814 remove_unretained_entry(&self.entry_directory).map_err(artifact_cache_fs_error)?;
815 fs::rename(self.staging_directory.path(), &self.entry_directory).map_err(|source| {
816 ArtifactCacheError::Io {
817 operation: "publish artifact cache entry",
818 path: self.entry_directory.clone(),
819 source,
820 }
821 })?;
822 self.staging_directory.disarm();
823 self.timings.publication = publication_started.elapsed();
824
825 let materialization_started = Instant::now();
826 materialize_outputs(&self.spec, &self.entry_directory, None)?;
827 self.timings.materialization = materialization_started.elapsed();
828 record_cache_entry_use(&self.entry_directory).map_err(artifact_cache_fs_error)?;
829 let (maintenance, maintenance_timing) = perform_maintenance_locked(
830 &self.spec,
831 &self.namespace_directory,
832 &self.entry_directory,
833 );
834 self.timings.maintenance = maintenance_timing;
835 self.timings.total = self.total_started.elapsed();
836
837 Ok(ArtifactCacheOutcome::Built(cache_record(
838 &self.spec,
839 self.resolved,
840 self.timings,
841 maintenance,
842 )?))
843 }
844}
845
846pub fn prepare_artifact_cache(
865 spec: &ArtifactCacheSpec,
866) -> Result<ArtifactCachePreparation, ArtifactCacheError> {
867 let total_started = Instant::now();
868 validate_spec(spec)?;
869 validate_filesystem_boundaries(spec)?;
870 let namespace_directory = initialize_cache(spec)?;
871
872 let coordination_lock_path = coordination_lock_path(spec);
873 let (coordination_lock, coordination_wait) =
874 lock_cache_file(&coordination_lock_path).map_err(artifact_cache_fs_error)?;
875 let mut timings = ArtifactCacheTimings {
876 coordination_lock_wait: coordination_wait,
877 ..ArtifactCacheTimings::default()
878 };
879 let initial_cargo_started = Instant::now();
880 revalidate_cargo_build_input_fingerprints(spec)?;
881 timings.input_capture = initial_cargo_started.elapsed();
882 let mut last_change = None;
883
884 for _ in 0..MAX_PREPARATION_RETRIES {
885 let capture_started = Instant::now();
886 let resolved = resolve_key(spec)?;
887 timings.input_capture = timings
888 .input_capture
889 .saturating_add(capture_started.elapsed());
890
891 let content_lock_path = content_lock_path(spec, resolved.key);
892 let (content_lock, content_wait) =
893 lock_cache_file(&content_lock_path).map_err(artifact_cache_fs_error)?;
894 timings.content_lock_wait = timings.content_lock_wait.saturating_add(content_wait);
895
896 let verification_started = Instant::now();
897 let verified = resolve_key(spec)?;
898 timings.input_capture = timings
899 .input_capture
900 .saturating_add(verification_started.elapsed());
901 if resolved.input_digest != verified.input_digest {
902 last_change = Some((resolved.input_digest, verified.input_digest));
903 drop(content_lock);
904 continue;
905 }
906
907 let entry_directory = entry_directory(&namespace_directory, resolved.key);
908 let namespace_lock_path = namespace_lock_path(spec);
909 let (namespace_lock, namespace_wait) =
910 lock_cache_file(&namespace_lock_path).map_err(artifact_cache_fs_error)?;
911 timings.namespace_lock_wait = timings.namespace_lock_wait.saturating_add(namespace_wait);
912 let lookup_started = Instant::now();
913 let verified_outputs = validated_cache_outputs(spec, resolved.key, &entry_directory)?;
914 timings.cache_lookup = timings
915 .cache_lookup
916 .saturating_add(lookup_started.elapsed());
917
918 if let Some(output_info) = verified_outputs {
919 let materialization_started = Instant::now();
920 materialize_outputs(spec, &entry_directory, Some(&output_info))?;
921 timings.materialization = timings
922 .materialization
923 .saturating_add(materialization_started.elapsed());
924 let after_started = Instant::now();
925 revalidate_cargo_build_input_fingerprints(spec)?;
926 let after = resolve_key(spec)?;
927 timings.input_capture = timings
928 .input_capture
929 .saturating_add(after_started.elapsed());
930 if after.input_digest != resolved.input_digest {
931 last_change = Some((resolved.input_digest, after.input_digest));
932 drop(namespace_lock);
933 drop(content_lock);
934 continue;
935 }
936 record_cache_entry_use(&entry_directory).map_err(artifact_cache_fs_error)?;
937 let (maintenance, maintenance_timing) =
938 perform_maintenance_locked(spec, &namespace_directory, &entry_directory);
939 timings.maintenance = maintenance_timing;
940 timings.total = total_started.elapsed();
941 return Ok(ArtifactCachePreparation::Reused(cache_record(
942 spec,
943 resolved,
944 timings,
945 maintenance,
946 )?));
947 }
948
949 remove_unretained_entry(&entry_directory).map_err(artifact_cache_fs_error)?;
950 let staging_directory = create_staging_directory(&namespace_directory, resolved.key)?;
951 drop(namespace_lock);
952 return Ok(ArtifactCachePreparation::Build(ArtifactBuildTransaction {
953 spec: Box::new(spec.clone()),
954 resolved,
955 staging_directory: OwnedDirectory::new(staging_directory),
956 entry_directory,
957 namespace_directory,
958 _coordination_lock: coordination_lock,
959 _content_lock: content_lock,
960 timings,
961 total_started,
962 caller_build_started: Instant::now(),
963 }));
964 }
965
966 let (before, after) = last_change.expect("preparation retries require a recorded input change");
967 Err(ArtifactCacheError::InputsChangedDuringPreparation { before, after })
968}
969
970fn revalidate_cargo_build_input_fingerprints(
971 spec: &ArtifactCacheSpec,
972) -> Result<(), ArtifactCacheError> {
973 for cargo_input in &spec.cargo_build_inputs {
974 let current = resolve_cargo_build_inputs(&cargo_input.build_spec).map_err(|source| {
975 ArtifactCacheError::CargoBuildInputRevalidation {
976 label: cargo_input.label.clone(),
977 source,
978 }
979 })?;
980 let before_validation = cargo_input.resolved.validation_digest();
981 let after_validation = current.validation_digest();
982 if after_validation != before_validation {
983 return Err(ArtifactCacheError::CargoBuildInputsChanged {
984 label: cargo_input.label.clone(),
985 before: before_validation,
986 after: after_validation,
987 });
988 }
989 let before = cargo_input.resolved.fingerprint();
990 let after = current.fingerprint();
991 if after != before {
992 return Err(ArtifactCacheError::CargoBuildInputsChanged {
993 label: cargo_input.label.clone(),
994 before,
995 after,
996 });
997 }
998 }
999 Ok(())
1000}
1001
1002pub fn prune_artifact_cache(
1014 cache_root: &Path,
1015 namespace: &str,
1016 policy: ArtifactCachePrunePolicy,
1017) -> Result<ArtifactCachePruneReport, ArtifactCacheError> {
1018 validate_identifier("namespace", namespace)?;
1019 if cache_root.as_os_str().is_empty() {
1020 return invalid_spec("cache root must not be empty");
1021 }
1022 ensure_cache_directory_tag(cache_root).map_err(artifact_cache_fs_error)?;
1023 let namespace_directory = namespace_directory_for(cache_root, namespace);
1024 let lock_path = namespace_lock_path_for(cache_root, namespace);
1025 let (_lock, _) = lock_cache_file(&lock_path).map_err(artifact_cache_fs_error)?;
1026 prune_artifact_namespace_locked(cache_root, &namespace_directory, policy, None)
1027}
1028
1029fn initialize_cache(spec: &ArtifactCacheSpec) -> Result<PathBuf, ArtifactCacheError> {
1030 ensure_cache_directory_tag(&spec.cache_root).map_err(artifact_cache_fs_error)?;
1031 let namespace = namespace_directory(spec);
1032 fs::create_dir_all(entries_directory(&namespace)).map_err(|source| ArtifactCacheError::Io {
1033 operation: "create artifact cache namespace",
1034 path: namespace.clone(),
1035 source,
1036 })?;
1037 Ok(namespace)
1038}
1039
1040fn validate_spec(spec: &ArtifactCacheSpec) -> Result<(), ArtifactCacheError> {
1041 validate_identifier("namespace", &spec.namespace)?;
1042 validate_identifier("recipe identity", &spec.recipe_id)?;
1043 validate_identifier("coordination scope", &spec.coordination_scope)?;
1044 if spec.cache_root.as_os_str().is_empty() {
1045 return invalid_spec("cache root must not be empty");
1046 }
1047 if spec.outputs.is_empty() {
1048 return invalid_spec("at least one artifact output is required");
1049 }
1050
1051 let mut labels = BTreeSet::new();
1052 for (kind, paths) in [("input", &spec.inputs), ("tool", &spec.tools)] {
1053 for path in paths {
1054 validate_path_label(kind, &path.label)?;
1055 if !labels.insert((kind, path.label.as_str())) {
1056 return invalid_spec(&format!("duplicate {kind} label `{}`", path.label));
1057 }
1058 }
1059 }
1060 let mut identity_labels = BTreeSet::new();
1061 for identity in &spec.identities {
1062 validate_label("identity", &identity.label)?;
1063 if !identity_labels.insert(&identity.label) {
1064 return invalid_spec(&format!("duplicate identity label `{}`", identity.label));
1065 }
1066 }
1067 let mut cargo_input_labels = BTreeSet::new();
1068 for cargo_inputs in &spec.cargo_build_inputs {
1069 validate_label("Cargo build input", &cargo_inputs.label)?;
1070 if !cargo_input_labels.insert(&cargo_inputs.label) {
1071 return invalid_spec(&format!(
1072 "duplicate Cargo build input label `{}`",
1073 cargo_inputs.label
1074 ));
1075 }
1076 }
1077 if spec
1078 .environment
1079 .keys()
1080 .any(|name| name.as_os_str().is_empty())
1081 {
1082 return invalid_spec("environment names must not be empty");
1083 }
1084 let mut output_names = BTreeSet::new();
1085 let mut destinations = BTreeSet::new();
1086 for output in &spec.outputs {
1087 validate_output_name(&output.name)?;
1088 if !output_names.insert(&output.name) {
1089 return invalid_spec(&format!("duplicate output name `{}`", output.name));
1090 }
1091 if output.destination.as_os_str().is_empty() {
1092 return invalid_spec(&format!(
1093 "output `{}` destination must not be empty",
1094 output.name
1095 ));
1096 }
1097 if !destinations.insert(&output.destination) {
1098 return invalid_spec(&format!(
1099 "output `{}` shares a destination with another output",
1100 output.name
1101 ));
1102 }
1103 }
1104 Ok(())
1105}
1106
1107fn validate_filesystem_boundaries(spec: &ArtifactCacheSpec) -> Result<(), ArtifactCacheError> {
1108 let cache_root =
1109 canonicalize_allow_missing(&spec.cache_root).map_err(|source| ArtifactCacheError::Io {
1110 operation: "resolve artifact cache root",
1111 path: spec.cache_root.clone(),
1112 source,
1113 })?;
1114 let mut declared_paths = Vec::with_capacity(spec.inputs.len() + spec.tools.len());
1115 for (kind, labeled_paths) in [("input", &spec.inputs), ("tool", &spec.tools)] {
1116 for labeled in labeled_paths {
1117 let canonical =
1118 canonicalize_path(&labeled.path, "canonicalize declared artifact cache path")?;
1119 if canonical.starts_with(&cache_root) {
1120 return invalid_spec(&format!(
1121 "{kind} `{}` must not be located inside the artifact cache root",
1122 labeled.label
1123 ));
1124 }
1125 let is_directory = fs::metadata(&canonical)
1126 .map_err(|source| ArtifactCacheError::Io {
1127 operation: "inspect declared artifact cache path",
1128 path: canonical.clone(),
1129 source,
1130 })?
1131 .is_dir();
1132 let entry_path =
1133 resolve_file_entry(&labeled.path, "resolve declared artifact cache path entry")?;
1134 if entry_path != canonical {
1135 declared_paths.push((kind, labeled.label.as_str(), entry_path, false));
1136 }
1137 declared_paths.push((kind, labeled.label.as_str(), canonical, is_directory));
1138 }
1139 }
1140 for cargo_inputs in &spec.cargo_build_inputs {
1141 if resolved_cargo_inputs_watch_path(&cargo_inputs.resolved, &cache_root)? {
1142 return invalid_spec(&format!(
1143 "artifact cache root must be outside resolved Cargo build inputs `{}` or inside one of their generated-state exclusions",
1144 cargo_inputs.label
1145 ));
1146 }
1147 }
1148
1149 let mut destinations = BTreeSet::new();
1150 for output in &spec.outputs {
1151 let destination =
1152 resolve_file_entry(&output.destination, "resolve artifact output destination")?;
1153 if destination.starts_with(&cache_root) {
1154 return invalid_spec(&format!(
1155 "output `{}` destination must be outside the artifact cache root",
1156 output.name
1157 ));
1158 }
1159 if destinations.iter().any(|other: &PathBuf| {
1160 destination.starts_with(other) || other.starts_with(&destination)
1161 }) {
1162 return invalid_spec(&format!(
1163 "output `{}` destination overlaps another output",
1164 output.name
1165 ));
1166 }
1167 destinations.insert(destination.clone());
1168 for (kind, label, declared, is_directory) in &declared_paths {
1169 if destination == *declared || (*is_directory && destination.starts_with(declared)) {
1170 return invalid_spec(&format!(
1171 "output `{}` destination overlaps declared {kind} `{label}`",
1172 output.name
1173 ));
1174 }
1175 }
1176 for cargo_inputs in &spec.cargo_build_inputs {
1177 if resolved_cargo_inputs_watch_path(&cargo_inputs.resolved, &destination)? {
1178 return invalid_spec(&format!(
1179 "output `{}` destination must be outside resolved Cargo build inputs `{}` or inside one of their generated-state exclusions",
1180 output.name, cargo_inputs.label
1181 ));
1182 }
1183 }
1184 match fs::symlink_metadata(&destination) {
1188 Ok(metadata)
1189 if metadata.is_dir()
1190 || (metadata.file_type().is_symlink()
1191 && fs::metadata(&destination).is_ok_and(|target| target.is_dir())) =>
1192 {
1193 return invalid_spec(&format!(
1194 "output `{}` destination must not be an existing directory",
1195 output.name
1196 ));
1197 }
1198 Ok(_) => {}
1199 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
1200 Err(source) => {
1201 return Err(ArtifactCacheError::Io {
1202 operation: "inspect artifact output destination",
1203 path: destination,
1204 source,
1205 });
1206 }
1207 }
1208 }
1209 Ok(())
1210}
1211
1212fn resolve_file_entry(path: &Path, operation: &'static str) -> Result<PathBuf, ArtifactCacheError> {
1215 let resolved = match (path.parent(), path.file_name()) {
1216 (Some(parent), Some(name)) => {
1217 canonicalize_allow_missing(parent).map(|parent| parent.join(name))
1218 }
1219 _ => canonicalize_allow_missing(path),
1220 };
1221 resolved.map_err(|source| ArtifactCacheError::Io {
1222 operation,
1223 path: path.to_owned(),
1224 source,
1225 })
1226}
1227
1228fn resolved_cargo_inputs_watch_path(
1229 resolved: &ResolvedCargoBuildInputs,
1230 candidate: &Path,
1231) -> Result<bool, ArtifactCacheError> {
1232 for exclusion in resolved.exclusions() {
1233 let exclusion =
1234 canonicalize_allow_missing(exclusion).map_err(|source| ArtifactCacheError::Io {
1235 operation: "resolve Cargo build input exclusion",
1236 path: exclusion.clone(),
1237 source,
1238 })?;
1239 if candidate.starts_with(exclusion) {
1240 return Ok(false);
1241 }
1242 }
1243
1244 for input in resolved.inputs() {
1245 let path = canonicalize_path(input.path(), "canonicalize resolved Cargo build input")?;
1246 let is_directory = fs::metadata(&path)
1247 .map_err(|source| ArtifactCacheError::Io {
1248 operation: "inspect resolved Cargo build input",
1249 path: path.clone(),
1250 source,
1251 })?
1252 .is_dir();
1253 if candidate == path || (is_directory && candidate.starts_with(path)) {
1254 return Ok(true);
1255 }
1256 }
1257 Ok(false)
1258}
1259
1260fn canonicalize_path(path: &Path, operation: &'static str) -> Result<PathBuf, ArtifactCacheError> {
1261 path.canonicalize()
1262 .map_err(|source| ArtifactCacheError::Io {
1263 operation,
1264 path: path.to_owned(),
1265 source,
1266 })
1267}
1268
1269fn validate_identifier(kind: &str, value: &str) -> Result<(), ArtifactCacheError> {
1270 if value.is_empty() {
1271 return invalid_spec(&format!("{kind} must not be empty"));
1272 }
1273 if value.len() > 256 {
1274 return invalid_spec(&format!("{kind} must not exceed 256 bytes"));
1275 }
1276 Ok(())
1277}
1278
1279fn validate_label(kind: &str, value: &str) -> Result<(), ArtifactCacheError> {
1280 if value.is_empty() {
1281 return invalid_spec(&format!("{kind} label must not be empty"));
1282 }
1283 if value.len() > 256 {
1284 return invalid_spec(&format!("{kind} label must not exceed 256 bytes"));
1285 }
1286 Ok(())
1287}
1288
1289fn validate_path_label(kind: &str, value: &str) -> Result<(), ArtifactCacheError> {
1290 validate_label(kind, value)?;
1291 if value
1292 .bytes()
1293 .any(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'/')))
1294 || value
1295 .split('/')
1296 .any(|component| component.is_empty() || matches!(component, "." | ".."))
1297 {
1298 return invalid_spec(&format!(
1299 "{kind} label `{value}` must be a portable relative logical path"
1300 ));
1301 }
1302 Ok(())
1303}
1304
1305fn validate_output_name(name: &str) -> Result<(), ArtifactCacheError> {
1306 if name.is_empty() || name.len() > 128 {
1307 return invalid_spec("output names must contain 1 to 128 bytes");
1308 }
1309 if !name
1310 .bytes()
1311 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
1312 {
1313 return invalid_spec(&format!(
1314 "output name `{name}` must use only ASCII letters, digits, dot, dash, or underscore"
1315 ));
1316 }
1317 if matches!(name, "." | "..") {
1318 return invalid_spec("output names must not be dot path components");
1319 }
1320 Ok(())
1321}
1322
1323fn invalid_spec<T>(message: &str) -> Result<T, ArtifactCacheError> {
1324 Err(ArtifactCacheError::InvalidSpec {
1325 message: message.to_owned(),
1326 })
1327}
1328
1329fn resolve_key(spec: &ArtifactCacheSpec) -> Result<ResolvedKey, ArtifactCacheError> {
1330 let paths = spec
1331 .inputs
1332 .iter()
1333 .map(|input| (PathBuf::from("input").join(&input.label), &input.path))
1334 .chain(
1335 spec.tools
1336 .iter()
1337 .map(|tool| (PathBuf::from("tool").join(&tool.label), &tool.path)),
1338 );
1339 let declared_input_digest = digest_labeled_paths(
1340 "artifact-set-inputs-v1",
1341 paths,
1342 std::slice::from_ref(&spec.cache_root),
1343 )
1344 .map_err(|source| ArtifactCacheError::Io {
1345 operation: "hash artifact cache inputs",
1346 path: spec.cache_root.clone(),
1347 source,
1348 })?;
1349 let input_digest = if spec.cargo_build_inputs.is_empty() {
1350 declared_input_digest
1351 } else {
1352 let mut inputs = InputHasher::new("artifact-set-inputs-with-cargo-v1");
1353 inputs.field("declared-input-digest", declared_input_digest.as_bytes());
1354 for cargo_input in &spec.cargo_build_inputs {
1355 let current = cargo_input
1356 .resolved
1357 .current_validation_digest()
1358 .map_err(|source| ArtifactCacheError::CargoBuildInputRevalidation {
1359 label: cargo_input.label.clone(),
1360 source,
1361 })?;
1362 let before = cargo_input.resolved.validation_digest();
1363 if current != before {
1364 return Err(ArtifactCacheError::CargoBuildInputsChanged {
1365 label: cargo_input.label.clone(),
1366 before,
1367 after: current,
1368 });
1369 }
1370 inputs.field("cargo-input-label", cargo_input.label.as_bytes());
1371 inputs.field(
1372 "cargo-build-fingerprint",
1373 cargo_input.resolved.fingerprint().as_bytes(),
1374 );
1375 inputs.field(
1376 "cargo-input-digest",
1377 cargo_input.resolved.input_digest().as_bytes(),
1378 );
1379 }
1380 inputs.finish()
1381 };
1382
1383 let mut hasher = InputHasher::new(ARTIFACT_CACHE_FORMAT);
1384 hasher.field("namespace", spec.namespace.as_bytes());
1385 hasher.field("recipe-id", spec.recipe_id.as_bytes());
1386 hasher.field("input-digest", input_digest.as_bytes());
1387 for argument in &spec.arguments {
1388 hasher.field("argument", &os_bytes(argument));
1389 }
1390 for (name, value) in &spec.environment {
1391 hasher.field("environment-name", &os_bytes(name));
1392 match value {
1393 Some(value) => hasher.field("environment-value", &os_bytes(value)),
1394 None => hasher.field("environment-unset", b""),
1395 }
1396 }
1397 for identity in &spec.identities {
1398 hasher.field("identity-label", identity.label.as_bytes());
1399 hasher.field("identity-value", &identity.value);
1400 }
1401 for output in &spec.outputs {
1402 hasher.field("output-name", output.name.as_bytes());
1403 hasher.field(
1404 "output-validation",
1405 output.validation.cache_token().as_bytes(),
1406 );
1407 }
1408 Ok(ResolvedKey {
1409 key: hasher.finish(),
1410 input_digest,
1411 })
1412}
1413
1414fn validated_cache_outputs(
1415 spec: &ArtifactCacheSpec,
1416 key: InputDigest,
1417 entry: &Path,
1418) -> Result<Option<Vec<FileDigest>>, ArtifactCacheError> {
1419 let entry_metadata = match fs::symlink_metadata(entry) {
1420 Ok(metadata) => metadata,
1421 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1422 Err(source) => {
1423 return Err(ArtifactCacheError::Io {
1424 operation: "inspect artifact cache entry",
1425 path: entry.to_owned(),
1426 source,
1427 });
1428 }
1429 };
1430 if !entry_metadata.file_type().is_dir() || !cache_entry_root_is_valid(entry)? {
1431 return Ok(None);
1432 }
1433 let manifest_path = entry.join(MANIFEST_FILE);
1434 let manifest_metadata = match fs::symlink_metadata(&manifest_path) {
1435 Ok(metadata) => metadata,
1436 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1437 Err(source) => {
1438 return Err(ArtifactCacheError::Io {
1439 operation: "inspect artifact cache manifest",
1440 path: manifest_path,
1441 source,
1442 });
1443 }
1444 };
1445 if !manifest_metadata.file_type().is_file() {
1446 return Ok(None);
1447 }
1448 let maximum_len = manifest_contents(
1452 key,
1453 spec,
1454 std::iter::repeat(FileDigest {
1455 bytes: u64::MAX,
1456 digest: key,
1457 }),
1458 )
1459 .len();
1460 let Some(manifest) = read_file_with_limit(&manifest_path, maximum_len).map_err(|source| {
1461 ArtifactCacheError::Io {
1462 operation: "read artifact cache manifest",
1463 path: manifest_path,
1464 source,
1465 }
1466 })?
1467 else {
1468 return Ok(None);
1469 };
1470 if !manifest.starts_with(manifest_header(key).as_bytes()) {
1471 return Ok(None);
1472 }
1473 let Some(output_info) = inspect_cached_output_set(spec, entry)? else {
1474 return Ok(None);
1475 };
1476 Ok(
1477 (manifest == manifest_contents(key, spec, output_info.iter().copied()).as_bytes())
1478 .then_some(output_info),
1479 )
1480}
1481
1482fn inspect_complete_output_set(
1483 spec: &ArtifactCacheSpec,
1484 root: &Path,
1485) -> Result<Vec<FileDigest>, ArtifactCacheError> {
1486 let mut info = Vec::new();
1487 let mut invalid = Vec::new();
1488 let output_directory = root.join("outputs");
1489 if !is_plain_directory(
1490 &output_directory,
1491 "inspect artifact staging output directory",
1492 )? {
1493 invalid.push(("<outputs>".to_owned(), output_directory));
1494 return Err(ArtifactCacheError::InvalidOutputs { outputs: invalid });
1495 }
1496 let outputs = &spec.outputs;
1497 for (index, output) in outputs.iter().enumerate() {
1498 let path = staged_output_path(root, index);
1499 match inspect_artifact(&path, output.validation) {
1500 Ok(Some(artifact)) => info.push(artifact),
1501 Ok(None) => invalid.push((output.name.clone(), path)),
1502 Err(source) => {
1503 return Err(ArtifactCacheError::Io {
1504 operation: "inspect staged artifact output",
1505 path,
1506 source,
1507 });
1508 }
1509 }
1510 }
1511 invalid.extend(
1512 undeclared_output_paths(root, outputs.len())?
1513 .into_iter()
1514 .map(|path| ("<undeclared>".to_owned(), path)),
1515 );
1516 invalid.extend(
1517 undeclared_child_paths(
1518 root,
1519 |name| name == "outputs",
1520 "read artifact staging directory",
1521 )?
1522 .into_iter()
1523 .map(|path| ("<undeclared>".to_owned(), path)),
1524 );
1525 if invalid.is_empty() {
1526 Ok(info)
1527 } else {
1528 Err(ArtifactCacheError::InvalidOutputs { outputs: invalid })
1529 }
1530}
1531
1532fn inspect_cached_output_set(
1533 spec: &ArtifactCacheSpec,
1534 root: &Path,
1535) -> Result<Option<Vec<FileDigest>>, ArtifactCacheError> {
1536 let mut info = Vec::new();
1537 let outputs = &spec.outputs;
1538 for (index, output) in outputs.iter().enumerate() {
1539 let path = staged_output_path(root, index);
1540 match inspect_artifact(&path, output.validation) {
1541 Ok(Some(artifact)) => info.push(artifact),
1542 Ok(None) => return Ok(None),
1543 Err(source) => {
1544 return Err(ArtifactCacheError::Io {
1545 operation: "inspect cached artifact output",
1546 path,
1547 source,
1548 });
1549 }
1550 }
1551 }
1552 if !undeclared_output_paths(root, outputs.len())?.is_empty() {
1553 return Ok(None);
1554 }
1555 Ok(Some(info))
1556}
1557
1558fn undeclared_output_paths(
1559 root: &Path,
1560 output_count: usize,
1561) -> Result<Vec<PathBuf>, ArtifactCacheError> {
1562 let output_directory = root.join("outputs");
1563 undeclared_child_paths(
1564 &output_directory,
1565 |name| {
1566 let Some(name) = name.to_str() else {
1567 return false;
1568 };
1569 name.strip_suffix(OUTPUT_FILE_SUFFIX)
1570 .and_then(|index| index.parse::<usize>().ok())
1571 .is_some_and(|index| index < output_count && name == format_output_index(index))
1572 },
1573 "read artifact output directory",
1574 )
1575}
1576
1577fn undeclared_child_paths(
1578 directory: &Path,
1579 is_expected: impl Fn(&OsStr) -> bool,
1580 operation: &'static str,
1581) -> Result<Vec<PathBuf>, ArtifactCacheError> {
1582 let entries = fs::read_dir(directory).map_err(|source| ArtifactCacheError::Io {
1583 operation,
1584 path: directory.to_owned(),
1585 source,
1586 })?;
1587 let mut undeclared = Vec::new();
1588 for entry in entries {
1589 let entry = entry.map_err(|source| ArtifactCacheError::Io {
1590 operation,
1591 path: directory.to_owned(),
1592 source,
1593 })?;
1594 if !is_expected(&entry.file_name()) {
1595 undeclared.push(entry.path());
1596 }
1597 }
1598 Ok(undeclared)
1599}
1600
1601fn cache_entry_root_is_valid(root: &Path) -> Result<bool, ArtifactCacheError> {
1602 let expected = [
1603 "outputs",
1604 MANIFEST_FILE,
1605 LAST_USED_FILE,
1606 super::cache_fs::RETENTION_LOCK_FILE,
1607 ];
1608 if !undeclared_child_paths(
1609 root,
1610 |name| expected.iter().any(|expected| name == *expected),
1611 "read artifact cache entry",
1612 )?
1613 .is_empty()
1614 {
1615 return Ok(false);
1616 }
1617 if !is_plain_directory(
1618 &root.join("outputs"),
1619 "inspect artifact cache output directory",
1620 )? {
1621 return Ok(false);
1622 }
1623 let last_used = root.join(LAST_USED_FILE);
1624 match fs::symlink_metadata(&last_used) {
1625 Ok(metadata) => Ok(metadata.file_type().is_file()),
1626 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(true),
1627 Err(source) => Err(ArtifactCacheError::Io {
1628 operation: "inspect artifact cache use marker",
1629 path: last_used,
1630 source,
1631 }),
1632 }
1633}
1634
1635fn is_plain_directory(path: &Path, operation: &'static str) -> Result<bool, ArtifactCacheError> {
1636 match fs::symlink_metadata(path) {
1637 Ok(metadata) => Ok(metadata.file_type().is_dir()),
1638 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
1639 Err(source) => Err(ArtifactCacheError::Io {
1640 operation,
1641 path: path.to_owned(),
1642 source,
1643 }),
1644 }
1645}
1646
1647fn inspect_artifact(
1648 path: &Path,
1649 validation: ArtifactOutputValidation,
1650) -> io::Result<Option<FileDigest>> {
1651 let metadata = match fs::symlink_metadata(path) {
1652 Ok(metadata) => metadata,
1653 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1654 Err(error) => return Err(error),
1655 };
1656 if !metadata.file_type().is_file() {
1657 return Ok(None);
1658 }
1659 if validation == ArtifactOutputValidation::NonEmptyFile && metadata.len() == 0 {
1660 return Ok(None);
1661 }
1662 digest_file("artifact-set-output-v1", path).map(Some)
1663}
1664
1665fn manifest_header(key: InputDigest) -> String {
1666 format!("{ARTIFACT_CACHE_FORMAT}\nkey:{key}\n")
1667}
1668
1669fn manifest_contents(
1670 key: InputDigest,
1671 spec: &ArtifactCacheSpec,
1672 output_info: impl IntoIterator<Item = FileDigest>,
1673) -> String {
1674 let mut manifest = manifest_header(key);
1675 for ((index, output), info) in spec.outputs.iter().enumerate().zip(output_info) {
1676 writeln!(
1677 manifest,
1678 "output:{index}:{}:{}:{}:{}",
1679 output.name,
1680 output.validation.cache_token(),
1681 info.bytes,
1682 info.digest,
1683 )
1684 .expect("writing an artifact manifest to a String cannot fail");
1685 }
1686 manifest
1687}
1688
1689fn materialize_outputs(
1690 spec: &ArtifactCacheSpec,
1691 entry: &Path,
1692 verified_outputs: Option<&[FileDigest]>,
1693) -> Result<(), ArtifactCacheError> {
1694 for (index, output) in spec.outputs.iter().enumerate() {
1695 let cached = staged_output_path(entry, index);
1698 materialize_verified_output(
1699 "artifact-set-output-v1",
1700 &cached,
1701 &output.destination,
1702 verified_outputs.map(|info| &info[index]),
1703 )
1704 .map_err(|source| ArtifactCacheError::Io {
1705 operation: "materialize artifact output",
1706 path: output.destination.clone(),
1707 source,
1708 })?;
1709 }
1710 Ok(())
1711}
1712
1713fn perform_maintenance_locked(
1714 spec: &ArtifactCacheSpec,
1715 namespace: &Path,
1716 protected_entry: &Path,
1717) -> (Option<ArtifactCacheMaintenance>, Option<Duration>) {
1718 spec.prune_policy.map_or((None, None), |policy| {
1719 let identity = policy.maintenance_identity();
1720 perform_scheduled_cache_maintenance(namespace, spec.prune_interval, &identity, || {
1721 prune_artifact_namespace_locked(
1722 &spec.cache_root,
1723 namespace,
1724 policy,
1725 Some(protected_entry),
1726 )
1727 .map_err(|error| error.to_string())
1728 })
1729 })
1730}
1731
1732fn prune_artifact_namespace_locked(
1733 cache_root: &Path,
1734 namespace: &Path,
1735 policy: ArtifactCachePrunePolicy,
1736 protected_entry: Option<&Path>,
1737) -> Result<ArtifactCachePruneReport, ArtifactCacheError> {
1738 let mut report = prune_direct_child_directories(
1739 &entries_directory(namespace),
1740 policy,
1741 protected_entry,
1742 is_sha256_directory,
1743 )
1744 .map_err(artifact_cache_fs_error)?;
1745 remove_abandoned_staging(cache_root, namespace, &mut report)?;
1746 Ok(report)
1747}
1748
1749fn remove_abandoned_staging(
1750 cache_root: &Path,
1751 namespace: &Path,
1752 report: &mut ArtifactCachePruneReport,
1753) -> Result<(), ArtifactCacheError> {
1754 let staging_root = namespace.join("staging");
1755 let entries = match fs::read_dir(&staging_root) {
1756 Ok(entries) => entries,
1757 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
1758 Err(source) => {
1759 return Err(ArtifactCacheError::Io {
1760 operation: "read artifact staging root during pruning",
1761 path: staging_root,
1762 source,
1763 });
1764 }
1765 };
1766 for entry in entries {
1767 let entry = entry.map_err(|source| ArtifactCacheError::Io {
1768 operation: "read artifact staging entry during pruning",
1769 path: staging_root.clone(),
1770 source,
1771 })?;
1772 let file_type = entry.file_type().map_err(|source| ArtifactCacheError::Io {
1773 operation: "inspect artifact staging entry during pruning",
1774 path: entry.path(),
1775 source,
1776 })?;
1777 if !file_type.is_dir() {
1778 continue;
1779 }
1780 let file_name = entry.file_name();
1781 let Some(key) = staging_content_key(&file_name) else {
1782 continue;
1783 };
1784 let lock_path = content_lock_path_for_key(cache_root, key);
1785 let Some(_content_lock) =
1786 try_lock_cache_file(&lock_path).map_err(artifact_cache_fs_error)?
1787 else {
1788 continue;
1789 };
1790 let path = entry.path();
1791 let bytes = directory_logical_size(&path).map_err(|source| ArtifactCacheError::Io {
1792 operation: "measure abandoned artifact staging directory",
1793 path: path.clone(),
1794 source,
1795 })?;
1796 remove_path_if_present(&path).map_err(|source| ArtifactCacheError::Io {
1797 operation: "remove abandoned artifact staging directory during pruning",
1798 path,
1799 source,
1800 })?;
1801 report.record_uncommitted_removal(bytes);
1802 }
1803 Ok(())
1804}
1805
1806fn staging_content_key(name: &OsStr) -> Option<&str> {
1807 let name = name.to_str()?;
1808 let (key, suffix) = name.split_once('-')?;
1809 (!suffix.is_empty() && key.len() == 64 && key.as_bytes().iter().all(u8::is_ascii_hexdigit))
1810 .then_some(key)
1811}
1812
1813fn cache_record(
1814 spec: &ArtifactCacheSpec,
1815 resolved: ResolvedKey,
1816 timings: ArtifactCacheTimings,
1817 maintenance: Option<ArtifactCacheMaintenance>,
1818) -> Result<ArtifactCacheRecord, ArtifactCacheError> {
1819 let entry = entry_directory(&namespace_directory(spec), resolved.key);
1820 let retention = RetainedCacheEntry::acquire(&entry).map_err(artifact_cache_fs_error)?;
1821 Ok(ArtifactCacheRecord {
1822 key: resolved.key,
1823 input_digest: resolved.input_digest,
1824 artifacts: spec
1825 .outputs
1826 .iter()
1827 .enumerate()
1828 .map(|(index, output)| ArtifactCacheArtifact {
1829 name: output.name.clone(),
1830 path: staged_output_path(&entry, index),
1831 })
1832 .collect(),
1833 timings,
1834 maintenance,
1835 _retention: retention,
1836 })
1837}
1838
1839fn create_staging_directory(
1840 namespace: &Path,
1841 key: InputDigest,
1842) -> Result<PathBuf, ArtifactCacheError> {
1843 let staging_root = namespace.join("staging");
1844 fs::create_dir_all(&staging_root).map_err(|source| ArtifactCacheError::Io {
1845 operation: "create artifact staging root",
1846 path: staging_root.clone(),
1847 source,
1848 })?;
1849 remove_same_key_staging(&staging_root, key)?;
1850 let sequence = STAGING_SEQUENCE.fetch_add(1, Ordering::Relaxed);
1851 let staging = staging_root.join(format!("{key}-{}-{sequence}", std::process::id()));
1852 fs::create_dir_all(staging.join("outputs")).map_err(|source| ArtifactCacheError::Io {
1853 operation: "create artifact transaction staging directory",
1854 path: staging.clone(),
1855 source,
1856 })?;
1857 Ok(staging)
1858}
1859
1860fn remove_same_key_staging(root: &Path, key: InputDigest) -> Result<(), ArtifactCacheError> {
1861 let prefix = format!("{key}-");
1862 let entries = fs::read_dir(root).map_err(|source| ArtifactCacheError::Io {
1863 operation: "read artifact staging root",
1864 path: root.to_owned(),
1865 source,
1866 })?;
1867 for entry in entries {
1868 let entry = entry.map_err(|source| ArtifactCacheError::Io {
1869 operation: "read artifact staging entry",
1870 path: root.to_owned(),
1871 source,
1872 })?;
1873 if entry.file_name().to_string_lossy().starts_with(&prefix) {
1874 remove_path_if_present(&entry.path()).map_err(|source| ArtifactCacheError::Io {
1875 operation: "remove abandoned artifact staging directory",
1876 path: entry.path(),
1877 source,
1878 })?;
1879 }
1880 }
1881 Ok(())
1882}
1883
1884fn staged_output_path(root: &Path, index: usize) -> PathBuf {
1885 root.join("outputs").join(format_output_index(index))
1886}
1887
1888fn format_output_index(index: usize) -> String {
1889 format!("{index:04}{OUTPUT_FILE_SUFFIX}")
1890}
1891
1892fn namespace_directory(spec: &ArtifactCacheSpec) -> PathBuf {
1893 namespace_directory_for(&spec.cache_root, &spec.namespace)
1894}
1895
1896fn namespace_directory_for(cache_root: &Path, namespace: &str) -> PathBuf {
1897 cache_root
1898 .join(".ic-testkit/artifact-sets/namespaces")
1899 .join(identifier_digest("artifact-cache-namespace-v1", namespace))
1900}
1901
1902fn entries_directory(namespace: &Path) -> PathBuf {
1903 namespace.join("entries")
1904}
1905
1906fn entry_directory(namespace: &Path, key: InputDigest) -> PathBuf {
1907 entries_directory(namespace).join(key.to_hex())
1908}
1909
1910fn coordination_lock_path(spec: &ArtifactCacheSpec) -> PathBuf {
1911 spec.cache_root
1912 .join(".ic-testkit/artifact-sets/locks/coordination")
1913 .join(format!(
1914 "{}.lock",
1915 identifier_digest("artifact-cache-coordination-v1", &spec.coordination_scope,)
1916 ))
1917}
1918
1919fn content_lock_path(spec: &ArtifactCacheSpec, key: InputDigest) -> PathBuf {
1920 content_lock_path_for_key(&spec.cache_root, &key.to_hex())
1921}
1922
1923fn content_lock_path_for_key(cache_root: &Path, key: &str) -> PathBuf {
1924 cache_root
1925 .join(".ic-testkit/artifact-sets/locks/content")
1926 .join(format!("{key}.lock"))
1927}
1928
1929fn namespace_lock_path(spec: &ArtifactCacheSpec) -> PathBuf {
1930 namespace_lock_path_for(&spec.cache_root, &spec.namespace)
1931}
1932
1933fn namespace_lock_path_for(cache_root: &Path, namespace: &str) -> PathBuf {
1934 cache_root
1935 .join(".ic-testkit/artifact-sets/locks/namespaces")
1936 .join(format!(
1937 "{}.lock",
1938 identifier_digest("artifact-cache-namespace-v1", namespace)
1939 ))
1940}
1941
1942fn identifier_digest(domain: &str, identifier: &str) -> String {
1943 digest_bytes(domain, identifier.as_bytes()).to_hex()
1944}
1945
1946fn artifact_cache_fs_error(error: CacheFsError) -> ArtifactCacheError {
1947 ArtifactCacheError::Io {
1948 operation: error.operation,
1949 path: error.path,
1950 source: error.source,
1951 }
1952}
1953
1954impl ArtifactOutputValidation {
1955 const fn cache_token(self) -> &'static str {
1956 match self {
1957 Self::RegularFile => "regular-file",
1958 Self::NonEmptyFile => "nonempty-file",
1959 }
1960 }
1961}
1962
1963impl std::fmt::Display for ArtifactCacheError {
1964 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1965 match self {
1966 Self::InvalidSpec { message } => {
1967 write!(formatter, "invalid artifact cache spec: {message}")
1968 }
1969 Self::Io {
1970 operation,
1971 path,
1972 source,
1973 } => write!(
1974 formatter,
1975 "failed to {operation} at {}: {source}",
1976 path.display()
1977 ),
1978 Self::InputsChangedDuringPreparation { before, after } => write!(
1979 formatter,
1980 "artifact inputs repeatedly changed during cache preparation: {before} -> {after}",
1981 ),
1982 Self::InputsChangedDuringAcquisition { before, after } => write!(
1983 formatter,
1984 "artifact inputs changed while the caller was building: {before} -> {after}",
1985 ),
1986 Self::CargoBuildInputsChanged {
1987 label,
1988 before,
1989 after,
1990 } => write!(
1991 formatter,
1992 "resolved Cargo build inputs `{label}` changed: {before} -> {after}",
1993 ),
1994 Self::CargoBuildInputRevalidation { label, source } => write!(
1995 formatter,
1996 "failed to revalidate resolved Cargo build inputs `{label}`: {source}",
1997 ),
1998 Self::InvalidOutputs { outputs } => write!(
1999 formatter,
2000 "artifact transaction has missing or invalid outputs: {}",
2001 outputs
2002 .iter()
2003 .map(|(name, path)| format!("{name} ({})", path.display()))
2004 .collect::<Vec<_>>()
2005 .join(", "),
2006 ),
2007 Self::UnknownOutput { name } => {
2008 write!(
2009 formatter,
2010 "artifact transaction has no output named `{name}`"
2011 )
2012 }
2013 Self::FailedTransactionCleanup {
2014 transaction_error,
2015 path,
2016 source,
2017 } => write!(
2018 formatter,
2019 "artifact transaction failed ({transaction_error}) and staging cleanup at {} also failed: {source}",
2020 path.display(),
2021 ),
2022 }
2023 }
2024}
2025
2026impl std::error::Error for ArtifactCacheError {
2027 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2028 match self {
2029 Self::Io { source, .. } | Self::FailedTransactionCleanup { source, .. } => Some(source),
2030 Self::CargoBuildInputRevalidation { source, .. } => Some(source),
2031 _ => None,
2032 }
2033 }
2034}
2035
2036#[cfg(test)]
2037mod tests;