1use std::time::Duration;
15
16use super::{ProgressPhase, ProgressUnit, ReceivedObjects};
17
18#[derive(Debug, Clone, Copy, PartialEq)]
23pub struct PhaseRates {
24 pub indexing: f64,
26 pub resolving: f64,
28 pub checkout: f64,
30}
31
32impl Default for PhaseRates {
33 fn default() -> Self {
36 Self {
37 indexing: 250_000.0,
38 resolving: 300_000.0,
39 checkout: 10_000.0,
40 }
41 }
42}
43
44const ASSUMED_DELTA_SHARE: f64 = 0.7;
46const ASSUMED_FILES_PER_OBJECT: f64 = 0.015;
48const TRUST_MEASURED_AFTER: f64 = 0.1;
51const MAX_UNFINISHED_FRACTION: f64 = 0.99;
53
54#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct OverallEstimate {
57 pub fraction: f64,
60 pub remaining: Duration,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
66enum Stage {
67 Transfer,
68 Indexing,
69 Resolving,
70 Checkout,
71}
72
73const STAGES: [Stage; 4] = [
74 Stage::Transfer,
75 Stage::Indexing,
76 Stage::Resolving,
77 Stage::Checkout,
78];
79
80impl Stage {
81 fn of(phase: ProgressPhase) -> Option<Self> {
82 match phase {
83 ProgressPhase::ReceivingObjects
84 | ProgressPhase::SendingObjects
85 | ProgressPhase::EnumeratingObjects
86 | ProgressPhase::CopyingObjects
87 | ProgressPhase::CompressingObjects
88 | ProgressPhase::WritingObjects => Some(Self::Transfer),
89 ProgressPhase::IndexingObjects => Some(Self::Indexing),
90 ProgressPhase::ResolvingDeltas => Some(Self::Resolving),
91 ProgressPhase::CheckingOutFiles => Some(Self::Checkout),
92 ProgressPhase::TransferringBundle => None,
94 ProgressPhase::StagingFiles => None,
96 }
97 }
98}
99
100#[derive(Debug, Clone, Copy)]
101struct Active {
102 stage: Stage,
103 total: Option<u64>,
105 current: u64,
106 started: Duration,
107}
108
109#[derive(Debug, Clone)]
128pub struct OverallEstimator {
129 rates: PhaseRates,
130 checkout: bool,
131 objects: Option<u64>,
132 deltas: Option<u64>,
133 files: Option<u64>,
134 received: Option<ReceivedObjects>,
135 active: Option<Active>,
136 finished: Option<Stage>,
138 best: f64,
139}
140
141impl OverallEstimator {
142 #[must_use]
149 pub fn new(checkout: bool) -> Self {
150 Self {
151 rates: PhaseRates::default(),
152 checkout,
153 objects: None,
154 deltas: None,
155 files: None,
156 received: None,
157 active: None,
158 finished: None,
159 best: 0.0,
160 }
161 }
162
163 #[must_use]
165 pub fn with_rates(mut self, rates: PhaseRates) -> Self {
166 self.rates = rates;
167 self
168 }
169
170 pub fn start(
174 &mut self,
175 phase: ProgressPhase,
176 unit: ProgressUnit,
177 total: Option<u64>,
178 at: Duration,
179 ) {
180 self.finish(at);
181 let Some(stage) = Stage::of(phase) else {
182 return;
183 };
184 let total = total.filter(|_| unit != ProgressUnit::Bytes);
185 match stage {
186 Stage::Transfer | Stage::Indexing => {
187 if total.is_some() {
188 self.objects = total;
189 }
190 }
191 Stage::Resolving => self.deltas = total,
192 Stage::Checkout => self.files = total,
193 }
194 self.active = Some(Active {
195 stage,
196 total,
197 current: 0,
198 started: at,
199 });
200 }
201
202 pub fn set(&mut self, current: u64) {
204 if let Some(active) = &mut self.active {
205 active.current = current;
206 }
207 }
208
209 pub fn inc(&mut self, units: u64) {
211 if let Some(active) = &mut self.active {
212 active.current = active.current.saturating_add(units);
213 }
214 }
215
216 pub fn received_objects(&mut self, counts: ReceivedObjects, _at: Duration) {
221 self.objects = Some(counts.total);
222 if counts.received > 0 {
223 let share = counts.deltas as f64 / counts.received as f64;
224 self.deltas = Some((share * counts.total as f64).round() as u64);
225 }
226 self.received = Some(counts);
227 }
228
229 pub fn finish(&mut self, _at: Duration) {
231 if let Some(active) = self.active.take() {
232 self.finished = self.finished.max(Some(active.stage));
233 }
234 }
235
236 pub fn estimate(&mut self, at: Duration) -> Option<OverallEstimate> {
239 let remaining = self.remaining_secs(at)?;
240 let elapsed = at.as_secs_f64();
241 let all_done = self.active.is_none() && self.finished == Some(self.last_stage());
242 let raw = if all_done {
243 1.0
244 } else if elapsed + remaining <= 0.0 {
245 0.0
246 } else {
247 (elapsed / (elapsed + remaining)).min(MAX_UNFINISHED_FRACTION)
248 };
249 self.best = self.best.max(raw);
250 Some(OverallEstimate {
251 fraction: self.best,
252 remaining: Duration::from_secs_f64(remaining.max(0.0)),
253 })
254 }
255
256 fn last_stage(&self) -> Stage {
257 if self.checkout {
258 Stage::Checkout
259 } else {
260 Stage::Resolving
261 }
262 }
263
264 fn remaining_secs(&self, at: Duration) -> Option<f64> {
265 let mut total = 0.0;
266 for stage in STAGES {
267 if stage > self.last_stage() || Some(stage) <= self.finished {
268 continue;
269 }
270 match self.active {
271 Some(active) if active.stage == stage => total += self.active_secs(active, at)?,
272 Some(active) if active.stage > stage => {}
274 _ => total += self.pending_secs(stage)?,
275 }
276 }
277 Some(total)
278 }
279
280 fn active_secs(&self, active: Active, at: Duration) -> Option<f64> {
282 let elapsed = at.saturating_sub(active.started).as_secs_f64();
283 let (done, total) = match (active.stage, active.total) {
284 (_, Some(total)) => (active.current, total),
285 (Stage::Transfer, None) => {
286 let counts = self.received?;
287 (counts.received, counts.total)
288 }
289 (_, None) => return self.pending_secs(active.stage),
290 };
291 let left = total.saturating_sub(done) as f64;
292 if left == 0.0 {
293 return Some(0.0);
294 }
295 let share = if total == 0 {
296 1.0
297 } else {
298 done as f64 / total as f64
299 };
300 let typical = self.rate(active.stage).map(|rate| left / rate);
301 if share >= TRUST_MEASURED_AFTER || typical.is_none() {
302 if done == 0 {
303 return None;
304 }
305 return Some(elapsed * left / done as f64);
306 }
307 typical
308 }
309
310 fn pending_secs(&self, stage: Stage) -> Option<f64> {
312 let objects = self.objects? as f64;
313 let units = match stage {
314 Stage::Transfer => return None,
316 Stage::Indexing => objects,
317 Stage::Resolving => self
318 .deltas
319 .map_or(objects * ASSUMED_DELTA_SHARE, |d| d as f64),
320 Stage::Checkout => self
321 .files
322 .map_or(objects * ASSUMED_FILES_PER_OBJECT, |f| f as f64),
323 };
324 Some(units / self.rate(stage)?)
325 }
326
327 fn rate(&self, stage: Stage) -> Option<f64> {
328 let rate = match stage {
329 Stage::Transfer => return None,
330 Stage::Indexing => self.rates.indexing,
331 Stage::Resolving => self.rates.resolving,
332 Stage::Checkout => self.rates.checkout,
333 };
334 (rate > 0.0).then_some(rate)
335 }
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 fn secs(s: f64) -> Duration {
343 Duration::from_secs_f64(s)
344 }
345
346 fn rates() -> PhaseRates {
347 PhaseRates {
348 indexing: 1_000.0,
349 resolving: 1_000.0,
350 checkout: 100.0,
351 }
352 }
353
354 fn receiving(est: &mut OverallEstimator, at: f64) {
355 est.start(
356 ProgressPhase::ReceivingObjects,
357 ProgressUnit::Bytes,
358 None,
359 secs(at),
360 );
361 }
362
363 #[test]
364 fn no_estimate_until_objects_are_counted() {
365 let mut est = OverallEstimator::new(true);
366 assert!(est.estimate(secs(1.0)).is_none());
367 receiving(&mut est, 1.0);
368 est.inc(4096);
369 assert!(
370 est.estimate(secs(2.0)).is_none(),
371 "bytes alone are not enough"
372 );
373 }
374
375 #[test]
376 fn receive_projects_its_pace_and_sizes_later_phases() {
377 let mut est = OverallEstimator::new(true).with_rates(rates());
378 receiving(&mut est, 0.0);
379 est.received_objects(
381 ReceivedObjects {
382 received: 1_000,
383 total: 2_000,
384 deltas: 600,
385 },
386 secs(4.0),
387 );
388 let e = est.estimate(secs(4.0)).unwrap();
389 assert!(
391 (e.remaining.as_secs_f64() - 7.5).abs() < 1e-6,
392 "{:?}",
393 e.remaining
394 );
395 assert!((e.fraction - 4.0 / 11.5).abs() < 1e-6, "{}", e.fraction);
396 }
397
398 #[test]
399 fn active_phase_uses_measured_pace_once_trustworthy() {
400 let mut est = OverallEstimator::new(false).with_rates(rates());
401 est.start(
402 ProgressPhase::IndexingObjects,
403 ProgressUnit::Objects,
404 Some(1_000),
405 secs(10.0),
406 );
407 est.set(10);
409 let early = est.estimate(secs(10.5)).unwrap();
410 assert!((early.remaining.as_secs_f64() - (0.99 + 0.7)).abs() < 1e-6);
411 est.set(500);
413 let later = est.estimate(secs(12.0)).unwrap();
414 assert!((later.remaining.as_secs_f64() - (2.0 + 0.7)).abs() < 1e-6);
415 }
416
417 #[test]
418 fn known_totals_replace_assumptions() {
419 let mut est = OverallEstimator::new(true).with_rates(rates());
420 est.start(
421 ProgressPhase::ResolvingDeltas,
422 ProgressUnit::Objects,
423 Some(0),
424 secs(1.0),
425 );
426 est.finish(secs(1.0));
427 est.start(
428 ProgressPhase::CheckingOutFiles,
429 ProgressUnit::Files,
430 Some(200),
431 secs(1.0),
432 );
433 let e = est.estimate(secs(1.0)).unwrap();
435 assert!((e.remaining.as_secs_f64() - 2.0).abs() < 1e-6);
436 }
437
438 #[test]
439 fn fraction_never_goes_backwards_and_reaches_one_when_done() {
440 let mut est = OverallEstimator::new(false).with_rates(rates());
441 receiving(&mut est, 0.0);
442 est.received_objects(
443 ReceivedObjects {
444 received: 900,
445 total: 1_000,
446 deltas: 0,
447 },
448 secs(9.0),
449 );
450 let high = est.estimate(secs(9.0)).unwrap().fraction;
451 let stalled = est.estimate(secs(30.0)).unwrap().fraction;
453 assert!(stalled >= high);
454 est.start(
455 ProgressPhase::IndexingObjects,
456 ProgressUnit::Objects,
457 Some(1_000),
458 secs(30.0),
459 );
460 est.set(1_000);
461 est.start(
462 ProgressPhase::ResolvingDeltas,
463 ProgressUnit::Objects,
464 Some(0),
465 secs(31.0),
466 );
467 let unfinished = est.estimate(secs(31.0)).unwrap().fraction;
468 assert!(unfinished < 1.0);
469 est.finish(secs(31.0));
470 let done = est.estimate(secs(31.0)).unwrap();
471 assert_eq!(done.fraction, 1.0);
472 assert_eq!(done.remaining, Duration::ZERO);
473 }
474
475 #[test]
476 fn local_copy_with_known_total_is_estimated() {
477 let mut est = OverallEstimator::new(false).with_rates(rates());
478 est.start(
479 ProgressPhase::CopyingObjects,
480 ProgressUnit::Objects,
481 Some(100),
482 secs(0.0),
483 );
484 est.set(50);
485 let e = est.estimate(secs(1.0)).unwrap();
486 assert!((e.remaining.as_secs_f64() - 1.17).abs() < 1e-6, "{e:?}");
488 }
489}