Skip to main content

capsule_sdk/
fetch.rs

1//! Tiered, on-demand **blob fetch** (SSoT: [Download & Sync]).
2//!
3//! Where [`crate::sync`] discovers *what* changed, this module fetches *the
4//! smallest representation that satisfies the user's current intent, and nothing
5//! more*. It owns four things the transfer download doc specifies:
6//!
7//! - **Tiered fetch + cross-asset dedup.** [`plan_eager_fetches`] returns only the
8//!   content addresses the configured [`FetchScope`] wants that are not already in
9//!   the local cache (blobs are content-addressed, so a representation shared
10//!   between assets — an identical thumbnail — is fetched at most once).
11//! - **The degrade ladder.** When an above-tier representation cannot be fetched,
12//!   the client distinguishes *permanent* (`410 Gone` / purged) from *authorization
13//!   change* (`403`) from *transient*, and degrades gracefully to the best
14//!   representation already in hand ([`best_available`]) — down to the always-present
15//!   LQIP — never removing the asset's metadata or index entry
16//!   ([`open_representation`]).
17//! - **The render ladder.** [`render_step`] extends that ladder with what the device holds,
18//!   a RAW original's embedded preview included, and answers what a surface shows now and what
19//!   to fetch or generate next; it is the one ladder the apps reach over the FFI.
20//! - **Resumable ranged fetch.** [`fetch_blob`] fetches a blob with HTTP `Range`
21//!   windows; an interrupted transfer resumes from the last persisted byte instead
22//!   of restarting, and re-fetches zero bytes it already holds. [`fetch_blob_into`]
23//!   streams the same loop into a writer in bounded windows, so an original of any size
24//!   is fetched — and, through a `StreamDecryptor` sink, restored — in bounded memory.
25//!   [`RangedFetcher::fetch_to_file`] lands a blob in a file: it writes a fsynced partial
26//!   beside the destination, resumes from that partial's length across a process restart,
27//!   and renames it into place only once the content address verifies.
28//! - **Self-verification.** The client recomputes the ciphertext content hash
29//!   against the requested content address; any mismatch discards the blob.
30//! - **Opening a derivative.** Derivative bytes are ciphertext on the server
31//!   ([Encryption]). [`open_representation`] decrypts a fetched thumbnail or preview with
32//!   the material its signed `DerivativeManifest` records — the epoch, the source asset
33//!   id and the nonce prefix — after running the closed still-format check a receiver
34//!   owes a manifest it did not author. An AEAD failure is a corrupt blob: it is
35//!   discarded and the open degrades so the caller regenerates from the original. A
36//!   tier whose manifest carries the `format = "original"` sentinel is satisfied by the
37//!   original and is never fetched.
38//! - **Admitting derivative manifests.** [`verify_derivative_manifests`] decodes the exact
39//!   bytes a feed entry carries and runs each through core's `verify_derivative` chokepoint,
40//!   walking each `(asset, role)` chain from its start. Only what it accepts goes into
41//!   [`AssetBlobs::derivative_manifests`]; what fails is quarantined and returned, never
42//!   dropped.
43//!
44//! The [`BlobSource`] seam abstracts the wire so the resume loop and degrade ladder
45//! are driven by deterministic mocks; [`HttpBlobSource`] is the production
46//! `reqwest`-over-`Range` implementation against the media server's `GET /blob/{hash}`.
47//!
48//! [Download & Sync]: https://docs/design/transfer/download/
49//! [Encryption]: https://docs/design/cryptography/encryption/
50
51use std::collections::{BTreeMap, BTreeSet};
52
53use capsule_core::cbor;
54use capsule_core::crypto::authority::AlbumAuthority;
55use capsule_core::crypto::encryption::{NONCE_PREFIX_LEN, decrypt_asset_vec};
56use capsule_core::crypto::hash::Hash32;
57use capsule_core::crypto::keys::{Amk, AmkVersion, DeviceDirectory};
58use capsule_core::crypto::provenance::{DerivativeManifest, DerivativeRole};
59use capsule_core::crypto::verify_asset::{RejectReason, VerifyOutcome};
60use capsule_core::crypto::verify_derivative::verify_derivative;
61use capsule_core::derivative_format::{DerivativeFormat, verify_still_format};
62use capsule_i18n::error_codes;
63use sha2::{Digest, Sha256};
64use tracing::instrument;
65
66use crate::events::{TransferEvent, TransferEvents, millis};
67use crate::net::{
68    ConnectionClass, MonotonicClock, RetryClass, RetryDecision, RetryEngine, Sleeper, StallConfig,
69    StallDetector, SystemClock, TokioSleeper, TransferSignal,
70};
71
72mod ladder;
73mod resumable;
74
75pub use ladder::{
76    LocalHoldings, NextStep, PixelSize, RenderRequest, RenderStep, Rendition, RungSource,
77    render_step, thumbnail_long_edge,
78};
79pub use resumable::{PARTIAL_SUFFIX, fetch_blob_to_file, partial_path};
80
81// ─── Representation ladder ───────────────────────────────────────────────────
82
83/// The ladder of an asset's representations, cheapest first. `Ord` is the ladder
84/// order, so [`best_available`] can degrade with a plain `max`.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
86pub enum Representation {
87    /// Embedded in the metadata blob; available the instant metadata syncs, at
88    /// zero extra request. Always present.
89    Lqip,
90    /// Fetched when the asset scrolls into (or near) a grid.
91    Thumbnail,
92    /// A screen-resolution derivative, fetched when the asset is opened.
93    Preview,
94    /// Full fidelity, fetched only on explicit demand.
95    Original,
96}
97
98/// The per-library synchronization-scope setting: the eager fetch ceiling. LQIP is
99/// always present (embedded); Preview is *always* on-demand (fetched on open), so
100/// it never appears in the eager set even at the highest scope.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum FetchScope {
103    /// Fetch nothing beyond the synced metadata (LQIP is embedded).
104    MetadataOnly,
105    /// Eagerly fetch thumbnails.
106    MetadataThumbnails,
107    /// Eagerly fetch thumbnails and originals.
108    MetadataThumbnailsOriginal,
109}
110
111impl FetchScope {
112    /// The representations fetched eagerly (on sync) under this scope.
113    #[must_use]
114    pub fn eager_representations(self) -> &'static [Representation] {
115        match self {
116            Self::MetadataOnly => &[],
117            Self::MetadataThumbnails => &[Representation::Thumbnail],
118            Self::MetadataThumbnailsOriginal => {
119                &[Representation::Thumbnail, Representation::Original]
120            }
121        }
122    }
123}
124
125/// A single representation's content address and ciphertext size.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct RepBlob {
128    /// Ciphertext content address (lowercase hex).
129    pub hash: String,
130    /// Ciphertext size in bytes.
131    pub size: u64,
132}
133
134/// An asset's fetchable representations, resolved from a sync feed entry's blob
135/// manifest, plus the signed derivative manifests that open them. LQIP is not here —
136/// it rides the metadata blob.
137#[derive(Debug, Clone, Default, PartialEq, Eq)]
138pub struct AssetBlobs {
139    /// The thumbnail derivative, when present.
140    pub thumbnail: Option<RepBlob>,
141    /// The preview derivative, when present.
142    pub preview: Option<RepBlob>,
143    /// The original, when present (absent while `awaiting-original`).
144    pub original: Option<RepBlob>,
145    /// The `DerivativeManifest`s of each derivative role this asset carries, already verified:
146    /// [`verify_derivative_manifests`]'s [`VerifiedDerivatives::accepted`], which ran each
147    /// through core's `verify_derivative` chokepoint. The open path checks nothing a signature
148    /// covers.
149    ///
150    /// A derivative's ciphertext is opened with `AMK(amk_version).derive_file_key(
151    /// source_asset_id, nonce_prefix)`, and those three values live here and nowhere else: the
152    /// blob manifest carries only content addresses. A thumbnail or preview with no manifest
153    /// describing its blob is not opened ([`DegradeReason::NoManifest`]).
154    ///
155    /// A receiver gets them from the sync feed, as the exact signed bytes in
156    /// [`FeedEntry::derivative_manifests`](crate::sync::FeedEntry::derivative_manifests); they
157    /// are decoded and verified before they are put here.
158    pub derivative_manifests: Vec<DerivativeManifest>,
159}
160
161impl AssetBlobs {
162    /// The manifest that describes `role`'s tier: the one committing to the blob the feed
163    /// names, else a `format = "original"` sentinel, else whichever manifest of that role
164    /// comes first (which the caller's [`open_representation`] then rejects as not describing
165    /// the blob).
166    fn manifest_for(
167        &self,
168        role: DerivativeRole,
169        blob: Option<&RepBlob>,
170    ) -> Option<&DerivativeManifest> {
171        let of_role = || {
172            self.derivative_manifests
173                .iter()
174                .filter(move |manifest| manifest.core.role == role)
175        };
176        blob.and_then(|blob| {
177            of_role().find(|manifest| manifest.core.ciphertext_hash.to_hex() == blob.hash)
178        })
179        .or_else(|| {
180            of_role().find(|manifest| manifest.core.format == DerivativeFormat::Original.mime())
181        })
182        .or_else(|| of_role().next())
183    }
184
185    /// The blob backing a representation (`None` for [`Representation::Lqip`], which
186    /// is embedded, and for any representation this asset does not carry).
187    #[must_use]
188    pub fn blob_for(&self, representation: Representation) -> Option<&RepBlob> {
189        match representation {
190            Representation::Lqip => None,
191            Representation::Thumbnail => self.thumbnail.as_ref(),
192            Representation::Preview => self.preview.as_ref(),
193            Representation::Original => self.original.as_ref(),
194        }
195    }
196}
197
198// ─── Admitting derivative manifests ──────────────────────────────────────────
199
200/// Why a received derivative manifest was quarantined rather than admitted.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum DerivativeQuarantine {
203    /// The bytes are not a `DerivativeManifest` in CBOR.
204    Undecodable,
205    /// Core's `verify_derivative` refused it. [`RejectReason::ForgedChain`] also covers a
206    /// manifest no chain from its role's start reaches, and every manifest at a fork — two
207    /// that name the same predecessor, which a receiver cannot choose between.
208    Rejected(RejectReason),
209}
210
211/// One quarantined derivative manifest: surfaced with its reason, never silently dropped.
212#[derive(Debug, Clone, PartialEq, Eq)]
213pub struct QuarantinedDerivative {
214    /// The manifest blob's content address (lowercase hex of the digest of its exact bytes) —
215    /// the same address [`crate::staged::held_from_feed`] names it by.
216    pub address: String,
217    /// Why it was quarantined.
218    pub reason: DerivativeQuarantine,
219}
220
221/// The outcome of [`verify_derivative_manifests`] over one feed entry's manifests.
222#[derive(Debug, Clone, Default, PartialEq, Eq)]
223pub struct VerifiedDerivatives {
224    /// Accepted manifests, in chain order per role — what [`AssetBlobs::derivative_manifests`]
225    /// takes.
226    pub accepted: Vec<DerivativeManifest>,
227    /// Manifests that verify but whose epoch AMK has not arrived locally: hold and retry once
228    /// the key lands, never quarantine. They still advance their role's chain, so a later
229    /// manifest of the same role is placed behind them.
230    pub pending: Vec<DerivativeManifest>,
231    /// Manifests that failed, each with its reason.
232    pub quarantined: Vec<QuarantinedDerivative>,
233}
234
235/// The roles walked, in a fixed order so the output is deterministic.
236const DERIVATIVE_ROLES: [DerivativeRole; 3] = [
237    DerivativeRole::Thumbnail,
238    DerivativeRole::Preview,
239    DerivativeRole::Embedding,
240];
241
242/// Decode and verify a feed entry's derivative manifests
243/// ([`FeedEntry::derivative_manifests`](crate::sync::FeedEntry::derivative_manifests)) for the
244/// asset `asset_id`, so that only verified ones reach [`AssetBlobs::derivative_manifests`].
245///
246/// The feed serves **every** manifest the asset has accumulated, in content-address order —
247/// not in chain order, and not only the heads — so each role's chain is rebuilt from its start
248/// here rather than resumed from a stored head: beginning with the manifest whose
249/// `prior_provenance_hash` is `None`, each next link is the one manifest naming the previous
250/// one's [`link_hash`](DerivativeManifest::link_hash), and each link is checked by core's
251/// `verify_derivative` against exactly that head.
252///
253/// The walk of a role stops at the first link that is refused, and at a fork. What it never
254/// reached is quarantined with the reason `verify_derivative` gives it against the head the walk
255/// stopped at. So a poisoned `derivative-replace` — one that does not chain to the role's head —
256/// is quarantined and the head it tried to displace stays accepted: the existing derivative is
257/// preserved.
258///
259/// `directory` is the published directory of the account whose devices generate this asset's
260/// derivatives (as for `verify_asset`, the caller resolves whose it is); `authority` is the
261/// album's MLS-attested authority.
262#[instrument(
263    level = "debug",
264    skip(encoded, directory, authority),
265    fields(%asset_id, manifests = encoded.len())
266)]
267pub fn verify_derivative_manifests(
268    encoded: &[Vec<u8>],
269    asset_id: uuid::Uuid,
270    directory: &DeviceDirectory,
271    authority: &dyn AlbumAuthority,
272) -> VerifiedDerivatives {
273    let mut out = VerifiedDerivatives::default();
274    let mut decoded: Vec<(String, DerivativeManifest)> = Vec::with_capacity(encoded.len());
275    for bytes in encoded {
276        let address = hash_hex(bytes);
277        match cbor::from_slice::<DerivativeManifest>(bytes) {
278            Ok(manifest) => decoded.push((address, manifest)),
279            Err(error) => {
280                tracing::warn!(%address, %error, "derivative manifest is undecodable; quarantined");
281                out.quarantined.push(QuarantinedDerivative {
282                    address,
283                    reason: DerivativeQuarantine::Undecodable,
284                });
285            }
286        }
287    }
288    for role in DERIVATIVE_ROLES {
289        let remaining: Vec<(String, DerivativeManifest)> = decoded
290            .iter()
291            .filter(|(_, manifest)| manifest.core.role == role)
292            .cloned()
293            .collect();
294        walk_role_chain(remaining, asset_id, directory, authority, &mut out);
295    }
296    tracing::debug!(
297        accepted = out.accepted.len(),
298        pending = out.pending.len(),
299        quarantined = out.quarantined.len(),
300        "derivative manifests verified"
301    );
302    out
303}
304
305/// Walk one role's chain from its start, sorting each manifest into `out`.
306fn walk_role_chain(
307    mut remaining: Vec<(String, DerivativeManifest)>,
308    asset_id: uuid::Uuid,
309    directory: &DeviceDirectory,
310    authority: &dyn AlbumAuthority,
311    out: &mut VerifiedDerivatives,
312) {
313    let quarantine = |out: &mut VerifiedDerivatives, address: String, reason: RejectReason| {
314        tracing::warn!(%address, ?reason, "derivative manifest rejected; quarantined");
315        out.quarantined.push(QuarantinedDerivative {
316            address,
317            reason: DerivativeQuarantine::Rejected(reason),
318        });
319    };
320    let mut head: Option<Hash32> = None;
321    loop {
322        let (mut next, rest): (Vec<_>, Vec<_>) = remaining
323            .into_iter()
324            .partition(|(_, manifest)| manifest.core.prior_provenance_hash == head);
325        remaining = rest;
326        let (address, manifest) = match (next.pop(), next.is_empty()) {
327            (Some(link), true) => link,
328            // No successor (the chain ends), or a fork: links naming one predecessor are all
329            // refused, since nothing a receiver holds can say which is the real one.
330            (popped, _) => {
331                for (address, _) in popped.into_iter().chain(next) {
332                    quarantine(out, address, RejectReason::ForgedChain);
333                }
334                break;
335            }
336        };
337        match verify_derivative(&manifest, asset_id, directory, authority, head) {
338            VerifyOutcome::Accept => {
339                head = Some(manifest.link_hash());
340                out.accepted.push(manifest);
341            }
342            VerifyOutcome::Pending(_) => {
343                head = Some(manifest.link_hash());
344                out.pending.push(manifest);
345            }
346            VerifyOutcome::TerminalReject(reason) => {
347                quarantine(out, address, reason);
348                break;
349            }
350        }
351    }
352    // Whatever the walk never reached: report why, against the head it stopped at.
353    for (address, manifest) in remaining {
354        let reason = match verify_derivative(&manifest, asset_id, directory, authority, head) {
355            VerifyOutcome::TerminalReject(reason) => reason,
356            VerifyOutcome::Accept | VerifyOutcome::Pending(_) => RejectReason::ForgedChain,
357        };
358        quarantine(out, address, reason);
359    }
360}
361
362/// The album keys a reader holds, by epoch — what opens a derivative.
363///
364/// A seam rather than a concrete key store, so the SDK never owns AMKs: the caller's
365/// workspace answers from its album store, and tests answer from a map.
366pub trait AmkSource {
367    /// The AMK for `version`, or `None` when this reader does not hold that epoch.
368    fn amk(&self, version: AmkVersion) -> Option<Amk>;
369}
370
371impl AmkSource for BTreeMap<AmkVersion, Amk> {
372    fn amk(&self, version: AmkVersion) -> Option<Amk> {
373        self.get(&version).cloned()
374    }
375}
376
377/// A read-only view of the local content-addressed blob cache, for dedup.
378pub trait BlobCache {
379    /// Whether a blob with this content address is already cached.
380    fn contains(&self, hash: &str) -> bool;
381}
382
383/// A cache that holds nothing — every planned representation is fetched.
384#[derive(Debug, Clone, Copy, Default)]
385pub struct EmptyCache;
386
387impl BlobCache for EmptyCache {
388    fn contains(&self, _hash: &str) -> bool {
389        false
390    }
391}
392
393/// Plan the eager fetches for one asset under `scope`: the content addresses the
394/// scope wants that are not already cached, de-duplicated within the plan. A blob
395/// already in `cache` (looked up by content address) is skipped — the cross-asset
396/// dedup guarantee.
397#[must_use]
398pub fn plan_eager_fetches(
399    scope: FetchScope,
400    asset: &AssetBlobs,
401    cache: &impl BlobCache,
402) -> Vec<String> {
403    let mut planned: Vec<String> = Vec::new();
404    for &representation in scope.eager_representations() {
405        if let Some(blob) = asset.blob_for(representation)
406            && !cache.contains(&blob.hash)
407            && !planned.contains(&blob.hash)
408        {
409            planned.push(blob.hash.clone());
410        }
411    }
412    planned
413}
414
415/// The best locally-held representation no higher than `desired` — the degrade
416/// target. LQIP is always present, so this is `Some` whenever `held` contains it.
417#[must_use]
418pub fn best_available(
419    desired: Representation,
420    held: &BTreeSet<Representation>,
421) -> Option<Representation> {
422    held.iter()
423        .copied()
424        .filter(|representation| *representation <= desired)
425        .max()
426}
427
428// ─── Blob source seam ────────────────────────────────────────────────────────
429
430/// The outcome of one ranged request to a [`BlobSource`].
431#[derive(Debug, Clone)]
432pub enum RangeOutcome {
433    /// The remaining bytes from the requested `start` through end-of-blob arrived.
434    Complete {
435        /// The bytes from `start` to the end of the blob.
436        bytes: Vec<u8>,
437    },
438    /// A prefix of the remaining bytes arrived, then the stream dropped
439    /// (transient) — resume from the new offset.
440    Partial {
441        /// The bytes received before the drop.
442        bytes: Vec<u8>,
443    },
444    /// The server answered a status with no usable body (`403`/`410`/`5xx`/pending).
445    Status {
446        /// The HTTP status (`0` for a transport error with no response).
447        status: u16,
448        /// The stable `error.*` code from the body, when present.
449        code: Option<String>,
450    },
451    /// The session could not authorize the request: its refresh was refused or it holds no
452    /// tokens. Retrying cannot help; the user has to sign in again.
453    Unauthenticated {
454        /// The stable `error.*` code, when the refusal carried one.
455        code: Option<String>,
456        /// English detail (developer/log message).
457        message: String,
458    },
459}
460
461/// The ranged blob transport. Abstracted so the resume loop and degrade ladder are
462/// exercised by deterministic mocks; [`HttpBlobSource`] is the production impl.
463pub trait BlobSource {
464    /// Fetch the blob `hash` from byte offset `start` (an HTTP `Range` request).
465    ///
466    /// `max_len` caps how many bytes this one request asks for: `Some(w)` requests
467    /// the bounded window `bytes={start}-{start+w-1}` (the adverse-network posture's
468    /// bounded transfer windows), and `None` requests the open-ended remainder
469    /// `bytes={start}-`. A source may return fewer bytes than requested — the loop
470    /// resumes from wherever it actually reached.
471    fn get_range(
472        &self,
473        hash: &str,
474        start: u64,
475        max_len: Option<u64>,
476    ) -> impl std::future::Future<Output = RangeOutcome> + Send;
477}
478
479// ─── Errors ──────────────────────────────────────────────────────────────────
480
481/// Why a representation could not be fetched. The variants drive the degrade
482/// ladder: [`FetchError::Gone`] is permanent, [`FetchError::AuthorizationChanged`]
483/// triggers a membership re-sync, [`FetchError::PendingUpload`] is the transient
484/// `awaiting-original` state, and the rest are transient/structural.
485#[derive(Debug, thiserror::Error)]
486pub enum FetchError {
487    /// `410 Gone` / `404` / purged origin — permanently unavailable; degrade.
488    #[error("blob permanently unavailable")]
489    Gone,
490    /// `403` — an authorization change, not a durability loss. Re-sync membership
491    /// then retry; only then degrade (the asset may have been unshared).
492    ///
493    /// Carries the stable code, because the `403`s on this route no longer say one thing: an
494    /// account's `error.blob.access_revoked` means re-sync membership, while a federated
495    /// peer's `error.federation.scope_insufficient` means the grant never covered this blob and
496    /// re-syncing anything will not change that. A caller that could not tell them apart would
497    /// retry the second forever.
498    #[error("blob authorization changed")]
499    AuthorizationChanged {
500        /// Stable `error.*` code, when the refusal carried one.
501        code: Option<String>,
502    },
503    /// `error.blob.pending_upload` — the original has not landed yet
504    /// (`awaiting-original`); show the badge, never a failure, and re-fetch when
505    /// the feed flips `original_held`. Explicitly distinct from `410 Gone`.
506    #[error("blob pending upload (awaiting-original)")]
507    PendingUpload,
508    /// A transient failure (network drop, `5xx`): retry with backoff and resume.
509    #[error("transient fetch failure: {0}")]
510    Transient(String),
511    /// A structural server rejection the client does not model.
512    #[error("blob fetch rejected (status {status}, code {code:?})")]
513    Rejected {
514        /// HTTP status.
515        status: u16,
516        /// Stable `error.*` code, when present.
517        code: Option<String>,
518    },
519    /// The reassembled ciphertext did not hash to the requested content address —
520    /// the blob is discarded.
521    #[error("integrity check failed: ciphertext hash mismatch for {expected}")]
522    IntegrityFailed {
523        /// The requested content address.
524        expected: String,
525    },
526    /// The session could not authorize the fetch — a refused refresh, no tokens, or a `401`
527    /// that survived the session's one refresh-and-retry. Not transient: the caller signs in
528    /// again rather than retrying.
529    #[error("blob fetch unauthenticated ({code:?}): {message}")]
530    Unauthenticated {
531        /// Stable `error.*` code, when the refusal carried one.
532        code: Option<String>,
533        /// English detail (developer/log message).
534        message: String,
535    },
536    /// The bounded resume budget was spent without completing the transfer.
537    #[error("fetch gave up after exhausting the resume budget: {0}")]
538    Exhausted(String),
539    /// A blob fetched without a known size ([`RangedFetcher::fetch_unsized`]) kept going past
540    /// the caller's limit; the bytes held are discarded rather than grown without bound.
541    #[error("blob exceeds the {limit}-byte limit for a blob of unlisted size")]
542    TooLarge {
543        /// The limit the caller set, in bytes.
544        limit: u64,
545    },
546    /// The destination of a streamed fetch ([`RangedFetcher::fetch_into`]) refused bytes: a
547    /// local write failed, or a decrypting sink rejected a chunk. Whatever the sink holds is
548    /// unverified and must be discarded. For [`RangedFetcher::fetch_to_file`] it is a failure
549    /// reading, writing, syncing or renaming the partial file; the partial is kept, unverified,
550    /// for the next attempt to resume and verify. A failure to sync the destination's directory
551    /// after the rename is logged, not returned here.
552    #[error("writing the fetched blob failed: {0}")]
553    Sink(#[source] std::io::Error),
554    /// A derivative's ciphertext hashed correctly but failed AEAD authentication under the
555    /// key its manifest selects — a corrupt blob, discarded.
556    #[error("derivative {hash} failed authentication; discarded")]
557    Corrupt {
558        /// The content address that would not open.
559        hash: String,
560    },
561}
562
563impl FetchError {
564    /// The stable `error.*` catalog code, when one applies.
565    #[must_use]
566    pub fn error_code(&self) -> Option<&str> {
567        match self {
568            Self::PendingUpload => Some(error_codes::BLOB_PENDING_UPLOAD),
569            // A `404` folds in here too: either way the blob is not coming back, which is what a
570            // caller telling a permanent refusal from a transient one needs to read.
571            Self::Gone => Some(error_codes::BLOB_GONE),
572            Self::AuthorizationChanged { code }
573            | Self::Rejected { code, .. }
574            | Self::Unauthenticated { code, .. } => code.as_deref(),
575            _ => None,
576        }
577    }
578
579    /// Whether the failure is permanent (degrade) rather than retryable.
580    #[must_use]
581    pub fn is_permanent(&self) -> bool {
582        matches!(self, Self::Gone)
583    }
584}
585
586/// Map a status/code with no usable body onto a typed [`FetchError`]. The stable
587/// `error.*` code is authoritative; the bare status is the fallback.
588fn classify_status(status: u16, code: Option<String>) -> FetchError {
589    if code.as_deref() == Some(error_codes::BLOB_PENDING_UPLOAD) {
590        return FetchError::PendingUpload;
591    }
592    match status {
593        // The session already refreshed once and retried; a second `401` is the credential.
594        401 => FetchError::Unauthenticated {
595            code,
596            message: "the server refused the refreshed credential".to_string(),
597        },
598        403 => FetchError::AuthorizationChanged { code },
599        404 | 410 => FetchError::Gone,
600        0 => FetchError::Transient("transport error".to_string()),
601        s if (500..600).contains(&s) => FetchError::Transient(format!("server status {s}")),
602        s => FetchError::Rejected { status: s, code },
603    }
604}
605
606// ─── Resumable ranged fetch (adverse-hardened) ───────────────────────────────
607
608/// The resumable ranged-fetch engine: stall-cut-resume, bounded
609/// transfer windows under `adverse`, and the shared [`RetryEngine`] backoff — the
610/// `bulk-transfer` retry class the download-resume ladder instantiates.
611///
612/// Behavior per the networking doc's adverse-network posture:
613/// - **Bounded windows.** Under [`ConnectionClass::Adverse`] each request asks for
614///   a bounded [`Range`](crate::net::ADVERSE_RANGE_WINDOW) window so it usually
615///   completes between mid-transfer resets; other classes fetch the remainder.
616/// - **Stall detection over total timeouts.** A [`StallDetector`] cuts on
617///   *no-bytes-for-T* (never a total-duration timeout); the cut abandons the
618///   in-flight request and resumes from the persisted offset — re-fetching **zero**
619///   bytes already held. A stall emits a [`TransferSignal::Stall`] the caller folds
620///   into `adverse` promotion.
621/// - **Bounded give-up.** No-progress reads consume the `bulk-transfer` retry
622///   budget; a persistently black-holing source gives up
623///   ([`FetchError::Exhausted`]) rather than hot-looping.
624///
625/// The [`MonotonicClock`] and [`Sleeper`] are injected so the whole loop — the
626/// stall cut and the backoff — is a deterministic, sleep-free test.
627#[derive(Debug, Clone)]
628pub struct RangedFetcher<S = TokioSleeper, C = SystemClock> {
629    class: ConnectionClass,
630    stall: StallConfig,
631    window_override: Option<u64>,
632    sleeper: S,
633    clock: C,
634    events: TransferEvents,
635}
636
637impl RangedFetcher {
638    /// A production fetcher for the given connection class (real clock + real
639    /// tokio sleeper). The window is derived from the class:
640    /// [`ConnectionClass::Adverse`] bounds it, others fetch the remainder.
641    #[must_use]
642    pub fn new(class: ConnectionClass) -> Self {
643        Self {
644            class,
645            stall: StallConfig::default(),
646            window_override: None,
647            sleeper: TokioSleeper,
648            clock: SystemClock::new(),
649            events: TransferEvents::disabled(),
650        }
651    }
652}
653
654impl<S: Sleeper, C: MonotonicClock> RangedFetcher<S, C> {
655    /// Assemble a fetcher from explicit parts — the seam the deterministic
656    /// stall-cut-resume test drives (a mock clock + a no-op recording sleeper).
657    #[must_use]
658    pub fn from_parts(
659        class: ConnectionClass,
660        stall: StallConfig,
661        window_override: Option<u64>,
662        sleeper: S,
663        clock: C,
664    ) -> Self {
665        Self {
666            class,
667            stall,
668            window_override,
669            sleeper,
670            clock,
671            events: TransferEvents::disabled(),
672        }
673    }
674
675    /// Publish every fetch this fetcher drives to `events` (range requested and received,
676    /// retry, verified, integrity-rejected). Without a subscriber it costs nothing.
677    #[must_use]
678    pub fn with_events(mut self, events: TransferEvents) -> Self {
679        self.events = events;
680        self
681    }
682
683    /// The bounded `Range` window this fetch uses, or `None` for the open-ended
684    /// remainder. An explicit override wins; otherwise the connection class decides.
685    #[must_use]
686    fn window(&self) -> Option<u64> {
687        self.window_override.or_else(|| self.class.range_window())
688    }
689
690    /// Fetch a whole blob, resumable and stall-cut, verifying the reassembled
691    /// ciphertext against its content address.
692    pub async fn fetch<B: BlobSource>(
693        &self,
694        source: &B,
695        hash: &str,
696        expected_len: u64,
697    ) -> Result<Vec<u8>, FetchError> {
698        Ok(self.run(source, hash, expected_len).await?.0)
699    }
700
701    /// As [`fetch`](Self::fetch), also returning the [`TransferSignal`] trail (clean
702    /// windows and stall cuts) the caller folds into `adverse` promotion.
703    pub async fn fetch_with_signals<B: BlobSource>(
704        &self,
705        source: &B,
706        hash: &str,
707        expected_len: u64,
708    ) -> Result<(Vec<u8>, Vec<TransferSignal>), FetchError> {
709        self.run(source, hash, expected_len).await
710    }
711
712    /// Fetch a whole blob into `sink` as it arrives, never holding more than one `Range`
713    /// window of it — the path an original takes, at any size the server accepts.
714    ///
715    /// Each request asks for at most [`SINK_WINDOW`] bytes (or the class's smaller window), so
716    /// the memory a fetch holds is bounded by the window rather than the blob. The content
717    /// address is computed incrementally and checked once the last byte has landed: until this
718    /// returns `Ok`, what `sink` holds is **unverified** and a caller writing to a file must
719    /// discard it on any error. Composing the sink with a
720    /// [`StreamDecryptor`](capsule_core::crypto::encryption::StreamDecryptor) restores an
721    /// original to plaintext in the same bounded memory, each STREAM chunk authenticated
722    /// before it is written.
723    pub async fn fetch_into<B: BlobSource, W: std::io::Write>(
724        &self,
725        source: &B,
726        hash: &str,
727        expected_len: u64,
728        sink: &mut W,
729    ) -> Result<Vec<TransferSignal>, FetchError> {
730        self.run_into(source, hash, expected_len, self.sink_window(), sink)
731            .await
732    }
733
734    /// The window a streamed fetch asks for: [`SINK_WINDOW`], or the class's smaller one.
735    fn sink_window(&self) -> Option<u64> {
736        Some(self.window().map_or(SINK_WINDOW, |w| w.min(SINK_WINDOW)))
737    }
738
739    /// Fetch a whole blob whose size nobody listed, e.g. a metadata blob the sync feed names by
740    /// address only, verifying it against its content address.
741    ///
742    /// Each request asks for a bounded window ([`UNSIZED_WINDOW`], or the class's smaller one).
743    /// The blob ends at the first window that comes back short, or at a `416` for a range that
744    /// starts exactly at its end. No-progress reads back off through the same `bulk-transfer`
745    /// retry engine and status classification as [`fetch`](Self::fetch). The blob may not grow
746    /// past `limit` bytes: a source that keeps answering full windows gets
747    /// [`FetchError::TooLarge`], never an unbounded buffer.
748    #[instrument(skip(self, source), fields(class = ?self.class))]
749    pub async fn fetch_unsized<B: BlobSource>(
750        &self,
751        source: &B,
752        hash: &str,
753        limit: u64,
754    ) -> Result<Vec<u8>, FetchError> {
755        let window = self
756            .window()
757            .map_or(UNSIZED_WINDOW, |w| w.min(UNSIZED_WINDOW))
758            .max(1);
759        let mut bytes: Vec<u8> = Vec::new();
760        let mut engine: RetryEngine = RetryClass::BulkTransfer.engine();
761        let mut stall = StallDetector::new(self.stall, self.clock.now_millis());
762        loop {
763            let start = bytes.len() as u64;
764            self.emit_requested(hash, start, Some(window));
765            let outcome = source.get_range(hash, start, Some(window)).await;
766            let now = self.clock.now_millis();
767            match outcome {
768                RangeOutcome::Complete { bytes: landed } if !landed.is_empty() || start > 0 => {
769                    if !landed.is_empty() {
770                        self.emit_received(hash, start, landed.len() as u64);
771                    }
772                    let short = (landed.len() as u64) < window;
773                    bytes.extend_from_slice(&landed);
774                    if bytes.len() as u64 > limit {
775                        return Err(FetchError::TooLarge { limit });
776                    }
777                    if short {
778                        break;
779                    }
780                    stall.on_progress(now);
781                    engine.reset();
782                }
783                RangeOutcome::Partial { bytes: landed } if !landed.is_empty() => {
784                    self.emit_received(hash, start, landed.len() as u64);
785                    bytes.extend_from_slice(&landed);
786                    if bytes.len() as u64 > limit {
787                        return Err(FetchError::TooLarge { limit });
788                    }
789                    stall.on_progress(now);
790                    engine.reset();
791                }
792                RangeOutcome::Complete { .. } | RangeOutcome::Partial { .. } => {
793                    let stalled = stall.is_stalled(now);
794                    if stalled {
795                        tracing::debug!(offset = start, "unsized fetch stalled; resuming");
796                    }
797                    match engine.next_backoff(None) {
798                        RetryDecision::GiveUp => {
799                            return Err(FetchError::Exhausted(format!(
800                                "no progress fetching {hash} after {} retries",
801                                engine.policy().max_retries
802                            )));
803                        }
804                        RetryDecision::Retry { after } => {
805                            self.emit_retried(hash, start, stalled, after);
806                            self.sleeper.sleep(after).await;
807                        }
808                    }
809                }
810                RangeOutcome::Status { status: 416, .. } if start > 0 => break,
811                RangeOutcome::Status { status, code } => {
812                    return Err(classify_status(status, code));
813                }
814                RangeOutcome::Unauthenticated { code, message } => {
815                    tracing::warn!(hash, ?code, %message, "blob fetch unauthenticated; not retrying");
816                    return Err(FetchError::Unauthenticated { code, message });
817                }
818            }
819        }
820        if hash_hex(&bytes) != hash {
821            tracing::warn!(hash, "unsized blob content-hash mismatch; discarding");
822            self.emit_verdict(hash, bytes.len() as u64, false);
823            return Err(FetchError::IntegrityFailed {
824                expected: hash.to_string(),
825            });
826        }
827        self.emit_verdict(hash, bytes.len() as u64, true);
828        tracing::debug!(hash, bytes = bytes.len(), "unsized blob fetched");
829        Ok(bytes)
830    }
831
832    async fn run<B: BlobSource>(
833        &self,
834        source: &B,
835        hash: &str,
836        expected_len: u64,
837    ) -> Result<(Vec<u8>, Vec<TransferSignal>), FetchError> {
838        let mut buffer: Vec<u8> = Vec::with_capacity(usize::try_from(expected_len).unwrap_or(0));
839        let signals = self
840            .run_into(source, hash, expected_len, self.window(), &mut buffer)
841            .await?;
842        Ok((buffer, signals))
843    }
844
845    async fn run_into<B: BlobSource, W: std::io::Write>(
846        &self,
847        source: &B,
848        hash: &str,
849        expected_len: u64,
850        window: Option<u64>,
851        sink: &mut W,
852    ) -> Result<Vec<TransferSignal>, FetchError> {
853        let resume = Resume {
854            held: 0,
855            hasher: Sha256::new(),
856        };
857        self.run_from(source, hash, expected_len, window, resume, sink, |_| Ok(()))
858            .await
859    }
860
861    /// The resume loop: fetch `hash` from `resume.held` to `expected_len` into `sink`, then
862    /// verify the content address over every byte — the `resume.held` bytes `resume.hasher`
863    /// already absorbed and the ones fetched here.
864    ///
865    /// `checkpoint` runs after each window is written and before the next is requested: a
866    /// file-backed fetch makes the window durable there, so the length it later resumes from
867    /// never counts a byte that is not on disk.
868    #[instrument(
869        skip(self, source, resume, sink, checkpoint),
870        fields(hash, expected_len, ?window, held = resume.held, class = ?self.class)
871    )]
872    #[allow(clippy::too_many_arguments)]
873    async fn run_from<B: BlobSource, W: std::io::Write>(
874        &self,
875        source: &B,
876        hash: &str,
877        expected_len: u64,
878        window: Option<u64>,
879        resume: Resume,
880        sink: &mut W,
881        mut checkpoint: impl FnMut(&mut W) -> std::io::Result<()>,
882    ) -> Result<Vec<TransferSignal>, FetchError> {
883        let Resume {
884            held: mut received,
885            mut hasher,
886        } = resume;
887        let mut signals: Vec<TransferSignal> = Vec::new();
888        // The shared retry engine, `bulk-transfer` class: resume-first, patient,
889        // backoff between attempts, bounded give-up.
890        let mut engine: RetryEngine = RetryClass::BulkTransfer.engine();
891        let mut stall = StallDetector::new(self.stall, self.clock.now_millis());
892
893        while received < expected_len {
894            let start = received;
895            let remaining = expected_len - start;
896            let max_len = window.map(|w| w.min(remaining));
897            self.emit_requested(hash, start, max_len);
898            let outcome = source.get_range(hash, start, max_len).await;
899            let now = self.clock.now_millis();
900
901            match outcome {
902                // Progress: bytes landed. Rearm the stall timer, refresh the retry
903                // budget (each resumed window earns a fresh one), and continue —
904                // every request resumes from the bytes received, so zero held bytes are
905                // ever re-requested.
906                RangeOutcome::Complete { bytes } | RangeOutcome::Partial { bytes }
907                    if !bytes.is_empty() =>
908                {
909                    stall.on_progress(now);
910                    engine.reset();
911                    self.emit_received(hash, start, bytes.len() as u64);
912                    signals.push(TransferSignal::Clean);
913                    tracing::trace!(
914                        resumed_from = start,
915                        now = start + bytes.len() as u64,
916                        "range window landed; resuming from persisted offset"
917                    );
918                    hasher.update(&bytes);
919                    sink.write_all(&bytes).map_err(FetchError::Sink)?;
920                    checkpoint(sink).map_err(FetchError::Sink)?;
921                    received += bytes.len() as u64;
922                }
923                // A no-byte read: the request stalled or was black-holed. Cut on
924                // no-bytes-for-T (a stall counts toward `adverse`), back off through
925                // the shared engine, and resume from the SAME offset — the sink is
926                // untouched, so the resume re-fetches zero duplicate bytes.
927                RangeOutcome::Complete { .. } | RangeOutcome::Partial { .. } => {
928                    let stalled = stall.is_stalled(now);
929                    if stalled {
930                        tracing::debug!(
931                            offset = start,
932                            stall_after = ?stall.stall_after(),
933                            "no-bytes-for-T stall cut; resuming from persisted offset"
934                        );
935                        signals.push(TransferSignal::Stall);
936                    }
937                    match engine.next_backoff(None) {
938                        RetryDecision::GiveUp => {
939                            return Err(FetchError::Exhausted(format!(
940                                "no progress fetching {hash} after {} retries",
941                                engine.policy().max_retries
942                            )));
943                        }
944                        RetryDecision::Retry { after } => {
945                            self.emit_retried(hash, start, stalled, after);
946                            self.sleeper.sleep(after).await;
947                        }
948                    }
949                }
950                RangeOutcome::Status { status, code } => {
951                    return Err(classify_status(status, code));
952                }
953                RangeOutcome::Unauthenticated { code, message } => {
954                    tracing::warn!(hash, ?code, %message, "blob fetch unauthenticated; not retrying");
955                    return Err(FetchError::Unauthenticated { code, message });
956                }
957            }
958        }
959
960        // The server can only attest to ciphertext; the client verifies the content
961        // address itself before trusting the bytes.
962        if hex::encode(hasher.finalize()) != hash {
963            tracing::warn!(hash, "ciphertext content-hash mismatch; discarding blob");
964            self.emit_verdict(hash, received, false);
965            return Err(FetchError::IntegrityFailed {
966                expected: hash.to_string(),
967            });
968        }
969        sink.flush().map_err(FetchError::Sink)?;
970        self.emit_verdict(hash, received, true);
971        Ok(signals)
972    }
973
974    fn emit_requested(&self, hash: &str, offset: u64, max_len: Option<u64>) {
975        self.events.emit(|| TransferEvent::RangeRequested {
976            blob: hash.to_string(),
977            offset,
978            max_len,
979        });
980    }
981
982    fn emit_received(&self, hash: &str, offset: u64, len: u64) {
983        self.events.emit(|| TransferEvent::RangeReceived {
984            blob: hash.to_string(),
985            offset,
986            len,
987        });
988    }
989
990    fn emit_retried(&self, hash: &str, offset: u64, stalled: bool, wait: std::time::Duration) {
991        self.events.emit(|| TransferEvent::FetchRetried {
992            blob: hash.to_string(),
993            offset,
994            stalled,
995            wait_ms: millis(wait),
996        });
997    }
998
999    /// The content-address check's outcome over `size` fetched bytes.
1000    fn emit_verdict(&self, hash: &str, size: u64, verified: bool) {
1001        self.events.emit(|| {
1002            let blob = hash.to_string();
1003            if verified {
1004                TransferEvent::FetchVerified { blob, size }
1005            } else {
1006                TransferEvent::IntegrityRejected { blob, size }
1007            }
1008        });
1009    }
1010}
1011
1012/// Where a fetch starts: the bytes already held, and the content hash over exactly them.
1013struct Resume {
1014    held: u64,
1015    hasher: Sha256,
1016}
1017
1018/// The `Range` window [`RangedFetcher::fetch_unsized`] asks for (64 KiB). A sealed sidecar is a
1019/// few KiB, so one window is the usual whole fetch.
1020pub const UNSIZED_WINDOW: u64 = 64 * 1024;
1021
1022/// The largest `Range` window [`RangedFetcher::fetch_into`] asks for: the memory a streamed
1023/// fetch holds is one of these, whatever the blob's size. It is the upload protocol's largest
1024/// chunk ([`PROTOCOL_MAX_CHUNK`](crate::upload::PROTOCOL_MAX_CHUNK), 16 MiB), so a transfer
1025/// holds the same bound in either direction.
1026pub const SINK_WINDOW: u64 = crate::upload::PROTOCOL_MAX_CHUNK;
1027
1028/// Fetch a whole blob into `sink` with bounded `Range` windows, verifying it against its
1029/// content address — the unmetered convenience over [`RangedFetcher::fetch_into`], and the
1030/// bounded-memory counterpart of [`fetch_blob`]. `sink` holds unverified bytes until this
1031/// returns `Ok`.
1032pub async fn fetch_blob_into<S: BlobSource, W: std::io::Write>(
1033    source: &S,
1034    hash: &str,
1035    expected_len: u64,
1036    sink: &mut W,
1037) -> Result<(), FetchError> {
1038    RangedFetcher::new(ConnectionClass::Unmetered)
1039        .fetch_into(source, hash, expected_len, sink)
1040        .await
1041        .map(drop)
1042}
1043
1044/// Fetch a whole blob with resumable `Range` windows, verifying the reassembled
1045/// ciphertext against its content address.
1046///
1047/// The unmetered convenience over [`RangedFetcher`]: each request resumes from the
1048/// current buffer length, so an interruption re-fetches **zero** bytes already
1049/// held, and on completion the SHA-256 of the assembled ciphertext must equal
1050/// `hash` or the blob is discarded ([`FetchError::IntegrityFailed`]). A caller on a
1051/// detected [`ConnectionClass::Adverse`] link builds `RangedFetcher::new(Adverse)`
1052/// instead to get bounded transfer windows.
1053pub async fn fetch_blob<S: BlobSource>(
1054    source: &S,
1055    hash: &str,
1056    expected_len: u64,
1057) -> Result<Vec<u8>, FetchError> {
1058    RangedFetcher::new(ConnectionClass::Unmetered)
1059        .fetch(source, hash, expected_len)
1060        .await
1061}
1062
1063// ─── On-demand open with degrade ladder ──────────────────────────────────────
1064
1065/// Why an asset is shown at a lower representation than requested.
1066#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1067pub enum DegradeReason {
1068    /// The representation is permanently gone (`410` / purged).
1069    PermanentlyGone,
1070    /// Authorization changed (`403`) and, after a membership re-sync, the fetch
1071    /// still failed — the asset was likely unshared.
1072    AuthorizationChanged,
1073    /// A transient failure; the asset stays listed and re-fetches automatically.
1074    TemporarilyUnavailable,
1075    /// No signed derivative manifest describes the blob the feed names, so there is no key
1076    /// to open it with. Nothing was fetched. Recovery-first: the derivative is rebuildable
1077    /// from the original.
1078    NoManifest,
1079    /// The derivative's manifest names a still format outside the closed set, or records no
1080    /// AMK epoch — a structural rejection of a manifest this reader did not author. Nothing
1081    /// was fetched.
1082    ManifestRejected,
1083    /// This reader does not hold the AMK epoch the manifest names. Nothing was fetched.
1084    KeyUnavailable,
1085    /// The ciphertext matched its content address but failed authentication under the key its
1086    /// manifest selects; the copy was discarded. Recovery-first: regenerate from the original.
1087    Corrupt,
1088}
1089
1090/// The resolution of an on-demand open.
1091#[derive(Debug, Clone, PartialEq, Eq)]
1092pub enum FetchResolution {
1093    /// A thumbnail or preview was fetched, integrity-verified, and **decrypted**.
1094    Opened {
1095        /// Which representation landed.
1096        representation: Representation,
1097        /// The derivative's plaintext (an encoded still in the manifest's format).
1098        plaintext: Vec<u8>,
1099    },
1100    /// The original was fetched. Its bytes stay **ciphertext**: the original opens through its
1101    /// signed `AssetManifest` (which may carry a wrapped file key), not through this module.
1102    Fetched {
1103        /// Which representation landed (always [`Representation::Original`]).
1104        representation: Representation,
1105        /// The ciphertext bytes (integrity-verified).
1106        bytes: Vec<u8>,
1107    },
1108    /// The tier's signed manifest carries the `format = "original"` sentinel: the tier
1109    /// *references* the original rather than holding bytes of its own, so it is satisfied by
1110    /// the original and nothing was fetched. Never a missing derivative.
1111    ReferencesOriginal {
1112        /// The representation that the original satisfies.
1113        representation: Representation,
1114    },
1115    /// The desired representation is unavailable; the asset is shown at the best
1116    /// locally-held representation instead. The asset's metadata and index entry
1117    /// are untouched — nothing is removed.
1118    Degraded {
1119        /// The representation shown instead (down to the always-present LQIP).
1120        shown: Representation,
1121        /// Why.
1122        reason: DegradeReason,
1123    },
1124    /// The original has not landed yet (`awaiting-original`): show the badge at the
1125    /// best-held representation, never a failure.
1126    Pending {
1127        /// The representation shown while awaiting the original.
1128        shown: Representation,
1129    },
1130}
1131
1132/// Fetch `desired` for an asset, applying the degrade ladder on failure.
1133///
1134/// Before any byte moves, a thumbnail or preview is resolved against its signed manifest
1135/// in [`AssetBlobs::derivative_manifests`]:
1136///
1137/// - `format = "original"` → [`FetchResolution::ReferencesOriginal`], no fetch.
1138/// - a format outside the closed still set, or no AMK epoch →
1139///   [`DegradeReason::ManifestRejected`], no fetch (the receiver half of the tier table's
1140///   "every receiver compares `DerivativeManifest.format` against this list").
1141/// - no manifest committing to the blob the feed names → [`DegradeReason::NoManifest`].
1142/// - an epoch `keys` does not hold → [`DegradeReason::KeyUnavailable`].
1143///
1144/// Then the blob is fetched:
1145///
1146/// - Success → [`FetchResolution::Opened`] (a derivative, decrypted) or
1147///   [`FetchResolution::Fetched`] (the original, still ciphertext).
1148/// - AEAD failure on a derivative → the copy is discarded, [`DegradeReason::Corrupt`].
1149/// - `403` → invoke `on_authorization_change` (re-sync membership/capability),
1150///   retry once; if it still fails, [`FetchResolution::Degraded`] with
1151///   [`DegradeReason::AuthorizationChanged`] (a revocation surfaced as such, not
1152///   masked as a missing file).
1153/// - `410`/purged → [`FetchResolution::Degraded`] / [`DegradeReason::PermanentlyGone`].
1154/// - `pending_upload` → [`FetchResolution::Pending`].
1155/// - transient → [`FetchResolution::Degraded`] / [`DegradeReason::TemporarilyUnavailable`]
1156///   (the asset stays listed and re-fetches automatically later).
1157///
1158/// The degrade target is [`best_available`] over `locally_held`, so it steps down
1159/// preview → thumbnail → LQIP. The asset's metadata / index entry is never removed
1160/// — degrade only changes what is *shown*.
1161#[instrument(
1162    skip(source, asset, locally_held, keys, on_authorization_change),
1163    fields(?desired)
1164)]
1165pub async fn open_representation<S, K, H>(
1166    source: &S,
1167    asset: &AssetBlobs,
1168    desired: Representation,
1169    locally_held: &BTreeSet<Representation>,
1170    keys: &K,
1171    mut on_authorization_change: H,
1172) -> FetchResolution
1173where
1174    S: BlobSource,
1175    K: AmkSource,
1176    H: AsyncFnMut(),
1177{
1178    let opening = match plan_opening(asset, desired, keys) {
1179        Ok(opening) => opening,
1180        Err(PreFetch::ReferencesOriginal) => {
1181            tracing::debug!("tier carries the `original` sentinel; satisfied without a fetch");
1182            return FetchResolution::ReferencesOriginal {
1183                representation: desired,
1184            };
1185        }
1186        Err(PreFetch::Degrade(reason)) => return degrade(desired, locally_held, reason),
1187    };
1188    let opening = opening.as_ref();
1189    match fetch_representation(source, asset, desired, opening).await {
1190        Ok(bytes) => landed(desired, opening, bytes),
1191        Err(FetchError::AuthorizationChanged { .. }) => {
1192            tracing::info!("403 on fetch — re-syncing album membership before retrying");
1193            on_authorization_change().await;
1194            match fetch_representation(source, asset, desired, opening).await {
1195                Ok(bytes) => landed(desired, opening, bytes),
1196                // The re-sync admitted the fetch; the bytes themselves would not open.
1197                Err(FetchError::Corrupt { .. }) => {
1198                    degrade(desired, locally_held, DegradeReason::Corrupt)
1199                }
1200                Err(_) => degrade(desired, locally_held, DegradeReason::AuthorizationChanged),
1201            }
1202        }
1203        Err(FetchError::Gone) => degrade(desired, locally_held, DegradeReason::PermanentlyGone),
1204        Err(FetchError::PendingUpload) => FetchResolution::Pending {
1205            shown: best_available(desired, locally_held).unwrap_or(Representation::Lqip),
1206        },
1207        Err(FetchError::Corrupt { .. }) => degrade(desired, locally_held, DegradeReason::Corrupt),
1208        Err(_) => degrade(desired, locally_held, DegradeReason::TemporarilyUnavailable),
1209    }
1210}
1211
1212/// The key material that opens one derivative's ciphertext, resolved from its manifest.
1213struct Opening {
1214    file_key: [u8; 32],
1215    nonce_prefix: [u8; NONCE_PREFIX_LEN],
1216}
1217
1218/// An open that resolves before any byte is fetched.
1219enum PreFetch {
1220    /// The tier's manifest is the `original` sentinel.
1221    ReferencesOriginal,
1222    /// The tier cannot be opened; degrade for this reason.
1223    Degrade(DegradeReason),
1224}
1225
1226/// The derivative role a ladder rung is backed by, or `None` for a rung that is not a
1227/// derivative (LQIP rides the metadata blob; the original opens through its asset manifest).
1228fn derivative_role(representation: Representation) -> Option<DerivativeRole> {
1229    match representation {
1230        Representation::Thumbnail => Some(DerivativeRole::Thumbnail),
1231        Representation::Preview => Some(DerivativeRole::Preview),
1232        Representation::Lqip | Representation::Original => None,
1233    }
1234}
1235
1236/// Resolve how `desired` will be opened, before fetching anything. `Ok(None)` is a rung that
1237/// is fetched as-is (the original; LQIP, which then degrades as it always has).
1238fn plan_opening<K: AmkSource>(
1239    asset: &AssetBlobs,
1240    desired: Representation,
1241    keys: &K,
1242) -> Result<Option<Opening>, PreFetch> {
1243    let Some(role) = derivative_role(desired) else {
1244        return Ok(None);
1245    };
1246    let blob = asset.blob_for(desired);
1247    let Some(manifest) = asset.manifest_for(role, blob) else {
1248        // No manifest and no blob is the absent derivative it always was: the fetch answers
1249        // `Gone` and the ladder degrades. A blob nobody describes cannot be opened.
1250        return if blob.is_none() {
1251            Ok(None)
1252        } else {
1253            tracing::warn!(
1254                ?role,
1255                "no derivative manifest describes this blob; not fetching"
1256            );
1257            Err(PreFetch::Degrade(DegradeReason::NoManifest))
1258        };
1259    };
1260    let core = &manifest.core;
1261    match verify_still_format(manifest) {
1262        Ok(Some(DerivativeFormat::Original)) => return Err(PreFetch::ReferencesOriginal),
1263        Ok(Some(_)) => {}
1264        // `None` is an embedding-role manifest, which `manifest_for` never returns for a
1265        // still rung; reject it rather than guess.
1266        Ok(None) | Err(_) => {
1267            tracing::warn!(?role, format = %core.format, "derivative format outside the closed set");
1268            return Err(PreFetch::Degrade(DegradeReason::ManifestRejected));
1269        }
1270    }
1271    let Some(blob) = blob else {
1272        // A real derivative the server does not list: permanently unavailable.
1273        return Ok(None);
1274    };
1275    if core.ciphertext_hash.to_hex() != blob.hash {
1276        tracing::warn!(
1277            ?role,
1278            "derivative manifest commits to different bytes than the feed names"
1279        );
1280        return Err(PreFetch::Degrade(DegradeReason::NoManifest));
1281    }
1282    let Some(version) = core.amk_version else {
1283        tracing::warn!(?role, "derivative manifest records no AMK epoch");
1284        return Err(PreFetch::Degrade(DegradeReason::ManifestRejected));
1285    };
1286    let Some(amk) = keys.amk(version) else {
1287        tracing::info!(
1288            ?role,
1289            epoch = version.0,
1290            "AMK epoch not held; cannot open derivative"
1291        );
1292        return Err(PreFetch::Degrade(DegradeReason::KeyUnavailable));
1293    };
1294    Ok(Some(Opening {
1295        file_key: amk.derive_file_key(&core.source_asset_id, &core.nonce_prefix),
1296        nonce_prefix: core.nonce_prefix,
1297    }))
1298}
1299
1300/// The resolution for bytes that landed: plaintext when they were opened, ciphertext when
1301/// the rung is not a derivative.
1302fn landed(desired: Representation, opening: Option<&Opening>, bytes: Vec<u8>) -> FetchResolution {
1303    if opening.is_some() {
1304        FetchResolution::Opened {
1305            representation: desired,
1306            plaintext: bytes,
1307        }
1308    } else {
1309        FetchResolution::Fetched {
1310            representation: desired,
1311            bytes,
1312        }
1313    }
1314}
1315
1316fn degrade(
1317    desired: Representation,
1318    locally_held: &BTreeSet<Representation>,
1319    reason: DegradeReason,
1320) -> FetchResolution {
1321    let shown = best_available(desired, locally_held).unwrap_or(Representation::Lqip);
1322    tracing::info!(
1323        ?shown,
1324        ?reason,
1325        "degrading to best locally-held representation"
1326    );
1327    FetchResolution::Degraded { shown, reason }
1328}
1329
1330/// Fetch exactly one representation's blob (no degrade), and open it when `opening` says
1331/// how. A representation the asset does not carry is treated as permanently gone (degrade
1332/// upstream).
1333///
1334/// An opened blob that fails authentication is discarded as [`FetchError::Corrupt`] and is
1335/// **not** re-fetched: [`fetch_blob`] has already verified the bytes against their content
1336/// address, so a second fetch can only return the same bytes and fail the same way. The
1337/// recovery is the thumbnails doc's — regenerate from the original — and it is the caller's,
1338/// signalled by [`DegradeReason::Corrupt`].
1339async fn fetch_representation<S: BlobSource>(
1340    source: &S,
1341    asset: &AssetBlobs,
1342    representation: Representation,
1343    opening: Option<&Opening>,
1344) -> Result<Vec<u8>, FetchError> {
1345    let blob = asset.blob_for(representation).ok_or(FetchError::Gone)?;
1346    let ciphertext = fetch_blob(source, &blob.hash, blob.size).await?;
1347    let Some(opening) = opening else {
1348        return Ok(ciphertext);
1349    };
1350    decrypt_asset_vec(&opening.file_key, &opening.nonce_prefix, &ciphertext).map_err(|error| {
1351        tracing::warn!(hash = %blob.hash, %error, "derivative failed authentication; discarding");
1352        FetchError::Corrupt {
1353            hash: blob.hash.clone(),
1354        }
1355    })
1356}
1357
1358// ─── Production HTTP source ──────────────────────────────────────────────────
1359
1360/// The production ranged blob source: `reqwest` `GET /blob/{hash}` with a `Range`
1361/// header, authorized through the SDK session. rustls only.
1362///
1363/// The mid-stream-drop resume path ([`RangeOutcome::Partial`]) is exercised by the
1364/// module's mocks; this impl reads each `Range` window whole (a clean drop surfaces
1365/// as a transport error and the loop resumes from the persisted offset), and the
1366/// streaming-partial wiring lands with media serving.
1367#[derive(Clone)]
1368pub struct HttpBlobSource {
1369    session: crate::auth::Session,
1370    base_url: String,
1371}
1372
1373impl HttpBlobSource {
1374    /// Build a source against the media server's blob endpoint root (no trailing
1375    /// slash); a blob is fetched from `{base_url}/blob/{hash}`.
1376    pub fn new(session: crate::auth::Session, base_url: impl Into<String>) -> Self {
1377        Self {
1378            session,
1379            base_url: base_url.into().trim_end_matches('/').to_string(),
1380        }
1381    }
1382}
1383
1384impl BlobSource for HttpBlobSource {
1385    async fn get_range(&self, hash: &str, start: u64, max_len: Option<u64>) -> RangeOutcome {
1386        let url = format!("{}/blob/{hash}", self.base_url);
1387        // Under `adverse` the fetcher passes a bounded window; otherwise the
1388        // open-ended remainder. A zero-length window would be malformed — treat it
1389        // as open-ended (the loop never asks for zero when bytes remain).
1390        let range = match max_len {
1391            Some(len) if len > 0 => format!("bytes={start}-{}", start + len - 1),
1392            _ => format!("bytes={start}-"),
1393        };
1394        let response = match self
1395            .session
1396            .execute(|http| http.get(&url).header(reqwest::header::RANGE, &range))
1397            .await
1398        {
1399            Ok(response) => response,
1400            Err(error) => return session_failure(&error),
1401        };
1402
1403        let status = response.status().as_u16();
1404        if (200..300).contains(&status) {
1405            match response.bytes().await {
1406                Ok(bytes) => RangeOutcome::Complete {
1407                    bytes: bytes.to_vec(),
1408                },
1409                // A mid-stream drop reading the body: resume from the persisted
1410                // offset (no bytes are known to have landed here).
1411                Err(_) => RangeOutcome::Partial { bytes: Vec::new() },
1412            }
1413        } else {
1414            // The stable `error.*` code (e.g. `error.blob.pending_upload`) rides
1415            // the `x-capsule-error-code` header, mirroring the sync/upload surfaces.
1416            let code = response
1417                .headers()
1418                .get("x-capsule-error-code")
1419                .and_then(|value| value.to_str().ok())
1420                .map(str::to_string);
1421            RangeOutcome::Status { status, code }
1422        }
1423    }
1424}
1425
1426/// How a session that could not send a range request reads to the fetch loop.
1427///
1428/// Only a session that is over — refresh refused or revoked, no tokens, or a `401`-class
1429/// answer from the refresh — is [`RangeOutcome::Unauthenticated`], which tells the app to sign
1430/// in again. Everything else (a transport drop, an unreachable or rate-limited refresh, a
1431/// refresh `5xx`, a malformed refresh body) is temporary: it reads as a transient status, so a
1432/// blip never costs the user their session.
1433fn session_failure(error: &crate::auth::AuthError) -> RangeOutcome {
1434    use crate::auth::AuthError;
1435    match error {
1436        AuthError::SessionExpired
1437        | AuthError::NotAuthenticated
1438        | AuthError::Unexpected { status: 401, .. } => {
1439            tracing::debug!(%error, "blob range request could not be authorized");
1440            RangeOutcome::Unauthenticated {
1441                code: error.error_code().map(str::to_string),
1442                message: error.to_string(),
1443            }
1444        }
1445        AuthError::Unexpected { status, code, .. } if (500..600).contains(status) => {
1446            tracing::debug!(%error, "blob range request: the session's refresh failed server-side");
1447            RangeOutcome::Status {
1448                status: *status,
1449                code: code.clone(),
1450            }
1451        }
1452        _ => {
1453            tracing::debug!(%error, "blob range request: transient session or transport failure");
1454            RangeOutcome::Status {
1455                status: 0,
1456                code: None,
1457            }
1458        }
1459    }
1460}
1461
1462/// SHA-256 of the ciphertext as bare lowercase hex — byte-identical to the
1463/// server's content address (`capsule_core::crypto::hash::hash_bytes`).
1464fn hash_hex(bytes: &[u8]) -> String {
1465    let mut hasher = Sha256::new();
1466    hasher.update(bytes);
1467    hex::encode(hasher.finalize())
1468}
1469
1470#[cfg(test)]
1471mod tests;