Skip to main content

capsule_sdk/
upload.rs

1//! Upload client module for Capsule SDK.
2//!
3//! The hand-written, chunked, resumable, adaptive upload client. The protocol is too
4//! stateful for codegen — the spargen-generated REST client covers the plain request/response
5//! surfaces instead — so this module owns the wire directly:
6//!
7//! - `create`/`PATCH`/`HEAD`/`DELETE`/`list` with `application/octet-stream`
8//!   chunk bodies and the required per-chunk `X-Capsule-Checksum` (lowercase-hex
9//!   SHA-256), `X-Capsule-Offset`, and the `X-Capsule-Protocol` handshake header;
10//! - the **normative** adaptive chunk-size algorithm ([`AdaptiveChunkSizeStrategy`]),
11//!   clamped to `[PROTOCOL_MIN_CHUNK, PROTOCOL_MAX_CHUNK]` with 4 KiB alignment
12//!   guaranteed *by construction*;
13//! - the range scheduler ([`UploadClient::with_ranges_window`]): up to P ranges of one session
14//!   in flight, each planned from the server's committed set ([`committed`]) by filling the
15//!   lowest gap first, so a sequential transfer is the case P = 1. A session-level step (a wait,
16//!   a `HEAD`, a re-create) is taken only once every range in flight has returned, so no wait
17//!   ever stalls a request still sending;
18//! - the code-driven recovery matrix ([`UploadClient::upload`]): `range_conflict` → re-plan
19//!   from the committed set it carries (or `HEAD`), after its `Retry-After`; `too_fragmented` →
20//!   let the ranges in flight finish, wait, re-plan; `too_many_in_flight` → wait, narrow P to the
21//!   session's advertised `ranges`; a lost answer (a reset, or no response) → `HEAD` before
22//!   anything is re-sent; `offset_mismatch` (an older server) → re-align;
23//!   `session_not_found` → re-create; `duplicate_blob` → merge
24//!   (success carrying the existing asset ref); `426` → abort-with-upgrade;
25//!   `checksum_mismatch` → re-send the chunk; `chunk_timeout` → re-send at the
26//!   same offset, shorter; `content_hash_mismatch` at finalization → a typed
27//!   [`UploadError::SourceChanged`] when the source changed, one re-created session when it
28//!   affirms it is unchanged, else the refusal;
29//!   `rate_limited`, `unavailable`, `storage_full` and every
30//!   other answer the retry classification marks retryable (any `5xx`, `408`, `425`)
31//!   → wait out `Retry-After` (else the retry engine's backoff), then resume from
32//!   HEAD. The client switches on the stable `error.*` code (from
33//!   `capsule_i18n::error_codes`); the status decides only for an answer whose code
34//!   names no action;
35//! - per-request stall bounds ([`RequestBounds`]): a chunk body is cut when no bytes move for
36//!   the stall bound, the wait for a response once the body is sent runs under a separate,
37//!   longer bound, and nothing bounds a request's total duration — a slow but live link is
38//!   never cut. A client-cut chunk is re-sent at the same offset, shorter, like a `408`.
39//!
40//! Tokens stay SDK-owned: an upload composes with the SDK session — build the
41//! transport with [`UploadTransport::with_session`] and every request runs through
42//! [`crate::auth::Session::execute`] (pre-flight refresh, single-flight, one `401`
43//! replay), so callers never juggle raw access tokens. [`StaticToken`] +
44//! [`UploadTransport::with_static_token`] plug in a fixed bearer for tests and
45//! callers that already hold a live token. No filename or plaintext metadata ever
46//! rides the wire — it travels inside the encrypted metadata blob (transfer
47//! upload doc, §Chunk Rules).
48
49use std::borrow::Cow;
50use std::collections::VecDeque;
51use std::time::Duration;
52
53use capsule_i18n::error_codes;
54use serde::{Deserialize, Serialize};
55
56use crate::events::{RetryReason, TransferEvent, TransferEvents, millis};
57use crate::net::{
58    ConnectionClass, ExchangeProgress, LaneRetries, PacedBody, RequestBounds, RequestCut,
59    RetryClass, RetryDecision, RetryEngine, RetryVerdict, Sleeper, TokioSleeper, negotiation,
60    within_bounds,
61};
62
63pub mod advice;
64pub mod committed;
65pub mod queue;
66
67use self::advice::{ServerAdvice, SessionExpiry};
68use self::committed::{CommittedSet, next_range};
69use self::queue::{MAX_RANGES_WINDOW, RangeId};
70
71/// The scheduler a gated transfer runs under ([`UploadClient::upload_gated`]): it holds the
72/// memory each range in flight needs and hears the server's advice. The push driver implements
73/// it over the device's [`UploadQueue`](queue::UploadQueue), so every range any session sends
74/// reserves its length against the one shared byte budget.
75pub trait TransferGate: Sync {
76    /// Wait until the shared budget and the session's ranges window can hold one more range of
77    /// `len` bytes, and reserve it. `None` means the gate holds no session for this transfer any
78    /// more (it was revoked); the range is then sent unreserved and the caller's own report on
79    /// the session decides what happens to it.
80    fn reserve(
81        &self,
82        len: u64,
83    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Option<RangeId>> + Send + '_>>;
84
85    /// The range `range` returned (answered, refused or cut): give its bytes back.
86    fn release(&self, range: RangeId);
87
88    /// The server sent `advice` on this transfer's session create or `HEAD`.
89    fn advised(&self, advice: &ServerAdvice);
90}
91
92/// One range's reservation, given back however the request ends: answered, refused, cut, or an
93/// early return that drops it.
94struct RangeHold<'g> {
95    gate: &'g dyn TransferGate,
96    range: Option<RangeId>,
97}
98
99impl<'g> RangeHold<'g> {
100    async fn reserve(gate: Option<&'g dyn TransferGate>, len: u64) -> Option<Self> {
101        let gate = gate?;
102        let range = gate.reserve(len).await;
103        Some(Self { gate, range })
104    }
105}
106
107impl Drop for RangeHold<'_> {
108    fn drop(&mut self) {
109        if let Some(range) = self.range.take() {
110            self.gate.release(range);
111        }
112    }
113}
114
115// Constants for chunk sizes (4KB aligned)
116const KB: u64 = 1024;
117const CHUNK_SIZE_256KB: u64 = 256 * KB;
118const CHUNK_SIZE_1MB: u64 = 1024 * KB;
119const CHUNK_SIZE_4MB: u64 = 4 * 1024 * KB;
120const CHUNK_SIZE_16MB: u64 = 16 * 1024 * KB;
121
122/// All chunks MUST be multiples of 4KB (4096 bytes)
123const ALIGNMENT: u64 = 4096;
124/// Protocol-surface chunk bounds (transfer upload doc, §Chunk Rules and
125/// Strictness). Every adaptive tier range sits inside these; the server rejects
126/// outside them (400 / 413).
127pub const PROTOCOL_MIN_CHUNK: u64 = 4096;
128pub const PROTOCOL_MAX_CHUNK: u64 = CHUNK_SIZE_16MB;
129
130/// Upper bound on recovery actions (re-align / re-create / re-send) for a single
131/// blob transfer. A live server drives progress well inside this; hitting it
132/// means a stuck peer, so the transfer fails loudly ([`UploadError::RetriesExhausted`], or
133/// [`UploadError::WaitsExhausted`] carrying the answer when it was waiting out the server)
134/// rather than hot-looping (transfer upload doc, §Session Lifetime and Discard:
135/// "retrying with backoff and halting after a bounded number of attempts").
136const MAX_RECOVERIES: u32 = 64;
137
138/// Upper bound on shrinking cuts — a stalled or unanswered chunk re-sent at the same offset,
139/// shorter — between two accepted chunks. Unlike [`MAX_RECOVERIES`] this refills on every
140/// accepted chunk: a long upload over a link that slows down again and again cuts afresh each
141/// time, and only a link that never lands a chunk is a stuck peer. Twelve halvings take the
142/// 16 MiB ceiling to the protocol minimum, so a live link stays well inside it; it bounds a
143/// size that is re-grown (a re-created session) without anything landing.
144const MAX_CUTS_SINCE_PROGRESS: u32 = 32;
145
146/// The longest single wait a server's `Retry-After` is honoured for.
147///
148/// A server names its own wait (transfer upload doc, §Hostile Clients), and a
149/// client that waited however long it was told would hand a misconfigured or
150/// hostile server the power to park a transfer indefinitely. Five minutes is the
151/// server's own disk-full hint; anything longer is waited in five-minute steps,
152/// each one a HEAD that re-learns the offset and charges the recovery budget.
153const MAX_SERVER_BACKOFF: Duration = Duration::from_mins(5);
154
155/// How long one chunk request should take at the measured goodput, on an ordinary link: eight
156/// seconds.
157///
158/// Long enough that a round trip and the server's write are a small share of each request; short
159/// enough that a request lost to a reset or a stall costs seconds, not minutes.
160pub const TARGET_REQUEST_DURATION: Duration = Duration::from_secs(8);
161
162/// How long one chunk request should take under an [`ConnectionClass::Adverse`] link: two
163/// seconds, so a request usually completes between the resets that made the link adverse.
164pub const ADVERSE_TARGET_REQUEST_DURATION: Duration = Duration::from_secs(2);
165
166/// The sliding window goodput is measured over.
167const GOODPUT_WINDOW: Duration = Duration::from_secs(30);
168/// Maximum number of recent chunks to keep in history.
169const MAX_RECENT_CHUNKS: usize = 1000;
170/// Chunks measured at one size before the strategy grows it. Shrinking needs one: a chunk that
171/// took far longer than the target is evidence enough.
172const WARMUP_CHUNKS: u32 = 5;
173/// Successful chunks after a stall before the size may grow again: the link has to show it
174/// recovered first.
175const GROW_BACK_AFTER_SUCCESSES: u32 = 4;
176
177/// Chunk size strategy for adaptive upload.
178///
179/// Normative for `capsule-sdk` (transfer upload doc, §Adaptive Chunk Sizing): the size is the
180/// one that completes in a [target request duration](TARGET_REQUEST_DURATION) at the goodput
181/// measured over a sliding window — shorter under an adverse link. Because the server cuts a
182/// chunk only when it stalls, never for its total duration, a chunk's size never has to fit a
183/// deadline: a slow link gets chunks that take the target time at its own rate, a fast one
184/// chunks up to the file-size tier's ceiling.
185///
186/// It starts from the server's advised size, clamped to `[PROTOCOL_MIN_CHUNK, tier ceiling]`.
187/// After each chunk it moves towards the target size: down to it at once when the target is
188/// half the current size or less, up by doubling after a warm-up when it is twice or more.
189/// Every candidate is aligned down to 4 KiB and clamped, so the size is aligned and within the
190/// protocol bounds by construction.
191///
192/// A stall — the server's `408 error.upload.chunk_timeout`, or the client's own stall cut —
193/// re-sends the same offset at half the stalled length ([`shrink_after_stall`]), and the size
194/// does not grow again until a run of successes shows the link recovered. A chunk that got no
195/// answer within the response wait is shrunk the same way: its tail may have been too slow to
196/// drain out of the send buffers in time.
197///
198/// [`shrink_after_stall`]: Self::shrink_after_stall
199#[derive(Debug, Clone)]
200pub struct AdaptiveChunkSizeStrategy {
201    /// Current chunk size.
202    pub current_size: u64,
203    /// The file-size tier's ceiling: no chunk is larger.
204    pub max_size: u64,
205    /// Successful chunks measured since the size last changed.
206    pub successful_chunks: u32,
207    /// Total bytes uploaded.
208    pub bytes_uploaded: u64,
209    /// Total time spent uploading.
210    pub total_upload_time: Duration,
211    /// Recent chunk records for windowed goodput: (bytes, duration, when recorded).
212    recent_chunks: VecDeque<(u64, Duration, std::time::Instant)>,
213    /// How long one chunk request should take at the measured goodput.
214    target: Duration,
215    /// Successes still owed after a stall before the size may grow.
216    hold_growth: u32,
217}
218
219impl AdaptiveChunkSizeStrategy {
220    /// Create a new chunk size strategy based on total file size: the tier names the starting
221    /// size and the ceiling.
222    pub fn for_file_size(total_size: u64) -> Self {
223        let (current_size, max_size) = if total_size < 10 * 1024 * KB {
224            // < 10 MiB: start at 256 KiB, at most 1 MiB.
225            (CHUNK_SIZE_256KB, CHUNK_SIZE_1MB)
226        } else if total_size < 100 * 1024 * KB {
227            // < 100 MiB: start at 1 MiB, at most 4 MiB.
228            (CHUNK_SIZE_1MB, CHUNK_SIZE_4MB)
229        } else {
230            // >= 100 MiB: start at 4 MiB, at most 16 MiB.
231            (CHUNK_SIZE_4MB, CHUNK_SIZE_16MB)
232        };
233
234        Self {
235            current_size,
236            max_size,
237            successful_chunks: 0,
238            bytes_uploaded: 0,
239            total_upload_time: Duration::ZERO,
240            recent_chunks: VecDeque::with_capacity(32),
241            target: TARGET_REQUEST_DURATION,
242            hold_growth: 0,
243        }
244    }
245
246    /// `size` aligned down to 4 KiB and clamped into `[PROTOCOL_MIN_CHUNK, max_size]`.
247    fn bounded(&self, size: u64) -> u64 {
248        ((size / ALIGNMENT) * ALIGNMENT).clamp(PROTOCOL_MIN_CHUNK, self.max_size)
249    }
250
251    /// Shrink after a chunk of `stalled` bytes stalled — the server answered
252    /// `408 error.upload.chunk_timeout`, or the client cut it: the next chunk, sent at the same
253    /// offset, is half that, 4 KiB-aligned down, and at least [`PROTOCOL_MIN_CHUNK`]. The size
254    /// then holds until a run of chunks succeeds.
255    ///
256    /// Returns `false` when `stalled` is already at or below the protocol minimum, so nothing
257    /// smaller can be sent; the size is then left as it is.
258    pub fn shrink_after_stall(&mut self, stalled: u64) -> bool {
259        self.hold_growth = GROW_BACK_AFTER_SUCCESSES;
260        self.successful_chunks = 0;
261        if stalled <= PROTOCOL_MIN_CHUNK {
262            return false;
263        }
264        self.current_size = self.bounded(stalled / 2);
265        debug_assert!(self.current_size.is_multiple_of(ALIGNMENT));
266        true
267    }
268
269    /// Couple the chunk size to a detected [`ConnectionClass`]: under
270    /// [`ConnectionClass::Adverse`] each request targets
271    /// [`ADVERSE_TARGET_REQUEST_DURATION`], otherwise [`TARGET_REQUEST_DURATION`].
272    #[must_use]
273    pub fn with_connection_class(mut self, class: ConnectionClass) -> Self {
274        self.apply_connection_class(class);
275        self
276    }
277
278    /// Apply the connection-class coupling in place (see
279    /// [`with_connection_class`](Self::with_connection_class)).
280    pub fn apply_connection_class(&mut self, class: ConnectionClass) {
281        self.target = if class == ConnectionClass::Adverse {
282            ADVERSE_TARGET_REQUEST_DURATION
283        } else {
284            TARGET_REQUEST_DURATION
285        };
286    }
287
288    /// How long one chunk request should take at the measured goodput.
289    pub fn target_duration(&self) -> Duration {
290        self.target
291    }
292
293    /// Seed the starting chunk size from the server's suggestion: the `chunk` member of
294    /// `X-Capsule-Advice`, or the create body's `suggested_chunk_size` from a server that
295    /// sends no advice.
296    ///
297    /// The suggestion is a *starting point only* (transfer upload doc, §Adaptive Chunk Sizing):
298    /// 4 KiB-aligned down and clamped into `[PROTOCOL_MIN_CHUNK, tier ceiling]`, so the size
299    /// is aligned and within the protocol bounds by construction.
300    pub fn seeded_from_suggested(mut self, suggested: u64) -> Self {
301        self.current_size = self.bounded(suggested);
302        debug_assert!(self.current_size.is_multiple_of(ALIGNMENT));
303        self
304    }
305
306    /// Goodput in bytes per second over the sliding window.
307    pub fn throughput_bytes_per_second(&self) -> f64 {
308        let now = std::time::Instant::now();
309        let window_start = now.checked_sub(GOODPUT_WINDOW).unwrap_or(now);
310
311        let (bytes, time) = self
312            .recent_chunks
313            .iter()
314            .filter(|(_, _, timestamp)| *timestamp >= window_start)
315            .fold((0u64, Duration::ZERO), |(acc_b, acc_t), (b, t, _)| {
316                (acc_b + b, acc_t + *t)
317            });
318
319        if time.as_secs_f64() == 0.0 {
320            return 0.0;
321        }
322        bytes as f64 / time.as_secs_f64()
323    }
324
325    /// The size that completes in the target duration at the measured goodput, aligned and
326    /// clamped; `None` before anything was measured.
327    pub fn target_size(&self) -> Option<u64> {
328        let goodput = self.throughput_bytes_per_second();
329        (goodput > 0.0).then(|| self.bounded((goodput * self.target.as_secs_f64()) as u64))
330    }
331
332    /// Record a successful chunk upload and move the size towards the target.
333    pub fn record_chunk(&mut self, chunk_size: u64, upload_duration: Duration) {
334        self.successful_chunks += 1;
335        self.bytes_uploaded += chunk_size;
336        self.total_upload_time += upload_duration;
337        self.hold_growth = self.hold_growth.saturating_sub(1);
338
339        let now = std::time::Instant::now();
340        self.recent_chunks
341            .push_back((chunk_size, upload_duration, now));
342        if self.recent_chunks.len() > MAX_RECENT_CHUNKS {
343            self.recent_chunks.pop_front();
344        }
345        if let Some(window_start) = now.checked_sub(GOODPUT_WINDOW) {
346            // Sorted by time, so the stale records are all at the front.
347            while self
348                .recent_chunks
349                .front()
350                .is_some_and(|(_, _, timestamp)| *timestamp < window_start)
351            {
352                self.recent_chunks.pop_front();
353            }
354        }
355
356        let Some(target) = self.target_size() else {
357            return;
358        };
359        let current = self.current_size;
360        let next = if target.saturating_mul(2) <= current {
361            // Far above the target: down to it at once, since every chunk at this size costs
362            // more than the target to lose.
363            target
364        } else if target >= current.saturating_mul(2)
365            && self.successful_chunks >= WARMUP_CHUNKS
366            && self.hold_growth == 0
367        {
368            self.bounded(current.saturating_mul(2))
369        } else {
370            current
371        };
372        if next != current {
373            tracing::debug!(
374                from = current,
375                to = next,
376                target_bytes = target,
377                target_ms = self.target.as_millis(),
378                "chunk size moved towards the target request duration"
379            );
380            self.current_size = next;
381            self.successful_chunks = 0;
382        }
383    }
384
385    /// Get the next chunk size to use.
386    ///
387    /// Alignment is a hard guarantee by construction: every candidate is aligned down and
388    /// clamped by one function, so this can never return an unaligned size — the
389    /// debug_assert is a tripwire for future edits, not a runtime dependency.
390    pub fn next_chunk_size(&self) -> u64 {
391        debug_assert!(
392            self.current_size.is_multiple_of(ALIGNMENT),
393            "Chunk size must be 4KB aligned"
394        );
395        debug_assert!(
396            (PROTOCOL_MIN_CHUNK..=PROTOCOL_MAX_CHUNK).contains(&self.current_size),
397            "Chunk size must sit within the protocol bounds"
398        );
399        self.current_size
400    }
401}
402
403// ─── Transport seam ─────────────────────────────────────────────────────────
404
405/// A fixed bearer token, for tests and callers that already hold a live token.
406/// Production clients compose with the SDK session via
407/// [`UploadTransport::with_session`] instead.
408#[derive(Debug, Clone)]
409pub struct StaticToken(pub String);
410
411/// How upload requests are authorized. Closed on purpose: the SDK owns the
412/// complete user flow, so an upload either rides the session's token store or a
413/// caller-supplied fixed bearer — never a hand-rolled header.
414#[derive(Clone)]
415enum UploadAuth {
416    /// Drive every request through [`crate::auth::Session::execute`]: pre-flight
417    /// expiry refresh, single-flight coalescing, and one `401` refresh-and-replay.
418    Session(crate::auth::Session),
419    /// A fixed bearer token over a plain client.
420    Static {
421        http: reqwest::Client,
422        token: String,
423    },
424}
425
426/// The authorized HTTP transport for one upload endpoint: base URL, the pinned
427/// protocol date sent as `X-Capsule-Protocol`, the authorization seam, and the stall bounds
428/// every request runs under.
429#[derive(Clone)]
430pub struct UploadTransport {
431    base_url: String,
432    protocol_version: String,
433    auth: UploadAuth,
434    /// The per-request stall and response-wait bounds ([`crate::net::within_bounds`]).
435    bounds: RequestBounds,
436}
437
438impl UploadTransport {
439    /// Build a transport that authorizes through an authenticated
440    /// [`crate::auth::Session`] — the sanctioned production path: the session
441    /// injects (and auto-refreshes) the bearer token, so the upload client never
442    /// sees raw token material.
443    ///
444    /// `base_url` points at the upload endpoint root (no trailing slash) —
445    /// `create` posts to it, chunk/HEAD/DELETE hang under `{base_url}/{id}`, and
446    /// listing is `{base_url}/sessions`.
447    pub fn with_session(
448        session: crate::auth::Session,
449        base_url: impl Into<String>,
450        protocol_version: impl Into<String>,
451    ) -> Self {
452        Self {
453            base_url: base_url.into().trim_end_matches('/').to_string(),
454            protocol_version: protocol_version.into(),
455            auth: UploadAuth::Session(session),
456            bounds: RequestBounds::default(),
457        }
458    }
459
460    /// Build a transport over a fixed bearer token (tests; callers that already
461    /// hold a live token). Same URL layout as [`Self::with_session`].
462    ///
463    /// `http` **must** come from [`crate::net::http_builder`] or [`crate::net::http_client`]: a
464    /// client built any other way sends no protocol handshake, and every gated route refuses it.
465    pub fn with_static_token(
466        http: reqwest::Client,
467        base_url: impl Into<String>,
468        protocol_version: impl Into<String>,
469        token: StaticToken,
470    ) -> Self {
471        Self {
472            base_url: base_url.into().trim_end_matches('/').to_string(),
473            protocol_version: protocol_version.into(),
474            auth: UploadAuth::Static {
475                http,
476                token: token.0,
477            },
478            bounds: RequestBounds::default(),
479        }
480    }
481
482    /// Run every request under `bounds` instead of [`RequestBounds::default`].
483    #[must_use]
484    pub fn with_request_bounds(mut self, bounds: RequestBounds) -> Self {
485        self.bounds = bounds;
486        self
487    }
488
489    /// Send an authorized request whose body is small enough to be sent at once: the
490    /// response-wait bound runs from the start, then the stall bound over the response body.
491    async fn send<F>(&self, build: F) -> Result<reqwest::Response, UploadError>
492    where
493        F: Fn(&reqwest::Client) -> reqwest::RequestBuilder,
494    {
495        self.send_tracked(&ExchangeProgress::waiting(), build)
496            .await?
497            .map_err(|cut| UploadError::Transport(cut.to_string()))
498    }
499
500    /// Send an authorized request under the transport's [`RequestBounds`], reading its whole
501    /// response body before handing it back, so no read after this one can hang.
502    ///
503    /// `progress` is the exchange's: a request that streams a large body hands it to its
504    /// [`PacedBody`] in `build`, so the stall bound runs while the body is sent and the
505    /// response-wait bound once it is all sent. The inner `Err` is the [`RequestCut`] that ended
506    /// it, kept apart so a chunk can tell a stalled link from any other transport failure.
507    async fn send_tracked<F>(
508        &self,
509        progress: &ExchangeProgress,
510        build: F,
511    ) -> Result<Result<reqwest::Response, RequestCut>, UploadError>
512    where
513        F: Fn(&reqwest::Client) -> reqwest::RequestBuilder,
514    {
515        // Boxed: the send is the largest future in the upload state machine, and every caller
516        // up to the CLI's dispatch would otherwise carry it inline.
517        let send = Box::pin(self.send_unbounded(build));
518        let response = match within_bounds(self.bounds, progress, send).await {
519            Ok(response) => response?,
520            Err(cut) => return Ok(Err(self.cut(cut, "request"))),
521        };
522        progress.on_received();
523        let status = response.status();
524        let version = response.version();
525        let headers = response.headers().clone();
526        let mut response = response;
527        let mut body = Vec::new();
528        loop {
529            let piece = match within_bounds(self.bounds, progress, response.chunk()).await {
530                Ok(piece) => piece?,
531                Err(cut) => return Ok(Err(self.cut(cut, "response body"))),
532            };
533            let Some(piece) = piece else { break };
534            progress.on_received();
535            body.extend_from_slice(&piece);
536        }
537        let mut rebuilt = http::Response::new(body);
538        *rebuilt.status_mut() = status;
539        *rebuilt.version_mut() = version;
540        *rebuilt.headers_mut() = headers;
541        Ok(Ok(reqwest::Response::from(rebuilt)))
542    }
543
544    /// Log a cut request, and hand the cut back.
545    fn cut(&self, cut: RequestCut, during: &str) -> RequestCut {
546        tracing::info!(
547            ?cut,
548            during,
549            stall_ms = millis(self.bounds.stall),
550            response_wait_ms = millis(self.bounds.response_wait),
551            "an upload request was cut"
552        );
553        cut
554    }
555
556    /// Send an authorized request with no bound of its own. `build` constructs the
557    /// un-authenticated request (method, URL, headers, body) from the transport's HTTP client;
558    /// the seam adds the bearer. `build` may be invoked twice on the session path (the `401`
559    /// refresh-and-replay), so it must be reconstructible.
560    async fn send_unbounded<F>(&self, build: F) -> Result<reqwest::Response, UploadError>
561    where
562        F: Fn(&reqwest::Client) -> reqwest::RequestBuilder,
563    {
564        // Both paths go through the protocol window (issue #674): the session's `execute`
565        // screens its own sends, and the static path screens here, so a refusal from either is
566        // the same `UpgradeRequired`.
567        match &self.auth {
568            UploadAuth::Session(session) => match session.execute(build).await {
569                Ok(response) => Ok(response),
570                Err(crate::auth::AuthError::UpgradeRequired(refusal)) => Err((*refusal).into()),
571                Err(other) => Err(other.into()),
572            },
573            UploadAuth::Static { http, token } => {
574                match negotiation::send_negotiated(build(http).bearer_auth(token)).await {
575                    Ok(response) => Ok(response),
576                    Err(negotiation::SendError::Upgrade(refusal)) => Err(refusal.into()),
577                    Err(negotiation::SendError::Transport(error)) => Err(error.into()),
578                }
579            }
580        }
581    }
582
583    /// The upgrade refusal an error response carrying `error.protocol.version_unsupported`
584    /// answers, with the window its headers advertise.
585    fn upgrade_required(
586        &self,
587        headers: &reqwest::header::HeaderMap,
588        message: String,
589    ) -> UploadError {
590        negotiation::UpgradeRequired::refused(headers, &self.protocol_version, message).into()
591    }
592
593    fn session_url(&self, id: &str) -> String {
594        let base = &self.base_url;
595        format!("{base}/{id}")
596    }
597}
598
599// ─── Wire DTOs (mirror the server's transport JSON) ─────────────────────────
600
601/// The blob's role within its asset bundle (closed enum; snake_case on the wire
602/// to match the server).
603#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
604#[serde(rename_all = "snake_case")]
605pub enum BlobRole {
606    /// The source asset.
607    Original,
608    /// A client-generated thumbnail/preview.
609    Derivative,
610    /// The CBOR metadata document.
611    Metadata,
612    /// Append-only provenance.
613    Provenance,
614    /// A library backup artifact.
615    Backup,
616    /// A derivative tier's signed `DerivativeManifest`, canonical CBOR — what a receiver opens
617    /// that tier's derivative with.
618    DerivativeManifest,
619}
620
621/// The server-visible mirror of the signed manifest's envelope fields, declared
622/// at `POST /upload` (owned by the provenance design doc). Opaque to this client
623/// — the import pipeline builds and signs it; the SDK only carries it on the wire.
624#[derive(Debug, Clone, Serialize, Deserialize)]
625pub struct ManifestEnvelope {
626    /// Crypto suite the blob is sealed under.
627    pub crypto_suite_id: u16,
628    /// Protocol date (`YYYY-MM-DD`).
629    pub protocol_version: String,
630    /// Optional album this blob belongs to.
631    pub album_id: Option<String>,
632    /// The asset id this blob belongs to (UUIDv7).
633    pub file_id: String,
634    /// AMK epoch the blob is sealed under.
635    pub amk_version: u32,
636    /// Ciphertext content hash, lowercase hex — equals the top-level `hash`.
637    pub ciphertext_hash: String,
638    /// Plaintext size in bytes.
639    pub plaintext_size: u64,
640    /// STREAM plaintext chunk size.
641    pub chunk_size: u32,
642    /// `derived | wrapped`.
643    pub key_mode: String,
644    /// Hash of the bundle's metadata blob, when known.
645    pub metadata_blob_hash: Option<String>,
646    /// A derivative blob's role (`thumbnail | preview | embedding`), from its signed
647    /// `DerivativeManifest`. Set on a `derivative` blob and on nothing else: the server
648    /// requires it there, refuses it elsewhere, and checks the pair against the closed
649    /// still-derivative format set.
650    #[serde(default, skip_serializing_if = "Option::is_none")]
651    pub derivative_role: Option<String>,
652    /// A derivative blob's format (`DerivativeManifest.format`, e.g. `image/jxl`) — the same
653    /// value as the request's `content_type`. Set exactly when [`Self::derivative_role`] is.
654    #[serde(default, skip_serializing_if = "Option::is_none")]
655    pub derivative_format: Option<String>,
656    /// The authoring user.
657    pub created_by_user: String,
658    /// The authoring device.
659    pub created_by_device: String,
660    /// The exact client build.
661    pub client_version: String,
662    /// RFC 3339 authoring timestamp.
663    pub timestamp: String,
664    /// Lifecycle action (`create` for a fresh bundle).
665    pub action: String,
666    /// Prior provenance hash, for append-only chains.
667    pub prior_provenance_hash: Option<String>,
668    /// Optional retention floor.
669    pub retention_until: Option<String>,
670}
671
672/// The `POST /upload` request body. Plaintext metadata (filename, capture date)
673/// is deliberately absent — it rides the encrypted metadata blob.
674#[derive(Debug, Clone, Serialize, Deserialize)]
675pub struct CreateUploadRequest {
676    /// Ciphertext size in bytes (declared once, immutable thereafter).
677    pub size: u64,
678    /// Ciphertext content hash, lowercase hex.
679    pub hash: String,
680    /// MIME type (closed enum per protocol version).
681    pub content_type: String,
682    /// Crypto suite the blob is sealed under.
683    pub crypto_suite_id: u16,
684    /// Protocol date (`YYYY-MM-DD`) this client speaks — also sent as the
685    /// `X-Capsule-Protocol` header.
686    pub protocol_version: String,
687    /// This blob's role in its bundle.
688    pub blob_role: BlobRole,
689    /// The unencrypted manifest fields the server validates.
690    pub manifest_envelope: ManifestEnvelope,
691    /// Optional album to add the asset to.
692    #[serde(skip_serializing_if = "Option::is_none")]
693    pub album_id: Option<String>,
694    /// Optional owner id (defaults to the authenticated uploader).
695    #[serde(skip_serializing_if = "Option::is_none")]
696    pub owner_id: Option<String>,
697    /// Album-upgrade intent id (album upgrade ceremony only).
698    #[serde(skip_serializing_if = "Option::is_none")]
699    pub intent_id: Option<String>,
700}
701
702/// The `POST /upload` success body.
703#[derive(Debug, Clone, Serialize, Deserialize)]
704pub struct CreateSessionResponse {
705    /// Upload session ID.
706    pub id: String,
707    /// Server-reported upload URL (advisory; the client builds its own paths).
708    pub upload_url: String,
709    /// The server's starting chunk-size suggestion. The fallback for a server that sends no
710    /// `X-Capsule-Advice`; where both are present the advice's `chunk` member is used.
711    pub suggested_chunk_size: u64,
712}
713
714impl CreateSessionResponse {
715    /// The starting chunk size: the advice's `chunk` member while it holds, otherwise the body's
716    /// suggestion. Read at receipt, so the advice is never stale here.
717    fn starting_chunk(&self, advice: &ServerAdvice) -> u64 {
718        advice
719            .chunk(Duration::ZERO)
720            .unwrap_or(self.suggested_chunk_size)
721    }
722}
723
724/// A `HEAD /upload/{id}` result: the resumption primitive.
725#[derive(Debug, Clone)]
726pub struct HeadInfo {
727    /// The committed prefix (`X-Capsule-Offset`): where a client sending in order resumes.
728    pub offset: u64,
729    /// The full committed set (`X-Capsule-Committed`), what a client re-plans from. Absent from
730    /// an older server, and when the header is malformed; the prefix is then all there is.
731    pub committed: Option<CommittedSet>,
732    /// Declared total size, when known.
733    pub total_size: Option<u64>,
734    /// Session state (`X-Capsule-Upload-Status`).
735    pub status: String,
736    /// The server's advice (`X-Capsule-Advice`), already clamped; absent from an older server.
737    pub advice: ServerAdvice,
738    /// The session's remaining lifetime, relative to this response.
739    pub expiry: SessionExpiry,
740    /// For a `failed_processing` session, the `error.*` code finalization failed with
741    /// (`X-Capsule-Upload-Error`). Absent for every other state, and from an older server.
742    pub error_code: Option<String>,
743}
744
745/// A row from `GET /upload/sessions` — the subset the resuming client needs.
746/// Unknown server fields are tolerated (serde ignores them).
747#[derive(Debug, Clone, Deserialize)]
748pub struct SessionSummary {
749    /// Upload session ID.
750    pub id: String,
751    /// The asset the session's blob belongs to, so a client can find every session of one
752    /// asset (the redaction a delete makes). Empty when the server named none.
753    #[serde(default)]
754    pub asset_id: String,
755    /// Bytes the server has received so far.
756    pub received_bytes: u64,
757    /// Declared total size.
758    pub total_size: u64,
759    /// Session state (serialized enum variant name).
760    pub status: String,
761    /// For a `failed_processing` session, the `error.*` code finalization failed with — the
762    /// code `HEAD` carries in `X-Capsule-Upload-Error`. Absent otherwise, and from an older
763    /// server.
764    #[serde(default)]
765    pub error_code: Option<String>,
766}
767
768#[derive(Debug, Deserialize)]
769struct ListSessionsBody {
770    sessions: Vec<SessionSummary>,
771}
772
773/// The server's `ApiError` body: an English detail plus, when present, the stable
774/// `error.*` catalog code the client switches on.
775#[derive(Debug, Deserialize)]
776struct ApiErrorBody {
777    #[serde(default)]
778    error: String,
779    #[serde(default)]
780    code: Option<String>,
781    /// A `409 duplicate_blob`'s structured name for the asset that already holds the bytes.
782    #[serde(default)]
783    existing_asset: Option<String>,
784}
785
786/// A non-success answer, read: its stable code, English detail, headers, and the structured
787/// `existing_asset` a `duplicate_blob` carries.
788struct ErrorAnswer {
789    code: Option<String>,
790    message: String,
791    headers: reqwest::header::HeaderMap,
792    existing_asset: Option<String>,
793}
794
795// ─── Outcomes ───────────────────────────────────────────────────────────────
796
797/// How `POST /upload` resolved.
798#[derive(Debug, Clone)]
799pub enum CreateOutcome {
800    /// A session to transfer into. `resume_offset` is the authoritative
801    /// received-byte count: `0` on a fresh create (`201`); on an idempotent
802    /// re-create the server returns the **existing active session** (`200`) with
803    /// its current `X-Capsule-Offset`, so the client resumes without a `HEAD`.
804    Created {
805        /// The session body (`id`, advisory URL, suggested chunk size).
806        response: CreateSessionResponse,
807        /// Where the transfer continues from (bytes the server already holds).
808        resume_offset: u64,
809        /// The resumed session's full committed set (`X-Capsule-Committed`) on a `200`. Absent
810        /// on a fresh session, from an older server, and when the header is malformed.
811        committed: Option<CommittedSet>,
812        /// The server's advice (`X-Capsule-Advice`), already clamped; absent from an older
813        /// server.
814        advice: ServerAdvice,
815        /// The session's remaining lifetime, relative to this response.
816        expiry: SessionExpiry,
817        /// The resumed session's state (`X-Capsule-Upload-Status`) on a `200`:
818        /// `waiting_for_processing` once a duplicate create has started the finalization of a
819        /// full session. Absent on a fresh session, and from an older server.
820        status: Option<String>,
821    },
822    /// The server already holds this exact ciphertext (`duplicate_blob`): resolve
823    /// as a [merge](https://docs/design/transfer/upload/#deduplication-and-merge),
824    /// not a transfer. Carries the existing asset reference.
825    AlreadyStored {
826        /// The server-named existing asset the new reference should merge onto.
827        asset_ref: String,
828    },
829}
830
831/// How a full [`UploadClient::upload`] resolved.
832#[derive(Debug, Clone)]
833pub enum UploadOutcome {
834    /// Every declared byte was transferred and the server finalized the session: `HEAD` reported
835    /// it `completed`. From an older server, which finalized before it answered the completing
836    /// chunk and so never answered `waiting_for_processing`, the accepted final chunk is the
837    /// outcome.
838    ///
839    /// A session finalization refused is not this: it is [`UploadError::Rejected`] carrying the
840    /// `error.*` code `HEAD` reported in `X-Capsule-Upload-Error`.
841    Completed {
842        /// The session that was driven to completion.
843        session_id: String,
844    },
845    /// The blob was already stored server-side — treated as success carrying the
846    /// existing asset ref (the `duplicate_blob` → merge path).
847    AlreadyStored {
848        /// The existing asset the caller merges onto.
849        asset_ref: String,
850    },
851}
852
853/// Upload client errors.
854#[derive(Debug, thiserror::Error)]
855pub enum UploadError {
856    /// IO error over the local byte source.
857    #[error("io error: {0}")]
858    Io(#[from] std::io::Error),
859    /// Network / transport failure (connection, timeout, body read).
860    #[error("transport error: {0}")]
861    Transport(String),
862    /// A typed server rejection carrying its stable `error.*` code and status.
863    /// Non-recoverable at this layer — surfaced to the caller.
864    ///
865    /// A finalization the server refused is reported the same way, with the code `HEAD` carried
866    /// in `X-Capsule-Upload-Error` (`content_hash_mismatch`, `envelope_rejected`,
867    /// `replace_incomplete`, `stale_revival`, …) and the `200` of the `HEAD` that read it: no
868    /// request waits on finalization, so its refusal is read, never answered. A caller switches
869    /// on the code, as it always has.
870    #[error("upload rejected (HTTP {status}, code {code:?}): {message}")]
871    Rejected {
872        /// HTTP status.
873        status: u16,
874        /// The stable `error.*` code, when the server supplied one.
875        code: Option<String>,
876        /// The English detail message.
877        message: String,
878    },
879    /// The server will not take this client's uploads: it answered `426 Upgrade Required`, or
880    /// the window it advertised already refuses this build, so the request never left. The
881    /// SDK's one [`UpgradeRequired`](crate::net::negotiation::UpgradeRequired), flattened:
882    /// carries the advertised window so the UI can show an actionable "update Capsule to keep
883    /// uploading" message. Abort-with-upgrade.
884    #[error(
885        "protocol upgrade required ({reason:?}; server accepts {min:?}..={max:?}, client build \
886         >= {min_client_build:?}): {message}"
887    )]
888    UpgradeRequired {
889        /// Which rule refused.
890        reason: crate::net::negotiation::UpgradeReason,
891        /// `X-Capsule-Protocol-Min`.
892        min: Option<String>,
893        /// `X-Capsule-Protocol-Max`.
894        max: Option<String>,
895        /// `X-Capsule-Min-Client-Build`.
896        min_client_build: Option<String>,
897        /// The English detail message.
898        message: String,
899    },
900    /// A recovery action (re-align / re-create / re-send) exceeded its bounded
901    /// budget — the peer is stuck; fail loudly rather than hot-loop.
902    #[error("upload gave up after exhausting the recovery budget: {0}")]
903    RetriesExhausted(String),
904    /// The server kept answering with a retryable status (any `5xx`, `408`, `425`, `429`, or
905    /// a wait code) and the transfer gave up waiting it out once its recovery budget, the
906    /// lane's shared retry budget or the retry engine's backoff was spent; or it was still
907    /// finalizing the session when the finalization poll's deadline passed. Carries the last
908    /// answer's status and stable `error.*` code, so a caller still localizes what the server
909    /// said. Transient: a later run may find the server recovered.
910    #[error(
911        "upload gave up waiting out the server (last answer HTTP {status}, code {code:?}: \
912         {message}): {reason}"
913    )]
914    WaitsExhausted {
915        /// The last answer's HTTP status.
916        status: u16,
917        /// The last answer's stable `error.*` code, when the server supplied one.
918        code: Option<String>,
919        /// The last answer's English detail message.
920        message: String,
921        /// Which budget ran out, in English.
922        reason: String,
923    },
924    /// A server response was missing a required header or otherwise unparsable.
925    #[error("malformed server response: {0}")]
926    MalformedResponse(String),
927    /// The session's auth layer failed (not authenticated, refresh rejected,
928    /// session expired). Carries the typed session error so callers can trigger
929    /// interactive re-authentication.
930    #[error("authentication error: {0}")]
931    Auth(#[from] crate::auth::AuthError),
932    /// The source the blob is read from no longer matches what its bundle was built from, so
933    /// nothing more of it is sent: a re-derived range would put different bytes under the
934    /// nonces the first derivation spent. The session is cancelled; the asset is pushed again
935    /// once its bundle is rebuilt. Its code is `error.upload.source_changed`, which the client
936    /// mints itself: no server answer carries it.
937    #[error(transparent)]
938    SourceChanged(#[from] SourceChanged),
939}
940
941impl UploadError {
942    /// The stable `error.*` code of the answer this error reports: a refusal's, or the last
943    /// answer of a wait the transfer gave up on; for a changed source, the client's own
944    /// `error.upload.source_changed`.
945    #[must_use]
946    pub fn error_code(&self) -> Option<&str> {
947        match self {
948            Self::Rejected { code, .. } | Self::WaitsExhausted { code, .. } => code.as_deref(),
949            Self::SourceChanged(_) => Some(error_codes::UPLOAD_SOURCE_CHANGED),
950            _ => None,
951        }
952    }
953
954    /// A failed read of the source: [`Self::SourceChanged`] when the source said so through
955    /// the [`SourceChanged`] it carried, [`Self::Io`] otherwise.
956    fn of_read(error: std::io::Error) -> Self {
957        let carries_change = match error.get_ref() {
958            Some(inner) => inner.is::<SourceChanged>(),
959            None => false,
960        };
961        if !carries_change {
962            return Self::Io(error);
963        }
964        let kind = error.kind();
965        match error.into_inner() {
966            Some(inner) => match inner.downcast::<SourceChanged>() {
967                Ok(changed) => Self::SourceChanged(*changed),
968                Err(inner) => Self::Io(std::io::Error::new(kind, inner)),
969            },
970            None => Self::Io(kind.into()),
971        }
972    }
973}
974
975/// The source of a blob no longer matches what its bundle was built from.
976///
977/// A source reports it from [`UploadSource::check_unchanged`], or from a read by carrying it as
978/// the inner error of the [`std::io::Error`] it returns (`io::Error::other(changed)`), so a
979/// source that verifies what it re-derives (a re-read chunk's authentication tag against the
980/// one first recorded) can refuse the read itself.
981#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
982#[error("the upload source changed since its bundle was built: {reason}")]
983pub struct SourceChanged {
984    /// What changed, in English, for logs.
985    pub reason: String,
986}
987
988impl SourceChanged {
989    /// A changed source, described by `reason`.
990    pub fn new(reason: impl Into<String>) -> Self {
991        Self {
992            reason: reason.into(),
993        }
994    }
995}
996
997/// The bytes of one blob, read a chunk at a time.
998///
999/// The client asks for exactly the window it is about to send — again after a re-align, a
1000/// re-send or a resume — so a source never has to hold the blob. A byte slice is one; an
1001/// original, whose ciphertext is re-derived from its plaintext per window, is the other that
1002/// matters (`capsule_library::lifecycle::OriginalCiphertext`).
1003pub trait UploadSource: Sync {
1004    /// The bytes `[offset, offset + len)`. Fewer than `len` bytes is a source error: the
1005    /// declared size is the blob's, and a short read means the source changed under the upload.
1006    /// A source that finds what it re-derived differs from what it first sealed returns an
1007    /// error carrying [`SourceChanged`], which ends the transfer typed.
1008    fn read_at(&self, offset: u64, len: usize) -> std::io::Result<Cow<'_, [u8]>>;
1009
1010    /// The cheap check that the source is still what the bundle was built from (its size,
1011    /// modification time and file id), run before every window is read and when finalization
1012    /// refuses the blob's hash.
1013    ///
1014    /// [`SourceIdentity::Affirmed`] is a positive claim that every byte the source returns is
1015    /// the byte it returned before; only then is a range this transfer already read sent again
1016    /// (a lost answer, a re-plan, a re-created or resumed session) or a refused hash answered
1017    /// with a re-created session. A source that cannot say — the default — answers
1018    /// [`SourceIdentity::Unknown`], and its transfer ends at the first such re-send: ranges that
1019    /// may now seal to different ciphertexts under the same nonces would hand the server two
1020    /// ciphertexts per nonce. Bytes held in memory cannot change, so they affirm.
1021    ///
1022    /// # Errors
1023    ///
1024    /// [`SourceChanged`] naming what differs.
1025    fn check_unchanged(&self) -> Result<SourceIdentity, SourceChanged> {
1026        Ok(SourceIdentity::Unknown)
1027    }
1028
1029    /// Whether every window this source returns is checked against the bytes it first
1030    /// produced, so a window it returns again is byte-identical or refused with
1031    /// [`SourceChanged`]: bytes in memory cannot change, and an original re-derives every
1032    /// STREAM chunk a window touches and compares its tag with the one recorded when the bundle
1033    /// was built.
1034    ///
1035    /// Only such a source is sent with more than one range of a session in flight. A parallel
1036    /// schedule re-sends ranges far more often (a refused overlap, a lost answer, a cut), and a
1037    /// source that only answers [`check_unchanged`](Self::check_unchanged) can miss a change
1038    /// that keeps its identity, which a re-derived range would then put under nonces the first
1039    /// read spent. A source that cannot say — the default — is sent one range at a time.
1040    fn verifies_rederived(&self) -> bool {
1041        false
1042    }
1043}
1044
1045/// What [`UploadSource::check_unchanged`] can say about a source it found no change in.
1046#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1047pub enum SourceIdentity {
1048    /// The source positively affirms it returns the same bytes it did before.
1049    Affirmed,
1050    /// The source found no change but cannot affirm there was none.
1051    Unknown,
1052}
1053
1054impl UploadSource for [u8] {
1055    fn read_at(&self, offset: u64, len: usize) -> std::io::Result<Cow<'_, [u8]>> {
1056        usize::try_from(offset)
1057            .ok()
1058            .and_then(|start| self.get(start..start.checked_add(len)?))
1059            .map(Cow::Borrowed)
1060            .ok_or_else(|| {
1061                std::io::Error::new(
1062                    std::io::ErrorKind::UnexpectedEof,
1063                    "upload window past the end of the bytes",
1064                )
1065            })
1066    }
1067
1068    fn check_unchanged(&self) -> Result<SourceIdentity, SourceChanged> {
1069        Ok(SourceIdentity::Affirmed)
1070    }
1071
1072    fn verifies_rederived(&self) -> bool {
1073        true
1074    }
1075}
1076
1077impl UploadSource for Vec<u8> {
1078    fn read_at(&self, offset: u64, len: usize) -> std::io::Result<Cow<'_, [u8]>> {
1079        self.as_slice().read_at(offset, len)
1080    }
1081
1082    fn check_unchanged(&self) -> Result<SourceIdentity, SourceChanged> {
1083        Ok(SourceIdentity::Affirmed)
1084    }
1085
1086    fn verifies_rederived(&self) -> bool {
1087        true
1088    }
1089}
1090
1091impl<const N: usize> UploadSource for [u8; N] {
1092    fn read_at(&self, offset: u64, len: usize) -> std::io::Result<Cow<'_, [u8]>> {
1093        self.as_slice().read_at(offset, len)
1094    }
1095
1096    fn check_unchanged(&self) -> Result<SourceIdentity, SourceChanged> {
1097        Ok(SourceIdentity::Affirmed)
1098    }
1099
1100    fn verifies_rederived(&self) -> bool {
1101        true
1102    }
1103}
1104
1105impl<T: UploadSource + ?Sized> UploadSource for &T {
1106    fn read_at(&self, offset: u64, len: usize) -> std::io::Result<Cow<'_, [u8]>> {
1107        (**self).read_at(offset, len)
1108    }
1109
1110    fn check_unchanged(&self) -> Result<SourceIdentity, SourceChanged> {
1111        (**self).check_unchanged()
1112    }
1113
1114    fn verifies_rederived(&self) -> bool {
1115        (**self).verifies_rederived()
1116    }
1117}
1118
1119impl From<reqwest::Error> for UploadError {
1120    fn from(err: reqwest::Error) -> Self {
1121        UploadError::Transport(err.to_string())
1122    }
1123}
1124
1125impl From<crate::net::negotiation::UpgradeRequired> for UploadError {
1126    fn from(refusal: crate::net::negotiation::UpgradeRequired) -> Self {
1127        let crate::net::negotiation::UpgradeRequired {
1128            reason,
1129            window,
1130            message,
1131            ..
1132        } = refusal;
1133        UploadError::UpgradeRequired {
1134            reason,
1135            min: window.protocol_min,
1136            max: window.protocol_max,
1137            min_client_build: window.min_client_build,
1138            message,
1139        }
1140    }
1141}
1142
1143/// Compute the required `X-Capsule-Checksum`: the SHA-256 of the chunk bytes as
1144/// bare lowercase hex (byte-identical to the server's `hash_bytes`).
1145fn chunk_checksum(chunk: &[u8]) -> String {
1146    use sha2::{Digest, Sha256};
1147    let mut hasher = Sha256::new();
1148    hasher.update(chunk);
1149    hex::encode(hasher.finalize())
1150}
1151
1152/// The existing asset a `duplicate_blob` names: the structured `existing_asset` member the
1153/// server sends, which a typed client switches on.
1154///
1155/// An older server named it only in the English detail (`"This content is already stored as
1156/// asset {id}"`), so without the member the id is parsed out of that, falling back to the whole
1157/// message so nothing is lost.
1158fn duplicate_asset_ref(existing_asset: Option<&str>, message: &str) -> String {
1159    if let Some(id) = existing_asset.map(str::trim).filter(|id| !id.is_empty()) {
1160        return id.to_string();
1161    }
1162    message
1163        .rsplit_once("asset ")
1164        .map(|(_, id)| id.trim().to_string())
1165        .filter(|id| !id.is_empty())
1166        .unwrap_or_else(|| message.to_string())
1167}
1168
1169/// The outcome of a single `PATCH` attempt, folded into the recovery matrix.
1170#[derive(Debug)]
1171enum ChunkAck {
1172    /// Accepted: the range is committed (written now, or already). Carries what the answer said
1173    /// the session holds, and its state (`X-Capsule-Upload-Status`; absent from an older server).
1174    Accepted {
1175        /// The committed prefix after the chunk (`X-Capsule-Offset`), when the answer named it.
1176        offset: Option<u64>,
1177        /// The full committed set (`X-Capsule-Committed`), when the answer carried a usable one.
1178        committed: Option<CommittedSet>,
1179        /// `uploading`, or `waiting_for_processing` once the chunk completed the session.
1180        status: Option<String>,
1181    },
1182    /// `range_conflict` — the range overlaps one in flight or is partly committed, and nothing
1183    /// was written. Re-plan from the committed set it carries (or `HEAD`), after its
1184    /// `Retry-After` when it names one.
1185    RangeConflict {
1186        /// The committed set the refusal carried, when usable.
1187        committed: Option<CommittedSet>,
1188        /// The `Retry-After` it named: the overlap is with a range still in flight.
1189        after: Option<Duration>,
1190    },
1191    /// `too_fragmented` — admitting the range could leave too many committed fragments, and
1192    /// nothing was written. Let the ranges in flight finish, wait its `Retry-After` when it
1193    /// names one, then re-plan.
1194    TooFragmented {
1195        /// The `Retry-After` it named.
1196        after: Option<Duration>,
1197    },
1198    /// `too_many_in_flight` — the session already has its cap of ranges in flight (one may be a
1199    /// request this client abandoned). Wait its `Retry-After`, narrow the window to the
1200    /// session's advertised `ranges`, then continue.
1201    TooManyInFlight {
1202        /// The `Retry-After` it named.
1203        after: Option<Duration>,
1204    },
1205    /// `offset_mismatch` — re-align to the authoritative offset (from the 409's
1206    /// `X-Capsule-Offset` when present, else a follow-up HEAD).
1207    Realign(Option<u64>),
1208    /// `session_not_found` — re-create the session and resume from zero.
1209    Recreate,
1210    /// `checksum_mismatch` — nothing was persisted; re-send the same chunk.
1211    Resend,
1212    /// `chunk_timeout` — the server cut the body for stalling, and nothing of it was
1213    /// written; re-send at the same offset, shorter.
1214    TimedOut,
1215    /// The client cut the body for stalling: no bytes moved for the stall bound. Nothing of a
1216    /// chunk that did not arrive whole is written, so the same answer as [`Self::TimedOut`].
1217    Stalled,
1218    /// The client handed the whole body off and no response head came within the response
1219    /// wait. The tail may still have been in the HTTP stack's or the kernel's send buffer on a
1220    /// link too slow to drain it, or the server may have kept the chunk and never answered:
1221    /// re-send at the same offset, shorter — so a slow link converges on a chunk it drains in
1222    /// time, and a `409 offset_mismatch` re-aligns where the server did keep it. A cut that
1223    /// shrinks is charged as a stall re-send; only one at the protocol minimum backs off as for
1224    /// a reset.
1225    Unanswered,
1226    /// A retryable answer: `rate_limited`, `unavailable` or `storage_full`, or any other `5xx`,
1227    /// `408` or `425` — wait (for the `Retry-After` the server sent, when it sent one) and then
1228    /// resume from HEAD, which says whether anything of the chunk was kept.
1229    Backoff(WaitAsked),
1230}
1231
1232/// Whether `code` is one of the three answers that mean "wait, then resume".
1233fn asks_to_wait(code: &str) -> bool {
1234    code == error_codes::UPLOAD_RATE_LIMITED
1235        || code == error_codes::UPLOAD_UNAVAILABLE
1236        || code == error_codes::UPLOAD_STORAGE_FULL
1237}
1238
1239/// Whether the client recovery matrix names an action for `code` that the upload loop takes
1240/// itself: re-align, re-create, re-send (a checksum refusal or a server stall cut), merge, or
1241/// re-plan (a range the block grid's admission refused).
1242fn recovery_names_action(code: &str) -> bool {
1243    code == error_codes::UPLOAD_OFFSET_MISMATCH
1244        || code == error_codes::UPLOAD_SESSION_NOT_FOUND
1245        || code == error_codes::UPLOAD_CHECKSUM_MISMATCH
1246        || code == error_codes::UPLOAD_CHUNK_TIMEOUT
1247        || code == error_codes::UPLOAD_DUPLICATE_BLOB
1248        || code == error_codes::UPLOAD_RANGE_CONFLICT
1249        || code == error_codes::UPLOAD_TOO_FRAGMENTED
1250        || code == error_codes::UPLOAD_TOO_MANY_IN_FLIGHT
1251}
1252
1253/// What a non-success upload answer (to a create, a chunk or a `HEAD`) permits, classified
1254/// before anything is retried (networking doc, Retry Policy Classes).
1255///
1256/// A code the recovery matrix names an action for keeps that action ([`RetryVerdict::Recover`]),
1257/// whatever the status. A code that asks for a wait (`rate_limited`, `unavailable`,
1258/// `storage_full`) is [`RetryVerdict::Retryable`] whatever the status. Every other answer is
1259/// classified by its status: any `5xx`, `408`, `425` and `429` are retryable, coded or not —
1260/// a proxy's bare `502`, or a `500 storage_inconsistent` alike — and every other `4xx` ends the
1261/// transfer. A `HEAD` answer has no body by HTTP's rules, so there the status is all there is.
1262fn upload_answer_verdict(status: u16, code: Option<&str>) -> RetryVerdict {
1263    match code {
1264        Some(code) if recovery_names_action(code) => RetryVerdict::Recover,
1265        Some(code) if asks_to_wait(code) => RetryVerdict::Retryable,
1266        _ => RetryVerdict::of_status(status, false),
1267    }
1268}
1269
1270/// Whether a non-success answer asks the client to wait, then ask again: its verdict is
1271/// [`RetryVerdict::Retryable`]. The transfer loop waits it out — the `Retry-After` the server
1272/// named, else the retry engine's backoff — under the transfer's recovery cap and the lane's
1273/// shared retry budget.
1274fn answer_asks_to_wait(status: u16, code: Option<&str>) -> bool {
1275    upload_answer_verdict(status, code) == RetryVerdict::Retryable
1276}
1277
1278/// A single request the server answered with "wait, then ask again".
1279///
1280/// The single-shot public calls surface it as [`UploadError::Rejected`]; the
1281/// transfer loop waits it out under the recovery budget instead.
1282#[derive(Debug)]
1283struct WaitAsked {
1284    status: u16,
1285    code: Option<String>,
1286    message: String,
1287    /// The `Retry-After` the server sent, when it sent one.
1288    after: Option<Duration>,
1289}
1290
1291impl WaitAsked {
1292    /// The error a transfer ends with when it gives up waiting this answer out: it keeps the
1293    /// answer's status and code, and `reason` says which budget ran out.
1294    fn gave_up(self, reason: String) -> UploadError {
1295        UploadError::WaitsExhausted {
1296            status: self.status,
1297            code: self.code,
1298            message: self.message,
1299            reason,
1300        }
1301    }
1302}
1303
1304impl From<WaitAsked> for UploadError {
1305    fn from(wait: WaitAsked) -> Self {
1306        UploadError::Rejected {
1307            status: wait.status,
1308            code: wait.code,
1309            message: wait.message,
1310        }
1311    }
1312}
1313
1314/// The bounded recovery state one transfer shares across every request it makes:
1315/// the recovery budget, the shared retry engine's backoff schedule, the lane's shared retry
1316/// budget, and the gate its ranges reserve memory through.
1317struct Recovery<'g> {
1318    /// Recovery actions taken so far, bounded by [`MAX_RECOVERIES`].
1319    count: u32,
1320    /// Shrinking cuts since the last accepted chunk, bounded by [`MAX_CUTS_SINCE_PROGRESS`].
1321    cuts: u32,
1322    /// The shared retry engine, `bulk-transfer` class: exponential backoff with
1323    /// full jitter, bounded give-up. It governs mid-transfer transport resets and
1324    /// server-asked waits that name no `Retry-After`.
1325    engine: RetryEngine,
1326    /// The server lane's retry budget, shared with every other transfer to that server: each
1327    /// retry or recovery action spends from it besides this transfer's own caps, and each
1328    /// answered create, answered `HEAD` and accepted chunk earns toward it.
1329    lane: LaneRetries,
1330    /// Where each range reserves its memory and the server's advice is reported, when the
1331    /// transfer runs under a scheduler.
1332    gate: Option<&'g dyn TransferGate>,
1333    /// Every byte this transfer has read for a request, in any of its sessions. A range that
1334    /// overlaps it is a re-send, and is read again only from a source that affirms it is
1335    /// unchanged (see [`UploadClient::fly`]).
1336    sent: CommittedSet,
1337}
1338
1339impl<'g> Recovery<'g> {
1340    fn new(lane: LaneRetries, gate: Option<&'g dyn TransferGate>) -> Self {
1341        Self {
1342            count: 0,
1343            cuts: 0,
1344            engine: RetryClass::BulkTransfer.engine(),
1345            lane,
1346            gate,
1347            sent: CommittedSet::empty(),
1348        }
1349    }
1350
1351    /// An accepted chunk is real progress: it refills the shrinking-cut budget and the
1352    /// transient-reset backoff budget, and earns toward the lane's shared retry budget. The
1353    /// per-transfer [`MAX_RECOVERIES`] budget is not refilled.
1354    fn on_progress(&mut self) {
1355        self.cuts = 0;
1356        self.engine.reset();
1357        self.lane.record_success();
1358    }
1359
1360    /// Charge one shrinking cut, failing loudly once a run of them lands nothing or the
1361    /// lane's shared retry budget is spent: a cut is a retry like any other to the lane.
1362    fn charge_cut(&mut self, action: &str) -> Result<(), UploadError> {
1363        self.cuts += 1;
1364        if self.cuts > MAX_CUTS_SINCE_PROGRESS {
1365            return Err(UploadError::RetriesExhausted(format!(
1366                "{action}: exceeded {MAX_CUTS_SINCE_PROGRESS} shrinking cuts without an accepted chunk"
1367            )));
1368        }
1369        self.spend_lane(action)
1370    }
1371
1372    /// Charge one recovery action, failing loudly once this transfer's budget or its lane's
1373    /// shared retry budget is spent.
1374    fn charge(&mut self, action: &str) -> Result<(), UploadError> {
1375        self.count += 1;
1376        guard_budget(self.count, action)?;
1377        self.spend_lane(action)
1378    }
1379
1380    /// Spend one retry from the lane's shared budget.
1381    fn spend_lane(&self, action: &str) -> Result<(), UploadError> {
1382        if self.lane.try_spend() {
1383            return Ok(());
1384        }
1385        tracing::warn!(
1386            action,
1387            "the server lane's shared retry budget is spent; giving up"
1388        );
1389        Err(UploadError::RetriesExhausted(format!(
1390            "{action}: the retry budget shared by every upload to this server is spent"
1391        )))
1392    }
1393
1394    /// Report advice the server sent to the gate, when there is one.
1395    fn advised(&self, advice: &ServerAdvice) {
1396        if let Some(gate) = self.gate {
1397            gate.advised(advice);
1398        }
1399    }
1400
1401    /// Charge a server-asked wait and resolve how long to wait: the server's
1402    /// `Retry-After` up to [`MAX_SERVER_BACKOFF`], else the engine's schedule.
1403    ///
1404    /// Giving up ends the transfer with [`UploadError::WaitsExhausted`], carrying the answer
1405    /// waited on, so its stable code still reaches the caller.
1406    fn server_wait(&mut self, asked: WaitAsked, action: &str) -> Result<Duration, UploadError> {
1407        match self.charge(action) {
1408            Ok(()) => {}
1409            Err(UploadError::RetriesExhausted(reason)) => return Err(asked.gave_up(reason)),
1410            Err(other) => return Err(other),
1411        }
1412        match asked.after {
1413            Some(after) => Ok(after.min(MAX_SERVER_BACKOFF)),
1414            None => match self.engine.next_backoff(None) {
1415                RetryDecision::Retry { after } => Ok(after),
1416                RetryDecision::GiveUp => Err(asked.gave_up(format!(
1417                    "{action}: the backoff for retryable answers that name no Retry-After is spent"
1418                ))),
1419            },
1420        }
1421    }
1422}
1423
1424/// The first wait between two `HEAD`s while the server finalizes a session.
1425const FINALIZE_POLL_FIRST: Duration = Duration::from_millis(100);
1426
1427/// The longest wait between two `HEAD`s while the server finalizes a session. Each wait doubles
1428/// the one before it up to this.
1429const FINALIZE_POLL_MAX: Duration = Duration::from_secs(5);
1430
1431/// How long, in waits summed, the client polls a finalizing session before it gives up.
1432///
1433/// The server drives every claim to a terminal state — across its own restarts — so the poll
1434/// ends; this bound only stops a client from polling a server that never says so. Half an hour
1435/// re-hashes a 4 GiB blob on a disk slower than any the server is deployed on.
1436const FINALIZE_POLL_DEADLINE: Duration = Duration::from_mins(30);
1437
1438/// The session states the server reports while, and once, it finalizes.
1439const STATUS_WAITING: &str = "waiting_for_processing";
1440const STATUS_COMPLETED: &str = "completed";
1441const STATUS_FAILED: &str = "failed_processing";
1442
1443/// What the finalization poll found.
1444enum Settled {
1445    /// The session is terminal: completed, or the transfer ends here.
1446    Done(UploadOutcome),
1447    /// The server holds fewer bytes than declared after all; the transfer re-plans from the
1448    /// committed set it reported.
1449    Resume(CommittedSet),
1450    /// Finalization refused the blob's hash (`content_hash_mismatch`): the source decides
1451    /// between a typed source change and one re-created session. Carries the refusal, which
1452    /// ends the transfer when neither applies — and whenever the source cannot affirm its
1453    /// identity.
1454    HashMismatch(UploadError),
1455    /// The session went away (`404`) before it reached finalization: re-create it, as for
1456    /// `session_not_found`.
1457    Lost,
1458}
1459
1460/// What opening a session for a blob found.
1461enum Opened {
1462    /// A session to transfer into: its id, chunk strategy, and where it starts.
1463    Session(String, AdaptiveChunkSizeStrategy, Start),
1464    /// The blob is already stored (`duplicate_blob`), under this existing asset.
1465    Merged(String),
1466}
1467
1468/// Where a transfer starts on a session: what the server holds, its state as last reported, and
1469/// the session's ranges window.
1470struct Start {
1471    /// The session's committed set, as last reported.
1472    committed: CommittedSet,
1473    /// The session's state as last reported, when one was.
1474    state: Option<String>,
1475    /// P: the ranges this session may hold in flight.
1476    window: u32,
1477    /// The advice the session's create or `HEAD` carried.
1478    advice: ServerAdvice,
1479}
1480
1481/// Whether `held` still holds every byte of `acknowledged`.
1482fn holds_all(held: &CommittedSet, acknowledged: &CommittedSet) -> bool {
1483    acknowledged
1484        .ranges()
1485        .iter()
1486        .all(|&(start, end)| held.contains(start, end))
1487}
1488
1489/// How far along the state machine a reported session state is, so the answers of ranges that
1490/// return out of order never move it backwards: the completing range's `waiting_for_processing`
1491/// is not undone by an `uploading` answered before it.
1492fn state_rank(state: Option<&str>) -> u8 {
1493    match state {
1494        None => 0,
1495        Some(STATUS_COMPLETED | STATUS_FAILED) => 3,
1496        Some(STATUS_WAITING) => 2,
1497        Some(_) => 1,
1498    }
1499}
1500
1501/// The session's state once an answer reported `next`: `next` when it is as far along as
1502/// `current`, else `current`. An answer that reports no state is an older server's, which
1503/// finalized before it answered, so the state it leaves is none.
1504fn later_state(current: Option<String>, next: Option<String>) -> Option<String> {
1505    match next {
1506        None => None,
1507        Some(next) if state_rank(Some(&next)) >= state_rank(current.as_deref()) => Some(next),
1508        Some(_) => current,
1509    }
1510}
1511
1512/// The session-level step the scheduler takes once every range in flight has returned. Ranges
1513/// are not sent while one is pending: a wait taken while a request is still sending would
1514/// starve that request's stall timer, and a `HEAD` read while ranges are in flight would
1515/// describe a session they are still changing.
1516#[derive(Debug, Default)]
1517struct PendingStep {
1518    /// Stop planning until the ranges in flight return.
1519    quiesce: bool,
1520    /// Wait this long first.
1521    wait: Option<Duration>,
1522    /// Then read the session's state from `HEAD` and re-plan from it.
1523    head: bool,
1524    /// The `HEAD` re-aligns an older server's `offset_mismatch` that named no offset.
1525    realign: bool,
1526    /// Or re-create the session.
1527    recreate: bool,
1528    /// Narrow the ranges window: the server refused a range for its in-flight cap. Taken as
1529    /// soon as the refusal lands, not with the step.
1530    narrow: bool,
1531    /// The range (offset, length) whose answer first asked for the step, for the events it
1532    /// publishes.
1533    range: (u64, u64),
1534}
1535
1536impl PendingStep {
1537    fn is_set(&self) -> bool {
1538        self.quiesce || self.wait.is_some() || self.head || self.recreate
1539    }
1540
1541    /// Record the range that asked for the step, unless an earlier one already did.
1542    fn cause(&mut self, offset: u64, len: u64) {
1543        if !self.is_set() {
1544            self.range = (offset, len);
1545        }
1546    }
1547
1548    /// Wait at least `wait` before the step.
1549    fn wait_at_least(&mut self, wait: Duration) {
1550        self.quiesce = true;
1551        self.wait = Some(self.wait.map_or(wait, |w| w.max(wait)));
1552    }
1553
1554    /// Read the session's state from `HEAD` before anything is sent again.
1555    fn read_state(&mut self) {
1556        self.quiesce = true;
1557        self.head = true;
1558    }
1559}
1560
1561/// One session's transfer as the scheduler drives it.
1562struct Cursor {
1563    /// The session.
1564    session_id: String,
1565    /// What the server holds: the last committed set `HEAD` or a create reported, with every
1566    /// accepted range and every set an answer carried since added.
1567    committed: CommittedSet,
1568    /// The session's state, as far along as any answer reported it.
1569    state: Option<String>,
1570    /// P: the ranges this session may hold in flight.
1571    window: u32,
1572    /// The advice the session's create or last `HEAD` carried, for its `ranges`.
1573    advice: ServerAdvice,
1574    /// Until when each request this client abandoned (cut, or reset) may still hold a claim on
1575    /// the server: a claim lives until its write returns.
1576    abandoned: Vec<std::time::Instant>,
1577    /// The session-level step the ranges in flight are waited out for.
1578    step: PendingStep,
1579}
1580
1581impl Cursor {
1582    fn new(session_id: String, start: Start) -> Self {
1583        Self {
1584            session_id,
1585            committed: start.committed,
1586            state: start.state,
1587            window: start.window.max(1),
1588            advice: start.advice,
1589            abandoned: Vec::new(),
1590            step: PendingStep::default(),
1591        }
1592    }
1593
1594    /// Count a request this client just abandoned as holding a server claim for `bound`, the
1595    /// response-wait bound past which its write has surely returned.
1596    fn abandon(&mut self, bound: Duration) {
1597        self.abandoned.push(std::time::Instant::now() + bound);
1598    }
1599
1600    /// The abandoned requests that may still hold a claim.
1601    fn abandoned_claims(&mut self) -> usize {
1602        let now = std::time::Instant::now();
1603        self.abandoned.retain(|until| *until > now);
1604        self.abandoned.len()
1605    }
1606}
1607
1608/// How a session's ranges ended.
1609enum Transferred {
1610    /// Every byte was sent, or the server reported the session finalizing: settle it.
1611    Sent,
1612    /// A re-created session found the blob already stored (`duplicate_blob`): merge.
1613    Merged(String),
1614}
1615
1616/// What a session-level step led to.
1617enum StepTaken {
1618    /// Keep sending.
1619    Continue,
1620    /// `HEAD` reported the session finalizing or finalized: settle it.
1621    Settle,
1622    /// A re-create found the blob already stored: merge.
1623    Merged(String),
1624}
1625
1626/// The next range of `flights` to return, removed from it. `flights` must not be empty.
1627async fn next_landed<F: std::future::Future<Output = Flight>>(
1628    flights: &mut Vec<std::pin::Pin<Box<F>>>,
1629) -> Flight {
1630    std::future::poll_fn(|cx| {
1631        for at in 0..flights.len() {
1632            if let std::task::Poll::Ready(flight) = flights[at].as_mut().poll(cx) {
1633                drop(flights.swap_remove(at));
1634                return std::task::Poll::Ready(flight);
1635            }
1636        }
1637        std::task::Poll::Pending
1638    })
1639    .await
1640}
1641
1642/// One range's request, returned.
1643struct Flight {
1644    /// The half-open byte range it carried.
1645    range: (u64, u64),
1646    /// When its bytes started out, after its reservation and its read.
1647    started: std::time::Instant,
1648    /// How it ended.
1649    sent: Result<ChunkAck, UploadError>,
1650}
1651
1652/// The wait a `Retry-After` header names, in its delta-seconds form.
1653///
1654/// The server sends delta-seconds; the HTTP-date form is not parsed, and a value
1655/// that is neither leaves the client on its own backoff rather than guessing.
1656fn retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
1657    header_u64(headers, "Retry-After").map(Duration::from_secs)
1658}
1659
1660/// The hand-written chunked, resumable, adaptive upload client.
1661#[derive(Clone)]
1662pub struct UploadClient {
1663    transport: UploadTransport,
1664    /// The detected connection class, coupling the chunk strategy to the network: under
1665    /// [`ConnectionClass::Adverse`] each chunk targets the shorter
1666    /// [`ADVERSE_TARGET_REQUEST_DURATION`]. Defaults to [`ConnectionClass::Unmetered`].
1667    connection: ConnectionClass,
1668    /// The backoff sleeper for the shared retry engine's transient-reset retries.
1669    /// Real in production; kept as a seam for determinism.
1670    sleeper: TokioSleeper,
1671    /// Where each transfer step is published ([`crate::events`]); disabled by default.
1672    events: TransferEvents,
1673    /// The retry budget every transfer this client (and each clone of it) drives spends from:
1674    /// one server's lane.
1675    lane: LaneRetries,
1676    /// P: the most ranges of one session this client holds in flight, before the session's
1677    /// advertised `ranges` narrows it. [`DEFAULT_CLIENT_RANGES`] unless set.
1678    ranges: u32,
1679}
1680
1681/// The ranges of one session a client holds in flight unless told otherwise: the lane's default
1682/// P ([`queue::DEFAULT_RANGES_WINDOW`]).
1683///
1684/// It applies only to a source that verifies what it re-derives
1685/// ([`UploadSource::verifies_rederived`]): bytes in memory, and an original that checks every
1686/// re-derived STREAM chunk against the tag its bundle recorded. A parallel schedule re-sends
1687/// ranges far more often (a refused overlap, a lost answer, a cut), so any other source is sent
1688/// one range at a time, whatever this window, and a source changed mid-upload never puts two
1689/// ciphertexts under one nonce on the wire. [`UploadClient::with_ranges_window`] narrows or
1690/// widens it per client.
1691pub const DEFAULT_CLIENT_RANGES: u32 = queue::DEFAULT_RANGES_WINDOW;
1692
1693impl UploadClient {
1694    /// Build a client over an authorized [`UploadTransport`], on an unmetered link, with a
1695    /// lane retry budget of its own that every clone shares.
1696    pub fn new(transport: UploadTransport) -> Self {
1697        Self {
1698            transport,
1699            connection: ConnectionClass::Unmetered,
1700            sleeper: TokioSleeper,
1701            events: TransferEvents::disabled(),
1702            lane: LaneRetries::default(),
1703            ranges: DEFAULT_CLIENT_RANGES,
1704        }
1705    }
1706
1707    /// Hold up to `ranges` ranges of each session in flight (P), clamped into
1708    /// `1..=`[`MAX_RANGES_WINDOW`]. A session's advertised `ranges` narrows it further, and so
1709    /// does a `too_many_in_flight`; under a [scheduler](Self::upload_gated) each range also
1710    /// waits for the scheduler's own window and byte budget.
1711    #[must_use]
1712    pub fn with_ranges_window(mut self, ranges: u32) -> Self {
1713        self.ranges = ranges.clamp(1, MAX_RANGES_WINDOW);
1714        self
1715    }
1716
1717    /// P: the most ranges of one session this client holds in flight.
1718    #[must_use]
1719    pub fn ranges_window(&self) -> u32 {
1720        self.ranges
1721    }
1722
1723    /// P for a session whose create or `HEAD` advised `advice`.
1724    fn window_for(&self, advice: &ServerAdvice) -> u32 {
1725        advice
1726            .ranges_window(self.ranges)
1727            .clamp(1, MAX_RANGES_WINDOW)
1728    }
1729
1730    /// Spend retries from `lane` — the budget the upload queue holds for this client's server
1731    /// ([`UploadQueue::lane_retries`](queue::UploadQueue::lane_retries)) — so every transfer to
1732    /// the server, and the queue's own retries, share one bound.
1733    #[must_use]
1734    pub fn with_lane_retries(mut self, lane: LaneRetries) -> Self {
1735        self.lane = lane;
1736        self
1737    }
1738
1739    /// The lane retry budget this client spends from.
1740    #[must_use]
1741    pub fn lane_retries(&self) -> &LaneRetries {
1742        &self.lane
1743    }
1744
1745    /// Publish every transfer this client drives to `events` (session, chunk, retry,
1746    /// checksum-reject, finalize and merge steps). Without a subscriber it costs nothing.
1747    #[must_use]
1748    pub fn with_events(mut self, events: TransferEvents) -> Self {
1749        self.events = events;
1750        self
1751    }
1752
1753    /// The event handle this client publishes to.
1754    #[must_use]
1755    pub fn events(&self) -> &TransferEvents {
1756        &self.events
1757    }
1758
1759    /// Set the detected connection class (the target request duration follows it). On an
1760    /// [`ConnectionClass::Adverse`] link every transfer this client drives sizes its chunks to
1761    /// the shorter [`ADVERSE_TARGET_REQUEST_DURATION`].
1762    #[must_use]
1763    pub fn with_connection_class(mut self, class: ConnectionClass) -> Self {
1764        self.connection = class;
1765        self
1766    }
1767
1768    /// The connection class this client sizes its chunks for.
1769    #[must_use]
1770    pub fn connection_class(&self) -> ConnectionClass {
1771        self.connection
1772    }
1773
1774    /// Run every request this client sends under `bounds` instead of
1775    /// [`RequestBounds::default`].
1776    #[must_use]
1777    pub fn with_request_bounds(mut self, bounds: RequestBounds) -> Self {
1778        self.transport = self.transport.with_request_bounds(bounds);
1779        self
1780    }
1781
1782    /// Create an upload session (`POST /upload`).
1783    ///
1784    /// Resolves to [`CreateOutcome::Created`], or [`CreateOutcome::AlreadyStored`]
1785    /// on `duplicate_blob` (the merge trigger). A `426` returns
1786    /// [`UploadError::UpgradeRequired`] — the session is never created.
1787    ///
1788    /// This is one request: a retryable answer (`rate_limited`, `unavailable`,
1789    /// `storage_full`, any `5xx`, `408`, `425`) comes back as [`UploadError::Rejected`].
1790    /// [`UploadClient::upload`] waits those out.
1791    #[tracing::instrument(level = "debug", skip(self, request), fields(size = request.size, hash = %request.hash))]
1792    pub async fn create_session(
1793        &self,
1794        request: &CreateUploadRequest,
1795    ) -> Result<CreateOutcome, UploadError> {
1796        Ok(self.try_create(request).await??)
1797    }
1798
1799    /// One `POST /upload`, with a server-asked wait kept apart from a rejection.
1800    async fn try_create(
1801        &self,
1802        request: &CreateUploadRequest,
1803    ) -> Result<Result<CreateOutcome, WaitAsked>, UploadError> {
1804        let resp = self
1805            .transport
1806            .send(|http| {
1807                http.post(self.transport.base_url.as_str())
1808                    .header("X-Capsule-Protocol", &self.transport.protocol_version)
1809                    .json(request)
1810            })
1811            .await?;
1812
1813        let status = resp.status().as_u16();
1814        if (200..300).contains(&status) {
1815            // 201: fresh session (offset 0). 200: the idempotent re-create — the
1816            // existing active session, whose X-Capsule-Offset says where to resume.
1817            let resume_offset = header_u64(resp.headers(), "X-Capsule-Offset").unwrap_or(0);
1818            let committed = committed_of(resp.headers(), request.size);
1819            let (advice, expiry) = advice_of(resp.headers());
1820            let session_status = header_str(resp.headers(), "X-Capsule-Upload-Status");
1821            let body: CreateSessionResponse = resp.json().await?;
1822            tracing::debug!(session_id = %body.id, resume_offset, ?committed, ?session_status, ?advice, ?expiry, "upload session created");
1823            return Ok(Ok(CreateOutcome::Created {
1824                response: body,
1825                resume_offset,
1826                committed,
1827                advice,
1828                expiry,
1829                status: session_status,
1830            }));
1831        }
1832
1833        let after = retry_after(resp.headers());
1834        let ErrorAnswer {
1835            code,
1836            message,
1837            headers,
1838            existing_asset,
1839        } = read_error(resp).await?;
1840        if is_upgrade_required(status, code.as_deref()) {
1841            return Err(self.transport.upgrade_required(&headers, message));
1842        }
1843        if code.as_deref() == Some(error_codes::UPLOAD_DUPLICATE_BLOB) {
1844            let asset_ref = duplicate_asset_ref(existing_asset.as_deref(), &message);
1845            tracing::info!(%asset_ref, "duplicate_blob — resolving as a merge");
1846            return Ok(Ok(CreateOutcome::AlreadyStored { asset_ref }));
1847        }
1848        if answer_asks_to_wait(status, code.as_deref()) {
1849            tracing::debug!(status, ?code, ?after, "create: the server asked for a wait");
1850            return Ok(Err(WaitAsked {
1851                status,
1852                code,
1853                message,
1854                after,
1855            }));
1856        }
1857        Err(UploadError::Rejected {
1858            status,
1859            code,
1860            message,
1861        })
1862    }
1863
1864    /// Query progress (`HEAD /upload/{id}`). `Ok(None)` means the session is gone
1865    /// (`404`) — a discarded/expired/never-existent session is uniform.
1866    ///
1867    /// This is one request: a retryable answer (any `5xx`, `408`, `425`, `429`) comes
1868    /// back as [`UploadError::Rejected`]. The transfer loop waits those out.
1869    #[tracing::instrument(level = "debug", skip(self))]
1870    pub async fn head(&self, session_id: &str) -> Result<Option<HeadInfo>, UploadError> {
1871        Ok(self.try_head(session_id).await??)
1872    }
1873
1874    /// One `HEAD /upload/{id}`, with a server-asked wait kept apart from a rejection.
1875    async fn try_head(
1876        &self,
1877        session_id: &str,
1878    ) -> Result<Result<Option<HeadInfo>, WaitAsked>, UploadError> {
1879        let resp = self
1880            .transport
1881            .send(|http| {
1882                http.head(self.transport.session_url(session_id))
1883                    .header("X-Capsule-Protocol", &self.transport.protocol_version)
1884            })
1885            .await?;
1886
1887        let status = resp.status().as_u16();
1888        if status == 404 {
1889            return Ok(Ok(None));
1890        }
1891        if !(200..300).contains(&status) {
1892            let after = retry_after(resp.headers());
1893            let ErrorAnswer {
1894                code,
1895                message,
1896                headers,
1897                ..
1898            } = read_error(resp).await?;
1899            // A HEAD answer carries no body, so the bare `426` is all there is to switch on;
1900            // it is the same refusal a create or a chunk gets, and surfaces as the same error.
1901            if is_upgrade_required(status, code.as_deref()) {
1902                return Err(self.transport.upgrade_required(&headers, message));
1903            }
1904            if answer_asks_to_wait(status, code.as_deref()) {
1905                tracing::debug!(status, ?code, ?after, "HEAD: the server asked for a wait");
1906                return Ok(Err(WaitAsked {
1907                    status,
1908                    code,
1909                    message,
1910                    after,
1911                }));
1912            }
1913            return Err(UploadError::Rejected {
1914                status,
1915                code,
1916                message,
1917            });
1918        }
1919
1920        let headers = resp.headers();
1921        let offset = header_u64(headers, "X-Capsule-Offset").ok_or_else(|| {
1922            UploadError::MalformedResponse("HEAD response missing X-Capsule-Offset".into())
1923        })?;
1924        let total_size = header_u64(headers, "X-Capsule-Content-Length");
1925        // Without a declared length the set is only checked against itself.
1926        let committed = committed_of(headers, total_size.unwrap_or(u64::MAX));
1927        let statusv = header_str(headers, "X-Capsule-Upload-Status").unwrap_or_default();
1928        let error_code = header_str(headers, "X-Capsule-Upload-Error");
1929        let (advice, expiry) = advice_of(headers);
1930        Ok(Ok(Some(HeadInfo {
1931            offset,
1932            committed,
1933            total_size,
1934            status: statusv,
1935            advice,
1936            expiry,
1937            error_code,
1938        })))
1939    }
1940
1941    /// `POST /upload`, waiting out every retryable answer under the transfer's recovery
1942    /// budget and the lane's shared retry budget.
1943    async fn create_waiting(
1944        &self,
1945        request: &CreateUploadRequest,
1946        recovery: &mut Recovery<'_>,
1947    ) -> Result<CreateOutcome, UploadError> {
1948        loop {
1949            match self.try_create(request).await? {
1950                Ok(outcome) => {
1951                    // An answered create is a success the lane earns back from, so a server
1952                    // that paces creates with `Retry-After` does not drain the lane.
1953                    recovery.lane.record_success();
1954                    if let CreateOutcome::Created { advice, .. } = &outcome {
1955                        recovery.advised(advice);
1956                    }
1957                    return Ok(outcome);
1958                }
1959                Err(asked) => {
1960                    let wait = recovery.server_wait(asked, "session create")?;
1961                    tracing::debug!(?wait, "waiting as the server asked, then creating again");
1962                    self.sleeper.sleep(wait).await;
1963                }
1964            }
1965        }
1966    }
1967
1968    /// `HEAD /upload/{id}`, waiting out every retryable answer under the transfer's
1969    /// recovery budget and the lane's shared retry budget.
1970    async fn head_waiting(
1971        &self,
1972        session_id: &str,
1973        recovery: &mut Recovery<'_>,
1974    ) -> Result<Option<HeadInfo>, UploadError> {
1975        loop {
1976            match self.try_head(session_id).await? {
1977                Ok(info) => {
1978                    // An answered `HEAD` (the finalization poll's included) earns toward the
1979                    // lane's shared budget, as an accepted chunk does.
1980                    recovery.lane.record_success();
1981                    if let Some(info) = &info {
1982                        recovery.advised(&info.advice);
1983                    }
1984                    return Ok(info);
1985                }
1986                Err(asked) => {
1987                    let wait = recovery.server_wait(asked, "progress query")?;
1988                    tracing::debug!(?wait, "waiting as the server asked, then asking HEAD again");
1989                    self.sleeper.sleep(wait).await;
1990                }
1991            }
1992        }
1993    }
1994
1995    /// Cancel a session (`DELETE /upload/{id}`). Idempotent for the caller: a
1996    /// `404` (already gone) resolves as `Ok(())`; a `409` (finalization running,
1997    /// not interruptible, or the session already finished) surfaces as
1998    /// [`UploadError::Rejected`] with `error.upload.session_not_active`.
1999    /// [`push::redact_asset`](crate::push::redact_asset) reads that answer as a
2000    /// session that finalized during the abort.
2001    #[tracing::instrument(level = "debug", skip(self))]
2002    pub async fn delete(&self, session_id: &str) -> Result<(), UploadError> {
2003        let resp = self
2004            .transport
2005            .send(|http| {
2006                http.delete(self.transport.session_url(session_id))
2007                    .header("X-Capsule-Protocol", &self.transport.protocol_version)
2008            })
2009            .await?;
2010
2011        let status = resp.status().as_u16();
2012        if (200..300).contains(&status) || status == 404 {
2013            return Ok(());
2014        }
2015        let ErrorAnswer { code, message, .. } = read_error(resp).await?;
2016        Err(UploadError::Rejected {
2017            status,
2018            code,
2019            message,
2020        })
2021    }
2022
2023    /// List the uploader's active sessions (`GET /upload/sessions`), so a client
2024    /// can resume across app restarts.
2025    #[tracing::instrument(level = "debug", skip(self))]
2026    pub async fn list_sessions(&self) -> Result<Vec<SessionSummary>, UploadError> {
2027        let base = &self.transport.base_url;
2028        let resp = self
2029            .transport
2030            .send(|http| {
2031                http.get(format!("{base}/sessions"))
2032                    .header("X-Capsule-Protocol", &self.transport.protocol_version)
2033            })
2034            .await?;
2035
2036        let status = resp.status().as_u16();
2037        if !(200..300).contains(&status) {
2038            let ErrorAnswer { code, message, .. } = read_error(resp).await?;
2039            return Err(UploadError::Rejected {
2040                status,
2041                code,
2042                message,
2043            });
2044        }
2045        let body: ListSessionsBody = resp.json().await?;
2046        Ok(body.sessions)
2047    }
2048
2049    /// The chunk `PATCH` carrying `bytes` at `offset` on `http`, its body paced into `progress`.
2050    /// Built afresh per invocation over the same bytes: the session path may rebuild the request
2051    /// for its one 401 refresh-and-replay.
2052    fn chunk_request(
2053        &self,
2054        http: &reqwest::Client,
2055        session_id: &str,
2056        offset: u64,
2057        checksum: &str,
2058        bytes: &bytes::Bytes,
2059        progress: &ExchangeProgress,
2060    ) -> reqwest::RequestBuilder {
2061        let request = http
2062            .patch(self.transport.session_url(session_id))
2063            .header("X-Capsule-Protocol", &self.transport.protocol_version)
2064            .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
2065            .header("X-Capsule-Offset", offset.to_string())
2066            .header("X-Capsule-Checksum", checksum)
2067            .body(PacedBody::new(bytes.clone(), progress.clone()));
2068        // A chunk is addressed by offset and checked by checksum, so it is safe to send twice:
2069        // under `http3` it may ride QUIC.
2070        crate::net::replayable(request, bytes.clone(), progress)
2071    }
2072
2073    /// Append one chunk at `offset` (`PATCH /upload/{id}`), sending the required
2074    /// `X-Capsule-Checksum` and `X-Capsule-Offset`. Maps the server's response to
2075    /// a [`ChunkAck`]; `426` and other non-recoverable rejections are `Err`.
2076    #[tracing::instrument(level = "trace", skip(self, chunk), fields(session_id = %session_id, offset, len = chunk.len()))]
2077    async fn send_patch(
2078        &self,
2079        session_id: &str,
2080        chunk: &[u8],
2081        offset: u64,
2082        size: u64,
2083    ) -> Result<ChunkAck, UploadError> {
2084        let checksum = chunk_checksum(chunk);
2085        let bytes = bytes::Bytes::copy_from_slice(chunk);
2086        // The stall bound runs while the body is sent, the response-wait bound once it is all
2087        // sent: a slow link is never cut, a stalled one is.
2088        let progress = ExchangeProgress::waiting();
2089        let resp = self
2090            .transport
2091            .send_tracked(&progress, |http| {
2092                self.chunk_request(http, session_id, offset, &checksum, &bytes, &progress)
2093            })
2094            .await?;
2095        let resp = match resp {
2096            Ok(resp) => resp,
2097            // The link stopped moving: nothing of the chunk can have been kept, so it is the
2098            // same answer as the server's own stall cut.
2099            Err(RequestCut::Stalled) => return Ok(ChunkAck::Stalled),
2100            // The body was handed off whole and no answer came: either the server never
2101            // answered, or the link is too slow to drain the tail the stack still buffers.
2102            Err(RequestCut::NoResponse) => return Ok(ChunkAck::Unanswered),
2103        };
2104
2105        let status = resp.status().as_u16();
2106        if (200..300).contains(&status) {
2107            let prefix = header_u64(resp.headers(), "X-Capsule-Offset");
2108            let committed = committed_of(resp.headers(), size);
2109            let session_status = header_str(resp.headers(), "X-Capsule-Upload-Status");
2110            return Ok(ChunkAck::Accepted {
2111                offset: prefix,
2112                committed,
2113                status: session_status,
2114            });
2115        }
2116
2117        // The 409 offset_mismatch carries the authoritative offset in the header, and a
2118        // range_conflict the committed set; capture them before consuming the body.
2119        let authoritative = header_u64(resp.headers(), "X-Capsule-Offset");
2120        let committed = committed_of(resp.headers(), size);
2121        let wait = retry_after(resp.headers());
2122        let ErrorAnswer {
2123            code,
2124            message,
2125            headers,
2126            ..
2127        } = read_error(resp).await?;
2128
2129        // Recovery matrix — switch on the stable error.* code, never the status.
2130        match code.as_deref() {
2131            Some(c) if c == error_codes::UPLOAD_RANGE_CONFLICT => {
2132                tracing::debug!(?committed, ?wait, "range_conflict — re-planning");
2133                Ok(ChunkAck::RangeConflict {
2134                    committed,
2135                    after: wait,
2136                })
2137            }
2138            Some(c) if c == error_codes::UPLOAD_TOO_FRAGMENTED => {
2139                tracing::debug!(
2140                    ?wait,
2141                    "too_fragmented — letting the ranges in flight finish"
2142                );
2143                Ok(ChunkAck::TooFragmented { after: wait })
2144            }
2145            Some(c) if c == error_codes::UPLOAD_TOO_MANY_IN_FLIGHT => {
2146                tracing::debug!(?wait, "too_many_in_flight — narrowing the window");
2147                Ok(ChunkAck::TooManyInFlight { after: wait })
2148            }
2149            Some(c) if c == error_codes::UPLOAD_OFFSET_MISMATCH => {
2150                tracing::debug!(?authoritative, "offset_mismatch — re-aligning");
2151                Ok(ChunkAck::Realign(authoritative))
2152            }
2153            Some(c) if c == error_codes::UPLOAD_SESSION_NOT_FOUND => {
2154                tracing::debug!("session_not_found — re-creating");
2155                Ok(ChunkAck::Recreate)
2156            }
2157            Some(c) if c == error_codes::UPLOAD_CHECKSUM_MISMATCH => {
2158                tracing::debug!("checksum_mismatch — re-sending chunk");
2159                Ok(ChunkAck::Resend)
2160            }
2161            Some(c) if c == error_codes::UPLOAD_CHUNK_TIMEOUT => {
2162                tracing::debug!("chunk_timeout — re-sending smaller");
2163                Ok(ChunkAck::TimedOut)
2164            }
2165            _ if is_upgrade_required(status, code.as_deref()) => {
2166                Err(self.transport.upgrade_required(&headers, message))
2167            }
2168            // Every retryable answer — a wait the server asked for, any `5xx`, `408`, `425` —
2169            // waits and resumes from `HEAD`: a `5xx` may have kept the chunk (a completing
2170            // chunk's `500 storage_inconsistent` included), so only the server knows the offset.
2171            _ if answer_asks_to_wait(status, code.as_deref()) => {
2172                tracing::debug!(
2173                    status,
2174                    ?code,
2175                    ?wait,
2176                    "a retryable answer to a chunk — backing off"
2177                );
2178                Ok(ChunkAck::Backoff(WaitAsked {
2179                    status,
2180                    code,
2181                    message,
2182                    after: wait,
2183                }))
2184            }
2185            _ => Err(UploadError::Rejected {
2186                status,
2187                code,
2188                message,
2189            }),
2190        }
2191    }
2192
2193    /// Transfer a full ciphertext blob with the adaptive algorithm and the
2194    /// code-driven recovery matrix, starting from a fresh session.
2195    ///
2196    /// `data` is the ciphertext's source (opaque bytes); the client reads it one
2197    /// chunk window at a time — never whole — and checksums each chunk. Every byte is sent when
2198    /// the received-byte count reaches the declared size, at which point the server finalizes.
2199    /// The server answers the completing chunk `waiting_for_processing` without waiting for
2200    /// finalization, so the client then polls `HEAD` with backoff until the session is
2201    /// `completed` — the outcome — or `failed_processing`, which is an
2202    /// [`UploadError::Rejected`] carrying the `X-Capsule-Upload-Error` code.
2203    ///
2204    /// A retryable answer to any request it makes — the create, a chunk, or a `HEAD` —
2205    /// is waited out, each wait charging the one recovery budget the transfer shares and
2206    /// the lane's shared retry budget. That is `rate_limited`, `unavailable`,
2207    /// `storage_full`, and every other `5xx`, `408` or `425`; a chunk's wait resumes from
2208    /// `HEAD`, so a completing chunk answered `500 storage_inconsistent` settles on what
2209    /// the server says it holds.
2210    #[tracing::instrument(level = "debug", skip(self, data), fields(size = request.size, blob_role = ?request.blob_role))]
2211    pub async fn upload<S: UploadSource + ?Sized>(
2212        &self,
2213        request: &CreateUploadRequest,
2214        data: &S,
2215    ) -> Result<UploadOutcome, UploadError> {
2216        self.upload_with(request, data, &mut Recovery::new(self.lane.clone(), None))
2217            .await
2218    }
2219
2220    /// [`UploadClient::upload`] under a scheduler: every range the transfer sends first
2221    /// reserves its length through `gate` and gives it back once the request ends, and the
2222    /// advice the server sends on the session's create and `HEAD`s is reported to it. This is
2223    /// how a lane's sessions in flight share the device's one byte budget.
2224    #[tracing::instrument(level = "debug", skip(self, data, gate), fields(size = request.size, blob_role = ?request.blob_role))]
2225    pub async fn upload_gated<S: UploadSource + ?Sized>(
2226        &self,
2227        request: &CreateUploadRequest,
2228        data: &S,
2229        gate: &dyn TransferGate,
2230    ) -> Result<UploadOutcome, UploadError> {
2231        self.upload_with(
2232            request,
2233            data,
2234            &mut Recovery::new(self.lane.clone(), Some(gate)),
2235        )
2236        .await
2237    }
2238
2239    /// [`UploadClient::upload`] over a recovery budget the caller may already have
2240    /// charged.
2241    async fn upload_with<S: UploadSource + ?Sized>(
2242        &self,
2243        request: &CreateUploadRequest,
2244        data: &S,
2245        recovery: &mut Recovery<'_>,
2246    ) -> Result<UploadOutcome, UploadError> {
2247        match self.open(request, recovery).await? {
2248            Opened::Session(session, mut strategy, start) => {
2249                self.drive(session, request, data, &mut strategy, start, recovery)
2250                    .await
2251            }
2252            Opened::Merged(asset_ref) => Ok(self.merged(request, asset_ref)),
2253        }
2254    }
2255
2256    /// Open a session for `request` — a fresh one, or the active one the server returns for
2257    /// the same blob — with its chunk strategy and where it starts; or learn the blob is already
2258    /// stored.
2259    async fn open(
2260        &self,
2261        request: &CreateUploadRequest,
2262        recovery: &mut Recovery<'_>,
2263    ) -> Result<Opened, UploadError> {
2264        match self.create_waiting(request, recovery).await? {
2265            CreateOutcome::Created {
2266                response,
2267                resume_offset,
2268                committed,
2269                advice,
2270                status,
2271                ..
2272            } => {
2273                let strategy = AdaptiveChunkSizeStrategy::for_file_size(request.size)
2274                    .seeded_from_suggested(response.starting_chunk(&advice))
2275                    .with_connection_class(self.connection);
2276                let committed = committed
2277                    .unwrap_or_else(|| CommittedSet::prefix(resume_offset.min(request.size)));
2278                self.emit_created(request, &response.id, committed.prefix_end());
2279                let start = Start {
2280                    committed,
2281                    state: status,
2282                    window: self.window_for(&advice),
2283                    advice,
2284                };
2285                Ok(Opened::Session(response.id, strategy, start))
2286            }
2287            CreateOutcome::AlreadyStored { asset_ref } => Ok(Opened::Merged(asset_ref)),
2288        }
2289    }
2290
2291    /// The merge a `duplicate_blob` on a create resolved to: success, carrying the existing
2292    /// asset.
2293    fn merged(&self, request: &CreateUploadRequest, asset_ref: String) -> UploadOutcome {
2294        self.emit_merged(request, &asset_ref);
2295        UploadOutcome::AlreadyStored { asset_ref }
2296    }
2297
2298    /// Resume an existing session: HEAD for the authoritative offset, then
2299    /// continue from there — no bytes the server already holds are re-sent
2300    /// (transfer upload doc, §Idempotency and Resumption). If the session is gone
2301    /// (`404`), it is re-created and driven from zero.
2302    #[tracing::instrument(level = "debug", skip(self, data), fields(size = request.size))]
2303    pub async fn upload_resuming<S: UploadSource + ?Sized>(
2304        &self,
2305        session_id: &str,
2306        request: &CreateUploadRequest,
2307        data: &S,
2308    ) -> Result<UploadOutcome, UploadError> {
2309        let mut recovery = Recovery::new(self.lane.clone(), None);
2310        // The session predates this transfer, so any byte of the blob may already have been
2311        // sent: every read is a re-send, from a source that must affirm it is unchanged.
2312        recovery.sent = CommittedSet::prefix(request.size);
2313        if let Some(info) = self.head_waiting(session_id, &mut recovery).await? {
2314            let mut strategy = AdaptiveChunkSizeStrategy::for_file_size(request.size);
2315            if let Some(chunk) = info.advice.chunk(Duration::ZERO) {
2316                strategy = strategy.seeded_from_suggested(chunk);
2317            }
2318            let mut strategy = strategy.with_connection_class(self.connection);
2319            let committed = info
2320                .committed
2321                .unwrap_or_else(|| CommittedSet::prefix(info.offset.min(request.size)));
2322            tracing::debug!(offset = info.offset, committed = %committed.to_header(), "resuming from the server's committed set");
2323            self.events.emit(|| TransferEvent::SessionResumed {
2324                blob: request.hash.clone(),
2325                session_id: session_id.to_string(),
2326                size: request.size,
2327                offset: info.offset,
2328            });
2329            let start = Start {
2330                committed,
2331                state: Some(info.status),
2332                window: self.window_for(&info.advice),
2333                advice: info.advice,
2334            };
2335            self.drive(
2336                session_id.to_string(),
2337                request,
2338                data,
2339                &mut strategy,
2340                start,
2341                &mut recovery,
2342            )
2343            .await
2344        } else {
2345            tracing::debug!("session gone on resume — re-creating");
2346            self.upload_with(request, data, &mut recovery).await
2347        }
2348    }
2349
2350    /// The range scheduler with the recovery matrix, then the finalization poll, on the session
2351    /// `session_id` starting from `start`.
2352    ///
2353    /// Finalization refusing the blob's hash (`content_hash_mismatch`) is the source's to
2354    /// explain: a changed source ends the transfer with [`UploadError::SourceChanged`]; one that
2355    /// affirms it is unchanged ([`SourceIdentity::Affirmed`]) gets one re-created session, and a
2356    /// second refusal ends the transfer. One that cannot affirm it ends the transfer with the
2357    /// refusal, sending nothing again.
2358    async fn drive<S: UploadSource + ?Sized>(
2359        &self,
2360        session_id: String,
2361        request: &CreateUploadRequest,
2362        data: &S,
2363        strategy: &mut AdaptiveChunkSizeStrategy,
2364        start: Start,
2365        recovery: &mut Recovery<'_>,
2366    ) -> Result<UploadOutcome, UploadError> {
2367        let size = request.size;
2368        let mut cursor = Cursor::new(session_id, start);
2369        let mut recreated_after_mismatch = false;
2370        loop {
2371            if let Transferred::Merged(asset_ref) = self
2372                .transfer(&mut cursor, request, data, strategy, recovery)
2373                .await?
2374            {
2375                return Ok(self.merged(request, asset_ref));
2376            }
2377            let session_id = cursor.session_id.clone();
2378            tracing::info!(%session_id, size, "every byte sent — server finalizing");
2379            self.events.emit(|| TransferEvent::Finalize {
2380                blob: request.hash.clone(),
2381                session_id: session_id.clone(),
2382                size,
2383            });
2384            match self
2385                .settle(&session_id, size, cursor.state.as_deref(), recovery)
2386                .await?
2387            {
2388                Settled::Done(outcome) => return Ok(outcome),
2389                Settled::Resume(held) => {
2390                    // A server that keeps losing a range it acknowledged would otherwise loop
2391                    // here forever: each resume is a recovery like any other.
2392                    recovery.charge("resume after a lost range record")?;
2393                    tracing::info!(%session_id, committed = %held.to_header(), size, "the server holds fewer bytes than declared; resuming");
2394                    cursor.committed = held;
2395                    cursor.state = None;
2396                }
2397                Settled::Lost => {
2398                    recovery.charge("session re-create")?;
2399                    cursor.step.cause(0, size);
2400                    cursor.step.recreate = true;
2401                    if let StepTaken::Merged(asset_ref) = self
2402                        .take_step(&mut cursor, request, strategy, recovery)
2403                        .await?
2404                    {
2405                        return Ok(self.merged(request, asset_ref));
2406                    }
2407                }
2408                Settled::HashMismatch(refusal) => {
2409                    match data.check_unchanged() {
2410                        Err(changed) => {
2411                            tracing::warn!(%session_id, reason = %changed.reason, "finalization refused the hash and the source changed");
2412                            return Err(changed.into());
2413                        }
2414                        Ok(SourceIdentity::Unknown) => {
2415                            // Sending the blob again could seal changed bytes under the nonces
2416                            // already used: only a source that affirms its identity is re-sent.
2417                            tracing::warn!(%session_id, "finalization refused the hash of a source that cannot affirm it is unchanged; not re-sending");
2418                            return Err(refusal);
2419                        }
2420                        Ok(SourceIdentity::Affirmed) => {}
2421                    }
2422                    if recreated_after_mismatch {
2423                        tracing::warn!(%session_id, "finalization refused the hash of a re-created session too");
2424                        return Err(refusal);
2425                    }
2426                    recreated_after_mismatch = true;
2427                    recovery.charge("re-create after a refused hash")?;
2428                    tracing::warn!(%session_id, "finalization refused the hash of an unchanged source; re-creating the session once");
2429                    match self.open(request, recovery).await? {
2430                        Opened::Session(id, fresh, start) => {
2431                            *strategy = fresh;
2432                            cursor = Cursor::new(id, start);
2433                        }
2434                        Opened::Merged(asset_ref) => return Ok(self.merged(request, asset_ref)),
2435                    }
2436                }
2437            }
2438        }
2439    }
2440
2441    /// Send every byte of the cursor's session the server does not hold, up to the session's
2442    /// window of ranges at once.
2443    ///
2444    /// Each range is planned by [`next_range`] from the committed set the server last reported
2445    /// and the ranges already in flight: the lowest gap first, so a window of one is the
2446    /// sequential schedule. An accepted range adds what its answer says is committed. A refusal
2447    /// that needs a session-level step (a wait, a `HEAD`, a re-create) stops the planning until
2448    /// every range in flight has returned, then the step is taken once. Every refusal charges
2449    /// the transfer's bounded recovery budgets as it always did, so a server that never lets the
2450    /// transfer progress ends it. Returns once every byte is committed, or the server reported
2451    /// the session finalizing.
2452    async fn transfer<S: UploadSource + ?Sized>(
2453        &self,
2454        cursor: &mut Cursor,
2455        request: &CreateUploadRequest,
2456        data: &S,
2457        strategy: &mut AdaptiveChunkSizeStrategy,
2458        recovery: &mut Recovery<'_>,
2459    ) -> Result<Transferred, UploadError> {
2460        let size = request.size;
2461        let gate = recovery.gate;
2462        let mut flights = Vec::new();
2463        let mut flying: Vec<(u64, u64)> = Vec::new();
2464        // A source that does not check what it re-derives is sent one range at a time, the
2465        // schedule that re-sends least (`UploadSource::verifies_rederived`).
2466        let sequential = !data.verifies_rederived();
2467        if sequential && cursor.window > 1 {
2468            tracing::debug!(session_id = %cursor.session_id, window = cursor.window, "the source does not verify what it re-derives; sending one range at a time");
2469        }
2470        loop {
2471            if !cursor.step.is_set() {
2472                let window = if sequential {
2473                    1
2474                } else {
2475                    cursor.window as usize
2476                };
2477                // A request this client abandoned may still hold a claim on the server until its
2478                // write returns: it counts against the window, but never fills it.
2479                let ghosts = cursor.abandoned_claims().min(window - 1);
2480                while flying.len() + ghosts < window {
2481                    let want = strategy.next_chunk_size();
2482                    let Some(range) = next_range(&cursor.committed, &flying, size, want) else {
2483                        break;
2484                    };
2485                    flying.push(range);
2486                    let resend = recovery.sent.overlaps(range.0, range.1);
2487                    recovery.sent.insert(range.0, range.1);
2488                    flights.push(Box::pin(self.fly(
2489                        cursor.session_id.clone(),
2490                        request,
2491                        data,
2492                        gate,
2493                        range,
2494                        resend,
2495                    )));
2496                }
2497            }
2498            if flights.is_empty() {
2499                if !cursor.step.is_set() {
2500                    // Nothing in flight and nothing left to plan: every byte is committed.
2501                    return Ok(Transferred::Sent);
2502                }
2503                match self.take_step(cursor, request, strategy, recovery).await? {
2504                    StepTaken::Continue => continue,
2505                    StepTaken::Settle => return Ok(Transferred::Sent),
2506                    StepTaken::Merged(asset_ref) => return Ok(Transferred::Merged(asset_ref)),
2507                }
2508            }
2509            let flight = next_landed(&mut flights).await;
2510            flying.retain(|range| *range != flight.range);
2511            if let Err(error) = self.land(flight, cursor, request, strategy, recovery) {
2512                // The transfer ends here: the ranges still in flight are dropped, which cancels
2513                // their requests; the server releases each claim once its write returns.
2514                flights.clear();
2515                if let UploadError::SourceChanged(changed) = &error {
2516                    self.cancel_after_source_change(&cursor.session_id, changed)
2517                        .await;
2518                }
2519                return Err(error);
2520            }
2521            if std::mem::take(&mut cursor.step.narrow) {
2522                // The server held its cap of claims while this client had `flying` ranges
2523                // besides the refused one: the cap is no more than those, and no more than the
2524                // session's advertised `ranges`.
2525                let in_flight = u32::try_from(flying.len()).unwrap_or(u32::MAX).max(1);
2526                let narrowed = cursor
2527                    .window
2528                    .min(self.window_for(&cursor.advice))
2529                    .min(in_flight);
2530                tracing::info!(session_id = %cursor.session_id, from = cursor.window, to = narrowed, "ranges window narrowed after too_many_in_flight");
2531                cursor.window = narrowed;
2532            }
2533        }
2534    }
2535
2536    /// Send one planned range: reserve its bytes under the scheduler, check the source, read
2537    /// exactly that window — a re-send reads it again, so the client holds a window of the
2538    /// blob, never the blob — and `PATCH` it.
2539    ///
2540    /// A `resend` overlaps bytes this transfer already read for a request (a lost answer, a
2541    /// re-plan after `range_conflict`, a re-created or resumed session, a lost range record).
2542    /// Its window is re-derived only from a source whose check, made just before the read,
2543    /// affirms it is unchanged ([`SourceIdentity::Affirmed`]): re-deriving changed bytes would
2544    /// put a second ciphertext under the nonces the first read spent. Any other source ends the
2545    /// transfer with [`UploadError::SourceChanged`] and sends nothing again.
2546    async fn fly<S: UploadSource + ?Sized>(
2547        &self,
2548        session_id: String,
2549        request: &CreateUploadRequest,
2550        data: &S,
2551        gate: Option<&dyn TransferGate>,
2552        range: (u64, u64),
2553        resend: bool,
2554    ) -> Flight {
2555        let (offset, end) = range;
2556        let len = end - offset;
2557        // Under a scheduler the range's bytes are reserved against the shared budget before
2558        // they are read, and given back once its request ends, however it ends.
2559        let hold = RangeHold::reserve(gate, len).await;
2560        let mut started = std::time::Instant::now();
2561        let sent = async {
2562            let identity = data.check_unchanged()?;
2563            if resend && identity != SourceIdentity::Affirmed {
2564                tracing::warn!(%session_id, offset, len, "a range already sent would be read again from a source that cannot affirm it is unchanged; not re-sending");
2565                return Err(UploadError::SourceChanged(SourceChanged::new(
2566                    "the source cannot affirm it is unchanged, so a range already sent is not \
2567                     read and sent again",
2568                )));
2569            }
2570            let window = data
2571                .read_at(offset, usize::try_from(len).unwrap_or(usize::MAX))
2572                .map_err(UploadError::of_read)?;
2573            if window.len() as u64 != len {
2574                return Err(UploadError::Io(std::io::Error::new(
2575                    std::io::ErrorKind::UnexpectedEof,
2576                    format!(
2577                        "upload source returned {} of {len} bytes at offset {offset}",
2578                        window.len()
2579                    ),
2580                )));
2581            }
2582            started = std::time::Instant::now();
2583            self.events.emit(|| TransferEvent::ChunkSent {
2584                blob: request.hash.clone(),
2585                session_id: session_id.clone(),
2586                offset,
2587                len,
2588            });
2589            self.send_patch(&session_id, &window, offset, request.size)
2590                .await
2591        }
2592        .await;
2593        // The range's request is over: its bytes go back before anything waits on its answer.
2594        drop(hold);
2595        Flight {
2596            range,
2597            started,
2598            sent,
2599        }
2600    }
2601
2602    /// Fold one returned range into the cursor: what it committed, or the recovery its refusal
2603    /// asks for. A range that needs nothing more than a re-send is simply left unplanned, so the
2604    /// next plan picks it up again.
2605    fn land(
2606        &self,
2607        flight: Flight,
2608        cursor: &mut Cursor,
2609        request: &CreateUploadRequest,
2610        strategy: &mut AdaptiveChunkSizeStrategy,
2611        recovery: &mut Recovery<'_>,
2612    ) -> Result<(), UploadError> {
2613        let Flight {
2614            range: (offset, end),
2615            started,
2616            sent,
2617        } = flight;
2618        let len = end - offset;
2619        let size = request.size;
2620        let session_id = cursor.session_id.clone();
2621        let response_wait = self.transport.bounds.response_wait;
2622        let ack = match sent {
2623            Ok(ack) => ack,
2624            // A connection reset or a silent black-hole: the server may or may not have kept the
2625            // range, so its state is read from `HEAD` before anything is sent again (a lost
2626            // ACK), after the shared engine's backoff. Bounded give-up keeps a dead path from
2627            // becoming a hot loop.
2628            Err(UploadError::Transport(reason)) => {
2629                cursor.abandon(response_wait);
2630                cursor.step.cause(offset, len);
2631                if cursor.step.wait.is_none() {
2632                    let wait =
2633                        self.reset_backoff(recovery, request, &session_id, (offset, len), &reason)?;
2634                    cursor.step.wait_at_least(wait);
2635                }
2636                cursor.step.read_state();
2637                return Ok(());
2638            }
2639            Err(other) => return Err(other),
2640        };
2641        match ack {
2642            ChunkAck::Accepted {
2643                offset: prefix,
2644                committed,
2645                status,
2646            } => {
2647                match (&committed, prefix) {
2648                    // A block-grid server: the range is committed, and so is the set it names.
2649                    (Some(held), _) => {
2650                        cursor.committed.insert(offset, end);
2651                        cursor.committed.union(held);
2652                    }
2653                    // An older server holds a prefix and names it: that is all it holds,
2654                    // however much of the range it kept.
2655                    (None, Some(prefix)) => {
2656                        cursor.committed = CommittedSet::prefix(prefix.min(size));
2657                    }
2658                    (None, None) => cursor.committed.insert(offset, end),
2659                }
2660                cursor.state = later_state(cursor.state.take(), status);
2661                strategy.record_chunk(len, started.elapsed());
2662                // Real progress refills the shrinking-cut and transient-reset budgets, and
2663                // earns toward the lane's shared one.
2664                recovery.on_progress();
2665                let acked_offset = prefix.unwrap_or_else(|| cursor.committed.prefix_end());
2666                self.events.emit(|| TransferEvent::ChunkAcked {
2667                    blob: request.hash.clone(),
2668                    session_id: session_id.clone(),
2669                    offset,
2670                    len,
2671                    acked_offset,
2672                });
2673            }
2674            ChunkAck::RangeConflict { committed, after } => {
2675                recovery.charge("range conflict re-plan")?;
2676                cursor.step.cause(offset, len);
2677                match &committed {
2678                    Some(held) => cursor.committed.union(held),
2679                    None => cursor.step.read_state(),
2680                }
2681                if let Some(after) = after {
2682                    self.wait_asked(cursor, request, (offset, len), after);
2683                }
2684                tracing::info!(%session_id, offset, len, committed = ?committed.map(|c| c.to_header()), ?after, "a range overlapped one committed or in flight — re-planning");
2685            }
2686            ChunkAck::TooFragmented { after } => {
2687                recovery.charge("too fragmented re-plan")?;
2688                cursor.step.cause(offset, len);
2689                cursor.step.quiesce = true;
2690                if let Some(after) = after {
2691                    self.wait_asked(cursor, request, (offset, len), after);
2692                }
2693                tracing::info!(%session_id, offset, len, ?after, "the committed set would fragment — letting the ranges in flight finish, then re-planning");
2694            }
2695            ChunkAck::TooManyInFlight { after } => {
2696                recovery.charge("too many ranges in flight")?;
2697                cursor.step.cause(offset, len);
2698                cursor.step.quiesce = true;
2699                cursor.step.narrow = true;
2700                tracing::info!(%session_id, offset, len, ?after, "the session's ranges window was full — narrowing it");
2701                if let Some(after) = after {
2702                    self.wait_asked(cursor, request, (offset, len), after);
2703                }
2704            }
2705            ChunkAck::Realign(Some(to)) => {
2706                recovery.charge("offset re-align")?;
2707                self.emit_retried(
2708                    request,
2709                    &session_id,
2710                    offset,
2711                    len,
2712                    RetryReason::OffsetRealign { to },
2713                );
2714                cursor.committed = CommittedSet::prefix(to.min(size));
2715                cursor.state = None;
2716            }
2717            ChunkAck::Realign(None) => {
2718                recovery.charge("offset re-align")?;
2719                cursor.step.cause(offset, len);
2720                cursor.step.realign = true;
2721                cursor.step.read_state();
2722            }
2723            ChunkAck::Recreate => {
2724                recovery.charge("session re-create")?;
2725                cursor.step.cause(offset, len);
2726                cursor.step.quiesce = true;
2727                cursor.step.recreate = true;
2728            }
2729            ChunkAck::Resend => {
2730                recovery.charge("chunk re-send")?;
2731                self.events.emit(|| TransferEvent::ChecksumRejected {
2732                    blob: request.hash.clone(),
2733                    session_id: session_id.clone(),
2734                    offset,
2735                    len,
2736                });
2737                // Left unplanned: the next plan re-sends the same range.
2738            }
2739            ack @ (ChunkAck::TimedOut | ChunkAck::Stalled) => {
2740                // Nothing of a range that did not arrive whole is written, so it is re-planned
2741                // at the same offset, shorter. No wait either, since the link just spent a whole
2742                // stall bound on it. A cut that shrank is charged to the budget progress refills;
2743                // one at the minimum to the per-transfer one. A client-cut request may still hold
2744                // its claim on the server for a while.
2745                if matches!(ack, ChunkAck::Stalled) {
2746                    cursor.abandon(response_wait);
2747                }
2748                let shrunk = strategy.shrink_after_stall(len);
2749                if shrunk {
2750                    recovery.charge_cut("stalled chunk re-send")?;
2751                } else {
2752                    recovery.charge("stalled chunk re-send")?;
2753                }
2754                tracing::info!(
2755                    %session_id,
2756                    offset,
2757                    stalled_len = len,
2758                    next_len = strategy.next_chunk_size().min(size - offset),
2759                    shrunk,
2760                    cut_by = if matches!(ack, ChunkAck::Stalled) { "client" } else { "server" },
2761                    "a chunk stalled — re-sending at the same offset, shorter"
2762                );
2763            }
2764            ChunkAck::Unanswered => {
2765                // The whole body went out and no answer came: the server may have kept the
2766                // range, so `HEAD` is read before anything is sent again, and the range is
2767                // re-planned shorter only once it says the range is still missing. Shrink first:
2768                // a link too slow to drain the buffered tail inside the response wait would
2769                // otherwise be cut at the same size until the retries ran out.
2770                cursor.abandon(response_wait);
2771                cursor.step.cause(offset, len);
2772                let shrunk = strategy.shrink_after_stall(len);
2773                tracing::info!(
2774                    %session_id,
2775                    offset,
2776                    unanswered_len = len,
2777                    next_len = strategy.next_chunk_size().min(size - offset),
2778                    shrunk,
2779                    "a chunk got no answer — reading the session's state, then re-sending shorter where it can be"
2780                );
2781                if shrunk {
2782                    // A cut that shrank is a stall re-send, charged like one: to the budget
2783                    // each accepted chunk refills, so a long upload that slows down again and
2784                    // again is not failed by the per-transfer ceiling. No wait either, since the
2785                    // link just spent a whole response wait.
2786                    recovery.charge_cut("unanswered chunk re-send")?;
2787                } else if cursor.step.wait.is_none() {
2788                    // Nothing smaller can be sent: an unanswered minimum chunk is a dead path
2789                    // until shown otherwise, and backs off under the reset budget.
2790                    let wait = self.reset_backoff(
2791                        recovery,
2792                        request,
2793                        &session_id,
2794                        (offset, len),
2795                        &RequestCut::NoResponse.to_string(),
2796                    )?;
2797                    cursor.step.wait_at_least(wait);
2798                }
2799                cursor.step.read_state();
2800            }
2801            ChunkAck::Backoff(asked) => {
2802                // One wait per step: the ranges refused alongside this one are waited out by
2803                // the same wait, so P ranges refused together charge the budgets once.
2804                let wait = match cursor.step.wait {
2805                    None => recovery.server_wait(asked, "server-requested wait")?,
2806                    Some(_) => asked.after.unwrap_or_default().min(MAX_SERVER_BACKOFF),
2807                };
2808                cursor.step.cause(offset, len);
2809                tracing::debug!(
2810                    offset,
2811                    ?wait,
2812                    "waiting as the server asked, then resuming from HEAD"
2813                );
2814                self.wait_asked(cursor, request, (offset, len), wait);
2815                // The refused chunk left nothing behind, but anything may have moved while we
2816                // waited: the authoritative committed set is HEAD's.
2817                cursor.step.read_state();
2818            }
2819        }
2820        Ok(())
2821    }
2822
2823    /// Schedule the wait a refusal named, capped at [`MAX_SERVER_BACKOFF`], and publish it.
2824    fn wait_asked(
2825        &self,
2826        cursor: &mut Cursor,
2827        request: &CreateUploadRequest,
2828        (offset, len): (u64, u64),
2829        wait: Duration,
2830    ) {
2831        let wait = wait.min(MAX_SERVER_BACKOFF);
2832        self.emit_retried(
2833            request,
2834            &cursor.session_id,
2835            offset,
2836            len,
2837            RetryReason::ServerWait {
2838                wait_ms: millis(wait),
2839            },
2840        );
2841        cursor.step.wait_at_least(wait);
2842    }
2843
2844    /// Take the session-level step every range in flight has returned for: wait, then read the
2845    /// session's state from `HEAD`, or re-create the session (also when `HEAD` finds it gone).
2846    async fn take_step(
2847        &self,
2848        cursor: &mut Cursor,
2849        request: &CreateUploadRequest,
2850        strategy: &mut AdaptiveChunkSizeStrategy,
2851        recovery: &mut Recovery<'_>,
2852    ) -> Result<StepTaken, UploadError> {
2853        let size = request.size;
2854        let mut step = std::mem::take(&mut cursor.step);
2855        let (offset, len) = step.range;
2856        if let Some(wait) = step.wait {
2857            tracing::debug!(session_id = %cursor.session_id, ?wait, "every range returned — waiting before the next step");
2858            self.sleeper.sleep(wait).await;
2859        }
2860        if step.head && !step.recreate {
2861            match self.head_waiting(&cursor.session_id, recovery).await? {
2862                Some(info) => {
2863                    let held = info
2864                        .committed
2865                        .unwrap_or_else(|| CommittedSet::prefix(info.offset.min(size)));
2866                    // A server that lost ranges it acknowledged would otherwise have the
2867                    // client re-send them forever, each round refilling every budget that
2868                    // progress refills: a `HEAD` holding less than was acknowledged is a
2869                    // recovery like a lost range record at finalization. A re-align already
2870                    // charged for the `HEAD` it reads.
2871                    if !step.realign && !holds_all(&held, &cursor.committed) {
2872                        tracing::warn!(session_id = %cursor.session_id, acknowledged = %cursor.committed.to_header(), committed = %held.to_header(), "HEAD reports fewer bytes than the server acknowledged; re-planning from it");
2873                        recovery.charge("re-plan after the server lost acknowledged ranges")?;
2874                    }
2875                    if step.realign {
2876                        self.emit_retried(
2877                            request,
2878                            &cursor.session_id,
2879                            offset,
2880                            len,
2881                            RetryReason::OffsetRealign {
2882                                to: held.prefix_end(),
2883                            },
2884                        );
2885                    }
2886                    tracing::debug!(session_id = %cursor.session_id, committed = %held.to_header(), status = %info.status, "re-planning from HEAD");
2887                    cursor.committed = held;
2888                    cursor.window = cursor.window.min(self.window_for(&info.advice));
2889                    cursor.advice = info.advice;
2890                    let finalizing = matches!(
2891                        info.status.as_str(),
2892                        STATUS_WAITING | STATUS_COMPLETED | STATUS_FAILED
2893                    );
2894                    cursor.state = Some(info.status);
2895                    if finalizing {
2896                        return Ok(StepTaken::Settle);
2897                    }
2898                }
2899                // Vanished while recovering: re-create.
2900                None => step.recreate = true,
2901            }
2902        }
2903        if step.recreate {
2904            self.emit_retried(
2905                request,
2906                &cursor.session_id,
2907                offset,
2908                len,
2909                RetryReason::SessionLost,
2910            );
2911            match self.open(request, recovery).await? {
2912                Opened::Session(id, fresh, start) => {
2913                    *strategy = fresh;
2914                    *cursor = Cursor::new(id, start);
2915                }
2916                Opened::Merged(asset_ref) => return Ok(StepTaken::Merged(asset_ref)),
2917            }
2918        }
2919        Ok(StepTaken::Continue)
2920    }
2921
2922    /// Cancel a session whose source changed: nothing more of it can be sent, and its committed
2923    /// bytes can never finalize to the declared hash. Best effort — a session the server already
2924    /// discarded or is finalizing is left to its own end.
2925    async fn cancel_after_source_change(&self, session_id: &str, changed: &SourceChanged) {
2926        tracing::warn!(%session_id, reason = %changed.reason, "the upload source changed; cancelling its session");
2927        if let Err(error) = self.delete(session_id).await {
2928            tracing::warn!(%session_id, %error, "the session of a changed source could not be cancelled; it expires on its own");
2929        }
2930    }
2931
2932    /// Wait for the server to finish finalizing `session_id`, polling `HEAD` with backoff.
2933    ///
2934    /// `state` is the session's state as the answers reported it. An older server finalized
2935    /// before it answered the completing chunk and sends no state, so its accepted final chunk
2936    /// is the outcome, and `completed` is one too. Every other state is polled: a session still
2937    /// `uploading` once every range was answered may have lost a record the client was told it
2938    /// held, and `HEAD` either starts its finalization or names what to send again. A `HEAD` the
2939    /// server asks to wait is waited out under the transfer's
2940    /// recovery budget; the poll itself charges nothing and is bounded by
2941    /// [`FINALIZE_POLL_DEADLINE`], past which it gives up with [`UploadError::WaitsExhausted`]:
2942    /// a server that answered every poll is slow, not a stuck link.
2943    async fn settle(
2944        &self,
2945        session_id: &str,
2946        size: u64,
2947        state: Option<&str>,
2948        recovery: &mut Recovery<'_>,
2949    ) -> Result<Settled, UploadError> {
2950        if matches!(state, None | Some(STATUS_COMPLETED)) {
2951            tracing::debug!(%session_id, ?state, "no finalization to wait for");
2952            return Ok(Settled::Done(UploadOutcome::Completed {
2953                session_id: session_id.to_owned(),
2954            }));
2955        }
2956        let mut wait = FINALIZE_POLL_FIRST;
2957        let mut waited = Duration::ZERO;
2958        let mut polls: u32 = 0;
2959        // Whether the session is known to have reached finalization: a session that goes away
2960        // before that is one to re-create, after it a failure.
2961        let mut finalizing = matches!(state, Some(STATUS_WAITING | STATUS_FAILED));
2962        loop {
2963            polls += 1;
2964            let Some(info) = self.head_waiting(session_id, recovery).await? else {
2965                if !finalizing {
2966                    tracing::info!(%session_id, polls, "the session went away before it finalized; re-creating");
2967                    return Ok(Settled::Lost);
2968                }
2969                tracing::warn!(%session_id, polls, "the session went away while it finalized");
2970                return Err(UploadError::Rejected {
2971                    status: 404,
2972                    code: Some(error_codes::UPLOAD_SESSION_NOT_FOUND.to_owned()),
2973                    message: format!("session {session_id} went away while it finalized"),
2974                });
2975            };
2976            match info.status.as_str() {
2977                STATUS_COMPLETED => {
2978                    tracing::info!(%session_id, polls, waited_ms = millis(waited), "the server finalized the upload");
2979                    return Ok(Settled::Done(UploadOutcome::Completed {
2980                        session_id: session_id.to_owned(),
2981                    }));
2982                }
2983                STATUS_FAILED => {
2984                    tracing::warn!(%session_id, polls, code = ?info.error_code, "the server refused the upload at finalization");
2985                    let message = format!(
2986                        "the server refused session {session_id} at finalization ({})",
2987                        info.error_code.as_deref().unwrap_or("no code given")
2988                    );
2989                    let hash_refused = info.error_code.as_deref()
2990                        == Some(error_codes::UPLOAD_CONTENT_HASH_MISMATCH);
2991                    let refusal = UploadError::Rejected {
2992                        status: 200,
2993                        code: info.error_code,
2994                        message,
2995                    };
2996                    if hash_refused {
2997                        return Ok(Settled::HashMismatch(refusal));
2998                    }
2999                    return Err(refusal);
3000                }
3001                STATUS_WAITING => finalizing = true,
3002                // Full and not yet claimed: this `HEAD` started its finalization, and the next
3003                // one reads how it went. Short of full, the transfer re-plans from what it holds.
3004                _ => {
3005                    let held = info
3006                        .committed
3007                        .clone()
3008                        .unwrap_or_else(|| CommittedSet::prefix(info.offset.min(size)));
3009                    if !held.covers(size) {
3010                        return Ok(Settled::Resume(held));
3011                    }
3012                    finalizing = true;
3013                }
3014            }
3015            if waited >= FINALIZE_POLL_DEADLINE {
3016                // The server answered every poll; it is slow to finalize, not unreachable. That
3017                // is a wait the server asked for, never a stuck link.
3018                tracing::warn!(%session_id, polls, waited_ms = millis(waited), status = %info.status, "the server was still finalizing at the poll deadline; giving up waiting");
3019                return Err(UploadError::WaitsExhausted {
3020                    status: 200,
3021                    code: None,
3022                    message: format!("session {session_id} is still {}", info.status),
3023                    reason: format!(
3024                        "the finalization poll gave up after {polls} polls over {}s",
3025                        waited.as_secs()
3026                    ),
3027                });
3028            }
3029            tracing::debug!(%session_id, polls, ?wait, status = %info.status, "finalizing; polling HEAD again");
3030            self.sleeper.sleep(wait).await;
3031            waited += wait;
3032            wait = (wait * 2).min(FINALIZE_POLL_MAX);
3033        }
3034    }
3035
3036    fn emit_created(&self, request: &CreateUploadRequest, session_id: &str, resume_offset: u64) {
3037        self.events.emit(|| TransferEvent::SessionCreated {
3038            blob: request.hash.clone(),
3039            session_id: session_id.to_string(),
3040            size: request.size,
3041            resume_offset,
3042        });
3043    }
3044
3045    fn emit_merged(&self, request: &CreateUploadRequest, asset_ref: &str) {
3046        self.events.emit(|| TransferEvent::Merged {
3047            blob: request.hash.clone(),
3048            asset_ref: asset_ref.to_string(),
3049        });
3050    }
3051
3052    /// The backoff after a mid-transfer transport reset — or a chunk at the protocol minimum that
3053    /// got no answer — through the shared retry engine. The scheduler waits it out once every
3054    /// range in flight has returned, then reads `HEAD` before it sends anything again. The
3055    /// `(offset, len)` pair names the chunk that was cut.
3056    ///
3057    /// # Errors
3058    ///
3059    /// [`UploadError::RetriesExhausted`] once the engine gives up, or the server lane's shared
3060    /// retry budget is spent: a bounded give-up keeps a dead path from becoming a hot loop.
3061    fn reset_backoff(
3062        &self,
3063        recovery: &mut Recovery<'_>,
3064        request: &CreateUploadRequest,
3065        session_id: &str,
3066        (offset, len): (u64, u64),
3067        reason: &str,
3068    ) -> Result<Duration, UploadError> {
3069        recovery.spend_lane("transport reset")?;
3070        match recovery.engine.next_backoff(None) {
3071            RetryDecision::GiveUp => Err(UploadError::RetriesExhausted(format!(
3072                "transport reset unrecovered after {} retries: {reason}",
3073                recovery.engine.policy().max_retries
3074            ))),
3075            RetryDecision::Retry { after } => {
3076                tracing::debug!(offset, ?after, %reason, "mid-transfer reset — backing off, then reading HEAD");
3077                self.emit_retried(
3078                    request,
3079                    session_id,
3080                    offset,
3081                    len,
3082                    RetryReason::TransportReset {
3083                        wait_ms: millis(after),
3084                    },
3085                );
3086                Ok(after)
3087            }
3088        }
3089    }
3090
3091    fn emit_retried(
3092        &self,
3093        request: &CreateUploadRequest,
3094        session_id: &str,
3095        offset: u64,
3096        len: u64,
3097        reason: RetryReason,
3098    ) {
3099        self.events.emit(|| TransferEvent::ChunkRetried {
3100            blob: request.hash.clone(),
3101            session_id: session_id.to_string(),
3102            offset,
3103            len,
3104            reason,
3105        });
3106    }
3107}
3108
3109/// `426`, or the stable `error.protocol.version_unsupported` code. The code is
3110/// authoritative; the bare `426` is a defensive fallback.
3111fn is_upgrade_required(status: u16, code: Option<&str>) -> bool {
3112    code == Some(error_codes::PROTOCOL_VERSION_UNSUPPORTED) || status == 426
3113}
3114
3115/// Fail loudly once the bounded recovery budget is spent.
3116fn guard_budget(recoveries: u32, action: &str) -> Result<(), UploadError> {
3117    if recoveries > MAX_RECOVERIES {
3118        Err(UploadError::RetriesExhausted(format!(
3119            "{action}: exceeded {MAX_RECOVERIES} recovery attempts"
3120        )))
3121    } else {
3122        Ok(())
3123    }
3124}
3125
3126/// Read an error response into its code, message and headers — the headers for the window an
3127/// upgrade refusal carries — and a `duplicate_blob`'s structured `existing_asset`. Tolerates a
3128/// non-JSON (plain-text) body — such responses simply carry no code.
3129async fn read_error(resp: reqwest::Response) -> Result<ErrorAnswer, UploadError> {
3130    let headers = resp.headers().clone();
3131    let text = resp.text().await?;
3132    match serde_json::from_str::<ApiErrorBody>(&text) {
3133        Ok(body) => {
3134            let message = if body.error.is_empty() {
3135                text
3136            } else {
3137                body.error
3138            };
3139            Ok(ErrorAnswer {
3140                code: body.code,
3141                message,
3142                headers,
3143                existing_asset: body.existing_asset,
3144            })
3145        }
3146        Err(_) => Ok(ErrorAnswer {
3147            code: None,
3148            message: text,
3149            headers,
3150            existing_asset: None,
3151        }),
3152    }
3153}
3154
3155/// The committed set an answer carries on `X-Capsule-Committed`, for a session of `size` bytes.
3156/// Absent from an older server; a malformed one is ignored, never planned from.
3157fn committed_of(headers: &reqwest::header::HeaderMap, size: u64) -> Option<CommittedSet> {
3158    let raw = header_str(headers, "X-Capsule-Committed")?;
3159    let parsed = CommittedSet::parse(&raw, size);
3160    if parsed.is_none() {
3161        tracing::warn!(header = %raw, size, "ignoring a malformed X-Capsule-Committed");
3162    }
3163    parsed
3164}
3165
3166fn header_str(headers: &reqwest::header::HeaderMap, name: &str) -> Option<String> {
3167    headers
3168        .get(name)
3169        .and_then(|v| v.to_str().ok())
3170        .map(str::to_string)
3171}
3172
3173fn header_u64(headers: &reqwest::header::HeaderMap, name: &str) -> Option<u64> {
3174    header_str(headers, name).and_then(|s| s.parse().ok())
3175}
3176
3177/// The advice and the relative expiry a session create or `HEAD` carries, read leniently: a
3178/// server that sends neither, or sends them malformed, leaves the client on its own defaults.
3179fn advice_of(headers: &reqwest::header::HeaderMap) -> (ServerAdvice, SessionExpiry) {
3180    let advice = ServerAdvice::parse(header_str(headers, advice::ADVICE_HEADER).as_deref());
3181    let expiry = SessionExpiry::parse(
3182        header_str(headers, advice::EXPIRES_IN_HEADER).as_deref(),
3183        header_str(headers, advice::IDLE_EXPIRES_IN_HEADER).as_deref(),
3184    );
3185    (advice, expiry)
3186}
3187
3188#[cfg(test)]
3189mod tests;