Skip to main content

eggup_acquisition/
lib.rs

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/// An exact acquisition request selected by caller policy.
19///
20/// The URL is used verbatim: the transport performs no discovery, version
21/// selection, mirror choice, or fallback. Query and credential material is
22/// redacted in all diagnostics.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct AcquisitionRequest {
25    url: String,
26}
27
28impl AcquisitionRequest {
29    /// Creates a request for an exact URL after basic validation.
30    ///
31    /// Rejects empty URLs, control characters, and non-`http(s)` schemes.
32    /// The URL is stored verbatim; redaction applies only to diagnostics.
33    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    /// Returns the exact URL.
52    pub fn url(&self) -> &str {
53        &self.url
54    }
55
56    /// Returns the redacted URL for diagnostics.
57    pub fn redacted(&self) -> String {
58        redact_url(&self.url)
59    }
60}
61
62/// Caller-provided byte and time bounds for one fetch.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct FetchLimits {
65    /// Maximum decoded metadata bytes held in memory.
66    pub max_metadata_bytes: usize,
67    /// Maximum artifact bytes written to disk. Every fetch is finitely bounded.
68    pub max_artifact_bytes: u64,
69    /// Deadline for establishing the connection (advisory for fixtures).
70    pub connect_timeout: Duration,
71    /// Total wall-clock deadline for the fetch.
72    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    /// Validates caller-provided byte and time bounds.
88    ///
89    /// The fields remain public for 0.1.x source compatibility, so every
90    /// transport validates limits again at its I/O boundary. Invalid direct
91    /// struct literals are rejected before route, filesystem, or network I/O.
92    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    /// Creates limits with explicit bounds.
111    ///
112    /// Requires non-zero `connect_timeout` and `total_timeout` with
113    /// `connect_timeout <= total_timeout`. The connect phase is part of the
114    /// total wall-clock budget, so a connect deadline beyond the total
115    /// deadline cannot be satisfied truthfully.
116    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    /// Derives the authoritative effective deadlines for one fetch.
133    ///
134    /// ```text
135    /// effective connect timeout = min(request connect, adapter connect ceiling)
136    /// effective total timeout   = min(request total, adapter total ceiling)
137    /// ```
138    ///
139    /// A stricter adapter ceiling is allowed; an adapter may never silently
140    /// extend a caller deadline. Both metadata and artifact operations use
141    /// the same derivation, and the effective total deadline covers response
142    /// headers plus body streaming.
143    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/// Cooperative cancellation flag checked during streaming.
155///
156/// Dropping a fetch without completing it also cleans any owned incomplete
157/// output where safe (see `fetch_artifact`).
158#[derive(Debug, Default)]
159pub struct CancelFlag {
160    cancelled: AtomicBool,
161}
162
163impl CancelFlag {
164    /// Creates an uncancelled flag.
165    pub fn new() -> Self {
166        Self::default()
167    }
168
169    /// Requests cancellation.
170    pub fn cancel(&self) {
171        self.cancelled.store(true, Ordering::SeqCst);
172    }
173
174    /// Returns whether cancellation was requested.
175    pub fn is_cancelled(&self) -> bool {
176        self.cancelled.load(Ordering::SeqCst)
177    }
178}
179
180/// Typed success/absence outcome. Hard failures are `Err(AcquisitionError)`.
181///
182/// `NotFound` is data (the exact URL is absent); the consumer decides what it
183/// means. It never triggers fallback inside a transport.
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum FetchOutcome<T> {
186    /// The exact URL produced a usable response.
187    Success(T),
188    /// The exact URL is definitively absent (HTTP 404 equivalent).
189    NotFound,
190}
191
192impl<T> FetchOutcome<T> {
193    /// Returns the success value, if any.
194    pub fn success(self) -> Option<T> {
195        match self {
196            Self::Success(v) => Some(v),
197            Self::NotFound => None,
198        }
199    }
200
201    /// Returns true for `Success`.
202    pub fn is_success(&self) -> bool {
203        matches!(self, Self::Success(_))
204    }
205
206    /// Returns true for `NotFound`.
207    pub fn is_not_found(&self) -> bool {
208        matches!(self, Self::NotFound)
209    }
210}
211
212/// Bounded small-body metadata bytes.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct MetadataBytes {
215    bytes: Vec<u8>,
216}
217
218impl MetadataBytes {
219    /// Returns the exact body bytes.
220    pub fn bytes(&self) -> &[u8] {
221        &self.bytes
222    }
223
224    /// Returns the body length.
225    pub fn len(&self) -> usize {
226        self.bytes.len()
227    }
228
229    /// Returns whether the body is empty.
230    pub fn is_empty(&self) -> bool {
231        self.bytes.is_empty()
232    }
233}
234
235/// Streamed artifact evidence.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct ArtifactEvidence {
238    /// Bytes written to the destination file.
239    pub bytes_written: u64,
240}
241
242impl ArtifactEvidence {
243    /// Returns bytes written.
244    pub fn bytes_written(&self) -> u64 {
245        self.bytes_written
246    }
247}
248
249/// Hard acquisition failure. Never used for `NotFound`.
250///
251/// Only `Debug` is derived. The `Io` variant carries a [`std::io::Error`],
252/// which implements neither `Clone` nor `PartialEq`/`Eq`, so those derives are
253/// deliberately absent. This mirrors `eggup-core`'s published `Error`, which
254/// derives only `Debug` for the same reason. Match on the variant and its
255/// fields instead of comparing whole errors.
256#[derive(Debug)]
257#[non_exhaustive]
258pub enum AcquisitionError {
259    /// Caller input violates the seam contract.
260    InvalidInput(String),
261    /// A transport-level failure (TLS, proxy, 5xx, malformed response, early
262    /// disconnect). URL material is already redacted.
263    Transport(String),
264    /// The response exceeded a caller byte bound.
265    TooLarge {
266        /// The bound that was exceeded.
267        limit: u64,
268    },
269    /// A connect or total deadline elapsed.
270    Timeout {
271        /// Which deadline elapsed.
272        phase: &'static str,
273    },
274    /// Cooperative cancellation was observed.
275    Cancelled,
276    /// A transaction-owned filesystem operation failed.
277    ///
278    /// The variant is **typed**: `operation` names the filesystem operation
279    /// that failed and `source` preserves the underlying [`std::io::Error`].
280    /// A consumer can therefore match on [`std::io::ErrorKind`] and walk the
281    /// [`std::error::Error::source`] chain instead of parsing a flattened
282    /// string. `operation` is a stable label and never carries URL material;
283    /// the rendered detail is bounded exactly like every other variant.
284    Io {
285        /// The filesystem operation that failed.
286        operation: &'static str,
287        /// The underlying I/O error, preserved verbatim.
288        source: std::io::Error,
289    },
290    /// The adapter could not attempt the request (missing executable, failed
291    /// discovery, spawn failure). URL material is already redacted.
292    ///
293    /// Composition falls back to the next transport on `Unavailable`. Ordinary
294    /// `Transport`/`Timeout` failures fall back only under an explicit
295    /// opt-in policy. All other errors and `NotFound` are terminal.
296    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    /// Adapter-only constructor for unavailable evidence.
309    ///
310    /// `#[doc(hidden)]`: not part of the consumer contract; allows verified
311    /// adapters (`eggup-curl`) to report missing/spawn failures without
312    /// widening the public seam with a general constructor.
313    #[doc(hidden)]
314    pub fn __adapter_unavailable(detail: impl Into<String>) -> Self {
315        Self::Unavailable(bound_detail(detail.into()))
316    }
317
318    /// Adapter-only constructor for a typed I/O failure.
319    ///
320    /// `#[doc(hidden)]`: not part of the consumer contract; allows verified
321    /// adapters (`eggup-curl`, `eggup-eggfetch`) to report a filesystem
322    /// failure with the underlying [`std::io::Error`] intact instead of
323    /// flattening it into a string.
324    #[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    /// Returns true when the adapter was unavailable to attempt the request.
334    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    /// Returns the underlying I/O error for the `Io` variant.
358    ///
359    /// Every other variant is a seam-level category with no underlying cause,
360    /// so it reports `None`.
361    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/// Bounds an adapter-supplied diagnostic detail to 512 bytes, truncating only
370/// at a UTF-8 character boundary.
371///
372/// `#[doc(hidden)]`: adapter-facing. This is the **single** implementation of
373/// the seam's bounded-detail rule; adapters must call it instead of keeping a
374/// local copy of the truncation logic.
375#[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
395/// Redacts credential-bearing URL material for diagnostics.
396///
397/// Strips `user:password@` credentials, query strings, and fragments, then
398/// truncates overlong URLs. The exact URL is still used for the fetch; only
399/// the diagnostic string is redacted.
400///
401/// Upstream transport/proxy error text is never embedded in diagnostics: all
402/// transport failures use structured category text plus this redacted URL, so
403/// credential-bearing upstream strings cannot leak through `Display`.
404pub 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            // Keep host/path, drop credentials.
411            out = format!("{}://<redacted>@{}", &url[..scheme_end], &url[at_abs + 1..]);
412        }
413    }
414    // Redact fragments first so they cannot smuggle tokens past query handling.
415    if let Some(h) = out.find('#') {
416        out.truncate(h);
417        out.push_str("#<redacted>");
418    }
419    // Redact query strings, which commonly carry tokens.
420    if let Some(q) = out.find('?') {
421        out.truncate(q);
422        out.push_str("?<redacted>");
423    }
424    // Single UTF-8-safe truncation implementation: `truncate_utf8_bytes` is the
425    // seam's only primitive, so the cap cannot drift from the shared rule.
426    let truncated = out.len() > 256;
427    out = truncate_utf8_bytes(out, 256);
428    if truncated {
429        out.push('…');
430    }
431    out
432}
433
434/// Scrubs credential-like URL patterns from arbitrary upstream text.
435///
436/// This is defense-in-depth only. Production adapters must not embed raw
437/// upstream error display in diagnostics; they use structured category text
438/// plus [`redact_url`]. This helper strips `://credentials@` and `?query`
439/// patterns from any string that must be incorporated for debugging.
440#[doc(hidden)]
441pub fn __scrub_upstream_text(text: &str) -> String {
442    // Cheap deterministic scrub: redact userinfo and query-looking suffixes.
443    let mut out = text.to_string();
444    // Redact `://...@` credential blocks with an advancing cursor so each
445    // iteration makes progress and the loop always terminates.
446    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 another `://` appears before the `@`, the current scheme has no
458        // userinfo; skip past it instead of consuming a later URL's `@`.
459        if out[after..at_abs].contains("://") {
460            search_from = after;
461            continue;
462        }
463        // Bound the credential block to avoid runaway on non-URL text.
464        if at_abs - after > 512 {
465            break;
466        }
467        out.replace_range(after..at_abs, "<redacted>");
468        // Advance past the replacement and its trailing `@` so the same URL
469        // is never reprocessed.
470        search_from = after + "<redacted>".len() + 1;
471    }
472    // Redact query strings: truncate at first `?` and mark redacted, but
473    // only when the `?` looks like URL query material (has `=` or `&` or
474    // is followed by non-space token material). This avoids mangling
475    // ordinary prose containing `?`.
476    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    // Single UTF-8-safe truncation implementation (512-byte cap, no ellipsis).
484    truncate_utf8_bytes(out, 512)
485}
486
487/// Maximum exclusive-temp creation attempts before bounded failure.
488#[doc(hidden)]
489pub const __TEMP_COLLISION_BOUND: u32 = 32;
490
491/// Creates an exclusively-owned temporary sibling in `parent`.
492///
493/// The file is created with `create_new` (fails if the candidate already
494/// exists), retried with a fresh nonce on collision within
495/// [`__TEMP_COLLISION_BOUND`], never follows a precreated symlink, lives in
496/// the exact destination parent so promotion stays on the same filesystem,
497/// and uses owner-private `0600` permissions on Unix. Returns the open file
498/// plus its path; the caller owns cleanup of exactly this path.
499///
500/// `prefix` should identify the adapter (for example `eggup-acquire` or
501/// `eggup-eggfetch`) and must not contain path separators.
502#[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                // Enforce owner-private permissions even under permissive umask.
528                // Any failure here happens after the file exists, so this
529                // function is the only owner that can clean it up: callers build
530                // their `Guard` only after this returns `Ok`.
531                #[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/// Promotes an owned temporary file to `dest` without clobbering.
567///
568/// Uses a race-safe no-replace strategy (`hard_link` fails with
569/// `AlreadyExists` when `dest` exists, without overwriting). The temp and
570/// dest must share a parent directory (same filesystem). On success the temp
571/// link cleanup is best-effort after commit; failure may leave the owned temp
572/// link as residue but never turns a committed destination into ordinary
573/// failure. If `dest` already
574/// exists — before the call or raced in during the fetch — returns an
575/// explicit `InvalidInput` error and preserves the foreign destination;
576/// the caller must remove its owned temp separately.
577///
578/// This avoids platform-specific `rename`-overwrite semantics: Unix
579/// `rename` would silently replace `dest`, while Windows `rename` fails.
580/// `hard_link` fails closed on both when `dest` exists.
581#[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            // The destination is committed. Cleanup of the redundant owned
594            // name cannot retroactively make acquisition fail.
595            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/// Best-effort removal of exactly one owned temporary file.
606///
607/// Uses `remove_file` (never follows symlinks to targets, never recurses)
608/// and ignores failures; used in `Drop` guards where no error can be
609/// returned. Never performs prefix-based cleanup of unrelated siblings.
610#[doc(hidden)]
611pub fn __remove_owned_temp(path: &Path) {
612    let _ = std::fs::remove_file(path);
613}
614
615/// The minimal transport-neutral acquisition contract.
616///
617/// Implementations receive an exact URL, enforce caller bounds, and stream
618/// artifacts to files. They never select releases, versions, mirrors, or
619/// fallback sources, and never execute downloaded content.
620///
621/// Effective time bounds obey `min(request, adapter ceiling)` per
622/// [`FetchLimits::effective`]: a stricter adapter may tighten a deadline but
623/// never extend it. Artifact promotion requires `dest` to be absent; an
624/// existing or raced-in destination fails without overwrite.
625pub trait AcquisitionTransport {
626    /// Fetches a bounded small body (release metadata, checksums) into memory.
627    fn fetch_metadata(
628        &self,
629        request: &AcquisitionRequest,
630        limits: FetchLimits,
631        cancel: &CancelFlag,
632    ) -> Result<FetchOutcome<MetadataBytes>, AcquisitionError>;
633
634    /// Streams an artifact body to `dest` without requiring full buffering.
635    ///
636    /// The file at `dest` is created atomically: bytes stream to an
637    /// exclusively-created, owner-private temporary sibling and are promoted
638    /// with no-clobber semantics only on full success. `dest` must be absent
639    /// at promotion time; an existing or raced-in destination fails with an
640    /// explicit error and is never overwritten. Partial outputs clean only
641    /// the owned temp on failure or cancellation where safe. `dest`'s parent
642    /// must already exist as a real directory.
643    ///
644    /// Effective time bounds obey `min(request, adapter ceiling)`; see
645    /// [`FetchLimits::effective`].
646    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/// One deterministic fixture response.
658#[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    /// A successful body.
675    pub fn body(bytes: impl Into<Vec<u8>>) -> Self {
676        Self {
677            kind: FixtureKind::Body(bytes.into()),
678        }
679    }
680
681    /// A definitive absence (HTTP 404 equivalent).
682    pub fn not_found() -> Self {
683        Self {
684            kind: FixtureKind::NotFound,
685        }
686    }
687
688    /// A hard transport failure (TLS/5xx/malformed equivalent).
689    ///
690    /// The detail is accepted for call-site compatibility but never exposed
691    /// in diagnostics, mirroring production category-only errors so
692    /// credential-bearing strings cannot leak.
693    pub fn failure(_detail: impl Into<String>) -> Self {
694        Self {
695            kind: FixtureKind::Failure,
696        }
697    }
698
699    /// A body truncated after `prefix_len` bytes (early disconnect).
700    pub fn truncated(prefix_len: usize) -> Self {
701        Self {
702            kind: FixtureKind::Truncated { prefix_len },
703        }
704    }
705
706    /// A body delivered only after `delay` (timeout testing).
707    pub fn slow(body: Vec<u8>, delay: Duration) -> Self {
708        Self {
709            kind: FixtureKind::Slow { body, delay },
710        }
711    }
712
713    /// An adapter-unavailable condition (missing executable/spawn failure
714    /// equivalent) for composition fallback testing.
715    pub fn unavailable() -> Self {
716        Self {
717            kind: FixtureKind::Unavailable,
718        }
719    }
720}
721
722/// Deterministic in-memory transport for correctness tests.
723///
724/// Real network policy lives in `eggup-eggfetch`. This transport never touches
725/// the network; every URL must be registered explicitly, and unregistered URLs
726/// are hard failures (never silent fallback).
727#[derive(Debug, Default)]
728pub struct FixtureTransport {
729    routes: Mutex<HashMap<String, FixtureResponse>>,
730}
731
732impl FixtureTransport {
733    /// Creates an empty fixture transport.
734    pub fn new() -> Self {
735        Self::default()
736    }
737
738    /// Registers one exact URL response.
739    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            // Never echo fixture failure detail: it may contain test
777            // secrets and production adapters use category-only errors.
778            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        // Fast-fail when the destination already exists. The race-safe
841        // guarantee comes from `__promote_no_clobber` below; this pre-check
842        // avoids wasted work for the common case.
843        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                // Simulate a partial write then a hard failure; no file is promoted.
864                // Use exclusive creation so collision/symlink behavior matches
865                // the success path, then clean only the owned temp.
866                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        // Exclusive owner-private temp plus race-safe no-clobber promotion.
896        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        // Chunked write so cancellation and partial-write failures are observable.
913        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        // Re-check cancellation before promotion: never promote after cancel.
929        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                // Preserve the foreign destination; remove only the owned temp.
941                __remove_owned_temp(&tmp);
942                guard.disarm = true;
943                Err(e)
944            }
945        }
946    }
947}
948
949/// Shared ownership helper for tests that need a transport behind `Arc`.
950pub type SharedTransport = Arc<FixtureTransport>;
951
952/// Adapter-only constructor for metadata bytes.
953///
954/// `#[doc(hidden)]`: not part of the consumer contract; allows verified
955/// adapters (`eggup-eggfetch`) to return seam types without widening the
956/// public seam with a general constructor.
957#[doc(hidden)]
958pub fn __adapter_metadata(bytes: Vec<u8>) -> MetadataBytes {
959    MetadataBytes { bytes }
960}
961
962/// Adapter-only constructor for artifact evidence.
963///
964/// `#[doc(hidden)]`: see `__adapter_metadata`.
965#[doc(hidden)]
966pub fn __adapter_artifact(bytes_written: u64) -> ArtifactEvidence {
967    ArtifactEvidence { bytes_written }
968}
969
970/// Caller-selected fallback scope for a composed transport.
971///
972/// Transport fallback (`curl <-> Eggfetch` for the same exact URL) is never
973/// release/source fallback. `NotFound` is terminal for the exact URL under
974/// every policy. `InvalidInput`, `Cancelled`, `TooLarge`, and `Io`
975/// (staging/promotion) failures are terminal under every policy.
976/// Verification/candidate failures occur above this layer and are never
977/// transport-fallback inputs.
978#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
979pub enum CompositionPolicy {
980    /// Fall back only when the preferred adapter is unavailable
981    /// (`AcquisitionError::Unavailable`). This is the default.
982    #[default]
983    UnavailableOnly,
984    /// Fall back on unavailability plus ordinary transport failures
985    /// (`Transport` and `Timeout`). Terminal conditions above remain terminal.
986    UnavailableOrTransport,
987}
988
989/// Explicit caller-selected preferred/fallback composition over two transports.
990///
991/// The composition itself implements [`AcquisitionTransport`] so callers keep
992/// a single seam. Preferred order is the construction order: `primary` is
993/// attempted first, `secondary` only when the policy allows fallback for the
994/// primary outcome.
995///
996/// Fallback is decided from typed outcomes, never by parsing human-readable
997/// errors.
998pub 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    /// Creates a composed transport with an explicit fallback policy.
1014    ///
1015    /// No network, filesystem, or process work occurs here; policy and
1016    /// ordering are the only decisions recorded.
1017    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    /// Returns the fallback policy.
1030    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    /// Reduces the caller's budget to what is left after the primary attempt.
1045    ///
1046    /// `FetchLimits::total_timeout` is the *total* wall-clock deadline for the
1047    /// fetch, so handing the secondary adapter the original limits would let
1048    /// one composed fetch run for roughly twice the caller's deadline. The
1049    /// connect bound is clamped alongside it because the seam requires
1050    /// `connect_timeout <= total_timeout`. Exhausting the budget is reported as
1051    /// a total timeout rather than starting a doomed attempt.
1052    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        // Validate once at the composition boundary so invalid caller limits
1081        // fail before either adapter performs route/filesystem/network I/O.
1082        // Adapters revalidate at their own boundaries per the seam contract.
1083        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                    // The fallback shares the caller's single total budget.
1093                    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                    // The fallback shares the caller's single total budget.
1119                    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    // ---- M003 corrective: timeout contract ----
1475
1476    #[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        // Request stricter than adapter: request wins.
1498        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        // Adapter stricter than request: adapter wins.
1502        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        // Mixed: each phase takes its own minimum.
1512        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    // ---- M003 corrective: exclusive temp + no-clobber ----
1547
1548    #[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        // Foreign destination bytes are preserved verbatim.
1571        assert_eq!(fs::read(&dest).unwrap(), b"FOREIGN-BYTES");
1572        // No owned temp residue.
1573        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        // Direct helper test for the race window: dest appears after the
1606        // pre-check but before promotion.
1607        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        // Owned temp still exists for caller cleanup; remove it explicitly.
1620        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        // The creation primitive itself must fail on an existing path.
1660        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        // Helper creates a distinct sibling and leaves the victim alone.
1668        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        // create_new on the symlink path itself must fail without touching target.
1687        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        // A fixture fetch must not modify the symlink target either.
1695        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    // ---- M003 corrective: redaction ----
1775
1776    #[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        // Unregistered URL error embeds only the redacted URL.
1783        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        // Fixture failure detail is never echoed.
1792        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        // Fragment is also redacted.
1810        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        // Category-only errors never contain the sentinel at all.
1822        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    // ---- M005: explicit transport composition ----
1834
1835    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    /// Burns wall-clock time, then fails, so the composed budget can be
1891    /// exercised against a real elapsed duration rather than a simulated one.
1892    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        // The failure is expected; what matters is what the secondary was handed.
1958        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        // The budget actually left is close to the original minus the stall.
1971        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        // NotFound is terminal even under the broad policy.
2135        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        // Cancellation is terminal.
2158        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        // TooLarge is terminal.
2165        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        // InvalidInput is terminal (fails before either adapter).
2187        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}