capsule_sdk/net.rs
1//! Connection-class and retry-policy contract types (SSoT: the Network
2//! Resilience design doc). Detection (OS signals + behavioral promotion to
3//! [`ConnectionClass::Adverse`]) and the per-class retry engines
4//! live here: class detection feeds the sync and cache budgets, and the adverse class hardens
5//! the network behaviour.
6//!
7//! This module fills the `capsule-sdk::net` seam named by the networking doc:
8//! it maps **mocked OS path signals** ([`PathSignals`]) to a base
9//! [`ConnectionClass`], layers the behavioral **`adverse` promotion/demotion**
10//! ([`AdverseDetector`]) on top, and exposes the two gate surfaces the class
11//! feeds — the **staged-upload tier gates** ([`ConnectionClass::permits_tier`],
12//! over the canonical [`UploadTier`]) and the **cache-eviction byte budget**
13//! ([`ConnectionClass::cache_retention_budget`], which [`crate::cache_budget`] feeds to the
14//! eviction sweep). Detection is signal-driven,
15//! never a live NIC probe, so every rule is a deterministic unit test.
16
17use std::collections::VecDeque;
18use std::sync::{Arc, Mutex, PoisonError};
19use std::time::{Duration, Instant};
20
21use capsule_library::import::UploadTier;
22use tracing::instrument;
23
24pub mod h3;
25pub mod negotiation;
26pub mod path;
27
28/// The closed connection-class enum, evaluated continuously on-device.
29/// Consumers: sync criteria (small/large reconciliation), staged-upload tier
30/// gates, the cache-eviction byte budget, prefetch, adaptive chunk sizing.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum ConnectionClass {
33 /// Bulk transfer is acceptable.
34 Unmetered,
35 /// Byte-counted link; bulk work is deferred.
36 Metered,
37 /// OS-level data saver (iOS Low Data Mode / Android Data Saver).
38 Constrained,
39 /// Connectivity present but unreliable — behavioral promotion on repeated
40 /// mid-transfer resets/stalls within a sliding window; demoted after a
41 /// clean period. No OS reports this class; it is derived.
42 Adverse,
43 /// No usable path.
44 Offline,
45}
46
47/// The mocked OS path signals a platform samples to classify the current link.
48///
49/// Named after the platform detection inputs in the networking doc's
50/// connection-class table: iOS `NWPathMonitor` (`isExpensive`, `isConstrained`),
51/// Android `NET_CAPABILITY_NOT_METERED` / Data Saver, desktop default. Tests
52/// drive [`ConnectionClass::from_signals`] with these directly — there is no live
53/// NIC probing anywhere in the crate.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct PathSignals {
56 /// The OS reports a usable network path at all (`false` ⇒ `offline`).
57 pub has_path: bool,
58 /// iOS `isExpensive` / a metered cellular capability is present.
59 pub is_expensive: bool,
60 /// Android `NET_CAPABILITY_NOT_METERED` is present (an explicitly unmetered
61 /// link). Absent metered capability alone is treated as metered.
62 pub not_metered_capability: bool,
63 /// OS-level data saver is active (iOS Low Data Mode / Android Data Saver).
64 pub is_constrained: bool,
65}
66
67impl PathSignals {
68 /// The desktop / wired default: a usable, unmetered, unconstrained path.
69 #[must_use]
70 pub fn unmetered() -> Self {
71 Self {
72 has_path: true,
73 is_expensive: false,
74 not_metered_capability: true,
75 is_constrained: false,
76 }
77 }
78
79 /// No usable path at all.
80 #[must_use]
81 pub fn offline() -> Self {
82 Self {
83 has_path: false,
84 is_expensive: true,
85 not_metered_capability: false,
86 is_constrained: false,
87 }
88 }
89}
90
91impl ConnectionClass {
92 /// Map sampled OS signals to the **base** class, before any behavioral
93 /// promotion to [`ConnectionClass::Adverse`] (which no OS reports — see
94 /// [`AdverseDetector`]).
95 ///
96 /// Precedence is deliberate and total: no path ⇒ `offline`; else data saver
97 /// ⇒ `constrained` (the strongest user "minimize data" signal wins over a
98 /// merely metered link); else an expensive / not-explicitly-unmetered link ⇒
99 /// `metered`; else `unmetered`. `constrained` and `metered` are always
100 /// distinguished (networking doc Validation: "class detection").
101 #[must_use]
102 pub fn from_signals(signals: PathSignals) -> Self {
103 if !signals.has_path {
104 Self::Offline
105 } else if signals.is_constrained {
106 Self::Constrained
107 } else if signals.is_expensive || !signals.not_metered_capability {
108 Self::Metered
109 } else {
110 Self::Unmetered
111 }
112 }
113
114 /// Whether any usable path exists (every class but [`ConnectionClass::Offline`]).
115 #[must_use]
116 pub fn is_usable(self) -> bool {
117 self != Self::Offline
118 }
119
120 /// Whether the link is treated as **non-metered** for tier and reconciliation
121 /// gating.
122 ///
123 /// Only [`ConnectionClass::Unmetered`] qualifies: its definition is precisely
124 /// "bulk transfer is acceptable". [`ConnectionClass::Metered`] (byte-counted)
125 /// and [`ConnectionClass::Constrained`] (data saver) are byte-conscious, and
126 /// [`ConnectionClass::Adverse`] is unreliable — so above-index tiers defer on
127 /// all three, matching the tier ladder's "even constrained/adverse" T0 row and
128 /// the adverse posture's "the staged-upload T0 index still escapes over the
129 /// thin link".
130 #[must_use]
131 pub fn is_non_metered(self) -> bool {
132 self == Self::Unmetered
133 }
134
135 /// Whether a staged-upload tier may open on this connection.
136 ///
137 /// Mirrors the download/upload tier ladder (transfer upload doc, "Upload
138 /// Tiering"): T0 index escapes on any usable connection (a few KB per asset);
139 /// T1 preview and T2 original need a non-metered link — or an explicit
140 /// user-consented `force_sync`, which overrides the metered/Wi-Fi criteria but
141 /// never resurrects an offline path.
142 #[must_use]
143 pub fn permits_tier(self, tier: UploadTier, force_sync: bool) -> bool {
144 match tier {
145 UploadTier::Index => self.is_usable(),
146 UploadTier::Preview | UploadTier::Original => {
147 self.is_usable() && (self.is_non_metered() || force_sync)
148 }
149 }
150 }
151
152 /// Whether a reconciliation of the given size may run now (sync criteria:
153 /// small vs. large). Small (a handful of assets / metadata deltas) and large
154 /// (bulk originals) both require a non-metered link; `force_sync` is the
155 /// two-week-staleness "force sync now" consent that overrides it. The extra
156 /// deferral of a large reconciliation (idle/on-power scheduling) is the
157 /// scheduler's concern, layered above this connection gate.
158 #[must_use]
159 pub fn permits_reconciliation(self, class: ReconciliationClass, force_sync: bool) -> bool {
160 let _ = class;
161 self.is_usable() && (self.is_non_metered() || force_sync)
162 }
163
164 /// The cache-eviction **byte budget** for this class, from a base budget.
165 ///
166 /// The budget is the ceiling of cache bytes the client retains before the
167 /// last-access eviction sweep (owned by Filesystem — Client) reclaims space.
168 /// It scales inversely with re-fetch cost: on an [`ConnectionClass::Unmetered`]
169 /// link re-fetching an evicted blob is cheap, so the client keeps the tight
170 /// base budget and evicts freely; on byte-conscious, unreliable, or offline
171 /// links re-fetch is expensive or impossible, so it retains more. The
172 /// multipliers are client-tunable policy, not protocol surface; only their
173 /// monotonicity (`unmetered ≤ metered/constrained ≤ adverse ≤ offline`) is a
174 /// contract.
175 #[must_use]
176 pub fn cache_retention_budget(self, base_budget_bytes: u64) -> u64 {
177 let multiplier = match self {
178 Self::Unmetered => 1,
179 Self::Metered | Self::Constrained => 2,
180 Self::Adverse => 3,
181 Self::Offline => 4,
182 };
183 base_budget_bytes.saturating_mul(multiplier)
184 }
185
186 /// The **bounded `Range` window** a blob fetch uses on this class, or `None`
187 /// for the open-ended remainder.
188 ///
189 /// Adverse-network posture (networking doc, "Bounded transfer windows under
190 /// `adverse`"): only [`ConnectionClass::Adverse`] shrinks fetches to a bounded
191 /// window ([`ADVERSE_RANGE_WINDOW`]) so each request is small enough to usually
192 /// complete between mid-transfer resets; every other class fetches the whole
193 /// remaining range in one request (`None`). The window size is client-tunable
194 /// policy, not protocol surface.
195 #[must_use]
196 pub fn range_window(self) -> Option<u64> {
197 match self {
198 Self::Adverse => Some(ADVERSE_RANGE_WINDOW),
199 _ => None,
200 }
201 }
202}
203
204/// The bounded `Range` window (256 KiB) a blob fetch shrinks to under
205/// [`ConnectionClass::Adverse`]. Small enough that a single window usually
206/// completes between the mid-transfer resets that define an adverse path;
207/// client-tunable policy, not protocol surface.
208pub const ADVERSE_RANGE_WINDOW: u64 = 256 * 1024;
209
210/// The size class of a pending reconciliation (sync criteria). Scales with the
211/// total upload + download transfer amount.
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub enum ReconciliationClass {
214 /// A handful of new assets, or metadata-only deltas.
215 Small,
216 /// Bulk uploads, or original-tier downloads (also a storage-constrained
217 /// streaming import).
218 Large,
219}
220
221/// An observed transfer outcome, fed to the [`AdverseDetector`]. A reset, stall,
222/// or black-hole counts toward `adverse`; a clean completion counts toward
223/// demotion.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum TransferSignal {
226 /// The transfer chunk/window completed cleanly.
227 Clean,
228 /// The connection reset mid-transfer.
229 Reset,
230 /// A stall (no bytes for the stall bound) cut the transfer.
231 Stall,
232 /// The request was silently black-holed (no response, no error).
233 BlackHole,
234}
235
236impl TransferSignal {
237 /// Whether this outcome counts toward `adverse` promotion.
238 #[must_use]
239 fn is_adverse(self) -> bool {
240 !matches!(self, Self::Clean)
241 }
242}
243
244/// Tunable thresholds for behavioral [`ConnectionClass::Adverse`] promotion. Not
245/// protocol surface — a client picks values to match its network posture.
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub struct AdverseThresholds {
248 /// Size of the sliding window (most-recent transfer outcomes considered).
249 pub window: usize,
250 /// Adverse outcomes within the window that promote to `adverse`.
251 pub promote_at: usize,
252 /// Consecutive clean outcomes that demote back out of `adverse`.
253 pub demote_after_clean: usize,
254}
255
256impl Default for AdverseThresholds {
257 fn default() -> Self {
258 // Conservative defaults: three bad outcomes in the last eight promote;
259 // four clean transfers in a row demote.
260 Self {
261 window: 8,
262 promote_at: 3,
263 demote_after_clean: 4,
264 }
265 }
266}
267
268/// The behavioral `adverse` detector: a deterministic sliding-window state
269/// machine over recent transfer outcomes.
270///
271/// No OS reports `adverse` — the networks that need it most look "connected" to
272/// every OS API — so it is *derived*: `≥ promote_at` reset/stall/black-hole
273/// outcomes within the last `window` transfers promote the link to `adverse`
274/// (which bounds fetch windows and pins staged uploads to the index tier), and a
275/// run of `demote_after_clean` clean transfers demotes it back. Being event-
276/// driven rather than clock-driven, it is fully deterministic under test.
277#[derive(Debug, Clone)]
278pub struct AdverseDetector {
279 thresholds: AdverseThresholds,
280 recent: VecDeque<TransferSignal>,
281 consecutive_clean: usize,
282 adverse: bool,
283}
284
285impl AdverseDetector {
286 /// A fresh detector with the given thresholds, starting non-adverse.
287 #[must_use]
288 pub fn new(thresholds: AdverseThresholds) -> Self {
289 Self {
290 thresholds,
291 recent: VecDeque::with_capacity(thresholds.window.max(1)),
292 consecutive_clean: 0,
293 adverse: false,
294 }
295 }
296
297 /// A detector with the [default thresholds](AdverseThresholds::default).
298 #[must_use]
299 pub fn with_defaults() -> Self {
300 Self::new(AdverseThresholds::default())
301 }
302
303 /// Fold one transfer outcome into the window and recompute the state.
304 pub fn record(&mut self, signal: TransferSignal) {
305 if self.recent.len() == self.thresholds.window {
306 self.recent.pop_front();
307 }
308 self.recent.push_back(signal);
309
310 if signal.is_adverse() {
311 self.consecutive_clean = 0;
312 } else {
313 self.consecutive_clean += 1;
314 }
315
316 if self.adverse {
317 // Demote only after a sustained clean run.
318 if self.consecutive_clean >= self.thresholds.demote_after_clean {
319 self.adverse = false;
320 self.recent.clear();
321 }
322 } else {
323 let adverse_in_window = self.recent.iter().filter(|s| s.is_adverse()).count();
324 if adverse_in_window >= self.thresholds.promote_at {
325 self.adverse = true;
326 self.consecutive_clean = 0;
327 }
328 }
329 }
330
331 /// Forget every outcome observed so far and return to non-adverse: the link they were
332 /// observed on is gone ([`path::PathMonitor::observe`] calls this on a new path).
333 pub fn reset(&mut self) {
334 self.recent.clear();
335 self.consecutive_clean = 0;
336 self.adverse = false;
337 }
338
339 /// Whether the link is currently promoted to `adverse`.
340 #[must_use]
341 pub fn is_adverse(&self) -> bool {
342 self.adverse
343 }
344
345 /// The effective class: `offline` is never overridden; any other base class is
346 /// promoted to [`ConnectionClass::Adverse`] while the detector is tripped.
347 #[must_use]
348 pub fn classify(&self, base: ConnectionClass) -> ConnectionClass {
349 if base == ConnectionClass::Offline || !self.adverse {
350 base
351 } else {
352 ConnectionClass::Adverse
353 }
354 }
355}
356
357/// The three retry policy classes every retrying surface instantiates.
358/// Universal rules (owned by the Network Resilience doc): exponential backoff
359/// with full jitter, honor server backoff signals, bounded give-up surfaced to
360/// the user, never hot-loop.
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362pub enum RetryClass {
363 /// Short timeout, ≤ 2 retries, then a visible failure state.
364 Interactive,
365 /// Resume-first (HEAD offset / Range), patient within the session lifetime.
366 BulkTransfer,
367 /// Slow ladder, long horizon, never abandons silently (MLS recovery,
368 /// federation circuit breaker are instances).
369 ControlCeremony,
370}
371
372impl RetryClass {
373 /// The canonical [`RetryPolicy`] for this class (networking doc, "Retry Policy
374 /// Classes"). The three per-doc retry ladders are *instances of this shared
375 /// shape*, not reinventions — sync, upload, and fetch each build a
376 /// [`RetryEngine`] from one of these.
377 #[must_use]
378 pub fn policy(self) -> RetryPolicy {
379 match self {
380 // Short timeout, ≤ 2 retries, then a visible failure state.
381 Self::Interactive => RetryPolicy {
382 max_retries: 2,
383 base_delay: Duration::from_millis(200),
384 max_delay: Duration::from_secs(2),
385 },
386 // Resume-first and patient within the session's lifetime.
387 Self::BulkTransfer => RetryPolicy {
388 max_retries: 8,
389 base_delay: Duration::from_millis(500),
390 max_delay: Duration::from_secs(30),
391 },
392 // Slow ladder, long horizon, never abandons silently.
393 Self::ControlCeremony => RetryPolicy {
394 max_retries: 12,
395 base_delay: Duration::from_secs(30),
396 max_delay: Duration::from_secs(600),
397 },
398 }
399 }
400
401 /// A fresh [`RetryEngine`] instance for this class, with production full-jitter
402 /// seeded from the wall clock. The single constructor sync/upload/fetch call.
403 #[must_use]
404 pub fn engine(self) -> RetryEngine {
405 RetryEngine::new(self)
406 }
407}
408
409// ─── Shared retry engine ─────────────────────────────────────────────────────
410
411/// The concrete parameters of a [`RetryClass`]: a bounded retry count and the
412/// exponential-backoff envelope. `max_retries` is finite by type, so no policy —
413/// and therefore no surface instantiating one — can ever hot-loop (networking doc:
414/// "every retry loop has a bounded give-up"; "no surface ever hot-loops").
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub struct RetryPolicy {
417 /// Attempts after the first failure before a visible give-up.
418 pub max_retries: u32,
419 /// The first backoff ceiling; doubles each attempt up to `max_delay`.
420 pub base_delay: Duration,
421 /// The backoff ceiling cap (the doubling never exceeds this).
422 pub max_delay: Duration,
423}
424
425/// The engine's decision after one failure.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427pub enum RetryDecision {
428 /// Wait `after` (already jittered and reconciled with any server hint), then
429 /// retry.
430 Retry {
431 /// The reconciled backoff for this attempt.
432 after: Duration,
433 },
434 /// The bounded retry budget is spent — surface a user-visible failure state.
435 GiveUp,
436}
437
438/// The randomness source for **full jitter**. Production draws a spread value in
439/// `[0, 1)`; tests pin a fixed fraction so the whole backoff sequence is
440/// deterministic.
441#[derive(Debug, Clone)]
442enum Jitter {
443 /// An `xorshift64*` state, advanced per draw (fast, dependency-free spread).
444 Random(u64),
445 /// A fixed fraction in `[0, 1]`, for deterministic tests.
446 Fixed(f64),
447}
448
449impl Jitter {
450 /// The next jitter fraction in `[0, 1)` (or the pinned fixed value).
451 fn next_fraction(&mut self) -> f64 {
452 match self {
453 Self::Random(state) => {
454 // xorshift64*: cheap, well-distributed, and enough for jitter
455 // (this is spread, not security). Kept nonzero at construction.
456 let mut x = *state;
457 x ^= x >> 12;
458 x ^= x << 25;
459 x ^= x >> 27;
460 *state = x;
461 let v = x.wrapping_mul(0x2545_f491_4f6c_dd1d);
462 // Top 53 bits → a double in [0, 1).
463 (v >> 11) as f64 / ((1u64 << 53) as f64)
464 }
465 Self::Fixed(fraction) => *fraction,
466 }
467 }
468}
469
470/// The one shared retry engine every retrying surface instantiates
471/// ([`RetryClass::engine`]). It owns the universal rules so no surface re-derives
472/// them: **exponential backoff with full jitter**, honoring a server backoff
473/// signal (`Retry-After` / 429 / 503) as a floor, and a **bounded give-up** after
474/// `max_retries` — never an unbounded hot loop.
475///
476/// The engine is a pure state machine over the attempt counter and the jitter
477/// source: [`RetryEngine::next_backoff`] computes the wait and the give-up without
478/// sleeping, so backoff discipline is a deterministic unit test. Callers perform
479/// the wait through a [`Sleeper`] (real in production, a no-op recorder in tests).
480#[derive(Debug, Clone)]
481pub struct RetryEngine {
482 class: RetryClass,
483 policy: RetryPolicy,
484 attempt: u32,
485 jitter: Jitter,
486}
487
488impl RetryEngine {
489 /// A production engine for `class`, full-jitter seeded from the wall clock.
490 #[must_use]
491 pub fn new(class: RetryClass) -> Self {
492 Self::with_jitter(class, Jitter::Random(seed()))
493 }
494
495 /// A deterministic engine that always jitters by the fixed `fraction`
496 /// (clamped to `[0, 1]`) — for tests that assert exact backoff values.
497 #[must_use]
498 pub fn deterministic(class: RetryClass, fraction: f64) -> Self {
499 Self::with_jitter(class, Jitter::Fixed(fraction.clamp(0.0, 1.0)))
500 }
501
502 /// A production-shaped engine (full jitter) with a fixed seed — for tests that
503 /// assert the *spread* property of full jitter deterministically.
504 #[must_use]
505 pub fn seeded(class: RetryClass, seed: u64) -> Self {
506 Self::with_jitter(class, Jitter::Random(seed | 1))
507 }
508
509 fn with_jitter(class: RetryClass, jitter: Jitter) -> Self {
510 Self {
511 class,
512 policy: class.policy(),
513 attempt: 0,
514 jitter,
515 }
516 }
517
518 /// The class this engine instantiates.
519 #[must_use]
520 pub fn class(&self) -> RetryClass {
521 self.class
522 }
523
524 /// The policy bounds this engine enforces.
525 #[must_use]
526 pub fn policy(&self) -> RetryPolicy {
527 self.policy
528 }
529
530 /// Failures observed so far (retries consumed).
531 #[must_use]
532 pub fn attempts(&self) -> u32 {
533 self.attempt
534 }
535
536 /// Reset the attempt counter after real progress, so a long-lived transfer's
537 /// backoff does not ratchet across independent stalls (resume-first: each
538 /// resumed window earns a fresh budget).
539 pub fn reset(&mut self) {
540 self.attempt = 0;
541 }
542
543 /// The un-jittered backoff ceiling for the *next* attempt: `base · 2^attempt`,
544 /// saturating and capped at `max_delay`.
545 fn ceiling(&self) -> Duration {
546 let base_ms = self.policy.base_delay.as_millis() as u64;
547 let cap_ms = self.policy.max_delay.as_millis() as u64;
548 // Cap the exponent so the shift never overflows before the min() clamps it.
549 let exp = self.attempt.min(32);
550 let scaled = base_ms.saturating_mul(1u64.checked_shl(exp).unwrap_or(u64::MAX));
551 Duration::from_millis(scaled.min(cap_ms))
552 }
553
554 /// Decide the next action after a failure, folding in an optional server
555 /// backoff hint (`Retry-After` / 429 / 503).
556 ///
557 /// Returns [`RetryDecision::GiveUp`] once the bounded budget is spent (so no
558 /// configuration can hot-loop). Otherwise the wait is **full jitter** over the
559 /// ceiling — a uniform draw in `[0, ceiling]` — reconciled with the server hint
560 /// as a *floor* (`Retry-After` is honored even when it exceeds the jittered
561 /// value). The ceiling itself is bounded by `max_delay`, so the client-chosen
562 /// component of the wait never exceeds the policy cap.
563 #[instrument(level = "trace", skip(self), fields(class = ?self.class, attempt = self.attempt))]
564 pub fn next_backoff(&mut self, server_backoff: Option<Duration>) -> RetryDecision {
565 if self.attempt >= self.policy.max_retries {
566 tracing::debug!(
567 max_retries = self.policy.max_retries,
568 "retry budget exhausted — giving up (visible failure state)"
569 );
570 return RetryDecision::GiveUp;
571 }
572 let ceiling = self.ceiling();
573 self.attempt += 1;
574 let fraction = self.jitter.next_fraction().clamp(0.0, 1.0);
575 let jittered = ceiling.mul_f64(fraction);
576 // The server's backoff signal is a floor we always honor; the jittered
577 // value is our own spread. Take the larger.
578 let after = match server_backoff {
579 Some(hint) => jittered.max(hint),
580 None => jittered,
581 };
582 tracing::trace!(?after, ?ceiling, "backing off before retry");
583 RetryDecision::Retry { after }
584 }
585}
586
587// ─── Retry classification ────────────────────────────────────────────────────
588
589/// What one failed request permits, decided before any retry is taken (networking doc, Retry
590/// Policy Classes: "errors are classified before any retry").
591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
592pub enum RetryVerdict {
593 /// A transient failure: a transport failure, any `5xx`, `408`, `425` or `429`. It may be
594 /// retried under the surface's class, its item's attempt cap and the lane's retry budget.
595 Retryable,
596 /// A contract `4xx` the recovery matrix names an action for (re-align, re-create, re-send,
597 /// merge): the client takes that action, and it charges the same budgets a retry does.
598 Recover,
599 /// A contract refusal the recovery matrix names no action for, or an answer that is not a
600 /// failure at all: surfaced, never retried.
601 Terminal,
602}
603
604impl RetryVerdict {
605 /// A request that got no answer: the connection failed, reset, or timed out.
606 #[must_use]
607 pub const fn of_transport() -> Self {
608 Self::Retryable
609 }
610
611 /// An answer with HTTP `status`. `recovery_names_action` says whether the recovery matrix
612 /// names an action for the `error.*` code the answer carried; it only matters for a `4xx`
613 /// outside the transient set, because a transient status is retryable whatever its code.
614 #[must_use]
615 pub const fn of_status(status: u16, recovery_names_action: bool) -> Self {
616 match status {
617 408 | 425 | 429 | 500..=599 => Self::Retryable,
618 400..=499 if recovery_names_action => Self::Recover,
619 _ => Self::Terminal,
620 }
621 }
622
623 /// Whether this verdict permits another request at all.
624 #[must_use]
625 pub const fn permits_retry(self) -> bool {
626 !matches!(self, Self::Terminal)
627 }
628}
629
630// ─── Lane retry budget ───────────────────────────────────────────────────────
631
632/// The retries one server lane may take while nothing succeeds. Twice an upload's own
633/// recovery cap, so a single item's attempt cap binds before the lane's budget does and the
634/// budget only bites when several items fail against the same server.
635pub const DEFAULT_LANE_RETRY_BUDGET: u32 = 128;
636
637/// Successes that earn one retry back, up to the budget's capacity. Two bounds the retries a
638/// steadily working lane adds to half its successful requests.
639pub const LANE_SUCCESSES_PER_RETRY: u32 = 2;
640
641/// One server lane's shared retry budget (networking doc, Retry Policy Classes: "each server
642/// lane holds one shared retry budget").
643///
644/// Every retry any item on the lane takes spends one token; successes earn tokens back, one per
645/// [`LANE_SUCCESSES_PER_RETRY`], never above the capacity. A server that fails every request
646/// therefore costs at most `capacity` retries in total, however many items are queued for it,
647/// rather than one full retry ladder per item. A pure value; [`LaneRetries`] shares one.
648#[derive(Debug, Clone, Copy, PartialEq, Eq)]
649pub struct LaneRetryBudget {
650 capacity: u32,
651 tokens: u32,
652 /// Successes counted toward the next earned token.
653 successes: u32,
654}
655
656impl Default for LaneRetryBudget {
657 fn default() -> Self {
658 Self::new(DEFAULT_LANE_RETRY_BUDGET)
659 }
660}
661
662impl LaneRetryBudget {
663 /// A full budget of `capacity` retries. Zero is a lane that never retries.
664 #[must_use]
665 pub const fn new(capacity: u32) -> Self {
666 Self {
667 capacity,
668 tokens: capacity,
669 successes: 0,
670 }
671 }
672
673 /// The most retries the budget ever holds.
674 #[must_use]
675 pub const fn capacity(&self) -> u32 {
676 self.capacity
677 }
678
679 /// The retries left before the lane stops retrying.
680 #[must_use]
681 pub const fn remaining(&self) -> u32 {
682 self.tokens
683 }
684
685 /// Spend one retry. `false` means the budget is spent: the caller must not retry, and gives
686 /// the item up as the failure it is.
687 pub fn try_spend(&mut self) -> bool {
688 if self.tokens == 0 {
689 tracing::debug!(
690 capacity = self.capacity,
691 "lane retry budget spent; refusing a retry"
692 );
693 return false;
694 }
695 self.tokens -= 1;
696 tracing::trace!(
697 remaining = self.tokens,
698 "lane retry budget: one retry spent"
699 );
700 true
701 }
702
703 /// Record one request that succeeded, earning a retry back every
704 /// [`LANE_SUCCESSES_PER_RETRY`] successes.
705 pub fn record_success(&mut self) {
706 if self.tokens >= self.capacity {
707 self.successes = 0;
708 return;
709 }
710 self.successes += 1;
711 if self.successes >= LANE_SUCCESSES_PER_RETRY {
712 self.successes = 0;
713 self.tokens += 1;
714 tracing::trace!(
715 remaining = self.tokens,
716 "lane retry budget: one retry earned back"
717 );
718 }
719 }
720}
721
722/// A [`LaneRetryBudget`] shared by everything that retries against one server: every clone is
723/// the same budget. The upload queue holds one per lane and hands it to the upload client that
724/// drives the lane's sessions, so the queue's requeues and the client's request retries spend
725/// from one pool.
726#[derive(Debug, Clone, Default)]
727pub struct LaneRetries(Arc<Mutex<LaneRetryBudget>>);
728
729impl LaneRetries {
730 /// A fresh shared budget of `capacity` retries.
731 #[must_use]
732 pub fn new(capacity: u32) -> Self {
733 Self(Arc::new(Mutex::new(LaneRetryBudget::new(capacity))))
734 }
735
736 /// Spend one retry; `false` when the lane's budget is spent. See
737 /// [`LaneRetryBudget::try_spend`].
738 pub fn try_spend(&self) -> bool {
739 self.with(LaneRetryBudget::try_spend)
740 }
741
742 /// Record one success. See [`LaneRetryBudget::record_success`].
743 pub fn record_success(&self) {
744 self.with(LaneRetryBudget::record_success);
745 }
746
747 /// The retries left.
748 #[must_use]
749 pub fn remaining(&self) -> u32 {
750 self.with(|budget| budget.remaining())
751 }
752
753 /// Whether `other` is this same shared budget.
754 #[must_use]
755 pub fn same_as(&self, other: &Self) -> bool {
756 Arc::ptr_eq(&self.0, &other.0)
757 }
758
759 fn with<T>(&self, f: impl FnOnce(&mut LaneRetryBudget) -> T) -> T {
760 // A panic while holding the lock left a plain counter behind, never a broken invariant,
761 // so a poisoned lock is still a usable budget.
762 let mut budget = self.0.lock().unwrap_or_else(PoisonError::into_inner);
763 f(&mut budget)
764 }
765}
766
767/// A non-cryptographic seed for the jitter PRNG from the wall clock, X's a fixed
768/// odd constant and forced nonzero. Only spread matters here.
769fn seed() -> u64 {
770 let nanos = std::time::SystemTime::now()
771 .duration_since(std::time::UNIX_EPOCH)
772 .map_or(0x9e37_79b9_7f4a_7c15, |d| d.as_nanos() as u64);
773 (nanos ^ 0x9e37_79b9_7f4a_7c15) | 1
774}
775
776// ─── Stall detection (no-bytes-for-T) ────────────────────────────────────────
777
778/// A monotonic millisecond clock, injectable so the stall detector's cut is a
779/// deterministic test (a mock clock the test advances) rather than a wall-clock
780/// sleep.
781pub trait MonotonicClock {
782 /// Milliseconds since some fixed, monotonic origin.
783 fn now_millis(&self) -> u64;
784}
785
786/// The production monotonic clock (a process-relative [`Instant`]).
787#[derive(Debug, Clone)]
788pub struct SystemClock {
789 origin: Instant,
790}
791
792impl SystemClock {
793 /// A clock whose origin is now.
794 #[must_use]
795 pub fn new() -> Self {
796 Self {
797 origin: Instant::now(),
798 }
799 }
800}
801
802impl Default for SystemClock {
803 fn default() -> Self {
804 Self::new()
805 }
806}
807
808impl MonotonicClock for SystemClock {
809 fn now_millis(&self) -> u64 {
810 self.origin.elapsed().as_millis() as u64
811 }
812}
813
814/// The stall bound: bulk transfers cut on **no-bytes-for-T**, not on a total
815/// duration (networking doc, "Stall detection over total timeouts"). Client-tunable.
816#[derive(Debug, Clone, Copy, PartialEq, Eq)]
817pub struct StallConfig {
818 /// The no-progress interval that trips a stall cut.
819 pub stall_after: Duration,
820}
821
822impl StallConfig {
823 /// A config with an explicit stall bound.
824 #[must_use]
825 pub fn new(stall_after: Duration) -> Self {
826 Self { stall_after }
827 }
828}
829
830impl Default for StallConfig {
831 fn default() -> Self {
832 // Long enough not to punish slow-but-live links; short enough that a
833 // silently black-holed request is cut in seconds, not minutes.
834 Self {
835 stall_after: Duration::from_secs(20),
836 }
837 }
838}
839
840/// The **no-bytes-for-T** stall detector: tracks the last time bytes arrived and
841/// reports when the gap since then has crossed the stall bound. Event-driven over
842/// an injected [`MonotonicClock`] (never `sleep`), so the "cut within its bound"
843/// behavior is fully deterministic under test.
844#[derive(Debug, Clone)]
845pub struct StallDetector {
846 stall_after_millis: u64,
847 last_progress_millis: u64,
848}
849
850impl StallDetector {
851 /// A detector armed at `now_millis` with `config`'s stall bound.
852 #[must_use]
853 pub fn new(config: StallConfig, now_millis: u64) -> Self {
854 Self {
855 stall_after_millis: config.stall_after.as_millis() as u64,
856 last_progress_millis: now_millis,
857 }
858 }
859
860 /// Record that bytes arrived at `now_millis`: the no-progress timer resets.
861 pub fn on_progress(&mut self, now_millis: u64) {
862 self.last_progress_millis = now_millis;
863 }
864
865 /// Whether the transfer has gone `stall_after` with no bytes as of `now_millis`
866 /// — the cut condition.
867 #[must_use]
868 pub fn is_stalled(&self, now_millis: u64) -> bool {
869 now_millis.saturating_sub(self.last_progress_millis) >= self.stall_after_millis
870 }
871
872 /// The configured stall bound.
873 #[must_use]
874 pub fn stall_after(&self) -> Duration {
875 Duration::from_millis(self.stall_after_millis)
876 }
877}
878
879// ─── Sleeper seam ────────────────────────────────────────────────────────────
880
881/// How a retry/stall loop performs its backoff wait. Abstracted so the wait is
882/// real in production ([`TokioSleeper`]) but a deterministic no-op in tests — the
883/// stall-cut-resume smoke asserts *zero duplicate bytes* with no wall-clock sleep.
884pub trait Sleeper: Clone + Send + Sync {
885 /// Wait for `dur`.
886 fn sleep(&self, dur: Duration) -> impl std::future::Future<Output = ()> + Send;
887}
888
889/// The production sleeper (`tokio::time::sleep`).
890#[derive(Debug, Clone, Copy, Default)]
891pub struct TokioSleeper;
892
893impl Sleeper for TokioSleeper {
894 async fn sleep(&self, dur: Duration) {
895 tokio::time::sleep(dur).await;
896 }
897}
898
899// ─── Per-request stall bounds ────────────────────────────────────────────────
900
901/// How long a request waits for its response once its body is fully sent: one minute.
902///
903/// Longer than the stall bound, because it covers the server's own work on a write — a chunk's
904/// staging write and `fsync` — rather than bytes on the wire (networking doc, Adverse-Network
905/// Posture). Waiting on a session whose finalization is still running is not this wait: that is
906/// observed by polling `HEAD`, never by holding a request open.
907pub const DEFAULT_RESPONSE_WAIT: Duration = Duration::from_mins(1);
908
909/// The size of one piece a [`PacedBody`] hands the HTTP stack: 16 KiB.
910///
911/// Once the stack's write buffer is full it pulls about one piece per piece written, so a live
912/// link must move one piece per stall bound to be seen moving. At 16 KiB over the default
913/// 20 s stall bound that is 0.8 KiB/s — below the server's 1 KiB/s minimum sustained rate, so
914/// the client never cuts as stalled a link the server would accept. Large enough that the
915/// per-piece bookkeeping is noise beside the bytes.
916pub const PACED_PIECE: usize = 16 * 1024;
917
918/// The two bounds every request runs under: the **stall** bound while bytes should be moving —
919/// sending the request body, or receiving the response body — and the longer **response-wait**
920/// bound between the last request byte and the response head.
921///
922/// Neither is a total-duration timeout: a slow but live request is never cut.
923#[derive(Debug, Clone, Copy, PartialEq, Eq)]
924pub struct RequestBounds {
925 /// No bytes moved for this long while sending or receiving cuts the request.
926 pub stall: Duration,
927 /// No response head this long after the body was sent cuts the request.
928 pub response_wait: Duration,
929}
930
931impl RequestBounds {
932 /// Bounds of `stall` and `response_wait`.
933 #[must_use]
934 pub const fn new(stall: Duration, response_wait: Duration) -> Self {
935 Self {
936 stall,
937 response_wait,
938 }
939 }
940}
941
942impl Default for RequestBounds {
943 /// The [`StallConfig`] default stall bound — below the server's own, so the client usually
944 /// notices first — and [`DEFAULT_RESPONSE_WAIT`].
945 fn default() -> Self {
946 Self::new(StallConfig::default().stall_after, DEFAULT_RESPONSE_WAIT)
947 }
948}
949
950/// Why a request was cut.
951#[derive(Debug, Clone, Copy, PartialEq, Eq)]
952pub enum RequestCut {
953 /// No bytes moved for the stall bound, sending or receiving.
954 Stalled,
955 /// The body was handed to the HTTP stack, and no response head came within the
956 /// response-wait bound.
957 ///
958 /// Handed off is not on the wire: the stack's write buffer and the kernel's send buffer may
959 /// still hold the tail of the body, so on a slow enough link this is the body still
960 /// draining as much as a server that never answered.
961 NoResponse,
962}
963
964impl std::fmt::Display for RequestCut {
965 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
966 f.write_str(match self {
967 Self::Stalled => "the request stalled: no bytes moved for the stall bound",
968 Self::NoResponse => "no response arrived within the response-wait bound",
969 })
970 }
971}
972
973/// Where one request's exchange is, and when it last moved.
974#[derive(Debug, Clone, Copy)]
975enum Phase {
976 /// Sending the body; a piece last left at `last`.
977 Sending { last: tokio::time::Instant },
978 /// The body is sent; waiting for the head since `since`.
979 Waiting { since: tokio::time::Instant },
980 /// Receiving the response body; bytes last arrived at `last`.
981 Receiving { last: tokio::time::Instant },
982}
983
984/// The progress of one request, shared between the body that sends it, the code that reads its
985/// response, and [`within_bounds`] that watches both. Cheap to clone: every clone is the same
986/// progress.
987///
988/// Read on tokio's clock, so a paused test clock drives it like every other timer.
989#[derive(Debug, Clone)]
990pub struct ExchangeProgress {
991 phase: std::sync::Arc<std::sync::Mutex<Phase>>,
992}
993
994impl ExchangeProgress {
995 /// A request with nothing (more) to send, waiting for its response from now.
996 #[must_use]
997 pub fn waiting() -> Self {
998 Self {
999 phase: std::sync::Arc::new(std::sync::Mutex::new(Phase::Waiting {
1000 since: tokio::time::Instant::now(),
1001 })),
1002 }
1003 }
1004
1005 fn set(&self, phase: Phase) {
1006 // A poisoned lock holds a phase still worth reading: the watcher only reads instants.
1007 *self
1008 .phase
1009 .lock()
1010 .unwrap_or_else(std::sync::PoisonError::into_inner) = phase;
1011 }
1012
1013 fn phase(&self) -> Phase {
1014 *self
1015 .phase
1016 .lock()
1017 .unwrap_or_else(std::sync::PoisonError::into_inner)
1018 }
1019
1020 /// The body started sending, or a piece of it left, now.
1021 pub fn on_sent(&self) {
1022 self.set(Phase::Sending {
1023 last: tokio::time::Instant::now(),
1024 });
1025 }
1026
1027 /// The whole body has been handed off, now: the response wait starts.
1028 pub fn on_sent_all(&self) {
1029 self.set(Phase::Waiting {
1030 since: tokio::time::Instant::now(),
1031 });
1032 }
1033
1034 /// Response bytes arrived — or the head did — now.
1035 pub fn on_received(&self) {
1036 self.set(Phase::Receiving {
1037 last: tokio::time::Instant::now(),
1038 });
1039 }
1040
1041 /// When the exchange is cut unless it moves first, and as what.
1042 fn deadline(&self, bounds: RequestBounds) -> (tokio::time::Instant, RequestCut) {
1043 match self.phase() {
1044 Phase::Sending { last } | Phase::Receiving { last } => {
1045 (last + bounds.stall, RequestCut::Stalled)
1046 }
1047 Phase::Waiting { since } => (since + bounds.response_wait, RequestCut::NoResponse),
1048 }
1049 }
1050}
1051
1052/// Drive `exchange` while `progress` keeps moving inside `bounds`; cut it when it does not.
1053///
1054/// The deadline moves with the progress, so the watcher sleeps to the current deadline, and on
1055/// waking re-reads it: progress since pushes it out, and none means the cut. Nothing here bounds
1056/// the exchange's total duration.
1057///
1058/// On a cut `exchange` is dropped, and with it the connection: on HTTP/1.1 it closes, on HTTP/2
1059/// the stream resets (networking doc, HTTP Transport).
1060///
1061/// # Errors
1062///
1063/// The [`RequestCut`] that ended it.
1064pub async fn within_bounds<F: std::future::Future>(
1065 bounds: RequestBounds,
1066 progress: &ExchangeProgress,
1067 exchange: F,
1068) -> Result<F::Output, RequestCut> {
1069 let mut exchange = std::pin::pin!(exchange);
1070 loop {
1071 let (deadline, cut) = progress.deadline(bounds);
1072 if tokio::time::Instant::now() >= deadline {
1073 return Err(cut);
1074 }
1075 if let Ok(output) = tokio::time::timeout_at(deadline, exchange.as_mut()).await {
1076 return Ok(output);
1077 }
1078 }
1079}
1080
1081/// A request body sent in [`PACED_PIECE`] pieces, recording each piece the HTTP stack pulls in
1082/// an [`ExchangeProgress`].
1083///
1084/// The stack pulls the next piece once it has written the one before, so a pull is the link
1085/// moving and a long gap between pulls is the link stalled. Handing out the last piece starts
1086/// the response wait — while the stack's write buffer (hyper's holds up to about 400 KiB) and
1087/// the kernel's send buffer may still hold the tail unsent. A link too slow to drain that tail
1088/// inside the response wait is therefore cut as [`RequestCut::NoResponse`]; the upload client
1089/// answers that by re-sending the chunk shorter, so the tail shrinks until it drains in time.
1090/// The exact length is advertised, so the request still carries a `Content-Length` and is
1091/// never sent chunked.
1092#[derive(Debug)]
1093pub struct PacedBody {
1094 remaining: bytes::Bytes,
1095 progress: ExchangeProgress,
1096}
1097
1098impl PacedBody {
1099 /// A body of `bytes` that reports to `progress`. Starts the send clock now.
1100 #[must_use]
1101 pub fn new(bytes: bytes::Bytes, progress: ExchangeProgress) -> Self {
1102 progress.on_sent();
1103 Self {
1104 remaining: bytes,
1105 progress,
1106 }
1107 }
1108}
1109
1110impl http_body::Body for PacedBody {
1111 type Data = bytes::Bytes;
1112 type Error = std::convert::Infallible;
1113
1114 fn poll_frame(
1115 mut self: std::pin::Pin<&mut Self>,
1116 _: &mut std::task::Context<'_>,
1117 ) -> std::task::Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
1118 if self.remaining.is_empty() {
1119 self.progress.on_sent_all();
1120 return std::task::Poll::Ready(None);
1121 }
1122 let take = self.remaining.len().min(PACED_PIECE);
1123 let piece = self.remaining.split_to(take);
1124 if self.remaining.is_empty() {
1125 self.progress.on_sent_all();
1126 } else {
1127 self.progress.on_sent();
1128 }
1129 std::task::Poll::Ready(Some(Ok(http_body::Frame::data(piece))))
1130 }
1131
1132 fn size_hint(&self) -> http_body::SizeHint {
1133 http_body::SizeHint::with_exact(self.remaining.len() as u64)
1134 }
1135}
1136
1137impl From<PacedBody> for reqwest::Body {
1138 fn from(body: PacedBody) -> Self {
1139 reqwest::Body::wrap(body)
1140 }
1141}
1142
1143// ─── Happy Eyeballs at dial ──────────────────────────────────────────────────
1144
1145/// A bounded per-address TCP connect timeout applied at dial. Keeps a dead path
1146/// from hanging a connect indefinitely on an adverse network.
1147pub const DIAL_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
1148
1149/// Build the `reqwest` client the upload/fetch paths dial with: rustls, a bounded
1150/// connect timeout, and the HTTP stack's built-in **Happy Eyeballs v2** at dial.
1151///
1152/// Racing happens **at dial only** (networking doc, "Connection racing at dial
1153/// only"). The parallel IPv6/IPv4 TCP race (RFC 8305) is provided for free by the
1154/// underlying `hyper-util` `HttpConnector` (a 300 ms fallback delay between the
1155/// preferred and fallback address families), which both `reqwest` (this client)
1156/// and `tonic` (the sync channel) sit on — so this module does not re-implement address
1157/// racing. What this constructor *does* add is the bounded connect timeout and the
1158/// standing guarantee that Capsule never races whole *requests* across paths
1159/// (which would double server load): there is no per-request fan-out anywhere in
1160/// the SDK; a request rides exactly one dialed connection.
1161pub fn dial_client() -> reqwest::Result<reqwest::Client> {
1162 http_builder().connect_timeout(DIAL_CONNECT_TIMEOUT).build()
1163}
1164
1165// ─── The one HTTP client ─────────────────────────────────────────────────────
1166
1167/// The request half of the protocol handshake, as default headers for a `reqwest` client.
1168///
1169/// Every route the server gates requires `X-Capsule-Protocol` and refuses without it
1170/// (`capsule-server/src/negotiation.rs`, issue #404), and `X-Capsule-Crypto-Suite` names the
1171/// suite this build seals under. Both are constants of the build, so they belong on the
1172/// transport once rather than on every call: a `reqwest` default header rides every request
1173/// the client sends, the spargen-generated operations included. A header set explicitly on a
1174/// request still wins, which is how the hand-written upload path keeps pinning a per-transport
1175/// protocol date.
1176///
1177/// `X-Capsule-Sidecar-Schema` rides along too (#404, #520). The design has clients send it on
1178/// metadata updates, and this build writes exactly one sidecar schema
1179/// ([`SIDECAR_SCHEMA_V1`](capsule_core::sidecar::SIDECAR_SCHEMA_V1)), so it is a constant of the
1180/// build like the suite rather than a property of one write. On the transport, every request
1181/// that carries a sidecar carries the number — including a metadata update reached through a
1182/// generated operation no hand-written path wraps — and the server validates it only when
1183/// present, so a request that carries no sidecar is unaffected by it.
1184#[must_use]
1185pub fn protocol_headers() -> reqwest::header::HeaderMap {
1186 use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
1187
1188 let mut headers = HeaderMap::with_capacity(3);
1189 headers.insert(
1190 HeaderName::from_static(negotiation::PROTOCOL_HEADER),
1191 HeaderValue::from_static(negotiation::PROTOCOL_VERSION),
1192 );
1193 headers.insert(
1194 HeaderName::from_static("x-capsule-crypto-suite"),
1195 HeaderValue::from(capsule_core::crypto::primitives::CRYPTO_SUITE_ID),
1196 );
1197 headers.insert(
1198 HeaderName::from_static("x-capsule-sidecar-schema"),
1199 HeaderValue::from(capsule_core::sidecar::SIDECAR_SCHEMA_V1),
1200 );
1201 headers
1202}
1203
1204/// The builder every SDK transport starts from: rustls only (the SDK's `reqwest` has no
1205/// default features and only `rustls`), the bundled webpki roots as the only trust anchors
1206/// ([`trust_roots`]), and the protocol handshake as default headers.
1207///
1208/// One builder rather than one client because [`dial_client`] adds a connect timeout on top
1209/// and the auth, sync and typed clients do not; what they share is the handshake, and this is
1210/// the one place it is installed. A transport built any other way sends no handshake and is
1211/// refused by every gated route, which is why nothing in this crate calls
1212/// `reqwest::Client::builder()` directly outside tests.
1213///
1214/// **Parallelism is connections, not streams** (networking doc, HTTP Transport). Every
1215/// transport is pinned to HTTP/1.1, so each request in flight at once rides its own pooled
1216/// connection: a lane's sessions in flight spread across several TCP windows instead of sharing
1217/// the one an HTTP/2 connection would multiplex them onto, which is what keeps a lossy or
1218/// high-latency link busy. The pin is explicit rather than left to the SDK's `reqwest` features
1219/// leaving `http2` out, so a feature another crate enables can never fold the windows back
1220/// onto one connection.
1221pub fn http_builder() -> reqwest::ClientBuilder {
1222 ensure_crypto_provider();
1223 reqwest::Client::builder()
1224 .tls_certs_only(trust_roots())
1225 .default_headers(protocol_headers())
1226 .http1_only()
1227}
1228
1229/// Make `ring` the process's rustls crypto provider, unless the embedding application already
1230/// installed one — which is then respected.
1231///
1232/// The SDK's reqwest carries no provider of its own (`rustls-no-provider`): client builds link
1233/// `ring` alone, as the HTTP/3 leg and LAN peering already do, instead of the aws-lc-rs that
1234/// reqwest's `rustls` feature would add to every client binary. reqwest then takes the
1235/// process default, and panics building a client without one. Idempotent and cheap, so every
1236/// path that builds a reqwest client calls it first, which in this crate is [`http_builder`]:
1237/// spargen's `with_backend` builds no client of its own (spargen 0.8), so the generated client
1238/// needs no provider beyond the one its backend's client was built with.
1239pub fn ensure_crypto_provider() {
1240 if rustls::crypto::CryptoProvider::get_default().is_none() {
1241 // A concurrent first caller may win the race; whichever provider it installed is ring
1242 // too, so the loser's error carries nothing to act on.
1243 let _ = rustls::crypto::ring::default_provider().install_default();
1244 }
1245}
1246
1247/// A generated client over `backend` for `base_url`: the one way this crate constructs one.
1248///
1249/// Every byte the client sends is executed through `backend`; `with_backend` builds no
1250/// `reqwest::Client` of its own (spargen 0.8), so nothing here needs a crypto provider.
1251///
1252/// The error is the generated client's description of why it could not be built — a `base_url`
1253/// it cannot parse, in practice.
1254pub(crate) fn generated_client(
1255 backend: Arc<dyn crate::rest::HttpBackend>,
1256 base_url: &str,
1257) -> Result<crate::rest::Client, String> {
1258 crate::rest::Client::with_backend(backend, base_url).map_err(|error| error.to_string())
1259}
1260
1261/// The trust anchors every SDK reqwest client verifies a server against: the bundled Mozilla
1262/// root set (`webpki-root-certs`), the same release of the same bundle the HTTP/3 leg trusts, so
1263/// a server is trusted or refused alike over TCP and QUIC. reqwest 0.13's `rustls` would
1264/// otherwise consult the OS store instead.
1265///
1266/// The DER bytes are copied out of the bundle once per process; reqwest parses them into its
1267/// root store on every client build.
1268#[must_use]
1269pub fn trust_roots() -> Vec<reqwest::Certificate> {
1270 static ROOTS: std::sync::OnceLock<Vec<reqwest::Certificate>> = std::sync::OnceLock::new();
1271 ROOTS
1272 .get_or_init(|| {
1273 webpki_root_certs::TLS_SERVER_ROOT_CERTS
1274 .iter()
1275 .map(|der| {
1276 reqwest::Certificate::from_der(der)
1277 .expect("every bundled webpki root is a DER certificate")
1278 })
1279 .collect()
1280 })
1281 .clone()
1282}
1283
1284/// The plain SDK client: [`http_builder`], built.
1285///
1286/// # Errors
1287///
1288/// Whatever `reqwest` refuses to build with — in practice nothing, since the builder carries
1289/// no configuration a platform can lack.
1290pub fn http_client() -> reqwest::Result<reqwest::Client> {
1291 http_builder().build()
1292}
1293
1294// ─── The one send ────────────────────────────────────────────────────────────
1295
1296/// Send a prepared request on `client`: the one place a hand-written SDK request leaves.
1297///
1298/// A default build sends it on `client` and nothing else. Under the `http3` feature it is routed
1299/// through the HTTP/3 transport (`h3::route::execute`), which may carry it over QUIC and
1300/// otherwise sends it on `client` as before, feeding every response's `Alt-Svc` to the policy.
1301///
1302/// # Errors
1303///
1304/// The `reqwest::Error` the send over `client` ended with.
1305pub(crate) async fn execute(
1306 client: &reqwest::Client,
1307 request: reqwest::Request,
1308) -> reqwest::Result<reqwest::Response> {
1309 // Boxed: the routed send nests the transport's race, and every caller up to the CLI's
1310 // dispatch would otherwise carry it inline.
1311 #[cfg(feature = "http3")]
1312 {
1313 Box::pin(h3::route::execute(client, request)).await
1314 }
1315 #[cfg(not(feature = "http3"))]
1316 {
1317 client.execute(request).await
1318 }
1319}
1320
1321/// The generated client's transport over `http`: [`crate::rest::ReqwestBackend`] in a default
1322/// build, and the router (`h3::route::RoutedBackend`) under the `http3` feature, so a
1323/// generated operation leaves exactly as a hand-written request does ([`execute`]).
1324pub(crate) fn backend(http: reqwest::Client) -> Arc<dyn crate::rest::HttpBackend> {
1325 #[cfg(feature = "http3")]
1326 {
1327 Arc::new(h3::route::RoutedBackend::new(http))
1328 }
1329 #[cfg(not(feature = "http3"))]
1330 {
1331 Arc::new(crate::rest::ReqwestBackend::new(http))
1332 }
1333}
1334
1335/// A copy of a request crossing the generated client's transport seam, to send again: method,
1336/// URI, version, headers, extensions and body alike. `None` when the body is a stream, which can
1337/// be read only once — half a body on the wire twice is worse than the failure it would retry.
1338pub(crate) fn try_clone_request(
1339 request: &http::Request<crate::rest::HttpBody>,
1340) -> Option<http::Request<crate::rest::HttpBody>> {
1341 let mut clone = http::Request::new(request.body().try_clone()?);
1342 *clone.method_mut() = request.method().clone();
1343 *clone.uri_mut() = request.uri().clone();
1344 *clone.version_mut() = request.version();
1345 *clone.headers_mut() = request.headers().clone();
1346 *clone.extensions_mut() = request.extensions().clone();
1347 Some(clone)
1348}
1349
1350/// Mark the request `builder` holds as safe to send twice, so under the `http3` feature it may
1351/// ride QUIC (`h3::route::replayable`): `bytes` are the bytes of the streamed body it holds,
1352/// and `progress` what its caller bounds it by. A default build returns `builder` unchanged.
1353pub(crate) fn replayable(
1354 builder: reqwest::RequestBuilder,
1355 bytes: bytes::Bytes,
1356 progress: &ExchangeProgress,
1357) -> reqwest::RequestBuilder {
1358 #[cfg(feature = "http3")]
1359 {
1360 h3::route::replayable(builder, bytes, progress)
1361 }
1362 #[cfg(not(feature = "http3"))]
1363 {
1364 let _ = (bytes, progress);
1365 builder
1366 }
1367}
1368
1369// ─── Packet marking ──────────────────────────────────────────────────────────
1370
1371/// The Lower Effort per-hop behaviour's DSCP (RFC 8622), `000001`: traffic that yields to every
1372/// other class wherever a network honours the field (networking doc, Packet Marking).
1373pub const LOWER_EFFORT_DSCP: u8 = 1;
1374
1375/// [`LOWER_EFFORT_DSCP`] as the whole IPv4 TOS / IPv6 traffic-class octet: the six DSCP bits
1376/// above the two ECN bits, which stay clear for the kernel's TCP to manage.
1377pub const LOWER_EFFORT_TRAFFIC_CLASS: u32 = (LOWER_EFFORT_DSCP as u32) << 2;
1378
1379/// What [`mark_lower_effort`] did to a socket. Every outcome leaves the socket usable: marking is
1380/// a courtesy to other traffic, never a condition of the transfer.
1381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1382pub enum Marking {
1383 /// The socket's outgoing packets now carry the Lower Effort DSCP.
1384 Marked,
1385 /// The platform refused the option (or the socket's address could not be read); the socket
1386 /// is unmarked and otherwise unchanged.
1387 Refused,
1388 /// This build has no setter for the socket's address family on this platform; the socket is
1389 /// unmarked.
1390 Unsupported,
1391}
1392
1393/// Mark a bulk-transfer socket the SDK holds with the Lower Effort DSCP, best effort.
1394///
1395/// Sets `IP_TOS` on a socket carrying IPv4 (an IPv4-mapped IPv6 socket included, since its
1396/// packets are IPv4) and `IPV6_TCLASS` on one carrying IPv6, to
1397/// [`LOWER_EFFORT_TRAFFIC_CLASS`]. A platform that refuses either, or a target `socket2` exposes
1398/// no setter on, leaves the socket unmarked; the outcome is logged and returned, never an error,
1399/// so a caller proceeds the same whichever it is.
1400///
1401/// Only bulk transfers are marked: interactive requests and the server's sockets stay at the
1402/// default class, so marking can only make Capsule's bulk bytes yield, never make anything of
1403/// Capsule's slower to answer a person.
1404#[instrument(level = "debug", skip(socket))]
1405pub fn mark_lower_effort(socket: &tokio::net::TcpStream) -> Marking {
1406 let local = match socket.local_addr() {
1407 Ok(local) => local,
1408 Err(error) => {
1409 tracing::debug!(%error, "packet marking: socket address unreadable; left unmarked");
1410 return Marking::Refused;
1411 }
1412 };
1413 let carries_ipv4 = match local {
1414 std::net::SocketAddr::V4(_) => true,
1415 std::net::SocketAddr::V6(v6) => v6.ip().to_ipv4_mapped().is_some(),
1416 };
1417 let sock = socket2::SockRef::from(socket);
1418 let set = if carries_ipv4 {
1419 set_tos_v4(&sock)
1420 } else {
1421 set_tclass_v6(&sock)
1422 };
1423 match set {
1424 Some(Ok(())) => {
1425 tracing::debug!(%local, carries_ipv4, "packet marking: lower effort set");
1426 Marking::Marked
1427 }
1428 Some(Err(error)) => {
1429 tracing::debug!(%local, carries_ipv4, %error, "packet marking: refused; left unmarked");
1430 Marking::Refused
1431 }
1432 None => {
1433 tracing::debug!(%local, carries_ipv4, "packet marking: unsupported here; left unmarked");
1434 Marking::Unsupported
1435 }
1436 }
1437}
1438
1439/// `IP_TOS`, on every target `socket2` exposes it for.
1440#[cfg(not(any(
1441 target_os = "fuchsia",
1442 target_os = "redox",
1443 target_os = "solaris",
1444 target_os = "haiku",
1445 target_os = "wasi",
1446)))]
1447#[allow(clippy::unnecessary_wraps)]
1448fn set_tos_v4(sock: &socket2::SockRef<'_>) -> Option<std::io::Result<()>> {
1449 Some(sock.set_tos_v4(LOWER_EFFORT_TRAFFIC_CLASS))
1450}
1451
1452/// `IP_TOS` where `socket2` has no setter: unsupported.
1453#[cfg(any(
1454 target_os = "fuchsia",
1455 target_os = "redox",
1456 target_os = "solaris",
1457 target_os = "haiku",
1458 target_os = "wasi",
1459))]
1460fn set_tos_v4(_sock: &socket2::SockRef<'_>) -> Option<std::io::Result<()>> {
1461 None
1462}
1463
1464/// `IPV6_TCLASS`, on every target `socket2` exposes it for (not iOS or Windows).
1465#[cfg(any(
1466 target_os = "android",
1467 target_os = "dragonfly",
1468 target_os = "freebsd",
1469 target_os = "fuchsia",
1470 target_os = "linux",
1471 target_os = "macos",
1472 target_os = "netbsd",
1473 target_os = "openbsd",
1474 target_os = "cygwin",
1475 target_os = "illumos",
1476))]
1477#[allow(clippy::unnecessary_wraps)]
1478fn set_tclass_v6(sock: &socket2::SockRef<'_>) -> Option<std::io::Result<()>> {
1479 Some(sock.set_tclass_v6(LOWER_EFFORT_TRAFFIC_CLASS))
1480}
1481
1482/// `IPV6_TCLASS` where `socket2` has no setter: unsupported.
1483#[cfg(not(any(
1484 target_os = "android",
1485 target_os = "dragonfly",
1486 target_os = "freebsd",
1487 target_os = "fuchsia",
1488 target_os = "linux",
1489 target_os = "macos",
1490 target_os = "netbsd",
1491 target_os = "openbsd",
1492 target_os = "cygwin",
1493 target_os = "illumos",
1494)))]
1495fn set_tclass_v6(_sock: &socket2::SockRef<'_>) -> Option<std::io::Result<()>> {
1496 None
1497}
1498
1499#[cfg(test)]
1500mod tests;