1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum PathCost {
37 Unmetered,
39 Metered,
41 Constrained,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum Reachability {
48 Reachable,
50 Unreachable,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum PathInterface {
58 Wired,
60 Wifi,
62 Cellular,
64 Other,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum PowerState {
71 External,
73 Battery,
75 LowPower,
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
82pub enum ThermalState {
83 Nominal,
85 Fair,
87 Serious,
89 Critical,
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum Execution {
96 Foreground,
98 Background {
100 deadline: Duration,
102 },
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct PathSample {
108 pub cost: PathCost,
110 pub reachability: Reachability,
112 pub interface: PathInterface,
114 pub power: PowerState,
116 pub thermal: ThermalState,
118 pub execution: Execution,
120}
121
122impl PathSample {
123 #[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 #[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 #[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 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
188pub struct PathGeneration(pub u64);
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub struct PathSnapshot {
193 pub sample: PathSample,
197 pub generation: PathGeneration,
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
203pub struct LinkBehaviour {
204 pub adverse: bool,
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
210pub struct HeldAdvice {
211 pub advice: ServerAdvice,
213 pub age: Duration,
215}
216
217impl HeldAdvice {
218 #[must_use]
220 pub const fn none() -> Self {
221 Self {
222 advice: ServerAdvice::absent(),
223 age: Duration::ZERO,
224 }
225 }
226}
227
228pub const MIN_BULK_DEADLINE: Duration = Duration::from_mins(1);
232
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum TierAdmission {
236 All,
238 IndexOnly,
240 Nothing,
242}
243
244impl TierAdmission {
245 #[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 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum Hold {
284 Offline,
286 ThermalCritical,
288 Cost,
291 Adverse,
293 LowPower,
295 ThermalSerious,
297 Deadline,
299}
300
301impl Hold {
302 #[must_use]
306 pub const fn yields_to_force_sync(self) -> bool {
307 matches!(self, Self::Cost | Self::Adverse)
308 }
309}
310
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
313pub struct TransferPlan {
314 pub generation: PathGeneration,
316 pub class: ConnectionClass,
318 pub admission: TierAdmission,
320 pub hold: Option<Hold>,
322 pub windows: LaneWindows,
325 pub chunk_target: Duration,
327 pub suggested_chunk: Option<u64>,
329 pub range_window: Option<u64>,
331}
332
333impl TransferPlan {
334 #[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 #[must_use]
342 pub fn defers_bulk(&self) -> bool {
343 self.admission != TierAdmission::All
344 }
345
346 #[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
444pub enum PathUpdate {
445 NewPath(TransferPlan),
448 SamePath(TransferPlan),
450}
451
452impl PathUpdate {
453 #[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 snapshot: PathSnapshot,
466 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 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
492pub 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 #[must_use]
524 pub fn new(sample: PathSample, bounds: LaneWindows) -> Self {
525 Self::with_thresholds(sample, bounds, AdverseThresholds::default())
526 }
527
528 #[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 #[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 self.state.lock().unwrap_or_else(PoisonError::into_inner)
569 }
570
571 #[must_use]
573 pub fn snapshot(&self) -> PathSnapshot {
574 self.state().current(self.clock.now_millis())
575 }
576
577 #[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 #[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 #[must_use]
597 pub fn subscribe(&self) -> watch::Receiver<TransferPlan> {
598 let _ = self.plan();
599 self.plans.subscribe()
600 }
601
602 #[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 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 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 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
690pub 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 #[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 #[must_use]
725 pub fn sdk() -> Self {
726 Self::new(super::http_client)
727 }
728
729 #[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 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;