Skip to main content

capsule_sdk/net/
path.rs

1//! The normalized path snapshot and the pure transfer plan (networking doc, Path Snapshot).
2//!
3//! A platform shell (or the CLI's flags) reports what it sees as a [`PathSample`]: cost,
4//! reachability, interface, power, thermal state and how long the app may run. The
5//! [`PathMonitor`] stamps each sample with a [`PathGeneration`] — which advances only when
6//! reachability, interface or cost changes, never on a minor update — and keeps the latest
7//! [`PathSnapshot`].
8//!
9//! [`plan_transfer`] is the whole of the policy: a pure function of the snapshot, the link
10//! behaviour the [`AdverseDetector`] observed, the server's advice, and the client's compiled
11//! window bounds. The server is never in the loop; its advice can only lower a window.
12//!
13//! A new generation drops what belonged to the old path: the monitor resets its
14//! [`AdverseDetector`] (resets on the old network say nothing about the new one), a
15//! [`GenerationPool`] builds a fresh HTTP client so no pooled connection outlives its path, and
16//! [`crate::staged::run_under_path`] cancels in-flight work the new plan forbids and re-plans.
17
18use std::sync::{Mutex, PoisonError};
19use std::time::Duration;
20
21use capsule_library::import::{UploadPolicy, UploadTier};
22use tokio::sync::watch;
23use tracing::instrument;
24
25use super::{
26    AdverseDetector, AdverseThresholds, ConnectionClass, MonotonicClock, SystemClock,
27    TransferSignal,
28};
29use crate::upload::advice::ServerAdvice;
30use crate::upload::queue::LaneWindows;
31use crate::upload::{ADVERSE_TARGET_REQUEST_DURATION, TARGET_REQUEST_DURATION};
32
33/// What the OS says the path costs. `constrained` is the OS data saver (iOS Low Data Mode,
34/// Android Data Saver) and wins over a merely metered link.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum PathCost {
37    /// Bulk transfer is acceptable.
38    Unmetered,
39    /// The link is byte-counted (iOS `isExpensive`, Android without `NOT_METERED`).
40    Metered,
41    /// The OS data saver is on.
42    Constrained,
43}
44
45/// Whether the OS reports a usable path at all.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum Reachability {
48    /// A usable path exists.
49    Reachable,
50    /// No usable path.
51    Unreachable,
52}
53
54/// The kind of interface the path runs over. It plans nothing by itself — cost is what the OS
55/// reports about money — but a change of interface is a new path.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum PathInterface {
58    /// Ethernet or another wired link.
59    Wired,
60    /// Wi-Fi.
61    Wifi,
62    /// A cellular radio.
63    Cellular,
64    /// Anything else, or unknown (a VPN, a loopback, a desktop without a probe).
65    Other,
66}
67
68/// The device's power source.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum PowerState {
71    /// On external power.
72    External,
73    /// On battery.
74    Battery,
75    /// On battery with the OS low-power mode on.
76    LowPower,
77}
78
79/// The device's thermal state, in the OS's four steps (iOS `ProcessInfo.ThermalState`,
80/// Android `PowerManager` thermal status folded into the same four).
81#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
82pub enum ThermalState {
83    /// No thermal pressure.
84    Nominal,
85    /// Slightly elevated.
86    Fair,
87    /// High: the OS asks apps to reduce work.
88    Serious,
89    /// Critical: the OS asks apps to stop discretionary work.
90    Critical,
91}
92
93/// How the app is running.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum Execution {
96    /// In the foreground, with no deadline.
97    Foreground,
98    /// In a background task the OS ends `deadline` from the sample.
99    Background {
100        /// The time left before the OS ends the task.
101        deadline: Duration,
102    },
103}
104
105/// One sample of the path as a platform reports it, before the monitor stamps a generation.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct PathSample {
108    /// What the path costs.
109    pub cost: PathCost,
110    /// Whether a usable path exists.
111    pub reachability: Reachability,
112    /// The interface the path runs over.
113    pub interface: PathInterface,
114    /// The device's power source.
115    pub power: PowerState,
116    /// The device's thermal state.
117    pub thermal: ThermalState,
118    /// How the app is running.
119    pub execution: Execution,
120}
121
122impl PathSample {
123    /// The desktop default: a reachable, unmetered path of unknown interface, on external
124    /// power, cool, in the foreground.
125    #[must_use]
126    pub const fn desktop() -> Self {
127        Self {
128            cost: PathCost::Unmetered,
129            reachability: Reachability::Reachable,
130            interface: PathInterface::Other,
131            power: PowerState::External,
132            thermal: ThermalState::Nominal,
133            execution: Execution::Foreground,
134        }
135    }
136
137    /// The desktop default on a path whose cost and reachability are `class`'s: the bridge
138    /// from a [`ConnectionClass`] source that reports nothing else. `adverse` is behavioural,
139    /// never reported, so it reads as an unmetered path.
140    #[must_use]
141    pub const fn from_class(class: ConnectionClass) -> Self {
142        let mut sample = Self::desktop();
143        match class {
144            ConnectionClass::Unmetered | ConnectionClass::Adverse => {}
145            ConnectionClass::Metered => sample.cost = PathCost::Metered,
146            ConnectionClass::Constrained => sample.cost = PathCost::Constrained,
147            ConnectionClass::Offline => sample.reachability = Reachability::Unreachable,
148        }
149        sample
150    }
151
152    /// This sample `elapsed` after it was reported: a background deadline has that much less
153    /// time left, down to zero. Everything else is the platform's to report again.
154    #[must_use]
155    pub fn aged(&self, elapsed: Duration) -> Self {
156        let mut sample = *self;
157        if let Execution::Background { deadline } = &mut sample.execution {
158            *deadline = deadline.saturating_sub(elapsed);
159        }
160        sample
161    }
162
163    /// Whether `other` is a different path: its reachability, interface or cost differs.
164    /// Power, thermal state and execution change the plan, never the path.
165    #[must_use]
166    pub fn is_new_path(&self, other: &Self) -> bool {
167        self.reachability != other.reachability
168            || self.interface != other.interface
169            || self.cost != other.cost
170    }
171
172    /// The class the OS reports, before behavioural promotion to `adverse`.
173    #[must_use]
174    pub const fn base_class(&self) -> ConnectionClass {
175        match (self.reachability, self.cost) {
176            (Reachability::Unreachable, _) => ConnectionClass::Offline,
177            (Reachability::Reachable, PathCost::Constrained) => ConnectionClass::Constrained,
178            (Reachability::Reachable, PathCost::Metered) => ConnectionClass::Metered,
179            (Reachability::Reachable, PathCost::Unmetered) => ConnectionClass::Unmetered,
180        }
181    }
182}
183
184/// Which path a snapshot belongs to. Advances by one each time reachability, interface or cost
185/// changes; everything planned or pooled under an older generation belongs to a path that is
186/// gone.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
188pub struct PathGeneration(pub u64);
189
190/// The normalized path: the latest sample, stamped with its generation.
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub struct PathSnapshot {
193    /// What the platform last reported. A [`PathMonitor`] hands it out
194    /// [aged](PathSample::aged) to the moment it is read, so a background deadline counts down
195    /// between reports.
196    pub sample: PathSample,
197    /// The path the sample belongs to.
198    pub generation: PathGeneration,
199}
200
201/// What the [`AdverseDetector`] has observed of the link: the resets and stalls it counts.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
203pub struct LinkBehaviour {
204    /// The detector has promoted the link to `adverse`.
205    pub adverse: bool,
206}
207
208/// Server advice as the plan reads it: the advice and how long ago it arrived.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
210pub struct HeldAdvice {
211    /// The advice, clamped when it was read.
212    pub advice: ServerAdvice,
213    /// Its age now, against its `ttl`.
214    pub age: Duration,
215}
216
217impl HeldAdvice {
218    /// No advice: every window is the client's own.
219    #[must_use]
220    pub const fn none() -> Self {
221        Self {
222            advice: ServerAdvice::absent(),
223            age: Duration::ZERO,
224        }
225    }
226}
227
228/// The shortest background deadline bulk work starts under: one minute. A preview or original
229/// started with less is likely cut by the OS before it lands, so only the index tier — a few
230/// KB per asset — runs.
231pub const MIN_BULK_DEADLINE: Duration = Duration::from_mins(1);
232
233/// Which tiers the plan admits.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum TierAdmission {
236    /// Every tier.
237    All,
238    /// Only the index tier; the bulk tiers wait.
239    IndexOnly,
240    /// Nothing: no transfer runs.
241    Nothing,
242}
243
244impl TierAdmission {
245    /// Whether `tier` is admitted.
246    #[must_use]
247    pub fn admits(self, tier: UploadTier) -> bool {
248        match self {
249            Self::All => true,
250            Self::IndexOnly => tier == UploadTier::Index,
251            Self::Nothing => false,
252        }
253    }
254
255    /// Whether `tier` may run under this admission and its `hold`, given the user's
256    /// force-sync consent, which lifts an index-only hold that
257    /// [yields to it](Hold::yields_to_force_sync).
258    #[must_use]
259    pub fn permits(self, hold: Option<Hold>, tier: UploadTier, force_sync: bool) -> bool {
260        self.admits(tier)
261            || (force_sync
262                && self == Self::IndexOnly
263                && hold.is_some_and(Hold::yields_to_force_sync))
264    }
265
266    /// The admission and hold `class` alone implies, for a caller that knows nothing else of
267    /// the path: the tier gate [`ConnectionClass::permits_tier`] states.
268    #[must_use]
269    pub const fn for_class(class: ConnectionClass) -> (Self, Option<Hold>) {
270        match class {
271            ConnectionClass::Unmetered => (Self::All, None),
272            ConnectionClass::Metered | ConnectionClass::Constrained => {
273                (Self::IndexOnly, Some(Hold::Cost))
274            }
275            ConnectionClass::Adverse => (Self::IndexOnly, Some(Hold::Adverse)),
276            ConnectionClass::Offline => (Self::Nothing, Some(Hold::Offline)),
277        }
278    }
279}
280
281/// Why the plan holds back work it would otherwise run.
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum Hold {
284    /// No usable path: nothing runs.
285    Offline,
286    /// The thermal state is critical: nothing runs.
287    ThermalCritical,
288    /// The path is metered or the data saver is on: bulk waits. A user's force-sync consent
289    /// overrides it.
290    Cost,
291    /// The link is behaving adversely: bulk waits. A user's force-sync consent overrides it.
292    Adverse,
293    /// Low-power mode is on: bulk waits.
294    LowPower,
295    /// The thermal state is serious: bulk waits.
296    ThermalSerious,
297    /// The background deadline is shorter than [`MIN_BULK_DEADLINE`]: bulk waits.
298    Deadline,
299}
300
301impl Hold {
302    /// Whether a user's force-sync consent lifts this hold. It overrides what the link costs or
303    /// how it behaves; it never resurrects a missing path or overrules the device's own power
304    /// and thermal limits.
305    #[must_use]
306    pub const fn yields_to_force_sync(self) -> bool {
307        matches!(self, Self::Cost | Self::Adverse)
308    }
309}
310
311/// What the client does on the current path. Produced only by [`plan_transfer`].
312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
313pub struct TransferPlan {
314    /// The path this plan was made for.
315    pub generation: PathGeneration,
316    /// The effective connection class: the OS's, promoted to `adverse` by the link behaviour.
317    pub class: ConnectionClass,
318    /// The tiers that may run.
319    pub admission: TierAdmission,
320    /// Why the plan admits less than every tier, if it does.
321    pub hold: Option<Hold>,
322    /// The sessions and ranges windows: the compiled bounds, lowered by fresh advice and by
323    /// the device's power and thermal state.
324    pub windows: LaneWindows,
325    /// How long one chunk request should take.
326    pub chunk_target: Duration,
327    /// The chunk size the server suggested, while its advice is fresh.
328    pub suggested_chunk: Option<u64>,
329    /// The bounded `Range` window a fetch uses, or `None` for the open remainder.
330    pub range_window: Option<u64>,
331}
332
333impl TransferPlan {
334    /// Whether `tier` may run, given the user's force-sync consent.
335    #[must_use]
336    pub fn permits_tier(&self, tier: UploadTier, force_sync: bool) -> bool {
337        self.admission.permits(self.hold, tier, force_sync)
338    }
339
340    /// Whether the plan holds bulk work back.
341    #[must_use]
342    pub fn defers_bulk(&self) -> bool {
343        self.admission != TierAdmission::All
344    }
345
346    /// The upload policy a push runs under, given the one the user `requested`: a plan that
347    /// holds bulk back stages the push, so the index tier still publishes each asset.
348    #[must_use]
349    pub fn upload_policy(&self, requested: UploadPolicy) -> UploadPolicy {
350        if self.defers_bulk() {
351            UploadPolicy::Staged
352        } else {
353            requested
354        }
355    }
356}
357
358/// Plan transfers on `snapshot`, given what the link has shown (`link`), the server's `advice`,
359/// and the client's compiled window `bounds`. Pure: the same inputs always plan the same.
360///
361/// The rules, in precedence order:
362///
363/// 1. An unreachable path admits nothing ([`Hold::Offline`]); a critical thermal state admits
364///    nothing ([`Hold::ThermalCritical`]).
365/// 2. The class is the cost's, promoted to `adverse` while the link behaves adversely.
366/// 3. Bulk tiers wait on anything but an unmetered, well-behaved link ([`Hold::Cost`],
367///    [`Hold::Adverse`]), then on low-power mode, a serious thermal state, and a background
368///    deadline under [`MIN_BULK_DEADLINE`], in that order. The index tier still runs.
369/// 4. The windows are `bounds`, lowered by fresh advice, and narrowed to one session in
370///    low-power mode or from a serious thermal state up.
371/// 5. Under `adverse` a chunk targets [`ADVERSE_TARGET_REQUEST_DURATION`] and a fetch uses the
372///    bounded range window; otherwise [`TARGET_REQUEST_DURATION`] and the open remainder.
373#[must_use]
374pub fn plan_transfer(
375    snapshot: &PathSnapshot,
376    link: LinkBehaviour,
377    advice: HeldAdvice,
378    bounds: LaneWindows,
379) -> TransferPlan {
380    let sample = &snapshot.sample;
381    let base = sample.base_class();
382    let class = if link.adverse && base != ConnectionClass::Offline {
383        ConnectionClass::Adverse
384    } else {
385        base
386    };
387
388    let stop = if base == ConnectionClass::Offline {
389        Some(Hold::Offline)
390    } else if sample.thermal == ThermalState::Critical {
391        Some(Hold::ThermalCritical)
392    } else {
393        None
394    };
395    let bulk_hold = match class {
396        ConnectionClass::Metered | ConnectionClass::Constrained => Some(Hold::Cost),
397        ConnectionClass::Adverse => Some(Hold::Adverse),
398        ConnectionClass::Offline => Some(Hold::Offline),
399        ConnectionClass::Unmetered if sample.power == PowerState::LowPower => Some(Hold::LowPower),
400        ConnectionClass::Unmetered if sample.thermal >= ThermalState::Serious => {
401            Some(Hold::ThermalSerious)
402        }
403        ConnectionClass::Unmetered => match sample.execution {
404            Execution::Background { deadline } if deadline < MIN_BULK_DEADLINE => {
405                Some(Hold::Deadline)
406            }
407            _ => None,
408        },
409    };
410    let (admission, hold) = match (stop, bulk_hold) {
411        (Some(stop), _) => (TierAdmission::Nothing, Some(stop)),
412        (None, Some(hold)) => (TierAdmission::IndexOnly, Some(hold)),
413        (None, None) => (TierAdmission::All, None),
414    };
415
416    let mut sessions = advice.advice.sessions_window(bounds.sessions, advice.age);
417    if sample.power == PowerState::LowPower || sample.thermal >= ThermalState::Serious {
418        sessions = 1;
419    }
420    let windows = LaneWindows::new(sessions, advice.advice.ranges_window(bounds.ranges));
421
422    let chunk_target = if class == ConnectionClass::Adverse {
423        ADVERSE_TARGET_REQUEST_DURATION
424    } else {
425        TARGET_REQUEST_DURATION
426    };
427
428    TransferPlan {
429        generation: snapshot.generation,
430        class,
431        admission,
432        hold,
433        windows,
434        chunk_target,
435        suggested_chunk: advice.advice.chunk(advice.age),
436        range_window: class.range_window(),
437    }
438}
439
440// ─── The monitor ─────────────────────────────────────────────────────────────
441
442/// What one [`PathMonitor::observe`] changed.
443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
444pub enum PathUpdate {
445    /// Reachability, interface or cost changed: a new generation, the detector reset, and
446    /// this plan made for the new path.
447    NewPath(TransferPlan),
448    /// The same path; power, thermal state or execution may have changed this plan.
449    SamePath(TransferPlan),
450}
451
452impl PathUpdate {
453    /// The plan after the update.
454    #[must_use]
455    pub const fn plan(&self) -> TransferPlan {
456        match self {
457            Self::NewPath(plan) | Self::SamePath(plan) => *plan,
458        }
459    }
460}
461
462#[derive(Debug)]
463struct MonitorState {
464    /// The snapshot as the platform reported it.
465    snapshot: PathSnapshot,
466    /// When it was reported, on the monitor's clock.
467    reported_at_ms: u64,
468    detector: AdverseDetector,
469}
470
471impl MonitorState {
472    fn link(&self) -> LinkBehaviour {
473        LinkBehaviour {
474            adverse: self.detector.is_adverse(),
475        }
476    }
477
478    /// The snapshot at `now_ms`: its background deadline aged by the time since the report.
479    fn current(&self, now_ms: u64) -> PathSnapshot {
480        let elapsed = Duration::from_millis(now_ms.saturating_sub(self.reported_at_ms));
481        PathSnapshot {
482            sample: self.snapshot.sample.aged(elapsed),
483            generation: self.snapshot.generation,
484        }
485    }
486
487    fn plan(&self, now_ms: u64, advice: HeldAdvice, bounds: LaneWindows) -> TransferPlan {
488        plan_transfer(&self.current(now_ms), self.link(), advice, bounds)
489    }
490}
491
492/// The current path, the link behaviour observed on it, and the plan they make, shared by
493/// everything that transfers.
494///
495/// Platform shells call [`observe`](Self::observe) with each sample, transfers report their
496/// outcomes through [`record`](Self::record), and a long transfer [`subscribe`](Self::subscribe)s
497/// to learn — within the tick the change lands — that the plan it runs under has changed.
498///
499/// A background deadline is aged on the monitor's [`MonotonicClock`]: every plan read through
500/// [`plan`](Self::plan), [`subscribe`](Self::subscribe), [`plan_with`](Self::plan_with) or
501/// [`snapshot`](Self::snapshot) sees the time left now, not the time left when the app last
502/// reported, so a push started late in a background task holds bulk back without a new report.
503pub struct PathMonitor {
504    state: Mutex<MonitorState>,
505    bounds: LaneWindows,
506    plans: watch::Sender<TransferPlan>,
507    clock: Box<dyn MonotonicClock + Send + Sync>,
508}
509
510impl std::fmt::Debug for PathMonitor {
511    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512        f.debug_struct("PathMonitor")
513            .field("state", &self.state)
514            .field("bounds", &self.bounds)
515            .field("plan", &*self.plans.borrow())
516            .finish_non_exhaustive()
517    }
518}
519
520impl PathMonitor {
521    /// A monitor whose first path is `sample`, generation 1, with the default adverse
522    /// thresholds and `bounds` as the compiled windows.
523    #[must_use]
524    pub fn new(sample: PathSample, bounds: LaneWindows) -> Self {
525        Self::with_thresholds(sample, bounds, AdverseThresholds::default())
526    }
527
528    /// [`new`](Self::new), with the detector's `thresholds`.
529    #[must_use]
530    pub fn with_thresholds(
531        sample: PathSample,
532        bounds: LaneWindows,
533        thresholds: AdverseThresholds,
534    ) -> Self {
535        let clock = SystemClock::new();
536        let state = MonitorState {
537            snapshot: PathSnapshot {
538                sample,
539                generation: PathGeneration(1),
540            },
541            reported_at_ms: clock.now_millis(),
542            detector: AdverseDetector::new(thresholds),
543        };
544        let plan = plan_transfer(&state.snapshot, state.link(), HeldAdvice::none(), bounds);
545        Self {
546            state: Mutex::new(state),
547            bounds,
548            plans: watch::Sender::new(plan),
549            clock: Box::new(clock),
550        }
551    }
552
553    /// Age background deadlines on `clock` instead of the process's monotonic clock. The
554    /// current sample counts as reported now, on `clock`.
555    #[must_use]
556    pub fn with_clock(mut self, clock: impl MonotonicClock + Send + Sync + 'static) -> Self {
557        let now = clock.now_millis();
558        self.clock = Box::new(clock);
559        self.state
560            .get_mut()
561            .unwrap_or_else(PoisonError::into_inner)
562            .reported_at_ms = now;
563        self
564    }
565
566    fn state(&self) -> std::sync::MutexGuard<'_, MonitorState> {
567        // A panic while holding the lock left plain values behind; they stay usable.
568        self.state.lock().unwrap_or_else(PoisonError::into_inner)
569    }
570
571    /// The latest snapshot, its background deadline aged to now.
572    #[must_use]
573    pub fn snapshot(&self) -> PathSnapshot {
574        self.state().current(self.clock.now_millis())
575    }
576
577    /// The current plan, without advice: re-made at now, so an aged background deadline holds
578    /// bulk back, and published to subscribers when that changed it.
579    #[must_use]
580    pub fn plan(&self) -> TransferPlan {
581        let state = self.state();
582        let plan = state.plan(self.clock.now_millis(), HeldAdvice::none(), self.bounds);
583        self.publish(plan);
584        drop(state);
585        plan
586    }
587
588    /// The current plan with `advice` applied to its windows and chunk size.
589    #[must_use]
590    pub fn plan_with(&self, advice: HeldAdvice) -> TransferPlan {
591        self.state()
592            .plan(self.clock.now_millis(), advice, self.bounds)
593    }
594
595    /// A receiver that wakes each time the plan changes, holding the plan as of now.
596    #[must_use]
597    pub fn subscribe(&self) -> watch::Receiver<TransferPlan> {
598        let _ = self.plan();
599        self.plans.subscribe()
600    }
601
602    /// Take a new sample. A change of reachability, interface or cost advances the
603    /// generation and resets the adverse detector; the plan is remade either way and published
604    /// when it changed.
605    #[instrument(level = "debug", skip(self))]
606    pub fn observe(&self, sample: PathSample) -> PathUpdate {
607        let mut state = self.state();
608        let new_path = state.snapshot.sample.is_new_path(&sample);
609        if new_path {
610            state.snapshot.generation = PathGeneration(state.snapshot.generation.0 + 1);
611            state.detector.reset();
612        }
613        let now = self.clock.now_millis();
614        state.snapshot.sample = sample;
615        state.reported_at_ms = now;
616        let plan = state.plan(now, HeldAdvice::none(), self.bounds);
617        // Published under the lock, so two samples racing publish in the order they planned.
618        self.publish(plan);
619        drop(state);
620        if new_path {
621            tracing::info!(
622                generation = plan.generation.0,
623                class = ?plan.class,
624                admission = ?plan.admission,
625                hold = ?plan.hold,
626                "path: a new path; the adverse detector is reset and transfers re-plan"
627            );
628            PathUpdate::NewPath(plan)
629        } else {
630            PathUpdate::SamePath(plan)
631        }
632    }
633
634    /// Fold one transfer outcome into the adverse detector, and return the plan after it.
635    pub fn record(&self, signal: TransferSignal) -> TransferPlan {
636        let mut state = self.state();
637        state.detector.record(signal);
638        let plan = state.plan(self.clock.now_millis(), HeldAdvice::none(), self.bounds);
639        self.publish(plan);
640        drop(state);
641        plan
642    }
643
644    /// [`record`](Self::record) an outcome observed on the path of `generation`, only while
645    /// that is still the current path: a transfer that began on a path since replaced says
646    /// nothing about the new one, whose detector has just been reset. `None` when it was
647    /// dropped.
648    pub fn record_on(
649        &self,
650        generation: PathGeneration,
651        signal: TransferSignal,
652    ) -> Option<TransferPlan> {
653        let mut state = self.state();
654        let current = state.snapshot.generation;
655        if current != generation {
656            drop(state);
657            tracing::debug!(
658                observed_on = generation.0,
659                current = current.0,
660                ?signal,
661                "path: dropping an outcome observed on a path since replaced"
662            );
663            return None;
664        }
665        state.detector.record(signal);
666        let plan = state.plan(self.clock.now_millis(), HeldAdvice::none(), self.bounds);
667        self.publish(plan);
668        drop(state);
669        Some(plan)
670    }
671
672    fn publish(&self, plan: TransferPlan) {
673        self.plans.send_if_modified(|current| {
674            if *current == plan {
675                return false;
676            }
677            tracing::debug!(
678                generation = plan.generation.0,
679                class = ?plan.class,
680                admission = ?plan.admission,
681                hold = ?plan.hold,
682                "path: the transfer plan changed"
683            );
684            *current = plan;
685            true
686        });
687    }
688}
689
690// ─── Pooled connections per generation ───────────────────────────────────────
691
692/// An HTTP client whose connection pool belongs to one path generation.
693///
694/// `reqwest` has no way to empty a pool, so a new generation builds a new client and drops the
695/// old one: no request on the new path rides a connection dialled over the old one. In-flight
696/// requests keep the clone they hold until they end.
697pub struct GenerationPool {
698    build: Box<dyn Fn() -> reqwest::Result<reqwest::Client> + Send + Sync>,
699    current: Mutex<Option<(PathGeneration, reqwest::Client)>>,
700}
701
702impl std::fmt::Debug for GenerationPool {
703    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
704        f.debug_struct("GenerationPool")
705            .field("generation", &self.generation())
706            .finish_non_exhaustive()
707    }
708}
709
710impl GenerationPool {
711    /// A pool whose clients come from `build`, which must start from
712    /// [`http_builder`](super::http_builder) so every client carries the handshake.
713    #[must_use]
714    pub fn new(
715        build: impl Fn() -> reqwest::Result<reqwest::Client> + Send + Sync + 'static,
716    ) -> Self {
717        Self {
718            build: Box::new(build),
719            current: Mutex::new(None),
720        }
721    }
722
723    /// A pool of [`http_client`](super::http_client)s: the SDK's one client shape.
724    #[must_use]
725    pub fn sdk() -> Self {
726        Self::new(super::http_client)
727    }
728
729    /// The generation the held client was built for, if one has been built.
730    #[must_use]
731    pub fn generation(&self) -> Option<PathGeneration> {
732        self.current
733            .lock()
734            .unwrap_or_else(PoisonError::into_inner)
735            .as_ref()
736            .map(|(generation, _)| *generation)
737    }
738
739    /// The client for `generation`: the held one while the generation is unchanged, a fresh one
740    /// — dropping the old pool — once it moves.
741    ///
742    /// # Errors
743    ///
744    /// Whatever building the fresh client refused with; the held client, if any, is kept, so
745    /// the next call tries again.
746    pub fn client(&self, generation: PathGeneration) -> reqwest::Result<reqwest::Client> {
747        let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner);
748        if let Some((held, client)) = current.as_ref()
749            && *held == generation
750        {
751            return Ok(client.clone());
752        }
753        let client = (self.build)()?;
754        if let Some((old, _)) = current.replace((generation, client.clone())) {
755            tracing::info!(
756                old = old.0,
757                new = generation.0,
758                "path: a new generation; dropping pooled connections"
759            );
760        }
761        Ok(client)
762    }
763}
764
765#[cfg(test)]
766mod tests;