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