1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3#![doc = "Transport-neutral acquisition seam and deterministic fixture transport."]
4#![doc = ""]
5#![doc = "An adapter receives an exact caller-selected URL, enforces caller-provided"]
6#![doc = "byte/time bounds, writes artifacts to a transaction-owned destination, and"]
7#![doc = "returns typed `Success | NotFound | Failure` without release or fallback"]
8#![doc = "policy. Downloaded bytes are data and are never executed."]
9
10use std::collections::HashMap;
11use std::fmt;
12use std::fs;
13use std::path::Path;
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15use std::sync::{Arc, Mutex};
16use std::time::{Duration, Instant};
17
18#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct AcquisitionRequest {
25 url: String,
26}
27
28impl AcquisitionRequest {
29 pub fn new(url: impl Into<String>) -> Result<Self, AcquisitionError> {
34 let url = url.into();
35 if url.is_empty() || url.chars().any(char::is_control) {
36 return Err(AcquisitionError::invalid(
37 "URL is empty or has control characters",
38 ));
39 }
40 if !(url.starts_with("http://") || url.starts_with("https://")) {
41 return Err(AcquisitionError::invalid(
42 "URL must use http:// or https://",
43 ));
44 }
45 if url.len() > 8192 {
46 return Err(AcquisitionError::invalid("URL exceeds bound"));
47 }
48 Ok(Self { url })
49 }
50
51 pub fn url(&self) -> &str {
53 &self.url
54 }
55
56 pub fn redacted(&self) -> String {
58 redact_url(&self.url)
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct FetchLimits {
65 pub max_metadata_bytes: usize,
67 pub max_artifact_bytes: u64,
69 pub connect_timeout: Duration,
71 pub total_timeout: Duration,
73}
74
75impl Default for FetchLimits {
76 fn default() -> Self {
77 Self {
78 max_metadata_bytes: 256 * 1024,
79 max_artifact_bytes: 128 * 1024 * 1024,
80 connect_timeout: Duration::from_secs(10),
81 total_timeout: Duration::from_secs(120),
82 }
83 }
84}
85
86impl FetchLimits {
87 pub fn validate(&self) -> Result<(), AcquisitionError> {
93 if self.max_metadata_bytes == 0 || self.max_metadata_bytes > 16 * 1024 * 1024 {
94 return Err(AcquisitionError::invalid("metadata bound out of range"));
95 }
96 if self.max_artifact_bytes == 0 {
97 return Err(AcquisitionError::invalid("artifact bound must be positive"));
98 }
99 if self.total_timeout.is_zero() || self.connect_timeout.is_zero() {
100 return Err(AcquisitionError::invalid("timeouts must be positive"));
101 }
102 if self.connect_timeout > self.total_timeout {
103 return Err(AcquisitionError::invalid(
104 "connect timeout must not exceed total timeout",
105 ));
106 }
107 Ok(())
108 }
109
110 pub fn new(
117 max_metadata_bytes: usize,
118 max_artifact_bytes: u64,
119 connect_timeout: Duration,
120 total_timeout: Duration,
121 ) -> Result<Self, AcquisitionError> {
122 let limits = Self {
123 max_metadata_bytes,
124 max_artifact_bytes,
125 connect_timeout,
126 total_timeout,
127 };
128 limits.validate()?;
129 Ok(limits)
130 }
131
132 pub fn effective(
144 &self,
145 adapter_connect_ceiling: Duration,
146 adapter_total_ceiling: Duration,
147 ) -> (Duration, Duration) {
148 let connect = std::cmp::min(self.connect_timeout, adapter_connect_ceiling);
149 let total = std::cmp::min(self.total_timeout, adapter_total_ceiling);
150 (connect, total)
151 }
152}
153
154#[derive(Debug, Default)]
159pub struct CancelFlag {
160 cancelled: AtomicBool,
161}
162
163impl CancelFlag {
164 pub fn new() -> Self {
166 Self::default()
167 }
168
169 pub fn cancel(&self) {
171 self.cancelled.store(true, Ordering::SeqCst);
172 }
173
174 pub fn is_cancelled(&self) -> bool {
176 self.cancelled.load(Ordering::SeqCst)
177 }
178}
179
180#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum FetchOutcome<T> {
186 Success(T),
188 NotFound,
190}
191
192impl<T> FetchOutcome<T> {
193 pub fn success(self) -> Option<T> {
195 match self {
196 Self::Success(v) => Some(v),
197 Self::NotFound => None,
198 }
199 }
200
201 pub fn is_success(&self) -> bool {
203 matches!(self, Self::Success(_))
204 }
205
206 pub fn is_not_found(&self) -> bool {
208 matches!(self, Self::NotFound)
209 }
210}
211
212#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct MetadataBytes {
215 bytes: Vec<u8>,
216}
217
218impl MetadataBytes {
219 pub fn bytes(&self) -> &[u8] {
221 &self.bytes
222 }
223
224 pub fn len(&self) -> usize {
226 self.bytes.len()
227 }
228
229 pub fn is_empty(&self) -> bool {
231 self.bytes.is_empty()
232 }
233}
234
235#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct ArtifactEvidence {
238 pub bytes_written: u64,
240}
241
242impl ArtifactEvidence {
243 pub fn bytes_written(&self) -> u64 {
245 self.bytes_written
246 }
247}
248
249#[derive(Debug)]
257#[non_exhaustive]
258pub enum AcquisitionError {
259 InvalidInput(String),
261 Transport(String),
264 TooLarge {
266 limit: u64,
268 },
269 Timeout {
271 phase: &'static str,
273 },
274 Cancelled,
276 Io {
285 operation: &'static str,
287 source: std::io::Error,
289 },
290 Unavailable(String),
297}
298
299impl AcquisitionError {
300 pub(crate) fn invalid(detail: impl Into<String>) -> Self {
301 Self::InvalidInput(bound_detail(detail.into()))
302 }
303
304 pub(crate) fn transport_redacted(detail: impl Into<String>) -> Self {
305 Self::Transport(bound_detail(detail.into()))
306 }
307
308 #[doc(hidden)]
314 pub fn __adapter_unavailable(detail: impl Into<String>) -> Self {
315 Self::Unavailable(bound_detail(detail.into()))
316 }
317
318 #[doc(hidden)]
325 pub fn __adapter_io(operation: &'static str, source: std::io::Error) -> Self {
326 Self::Io { operation, source }
327 }
328
329 pub(crate) fn io(operation: &'static str, source: std::io::Error) -> Self {
330 Self::Io { operation, source }
331 }
332
333 pub fn is_unavailable(&self) -> bool {
335 matches!(self, Self::Unavailable(_))
336 }
337}
338
339impl fmt::Display for AcquisitionError {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 match self {
342 Self::InvalidInput(d) => write!(f, "invalid acquisition input: {d}"),
343 Self::Transport(d) => write!(f, "acquisition transport failed: {d}"),
344 Self::TooLarge { limit } => write!(f, "response exceeded bound ({limit} bytes)"),
345 Self::Timeout { phase } => write!(f, "acquisition timed out ({phase})"),
346 Self::Cancelled => write!(f, "acquisition cancelled"),
347 Self::Io { operation, source } => {
348 let detail = bound_detail(format!("{operation}: {source}"));
349 write!(f, "acquisition I/O failed: {detail}")
350 }
351 Self::Unavailable(d) => write!(f, "acquisition transport unavailable: {d}"),
352 }
353 }
354}
355
356impl std::error::Error for AcquisitionError {
357 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
362 match self {
363 Self::Io { source, .. } => Some(source),
364 _ => None,
365 }
366 }
367}
368
369#[doc(hidden)]
376pub fn __adapter_bound_detail(detail: impl Into<String>) -> String {
377 bound_detail(detail.into())
378}
379
380fn bound_detail(s: String) -> String {
381 truncate_utf8_bytes(s, 512)
382}
383
384fn truncate_utf8_bytes(mut s: String, max: usize) -> String {
385 if s.len() > max {
386 let mut end = max;
387 while !s.is_char_boundary(end) {
388 end -= 1;
389 }
390 s.truncate(end);
391 }
392 s
393}
394
395pub fn redact_url(url: &str) -> String {
405 let mut out = url.to_string();
406 if let Some(scheme_end) = out.find("://") {
407 let after = scheme_end + 3;
408 if let Some(at) = out[after..].find('@') {
409 let at_abs = after + at;
410 out = format!("{}://<redacted>@{}", &url[..scheme_end], &url[at_abs + 1..]);
412 }
413 }
414 if let Some(h) = out.find('#') {
416 out.truncate(h);
417 out.push_str("#<redacted>");
418 }
419 if let Some(q) = out.find('?') {
421 out.truncate(q);
422 out.push_str("?<redacted>");
423 }
424 let truncated = out.len() > 256;
427 out = truncate_utf8_bytes(out, 256);
428 if truncated {
429 out.push('…');
430 }
431 out
432}
433
434#[doc(hidden)]
441pub fn __scrub_upstream_text(text: &str) -> String {
442 let mut out = text.to_string();
444 let mut search_from: usize = 0;
447 while search_from < out.len() {
448 let Some(rel_scheme) = out[search_from..].find("://") else {
449 break;
450 };
451 let scheme = search_from + rel_scheme;
452 let after = scheme + 3;
453 let Some(rel_at) = out[after..].find('@') else {
454 break;
455 };
456 let at_abs = after + rel_at;
457 if out[after..at_abs].contains("://") {
460 search_from = after;
461 continue;
462 }
463 if at_abs - after > 512 {
465 break;
466 }
467 out.replace_range(after..at_abs, "<redacted>");
468 search_from = after + "<redacted>".len() + 1;
471 }
472 if let Some(q) = out.find('?') {
477 let suffix = &out[q..];
478 if suffix.contains('=') || suffix.contains('&') {
479 out.truncate(q);
480 out.push_str("?<redacted>");
481 }
482 }
483 truncate_utf8_bytes(out, 512)
485}
486
487#[doc(hidden)]
489pub const __TEMP_COLLISION_BOUND: u32 = 32;
490
491#[doc(hidden)]
503pub fn __acquire_exclusive_temp(
504 parent: &Path,
505 prefix: &str,
506) -> Result<(std::fs::File, std::path::PathBuf), AcquisitionError> {
507 use std::fs::OpenOptions;
508 for _ in 0..__TEMP_COLLISION_BOUND {
509 let nonce = NEXT_TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
510 let nanos = std::time::SystemTime::now()
511 .duration_since(std::time::UNIX_EPOCH)
512 .map(|d| d.as_nanos())
513 .unwrap_or(0);
514 let candidate = parent.join(format!(
515 ".{prefix}-{}-{nanos}-{nonce}.part",
516 std::process::id()
517 ));
518 let mut opts = OpenOptions::new();
519 opts.write(true).create_new(true);
520 #[cfg(unix)]
521 {
522 use std::os::unix::fs::OpenOptionsExt;
523 opts.mode(0o600);
524 }
525 match opts.open(&candidate) {
526 Ok(file) => {
527 #[cfg(unix)]
532 {
533 use std::os::unix::fs::PermissionsExt;
534 let mut perms = match file.metadata() {
535 Ok(meta) => meta.permissions(),
536 Err(e) => {
537 drop(file);
538 let _ = fs::remove_file(&candidate);
539 return Err(AcquisitionError::io("reading part permissions", e));
540 }
541 };
542 if perms.mode() & 0o777 != 0o600 {
543 perms.set_mode(0o600);
544 if let Err(e) = fs::set_permissions(&candidate, perms) {
545 drop(file);
546 let _ = fs::remove_file(&candidate);
547 return Err(AcquisitionError::io("securing part file", e));
548 }
549 }
550 }
551 return Ok((file, candidate));
552 }
553 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
554 Err(e) => return Err(AcquisitionError::io("creating part file", e)),
555 }
556 }
557 Err(AcquisitionError::io(
558 "creating part file",
559 std::io::Error::new(
560 std::io::ErrorKind::AlreadyExists,
561 "too many temporary name collisions",
562 ),
563 ))
564}
565
566#[doc(hidden)]
582pub fn __promote_no_clobber(tmp: &Path, dest: &Path) -> Result<(), AcquisitionError> {
583 __promote_no_clobber_with(tmp, dest, |path| fs::remove_file(path))
584}
585
586fn __promote_no_clobber_with(
587 tmp: &Path,
588 dest: &Path,
589 remove_temp: impl FnOnce(&Path) -> std::io::Result<()>,
590) -> Result<(), AcquisitionError> {
591 match std::fs::hard_link(tmp, dest) {
592 Ok(()) => {
593 let _ = remove_temp(tmp);
596 Ok(())
597 }
598 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(AcquisitionError::invalid(
599 "artifact destination already exists; refusing to overwrite",
600 )),
601 Err(e) => Err(AcquisitionError::io("promoting artifact", e)),
602 }
603}
604
605#[doc(hidden)]
611pub fn __remove_owned_temp(path: &Path) {
612 let _ = std::fs::remove_file(path);
613}
614
615pub trait AcquisitionTransport {
626 fn fetch_metadata(
628 &self,
629 request: &AcquisitionRequest,
630 limits: FetchLimits,
631 cancel: &CancelFlag,
632 ) -> Result<FetchOutcome<MetadataBytes>, AcquisitionError>;
633
634 fn fetch_artifact(
647 &self,
648 request: &AcquisitionRequest,
649 dest: &Path,
650 limits: FetchLimits,
651 cancel: &CancelFlag,
652 ) -> Result<FetchOutcome<ArtifactEvidence>, AcquisitionError>;
653}
654
655static NEXT_TEMP_NONCE: AtomicU64 = AtomicU64::new(0);
656
657#[derive(Debug, Clone)]
659pub struct FixtureResponse {
660 kind: FixtureKind,
661}
662
663#[derive(Debug, Clone)]
664enum FixtureKind {
665 Body(Vec<u8>),
666 NotFound,
667 Failure,
668 Unavailable,
669 Truncated { prefix_len: usize },
670 Slow { body: Vec<u8>, delay: Duration },
671}
672
673impl FixtureResponse {
674 pub fn body(bytes: impl Into<Vec<u8>>) -> Self {
676 Self {
677 kind: FixtureKind::Body(bytes.into()),
678 }
679 }
680
681 pub fn not_found() -> Self {
683 Self {
684 kind: FixtureKind::NotFound,
685 }
686 }
687
688 pub fn failure(_detail: impl Into<String>) -> Self {
694 Self {
695 kind: FixtureKind::Failure,
696 }
697 }
698
699 pub fn truncated(prefix_len: usize) -> Self {
701 Self {
702 kind: FixtureKind::Truncated { prefix_len },
703 }
704 }
705
706 pub fn slow(body: Vec<u8>, delay: Duration) -> Self {
708 Self {
709 kind: FixtureKind::Slow { body, delay },
710 }
711 }
712
713 pub fn unavailable() -> Self {
716 Self {
717 kind: FixtureKind::Unavailable,
718 }
719 }
720}
721
722#[derive(Debug, Default)]
728pub struct FixtureTransport {
729 routes: Mutex<HashMap<String, FixtureResponse>>,
730}
731
732impl FixtureTransport {
733 pub fn new() -> Self {
735 Self::default()
736 }
737
738 pub fn route(&self, url: &str, response: FixtureResponse) {
740 self.routes
741 .lock()
742 .expect("fixture lock")
743 .insert(url.to_string(), response);
744 }
745
746 fn lookup(&self, url: &str) -> Result<FixtureResponse, AcquisitionError> {
747 self.routes
748 .lock()
749 .expect("fixture lock")
750 .get(url)
751 .cloned()
752 .ok_or_else(|| {
753 AcquisitionError::transport_redacted(format!(
754 "no fixture route for {}",
755 redact_url(url)
756 ))
757 })
758 }
759}
760
761impl AcquisitionTransport for FixtureTransport {
762 fn fetch_metadata(
763 &self,
764 request: &AcquisitionRequest,
765 limits: FetchLimits,
766 cancel: &CancelFlag,
767 ) -> Result<FetchOutcome<MetadataBytes>, AcquisitionError> {
768 limits.validate()?;
769 let start = Instant::now();
770 if cancel.is_cancelled() {
771 return Err(AcquisitionError::Cancelled);
772 }
773 let fixture = self.lookup(request.url())?;
774 match fixture.kind {
775 FixtureKind::NotFound => Ok(FetchOutcome::NotFound),
776 FixtureKind::Failure => Err(AcquisitionError::transport_redacted(
779 "fixture transport failure",
780 )),
781 FixtureKind::Unavailable => Err(AcquisitionError::__adapter_unavailable(
782 "fixture transport unavailable",
783 )),
784 FixtureKind::Body(bytes) => {
785 if start.elapsed() > limits.total_timeout {
786 return Err(AcquisitionError::Timeout { phase: "total" });
787 }
788 if cancel.is_cancelled() {
789 return Err(AcquisitionError::Cancelled);
790 }
791 if bytes.len() > limits.max_metadata_bytes {
792 return Err(AcquisitionError::TooLarge {
793 limit: limits.max_metadata_bytes as u64,
794 });
795 }
796 Ok(FetchOutcome::Success(MetadataBytes { bytes }))
797 }
798 FixtureKind::Truncated { .. } => Err(AcquisitionError::transport_redacted(
799 "truncated fixture body",
800 )),
801 FixtureKind::Slow { body, delay } => {
802 if delay > limits.total_timeout {
803 return Err(AcquisitionError::Timeout { phase: "total" });
804 }
805 if cancel.is_cancelled() {
806 return Err(AcquisitionError::Cancelled);
807 }
808 if body.len() > limits.max_metadata_bytes {
809 return Err(AcquisitionError::TooLarge {
810 limit: limits.max_metadata_bytes as u64,
811 });
812 }
813 Ok(FetchOutcome::Success(MetadataBytes { bytes: body }))
814 }
815 }
816 }
817
818 fn fetch_artifact(
819 &self,
820 request: &AcquisitionRequest,
821 dest: &Path,
822 limits: FetchLimits,
823 cancel: &CancelFlag,
824 ) -> Result<FetchOutcome<ArtifactEvidence>, AcquisitionError> {
825 limits.validate()?;
826 let start = Instant::now();
827 if cancel.is_cancelled() {
828 return Err(AcquisitionError::Cancelled);
829 }
830 let parent = dest
831 .parent()
832 .ok_or_else(|| AcquisitionError::invalid("artifact destination has no parent"))?;
833 let parent_meta = fs::symlink_metadata(parent)
834 .map_err(|e| AcquisitionError::io("reading artifact parent", e))?;
835 if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() {
836 return Err(AcquisitionError::invalid(
837 "artifact parent must be an existing real directory",
838 ));
839 }
840 if fs::symlink_metadata(dest).is_ok() {
844 return Err(AcquisitionError::invalid(
845 "artifact destination already exists; refusing to overwrite",
846 ));
847 }
848 let fixture = self.lookup(request.url())?;
849 let body = match fixture.kind {
850 FixtureKind::NotFound => return Ok(FetchOutcome::NotFound),
851 FixtureKind::Failure => {
852 return Err(AcquisitionError::transport_redacted(
853 "fixture transport failure",
854 ));
855 }
856 FixtureKind::Unavailable => {
857 return Err(AcquisitionError::__adapter_unavailable(
858 "fixture transport unavailable",
859 ));
860 }
861 FixtureKind::Body(b) => b,
862 FixtureKind::Truncated { prefix_len } => {
863 if let Ok((mut f, tmp)) = __acquire_exclusive_temp(parent, "eggup-acquire") {
867 use std::io::Write;
868 let prefix = vec![0u8; prefix_len.min(1024)];
869 let _ = f.write_all(&prefix);
870 drop(f);
871 __remove_owned_temp(&tmp);
872 }
873 return Err(AcquisitionError::transport_redacted(
874 "early disconnect during artifact body",
875 ));
876 }
877 FixtureKind::Slow { body, delay } => {
878 if delay > limits.total_timeout || start.elapsed() + delay > limits.total_timeout {
879 return Err(AcquisitionError::Timeout { phase: "total" });
880 }
881 body
882 }
883 };
884 if body.len() as u64 > limits.max_artifact_bytes {
885 return Err(AcquisitionError::TooLarge {
886 limit: limits.max_artifact_bytes,
887 });
888 }
889 if start.elapsed() > limits.total_timeout {
890 return Err(AcquisitionError::Timeout { phase: "total" });
891 }
892 if cancel.is_cancelled() {
893 return Err(AcquisitionError::Cancelled);
894 }
895 let (mut file, tmp) = __acquire_exclusive_temp(parent, "eggup-acquire")?;
897 struct Guard {
898 path: std::path::PathBuf,
899 disarm: bool,
900 }
901 impl Drop for Guard {
902 fn drop(&mut self) {
903 if !self.disarm {
904 __remove_owned_temp(&self.path);
905 }
906 }
907 }
908 let mut guard = Guard {
909 path: tmp.clone(),
910 disarm: false,
911 };
912 let mut written: u64 = 0;
914 {
915 use std::io::Write;
916 for chunk in body.chunks(8192) {
917 if cancel.is_cancelled() {
918 return Err(AcquisitionError::Cancelled);
919 }
920 file.write_all(chunk)
921 .map_err(|e| AcquisitionError::io("writing part file", e))?;
922 written += chunk.len() as u64;
923 }
924 file.flush()
925 .map_err(|e| AcquisitionError::io("flushing part file", e))?;
926 drop(file);
927 }
928 if cancel.is_cancelled() {
930 return Err(AcquisitionError::Cancelled);
931 }
932 match __promote_no_clobber(&tmp, dest) {
933 Ok(()) => {
934 guard.disarm = true;
935 Ok(FetchOutcome::Success(ArtifactEvidence {
936 bytes_written: written,
937 }))
938 }
939 Err(e) => {
940 __remove_owned_temp(&tmp);
942 guard.disarm = true;
943 Err(e)
944 }
945 }
946 }
947}
948
949pub type SharedTransport = Arc<FixtureTransport>;
951
952#[doc(hidden)]
958pub fn __adapter_metadata(bytes: Vec<u8>) -> MetadataBytes {
959 MetadataBytes { bytes }
960}
961
962#[doc(hidden)]
966pub fn __adapter_artifact(bytes_written: u64) -> ArtifactEvidence {
967 ArtifactEvidence { bytes_written }
968}
969
970#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
979pub enum CompositionPolicy {
980 #[default]
983 UnavailableOnly,
984 UnavailableOrTransport,
987}
988
989pub struct ComposedTransport<'a> {
999 primary: &'a dyn AcquisitionTransport,
1000 secondary: &'a dyn AcquisitionTransport,
1001 policy: CompositionPolicy,
1002}
1003
1004impl std::fmt::Debug for ComposedTransport<'_> {
1005 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1006 f.debug_struct("ComposedTransport")
1007 .field("policy", &self.policy)
1008 .finish_non_exhaustive()
1009 }
1010}
1011
1012impl<'a> ComposedTransport<'a> {
1013 pub fn new(
1018 primary: &'a dyn AcquisitionTransport,
1019 secondary: &'a dyn AcquisitionTransport,
1020 policy: CompositionPolicy,
1021 ) -> Self {
1022 Self {
1023 primary,
1024 secondary,
1025 policy,
1026 }
1027 }
1028
1029 pub fn policy(&self) -> CompositionPolicy {
1031 self.policy
1032 }
1033
1034 fn should_fallback(&self, err: &AcquisitionError) -> bool {
1035 match err {
1036 AcquisitionError::Unavailable(_) => true,
1037 AcquisitionError::Transport(_) | AcquisitionError::Timeout { .. } => {
1038 self.policy == CompositionPolicy::UnavailableOrTransport
1039 }
1040 _ => false,
1041 }
1042 }
1043
1044 fn remaining_limits(
1053 &self,
1054 limits: FetchLimits,
1055 started: Instant,
1056 ) -> Result<FetchLimits, AcquisitionError> {
1057 let elapsed = started.elapsed();
1058 let remaining = limits
1059 .total_timeout
1060 .checked_sub(elapsed)
1061 .ok_or(AcquisitionError::Timeout { phase: "total" })?;
1062 if remaining.is_zero() {
1063 return Err(AcquisitionError::Timeout { phase: "total" });
1064 }
1065 Ok(FetchLimits {
1066 connect_timeout: limits.connect_timeout.min(remaining),
1067 total_timeout: remaining,
1068 ..limits
1069 })
1070 }
1071}
1072
1073impl AcquisitionTransport for ComposedTransport<'_> {
1074 fn fetch_metadata(
1075 &self,
1076 request: &AcquisitionRequest,
1077 limits: FetchLimits,
1078 cancel: &CancelFlag,
1079 ) -> Result<FetchOutcome<MetadataBytes>, AcquisitionError> {
1080 limits.validate()?;
1084 if cancel.is_cancelled() {
1085 return Err(AcquisitionError::Cancelled);
1086 }
1087 let started = Instant::now();
1088 match self.primary.fetch_metadata(request, limits, cancel) {
1089 Ok(outcome) => Ok(outcome),
1090 Err(err) => {
1091 if self.should_fallback(&err) {
1092 let remaining = self.remaining_limits(limits, started)?;
1094 self.secondary.fetch_metadata(request, remaining, cancel)
1095 } else {
1096 Err(err)
1097 }
1098 }
1099 }
1100 }
1101
1102 fn fetch_artifact(
1103 &self,
1104 request: &AcquisitionRequest,
1105 dest: &Path,
1106 limits: FetchLimits,
1107 cancel: &CancelFlag,
1108 ) -> Result<FetchOutcome<ArtifactEvidence>, AcquisitionError> {
1109 limits.validate()?;
1110 if cancel.is_cancelled() {
1111 return Err(AcquisitionError::Cancelled);
1112 }
1113 let started = Instant::now();
1114 match self.primary.fetch_artifact(request, dest, limits, cancel) {
1115 Ok(outcome) => Ok(outcome),
1116 Err(err) => {
1117 if self.should_fallback(&err) {
1118 let remaining = self.remaining_limits(limits, started)?;
1120 self.secondary
1121 .fetch_artifact(request, dest, remaining, cancel)
1122 } else {
1123 Err(err)
1124 }
1125 }
1126 }
1127 }
1128}
1129
1130#[cfg(test)]
1131mod tests {
1132 use super::*;
1133 use std::path::PathBuf;
1134 use std::time::Duration;
1135
1136 fn req(url: &str) -> AcquisitionRequest {
1137 AcquisitionRequest::new(url).unwrap()
1138 }
1139
1140 fn limits() -> FetchLimits {
1141 FetchLimits {
1142 max_metadata_bytes: 1024,
1143 max_artifact_bytes: 4096,
1144 connect_timeout: Duration::from_secs(1),
1145 total_timeout: Duration::from_secs(5),
1146 }
1147 }
1148
1149 fn temp_dir(prefix: &str) -> PathBuf {
1150 let nanos = std::time::SystemTime::now()
1151 .duration_since(std::time::UNIX_EPOCH)
1152 .map(|d| d.as_nanos())
1153 .unwrap_or(0);
1154 let p = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
1155 let _ = fs::create_dir_all(&p);
1156 p
1157 }
1158
1159 #[test]
1160 fn exact_body_success() {
1161 let t = FixtureTransport::new();
1162 t.route(
1163 "https://example.com/meta",
1164 FixtureResponse::body(b"hello".to_vec()),
1165 );
1166 let out = t
1167 .fetch_metadata(
1168 &req("https://example.com/meta"),
1169 limits(),
1170 &CancelFlag::new(),
1171 )
1172 .unwrap();
1173 assert_eq!(out.success().unwrap().bytes(), b"hello");
1174 }
1175
1176 #[test]
1177 fn streamed_artifact_success() {
1178 let t = FixtureTransport::new();
1179 t.route(
1180 "https://example.com/app",
1181 FixtureResponse::body(vec![7u8; 2048]),
1182 );
1183 let dir = temp_dir("acq-stream");
1184 let dest = dir.join("app");
1185 let out = t
1186 .fetch_artifact(
1187 &req("https://example.com/app"),
1188 &dest,
1189 limits(),
1190 &CancelFlag::new(),
1191 )
1192 .unwrap();
1193 let ev = out.success().unwrap();
1194 assert_eq!(ev.bytes_written, 2048);
1195 assert_eq!(fs::read(&dest).unwrap().len(), 2048);
1196 assert!(!dir.join(".eggup-acquire-0.part").exists());
1197 let _ = fs::remove_dir_all(&dir);
1198 }
1199
1200 #[test]
1201 fn metadata_limit_is_enforced() {
1202 let t = FixtureTransport::new();
1203 t.route(
1204 "https://example.com/big",
1205 FixtureResponse::body(vec![0u8; 2048]),
1206 );
1207 let err = t
1208 .fetch_metadata(
1209 &req("https://example.com/big"),
1210 limits(),
1211 &CancelFlag::new(),
1212 )
1213 .unwrap_err();
1214 assert!(matches!(err, AcquisitionError::TooLarge { .. }));
1215 }
1216
1217 #[test]
1218 fn artifact_limit_is_enforced_without_promotion() {
1219 let t = FixtureTransport::new();
1220 t.route(
1221 "https://example.com/big",
1222 FixtureResponse::body(vec![0u8; 8192]),
1223 );
1224 let dir = temp_dir("acq-limit");
1225 let dest = dir.join("app");
1226 let err = t
1227 .fetch_artifact(
1228 &req("https://example.com/big"),
1229 &dest,
1230 limits(),
1231 &CancelFlag::new(),
1232 )
1233 .unwrap_err();
1234 assert!(matches!(err, AcquisitionError::TooLarge { .. }));
1235 assert!(!dest.exists());
1236 let _ = fs::remove_dir_all(&dir);
1237 }
1238
1239 #[test]
1240 fn not_found_is_data_not_failure() {
1241 let t = FixtureTransport::new();
1242 t.route("https://example.com/missing", FixtureResponse::not_found());
1243 let out = t
1244 .fetch_metadata(
1245 &req("https://example.com/missing"),
1246 limits(),
1247 &CancelFlag::new(),
1248 )
1249 .unwrap();
1250 assert!(out.is_not_found());
1251 let dir = temp_dir("acq-404");
1252 let dest = dir.join("app");
1253 let out = t
1254 .fetch_artifact(
1255 &req("https://example.com/missing"),
1256 &dest,
1257 limits(),
1258 &CancelFlag::new(),
1259 )
1260 .unwrap();
1261 assert!(out.is_not_found());
1262 assert!(!dest.exists());
1263 let _ = fs::remove_dir_all(&dir);
1264 }
1265
1266 #[test]
1267 fn hard_failures_never_become_not_found() {
1268 let t = FixtureTransport::new();
1269 t.route(
1270 "https://example.com/boom",
1271 FixtureResponse::failure("500 internal error"),
1272 );
1273 let err = t
1274 .fetch_metadata(
1275 &req("https://example.com/boom"),
1276 limits(),
1277 &CancelFlag::new(),
1278 )
1279 .unwrap_err();
1280 assert!(matches!(err, AcquisitionError::Transport(_)));
1281 }
1282
1283 #[test]
1284 fn timeout_is_a_hard_failure() {
1285 let t = FixtureTransport::new();
1286 t.route(
1287 "https://example.com/slow",
1288 FixtureResponse::slow(b"late".to_vec(), Duration::from_secs(30)),
1289 );
1290 let err = t
1291 .fetch_metadata(
1292 &req("https://example.com/slow"),
1293 limits(),
1294 &CancelFlag::new(),
1295 )
1296 .unwrap_err();
1297 assert!(matches!(err, AcquisitionError::Timeout { .. }));
1298 }
1299
1300 #[test]
1301 fn cancellation_cleans_partial_output() {
1302 let t = FixtureTransport::new();
1303 t.route(
1304 "https://example.com/app",
1305 FixtureResponse::body(vec![1u8; 1024]),
1306 );
1307 let dir = temp_dir("acq-cancel");
1308 let dest = dir.join("app");
1309 let cancel = CancelFlag::new();
1310 cancel.cancel();
1311 let err = t
1312 .fetch_artifact(&req("https://example.com/app"), &dest, limits(), &cancel)
1313 .unwrap_err();
1314 assert!(matches!(err, AcquisitionError::Cancelled));
1315 assert!(!dest.exists());
1316 let leftovers: Vec<_> = fs::read_dir(&dir)
1317 .unwrap()
1318 .filter_map(|e| e.ok())
1319 .filter(|e| {
1320 e.file_name()
1321 .to_string_lossy()
1322 .starts_with(".eggup-acquire-")
1323 })
1324 .collect();
1325 assert!(leftovers.is_empty());
1326 let _ = fs::remove_dir_all(&dir);
1327 }
1328
1329 #[test]
1330 fn partial_write_failure_promotes_nothing() {
1331 let t = FixtureTransport::new();
1332 t.route("https://example.com/cut", FixtureResponse::truncated(512));
1333 let dir = temp_dir("acq-partial");
1334 let dest = dir.join("app");
1335 let err = t
1336 .fetch_artifact(
1337 &req("https://example.com/cut"),
1338 &dest,
1339 limits(),
1340 &CancelFlag::new(),
1341 )
1342 .unwrap_err();
1343 assert!(matches!(err, AcquisitionError::Transport(_)));
1344 assert!(!dest.exists());
1345 let _ = fs::remove_dir_all(&dir);
1346 }
1347
1348 #[test]
1349 fn diagnostics_are_redacted() {
1350 let redacted = redact_url("https://user:s3cret@example.com/app?token=abc");
1351 assert!(!redacted.contains("s3cret"));
1352 assert!(!redacted.contains("token=abc"));
1353 assert!(redacted.contains("example.com"));
1354 let err = AcquisitionRequest::new("https://user:pw@example.com/x?k=v").unwrap();
1355 assert!(!err.redacted().contains("pw"));
1356 }
1357
1358 #[test]
1359 fn bounded_diagnostics_preserve_utf8_at_256_and_512_byte_edges() {
1360 for limit in [256, 512] {
1361 for (width, ch) in [(2, "é"), (3, "€"), (4, "🦀")] {
1362 let prefix = "a".repeat(limit - 1);
1363 let bounded = truncate_utf8_bytes(format!("{prefix}{ch}tail"), limit);
1364 assert!(bounded.len() <= limit);
1365 assert!(std::str::from_utf8(bounded.as_bytes()).is_ok());
1366 assert!(bounded.ends_with(&prefix));
1367 assert!(width > 1);
1368 }
1369 }
1370 }
1371
1372 #[test]
1373 fn zero_artifact_limit_is_rejected() {
1374 let invalid = FetchLimits {
1375 max_artifact_bytes: 0,
1376 ..FetchLimits::default()
1377 };
1378 assert!(matches!(
1379 invalid.validate(),
1380 Err(AcquisitionError::InvalidInput(_))
1381 ));
1382 }
1383
1384 #[test]
1385 fn no_fallback_on_unregistered_url() {
1386 let t = FixtureTransport::new();
1387 let err = t
1388 .fetch_metadata(
1389 &req("https://example.com/unknown"),
1390 limits(),
1391 &CancelFlag::new(),
1392 )
1393 .unwrap_err();
1394 assert!(matches!(err, AcquisitionError::Transport(_)));
1395 }
1396
1397 #[test]
1398 fn invalid_public_limits_are_rejected_before_fixture_io() {
1399 let transport = FixtureTransport::new();
1400 let request = req("https://example.com/no-route");
1401 let invalid = [
1402 FetchLimits {
1403 max_metadata_bytes: 0,
1404 ..limits()
1405 },
1406 FetchLimits {
1407 max_metadata_bytes: 16 * 1024 * 1024 + 1,
1408 ..limits()
1409 },
1410 FetchLimits {
1411 connect_timeout: Duration::ZERO,
1412 ..limits()
1413 },
1414 FetchLimits {
1415 total_timeout: Duration::ZERO,
1416 ..limits()
1417 },
1418 FetchLimits {
1419 connect_timeout: Duration::from_secs(6),
1420 total_timeout: Duration::from_secs(5),
1421 ..limits()
1422 },
1423 ];
1424 let dir = temp_dir("acq-invalid-limits");
1425 let dest = dir.join("app");
1426 for limits in invalid {
1427 assert!(matches!(
1428 limits.validate(),
1429 Err(AcquisitionError::InvalidInput(_))
1430 ));
1431 assert!(matches!(
1432 transport.fetch_metadata(&request, limits, &CancelFlag::new()),
1433 Err(AcquisitionError::InvalidInput(_))
1434 ));
1435 assert!(matches!(
1436 transport.fetch_artifact(&request, &dest, limits, &CancelFlag::new()),
1437 Err(AcquisitionError::InvalidInput(_))
1438 ));
1439 assert!(!dest.exists());
1440 assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
1441 }
1442 assert!(limits().validate().is_ok());
1443 assert!(
1444 FetchLimits::new(1024, 4096, Duration::from_secs(1), Duration::from_secs(5)).is_ok()
1445 );
1446 let _ = fs::remove_dir_all(&dir);
1447 }
1448
1449 #[test]
1450 fn missing_artifact_parent_fails_without_creation() {
1451 let t = FixtureTransport::new();
1452 t.route(
1453 "https://example.com/app",
1454 FixtureResponse::body(b"x".to_vec()),
1455 );
1456 let dir = temp_dir("acq-noparent");
1457 let dest = dir.join("no-such-dir/app");
1458 let err = t
1459 .fetch_artifact(
1460 &req("https://example.com/app"),
1461 &dest,
1462 limits(),
1463 &CancelFlag::new(),
1464 )
1465 .unwrap_err();
1466 assert!(matches!(
1467 err,
1468 AcquisitionError::InvalidInput(_) | AcquisitionError::Io { .. }
1469 ));
1470 assert!(!dir.join("no-such-dir").exists());
1471 let _ = fs::remove_dir_all(&dir);
1472 }
1473
1474 #[test]
1477 fn connect_exceeding_total_is_rejected() {
1478 let err = FetchLimits::new(1024, 4096, Duration::from_secs(5), Duration::from_secs(1))
1479 .unwrap_err();
1480 assert!(matches!(err, AcquisitionError::InvalidInput(_)));
1481 }
1482
1483 #[test]
1484 fn zero_timeouts_are_rejected() {
1485 assert!(FetchLimits::new(1024, 1, Duration::ZERO, Duration::from_secs(1)).is_err());
1486 assert!(FetchLimits::new(1024, 1, Duration::from_secs(1), Duration::ZERO).is_err());
1487 }
1488
1489 #[test]
1490 fn effective_timeouts_take_minimums() {
1491 let request = FetchLimits {
1492 max_metadata_bytes: 1024,
1493 max_artifact_bytes: 4096,
1494 connect_timeout: Duration::from_millis(50),
1495 total_timeout: Duration::from_millis(50),
1496 };
1497 let (c, t) = request.effective(Duration::from_secs(5), Duration::from_secs(5));
1499 assert_eq!(c, Duration::from_millis(50));
1500 assert_eq!(t, Duration::from_millis(50));
1501 let request2 = FetchLimits {
1503 max_metadata_bytes: 1024,
1504 max_artifact_bytes: 4096,
1505 connect_timeout: Duration::from_secs(5),
1506 total_timeout: Duration::from_secs(5),
1507 };
1508 let (c2, t2) = request2.effective(Duration::from_millis(50), Duration::from_millis(50));
1509 assert_eq!(c2, Duration::from_millis(50));
1510 assert_eq!(t2, Duration::from_millis(50));
1511 let (c3, t3) = request2.effective(Duration::from_secs(1), Duration::from_secs(10));
1513 assert_eq!(c3, Duration::from_secs(1));
1514 assert_eq!(t3, Duration::from_secs(5));
1515 }
1516
1517 #[test]
1518 fn timeout_never_maps_to_not_found() {
1519 let t = FixtureTransport::new();
1520 t.route(
1521 "https://example.com/slow-art",
1522 FixtureResponse::slow(vec![1u8; 16], Duration::from_secs(30)),
1523 );
1524 let dir = temp_dir("acq-timeout-nf");
1525 let dest = dir.join("app");
1526 let tiny = FetchLimits {
1527 max_metadata_bytes: 1024,
1528 max_artifact_bytes: 4096,
1529 connect_timeout: Duration::from_millis(10),
1530 total_timeout: Duration::from_millis(10),
1531 };
1532 let err = t
1533 .fetch_artifact(
1534 &req("https://example.com/slow-art"),
1535 &dest,
1536 tiny,
1537 &CancelFlag::new(),
1538 )
1539 .unwrap_err();
1540 assert!(matches!(err, AcquisitionError::Timeout { .. }));
1541 assert!(!matches!(err, AcquisitionError::InvalidInput(_)));
1542 assert!(!dest.exists());
1543 let _ = fs::remove_dir_all(&dir);
1544 }
1545
1546 #[test]
1549 fn existing_destination_is_a_hard_no_clobber_failure() {
1550 let t = FixtureTransport::new();
1551 t.route(
1552 "https://example.com/app",
1553 FixtureResponse::body(vec![9u8; 64]),
1554 );
1555 let dir = temp_dir("acq-noclobber");
1556 let dest = dir.join("app");
1557 fs::write(&dest, b"FOREIGN-BYTES").unwrap();
1558 let err = t
1559 .fetch_artifact(
1560 &req("https://example.com/app"),
1561 &dest,
1562 limits(),
1563 &CancelFlag::new(),
1564 )
1565 .unwrap_err();
1566 assert!(matches!(
1567 err,
1568 AcquisitionError::InvalidInput(_) | AcquisitionError::Io { .. }
1569 ));
1570 assert_eq!(fs::read(&dest).unwrap(), b"FOREIGN-BYTES");
1572 let leftovers: Vec<_> = fs::read_dir(&dir)
1574 .unwrap()
1575 .filter_map(|e| e.ok())
1576 .filter(|e| {
1577 let n = e.file_name().to_string_lossy().into_owned();
1578 n.ends_with(".part") && n.starts_with(".eggup-acquire-")
1579 })
1580 .collect();
1581 assert!(leftovers.is_empty());
1582 let _ = fs::remove_dir_all(&dir);
1583 }
1584
1585 #[test]
1586 fn post_link_cleanup_failure_keeps_committed_destination_successful() {
1587 let dir = temp_dir("acq-promote-cleanup");
1588 let tmp = dir.join("owned.part");
1589 let dest = dir.join("app");
1590 fs::write(&tmp, b"complete artifact").unwrap();
1591 let result = __promote_no_clobber_with(&tmp, &dest, |_| {
1592 Err(std::io::Error::new(
1593 std::io::ErrorKind::PermissionDenied,
1594 "injected",
1595 ))
1596 });
1597 assert!(result.is_ok());
1598 assert_eq!(fs::read(&dest).unwrap(), b"complete artifact");
1599 assert_eq!(fs::read(&tmp).unwrap(), b"complete artifact");
1600 let _ = fs::remove_dir_all(&dir);
1601 }
1602
1603 #[test]
1604 fn promote_no_clobber_preserves_raced_destination() {
1605 let dir = temp_dir("acq-race");
1608 let (mut f, tmp) = __acquire_exclusive_temp(&dir, "eggup-acquire").unwrap();
1609 use std::io::Write;
1610 f.write_all(b"race-payload").unwrap();
1611 let dest = dir.join("app");
1612 fs::write(&dest, b"RACED-FOREIGN").unwrap();
1613 let err = __promote_no_clobber(&tmp, &dest).unwrap_err();
1614 assert!(matches!(
1615 err,
1616 AcquisitionError::InvalidInput(_) | AcquisitionError::Io { .. }
1617 ));
1618 assert_eq!(fs::read(&dest).unwrap(), b"RACED-FOREIGN");
1619 assert!(tmp.exists());
1621 __remove_owned_temp(&tmp);
1622 assert!(!tmp.exists());
1623 let _ = fs::remove_dir_all(&dir);
1624 }
1625
1626 #[test]
1627 fn promote_succeeds_when_destination_absent() {
1628 let dir = temp_dir("acq-promote-ok");
1629 let (mut f, tmp) = __acquire_exclusive_temp(&dir, "eggup-acquire").unwrap();
1630 use std::io::Write;
1631 f.write_all(b"payload").unwrap();
1632 drop(f);
1633 let dest = dir.join("app");
1634 __promote_no_clobber(&tmp, &dest).unwrap();
1635 assert_eq!(fs::read(&dest).unwrap(), b"payload");
1636 assert!(!tmp.exists());
1637 let _ = fs::remove_dir_all(&dir);
1638 }
1639
1640 #[cfg(unix)]
1641 #[test]
1642 fn exclusive_temp_is_owner_private() {
1643 use std::os::unix::fs::PermissionsExt;
1644 let dir = temp_dir("acq-mode");
1645 let (f, tmp) = __acquire_exclusive_temp(&dir, "eggup-acquire").unwrap();
1646 let mode = f.metadata().unwrap().permissions().mode() & 0o777;
1647 assert_eq!(mode, 0o600, "temp must be owner-private 0600");
1648 drop(f);
1649 __remove_owned_temp(&tmp);
1650 let _ = fs::remove_dir_all(&dir);
1651 }
1652
1653 #[test]
1654 fn exclusive_temp_never_truncates_existing_file() {
1655 use std::fs::OpenOptions;
1656 let dir = temp_dir("acq-notrunc");
1657 let victim = dir.join("victim");
1658 fs::write(&victim, b"SENTINEL").unwrap();
1659 let err = OpenOptions::new()
1661 .write(true)
1662 .create_new(true)
1663 .open(&victim)
1664 .unwrap_err();
1665 assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists);
1666 assert_eq!(fs::read(&victim).unwrap(), b"SENTINEL");
1667 let (f, tmp) = __acquire_exclusive_temp(&dir, "eggup-acquire").unwrap();
1669 assert_ne!(tmp, victim);
1670 assert_eq!(fs::read(&victim).unwrap(), b"SENTINEL");
1671 drop(f);
1672 __remove_owned_temp(&tmp);
1673 let _ = fs::remove_dir_all(&dir);
1674 }
1675
1676 #[cfg(unix)]
1677 #[test]
1678 fn exclusive_temp_does_not_follow_symlink() {
1679 use std::fs::OpenOptions;
1680 use std::os::unix::fs::symlink;
1681 let dir = temp_dir("acq-symlink");
1682 let target = dir.join("target");
1683 fs::write(&target, b"TARGET-SENTINEL").unwrap();
1684 let link = dir.join("link");
1685 symlink(&target, &link).unwrap();
1686 let err = OpenOptions::new()
1688 .write(true)
1689 .create_new(true)
1690 .open(&link)
1691 .unwrap_err();
1692 assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists);
1693 assert_eq!(fs::read(&target).unwrap(), b"TARGET-SENTINEL");
1694 let t = FixtureTransport::new();
1696 t.route(
1697 "https://example.com/app",
1698 FixtureResponse::body(vec![1u8; 32]),
1699 );
1700 let dest = dir.join("app");
1701 t.fetch_artifact(
1702 &req("https://example.com/app"),
1703 &dest,
1704 limits(),
1705 &CancelFlag::new(),
1706 )
1707 .unwrap();
1708 assert_eq!(fs::read(&target).unwrap(), b"TARGET-SENTINEL");
1709 let _ = fs::remove_dir_all(&dir);
1710 }
1711
1712 #[test]
1713 fn cancellation_preserves_foreign_sibling_and_removes_only_owned() {
1714 let t = FixtureTransport::new();
1715 t.route(
1716 "https://example.com/app",
1717 FixtureResponse::body(vec![2u8; 128]),
1718 );
1719 let dir = temp_dir("acq-cancel-own");
1720 let foreign = dir.join("foreign-keep");
1721 fs::write(&foreign, b"KEEP").unwrap();
1722 let dest = dir.join("app");
1723 let cancel = CancelFlag::new();
1724 cancel.cancel();
1725 let err = t
1726 .fetch_artifact(&req("https://example.com/app"), &dest, limits(), &cancel)
1727 .unwrap_err();
1728 assert!(matches!(err, AcquisitionError::Cancelled));
1729 assert!(!dest.exists());
1730 assert_eq!(fs::read(&foreign).unwrap(), b"KEEP");
1731 let leftovers: Vec<_> = fs::read_dir(&dir)
1732 .unwrap()
1733 .filter_map(|e| e.ok())
1734 .filter(|e| {
1735 let n = e.file_name().to_string_lossy().into_owned();
1736 n.ends_with(".part")
1737 })
1738 .collect();
1739 assert!(leftovers.is_empty());
1740 let _ = fs::remove_dir_all(&dir);
1741 }
1742
1743 #[test]
1744 fn early_disconnect_removes_only_owned_temp() {
1745 let t = FixtureTransport::new();
1746 t.route("https://example.com/cut", FixtureResponse::truncated(256));
1747 let dir = temp_dir("acq-disconnect-own");
1748 let foreign = dir.join("keep");
1749 fs::write(&foreign, b"KEEP").unwrap();
1750 let dest = dir.join("app");
1751 let err = t
1752 .fetch_artifact(
1753 &req("https://example.com/cut"),
1754 &dest,
1755 limits(),
1756 &CancelFlag::new(),
1757 )
1758 .unwrap_err();
1759 assert!(matches!(err, AcquisitionError::Transport(_)));
1760 assert!(!dest.exists());
1761 assert_eq!(fs::read(&foreign).unwrap(), b"KEEP");
1762 let leftovers: Vec<_> = fs::read_dir(&dir)
1763 .unwrap()
1764 .filter_map(|e| e.ok())
1765 .filter(|e| {
1766 let n = e.file_name().to_string_lossy().into_owned();
1767 n.ends_with(".part")
1768 })
1769 .collect();
1770 assert!(leftovers.is_empty());
1771 let _ = fs::remove_dir_all(&dir);
1772 }
1773
1774 #[test]
1777 fn redaction_sentinels_are_absent_from_diagnostics() {
1778 let userinfo_sentinel = "S3CR3T-USERINFO-9917";
1779 let query_sentinel = "TOKEN-QUERY-5523";
1780 let url =
1781 format!("https://user:{userinfo_sentinel}@example.com/app?token={query_sentinel}");
1782 let t = FixtureTransport::new();
1784 let err = t
1785 .fetch_metadata(&req(&url), limits(), &CancelFlag::new())
1786 .unwrap_err();
1787 let msg = format!("{err}");
1788 assert!(!msg.contains(userinfo_sentinel));
1789 assert!(!msg.contains(query_sentinel));
1790 assert!(!msg.contains("token="));
1791 let t2 = FixtureTransport::new();
1793 t2.route(
1794 "https://example.com/secret",
1795 FixtureResponse::failure(format!(
1796 "upstream says {userinfo_sentinel} {query_sentinel}"
1797 )),
1798 );
1799 let err2 = t2
1800 .fetch_metadata(
1801 &req("https://example.com/secret"),
1802 limits(),
1803 &CancelFlag::new(),
1804 )
1805 .unwrap_err();
1806 let msg2 = format!("{err2}");
1807 assert!(!msg2.contains(userinfo_sentinel));
1808 assert!(!msg2.contains(query_sentinel));
1809 let red = redact_url("https://example.com/app#FRAG-SENTINEL-7788");
1811 assert!(!red.contains("FRAG-SENTINEL-7788"));
1812 }
1813
1814 #[test]
1815 fn upstream_scrub_removes_credential_patterns() {
1816 let scrubbed = __scrub_upstream_text(
1817 "fetch failed for https://alice:HUNTER2-PROXY-3311@example.com/x?token=abc&v=1",
1818 );
1819 assert!(!scrubbed.contains("HUNTER2-PROXY-3311"));
1820 assert!(!scrubbed.contains("alice"));
1821 let t = FixtureTransport::new();
1823 t.route(
1824 "https://example.com/p",
1825 FixtureResponse::failure("proxy password HUNTER2-PROXY-3311 in detail"),
1826 );
1827 let err = t
1828 .fetch_metadata(&req("https://example.com/p"), limits(), &CancelFlag::new())
1829 .unwrap_err();
1830 assert!(!format!("{err}").contains("HUNTER2-PROXY-3311"));
1831 }
1832
1833 struct CountingTransport {
1836 inner: FixtureTransport,
1837 metadata_calls: std::sync::atomic::AtomicUsize,
1838 artifact_calls: std::sync::atomic::AtomicUsize,
1839 }
1840
1841 impl CountingTransport {
1842 fn new() -> Self {
1843 Self {
1844 inner: FixtureTransport::new(),
1845 metadata_calls: std::sync::atomic::AtomicUsize::new(0),
1846 artifact_calls: std::sync::atomic::AtomicUsize::new(0),
1847 }
1848 }
1849
1850 fn route(&self, url: &str, response: FixtureResponse) {
1851 self.inner.route(url, response);
1852 }
1853
1854 fn metadata_calls(&self) -> usize {
1855 self.metadata_calls
1856 .load(std::sync::atomic::Ordering::SeqCst)
1857 }
1858
1859 fn artifact_calls(&self) -> usize {
1860 self.artifact_calls
1861 .load(std::sync::atomic::Ordering::SeqCst)
1862 }
1863 }
1864
1865 impl AcquisitionTransport for CountingTransport {
1866 fn fetch_metadata(
1867 &self,
1868 request: &AcquisitionRequest,
1869 limits: FetchLimits,
1870 cancel: &CancelFlag,
1871 ) -> Result<FetchOutcome<MetadataBytes>, AcquisitionError> {
1872 self.metadata_calls
1873 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1874 self.inner.fetch_metadata(request, limits, cancel)
1875 }
1876
1877 fn fetch_artifact(
1878 &self,
1879 request: &AcquisitionRequest,
1880 dest: &Path,
1881 limits: FetchLimits,
1882 cancel: &CancelFlag,
1883 ) -> Result<FetchOutcome<ArtifactEvidence>, AcquisitionError> {
1884 self.artifact_calls
1885 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1886 self.inner.fetch_artifact(request, dest, limits, cancel)
1887 }
1888 }
1889
1890 struct StallingTransport {
1893 delay: Duration,
1894 error: fn() -> AcquisitionError,
1895 seen: std::sync::Mutex<Vec<FetchLimits>>,
1896 }
1897
1898 impl AcquisitionTransport for StallingTransport {
1899 fn fetch_metadata(
1900 &self,
1901 _request: &AcquisitionRequest,
1902 limits: FetchLimits,
1903 _cancel: &CancelFlag,
1904 ) -> Result<FetchOutcome<MetadataBytes>, AcquisitionError> {
1905 self.seen.lock().unwrap().push(limits);
1906 std::thread::sleep(self.delay);
1907 Err((self.error)())
1908 }
1909
1910 fn fetch_artifact(
1911 &self,
1912 _request: &AcquisitionRequest,
1913 _dest: &Path,
1914 limits: FetchLimits,
1915 _cancel: &CancelFlag,
1916 ) -> Result<FetchOutcome<ArtifactEvidence>, AcquisitionError> {
1917 self.seen.lock().unwrap().push(limits);
1918 std::thread::sleep(self.delay);
1919 Err((self.error)())
1920 }
1921 }
1922
1923 fn unavailable() -> AcquisitionError {
1924 AcquisitionError::__adapter_unavailable("stalled then unavailable")
1925 }
1926
1927 fn totals(transport: &StallingTransport) -> Vec<Duration> {
1928 transport
1929 .seen
1930 .lock()
1931 .unwrap()
1932 .iter()
1933 .map(|l| l.total_timeout)
1934 .collect()
1935 }
1936
1937 #[test]
1938 fn composition_fallback_shares_one_total_budget() {
1939 let primary = StallingTransport {
1940 delay: Duration::from_millis(300),
1941 error: unavailable,
1942 seen: std::sync::Mutex::new(Vec::new()),
1943 };
1944 let secondary = StallingTransport {
1945 delay: Duration::ZERO,
1946 error: unavailable,
1947 seen: std::sync::Mutex::new(Vec::new()),
1948 };
1949 let composed =
1950 ComposedTransport::new(&primary, &secondary, CompositionPolicy::UnavailableOnly);
1951 let caller = FetchLimits {
1952 connect_timeout: Duration::from_secs(1),
1953 total_timeout: Duration::from_secs(10),
1954 ..limits()
1955 };
1956
1957 let _ =
1959 composed.fetch_metadata(&req("https://example.com/meta"), caller, &CancelFlag::new());
1960
1961 assert_eq!(totals(&primary), vec![caller.total_timeout]);
1962 let secondary_totals = totals(&secondary);
1963 assert_eq!(secondary_totals.len(), 1, "fallback must be attempted once");
1964 assert!(
1965 secondary_totals[0] < caller.total_timeout,
1966 "fallback must not restart the caller's budget: got {:?} of {:?}",
1967 secondary_totals[0],
1968 caller.total_timeout
1969 );
1970 assert!(
1972 caller.total_timeout - secondary_totals[0] >= Duration::from_millis(250),
1973 "the consumed time must be subtracted, not ignored"
1974 );
1975 }
1976
1977 #[test]
1978 fn composition_fallback_does_not_start_after_budget_exhaustion() {
1979 let primary = StallingTransport {
1980 delay: Duration::from_millis(300),
1981 error: unavailable,
1982 seen: std::sync::Mutex::new(Vec::new()),
1983 };
1984 let secondary = StallingTransport {
1985 delay: Duration::ZERO,
1986 error: unavailable,
1987 seen: std::sync::Mutex::new(Vec::new()),
1988 };
1989 let composed =
1990 ComposedTransport::new(&primary, &secondary, CompositionPolicy::UnavailableOnly);
1991 let caller = FetchLimits {
1992 connect_timeout: Duration::from_millis(20),
1993 total_timeout: Duration::from_millis(50),
1994 ..limits()
1995 };
1996
1997 let err = composed
1998 .fetch_artifact(
1999 &req("https://example.com/app"),
2000 &temp_dir("acq-exhausted").join("app"),
2001 caller,
2002 &CancelFlag::new(),
2003 )
2004 .unwrap_err();
2005 assert!(
2006 matches!(err, AcquisitionError::Timeout { .. }),
2007 "an exhausted total budget is a timeout, not a second attempt"
2008 );
2009 assert!(
2010 totals(&secondary).is_empty(),
2011 "no doomed attempt may start once the total budget is spent"
2012 );
2013 }
2014
2015 #[test]
2016 fn composition_prefers_primary_without_fallback_call() {
2017 let primary = CountingTransport::new();
2018 let secondary = CountingTransport::new();
2019 primary.route(
2020 "https://example.com/meta",
2021 FixtureResponse::body(b"primary".to_vec()),
2022 );
2023 secondary.route(
2024 "https://example.com/meta",
2025 FixtureResponse::body(b"secondary".to_vec()),
2026 );
2027 let composed =
2028 ComposedTransport::new(&primary, &secondary, CompositionPolicy::UnavailableOnly);
2029 let out = composed
2030 .fetch_metadata(
2031 &req("https://example.com/meta"),
2032 limits(),
2033 &CancelFlag::new(),
2034 )
2035 .unwrap();
2036 assert_eq!(out.success().unwrap().bytes(), b"primary");
2037 assert_eq!(primary.metadata_calls(), 1);
2038 assert_eq!(secondary.metadata_calls(), 0);
2039 }
2040
2041 #[test]
2042 fn composition_falls_back_on_unavailable_by_default() {
2043 let primary = CountingTransport::new();
2044 let secondary = CountingTransport::new();
2045 primary.route("https://example.com/meta", FixtureResponse::unavailable());
2046 secondary.route(
2047 "https://example.com/meta",
2048 FixtureResponse::body(b"fallback".to_vec()),
2049 );
2050 let composed =
2051 ComposedTransport::new(&primary, &secondary, CompositionPolicy::UnavailableOnly);
2052 let out = composed
2053 .fetch_metadata(
2054 &req("https://example.com/meta"),
2055 limits(),
2056 &CancelFlag::new(),
2057 )
2058 .unwrap();
2059 assert_eq!(out.success().unwrap().bytes(), b"fallback");
2060 assert_eq!(primary.metadata_calls(), 1);
2061 assert_eq!(secondary.metadata_calls(), 1);
2062 }
2063
2064 #[test]
2065 fn composition_default_does_not_retry_transport_failures() {
2066 let primary = CountingTransport::new();
2067 let secondary = CountingTransport::new();
2068 primary.route("https://example.com/meta", FixtureResponse::failure("boom"));
2069 secondary.route(
2070 "https://example.com/meta",
2071 FixtureResponse::body(b"secondary".to_vec()),
2072 );
2073 let composed =
2074 ComposedTransport::new(&primary, &secondary, CompositionPolicy::UnavailableOnly);
2075 let err = composed
2076 .fetch_metadata(
2077 &req("https://example.com/meta"),
2078 limits(),
2079 &CancelFlag::new(),
2080 )
2081 .unwrap_err();
2082 assert!(matches!(err, AcquisitionError::Transport(_)));
2083 assert_eq!(primary.metadata_calls(), 1);
2084 assert_eq!(secondary.metadata_calls(), 0);
2085 }
2086
2087 #[test]
2088 fn composition_broad_policy_retries_transport_and_timeout() {
2089 let primary = CountingTransport::new();
2090 let secondary = CountingTransport::new();
2091 primary.route("https://example.com/meta", FixtureResponse::failure("boom"));
2092 secondary.route(
2093 "https://example.com/meta",
2094 FixtureResponse::body(b"recovered".to_vec()),
2095 );
2096 let composed = ComposedTransport::new(
2097 &primary,
2098 &secondary,
2099 CompositionPolicy::UnavailableOrTransport,
2100 );
2101 let out = composed
2102 .fetch_metadata(
2103 &req("https://example.com/meta"),
2104 limits(),
2105 &CancelFlag::new(),
2106 )
2107 .unwrap();
2108 assert_eq!(out.success().unwrap().bytes(), b"recovered");
2109 assert_eq!(secondary.metadata_calls(), 1);
2110
2111 let p2 = CountingTransport::new();
2112 let s2 = CountingTransport::new();
2113 p2.route(
2114 "https://example.com/slow",
2115 FixtureResponse::slow(b"x".to_vec(), Duration::from_secs(30)),
2116 );
2117 s2.route(
2118 "https://example.com/slow",
2119 FixtureResponse::body(b"fast".to_vec()),
2120 );
2121 let composed2 = ComposedTransport::new(&p2, &s2, CompositionPolicy::UnavailableOrTransport);
2122 let out2 = composed2
2123 .fetch_metadata(
2124 &req("https://example.com/slow"),
2125 limits(),
2126 &CancelFlag::new(),
2127 )
2128 .unwrap();
2129 assert_eq!(out2.success().unwrap().bytes(), b"fast");
2130 }
2131
2132 #[test]
2133 fn composition_never_retries_terminal_conditions() {
2134 let primary = CountingTransport::new();
2136 let secondary = CountingTransport::new();
2137 primary.route("https://example.com/missing", FixtureResponse::not_found());
2138 secondary.route(
2139 "https://example.com/missing",
2140 FixtureResponse::body(b"other".to_vec()),
2141 );
2142 let composed = ComposedTransport::new(
2143 &primary,
2144 &secondary,
2145 CompositionPolicy::UnavailableOrTransport,
2146 );
2147 let out = composed
2148 .fetch_metadata(
2149 &req("https://example.com/missing"),
2150 limits(),
2151 &CancelFlag::new(),
2152 )
2153 .unwrap();
2154 assert!(out.is_not_found());
2155 assert_eq!(secondary.metadata_calls(), 0);
2156
2157 let cancel = CancelFlag::new();
2159 cancel.cancel();
2160 let out = composed.fetch_metadata(&req("https://example.com/missing"), limits(), &cancel);
2161 assert!(matches!(out, Err(AcquisitionError::Cancelled)));
2162 assert_eq!(secondary.metadata_calls(), 0);
2163
2164 let p3 = CountingTransport::new();
2166 let s3 = CountingTransport::new();
2167 p3.route(
2168 "https://example.com/big",
2169 FixtureResponse::body(vec![0u8; 2048]),
2170 );
2171 s3.route(
2172 "https://example.com/big",
2173 FixtureResponse::body(b"small".to_vec()),
2174 );
2175 let c3 = ComposedTransport::new(&p3, &s3, CompositionPolicy::UnavailableOrTransport);
2176 let err = c3
2177 .fetch_metadata(
2178 &req("https://example.com/big"),
2179 limits(),
2180 &CancelFlag::new(),
2181 )
2182 .unwrap_err();
2183 assert!(matches!(err, AcquisitionError::TooLarge { .. }));
2184 assert_eq!(s3.metadata_calls(), 0);
2185
2186 let err = c3
2188 .fetch_metadata(
2189 &req("https://example.com/big"),
2190 FetchLimits {
2191 max_metadata_bytes: 0,
2192 ..limits()
2193 },
2194 &CancelFlag::new(),
2195 )
2196 .unwrap_err();
2197 assert!(matches!(err, AcquisitionError::InvalidInput(_)));
2198 assert_eq!(p3.metadata_calls(), 1);
2199 assert_eq!(s3.metadata_calls(), 0);
2200 }
2201
2202 #[test]
2203 fn composition_artifact_fallback_preserves_no_clobber() {
2204 let primary = CountingTransport::new();
2205 let secondary = CountingTransport::new();
2206 primary.route("https://example.com/app", FixtureResponse::unavailable());
2207 secondary.route(
2208 "https://example.com/app",
2209 FixtureResponse::body(vec![9u8; 128]),
2210 );
2211 let composed =
2212 ComposedTransport::new(&primary, &secondary, CompositionPolicy::UnavailableOnly);
2213 let dir = temp_dir("acq-composed-artifact");
2214 let dest = dir.join("app");
2215 let out = composed
2216 .fetch_artifact(
2217 &req("https://example.com/app"),
2218 &dest,
2219 limits(),
2220 &CancelFlag::new(),
2221 )
2222 .unwrap();
2223 assert_eq!(out.success().unwrap().bytes_written, 128);
2224 assert_eq!(primary.artifact_calls(), 1);
2225 assert_eq!(secondary.artifact_calls(), 1);
2226 assert_eq!(fs::read(&dest).unwrap().len(), 128);
2227 let _ = fs::remove_dir_all(&dir);
2228 }
2229}