1use std::time::{Duration, Instant};
19
20use crate::backoff::BackoffPolicy;
21use crate::engine::{PassOutcome, PassReport, SyncEngine};
22use crate::ledger::ConsentRequest;
23use crate::traits::RecordMapper;
24
25#[derive(Debug, Clone, PartialEq)]
27pub struct SyncBudget {
28 pub max_passes: u32,
30 pub max_elapsed: Duration,
32 pub max_inline_delay_secs: f64,
37}
38
39impl Default for SyncBudget {
40 fn default() -> Self {
41 Self {
42 max_passes: 1,
43 max_elapsed: Duration::from_secs(60),
44 max_inline_delay_secs: 0.0,
45 }
46 }
47}
48
49#[derive(Debug, Clone, PartialEq)]
51pub struct SchedulePolicy {
52 pub backoff: BackoffPolicy,
53 pub idle_secs: f64,
55 pub min_secs: f64,
57 pub cancelled_secs: f64,
59}
60
61impl Default for SchedulePolicy {
62 fn default() -> Self {
63 Self {
64 backoff: BackoffPolicy::default(),
65 idle_secs: 900.0,
66 min_secs: 15.0,
67 cancelled_secs: 30.0,
68 }
69 }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum WorkOutcome {
78 Success,
80 Retry,
82 Failure,
85}
86
87#[derive(Debug, Clone, PartialEq)]
89pub struct SyncReport {
90 pub passes: u32,
92 pub outcome: PassOutcome,
94 pub uploaded: usize,
95 pub downloaded: usize,
96 pub tombstones_applied: usize,
97 pub tombstones_written: usize,
98 pub quarantined: usize,
99 pub elapsed_ms: u64,
100 pub work: WorkOutcome,
101 pub next_delay_secs: Option<f64>,
104 pub consent_required: Option<ConsentRequest>,
107}
108
109pub fn sync_once<M: RecordMapper + 'static>(
111 engine: &mut SyncEngine<M>,
112 budget: &SyncBudget,
113 policy: &SchedulePolicy,
114) -> SyncReport {
115 let started = Instant::now();
116 let mut passes = 0u32;
117 let mut total = PassReport {
118 outcome: PassOutcome::Synced,
119 uploaded: 0,
120 downloaded: 0,
121 tombstones_applied: 0,
122 tombstones_written: 0,
123 quarantined: 0,
124 blocked_reuploads: 0,
125 retry_after_secs: None,
126 };
127 let max_passes = budget.max_passes.max(1);
128 loop {
129 let rep = engine.run_pass();
130 passes += 1;
131 total.uploaded += rep.uploaded;
132 total.downloaded += rep.downloaded;
133 total.tombstones_applied += rep.tombstones_applied;
134 total.tombstones_written += rep.tombstones_written;
135 total.quarantined += rep.quarantined;
136 total.blocked_reuploads += rep.blocked_reuploads;
137 let progress =
138 rep.uploaded + rep.downloaded + rep.tombstones_applied + rep.tombstones_written;
139 total.outcome = rep.outcome;
140 total.retry_after_secs = rep.retry_after_secs;
141 if !should_continue(
142 &total.outcome,
143 total.retry_after_secs,
144 progress,
145 passes,
146 max_passes,
147 started.elapsed(),
148 budget,
149 ) {
150 break;
151 }
152 }
153 let failures = engine.ledger().consecutive_failures;
154 let consent_required = match &total.outcome {
155 PassOutcome::ConsentRequired(req) => Some(req.clone()),
156 _ => None,
157 };
158 SyncReport {
159 passes,
160 work: work_outcome(&total.outcome),
161 next_delay_secs: next_delay(&total.outcome, total.retry_after_secs, failures, policy),
162 outcome: total.outcome,
163 uploaded: total.uploaded,
164 downloaded: total.downloaded,
165 tombstones_applied: total.tombstones_applied,
166 tombstones_written: total.tombstones_written,
167 quarantined: total.quarantined,
168 elapsed_ms: started.elapsed().as_millis() as u64,
169 consent_required,
170 }
171}
172
173pub fn should_continue(
175 outcome: &PassOutcome,
176 retry_after_secs: Option<f64>,
177 progress: usize,
178 passes_run: u32,
179 max_passes: u32,
180 elapsed: Duration,
181 budget: &SyncBudget,
182) -> bool {
183 if passes_run >= max_passes || elapsed >= budget.max_elapsed {
184 return false;
185 }
186 if !matches!(outcome, PassOutcome::Pending(_)) || progress == 0 {
187 return false;
188 }
189 match retry_after_secs {
190 Some(s) => s.is_finite() && s <= budget.max_inline_delay_secs,
191 None => true,
192 }
193}
194
195pub fn work_outcome(outcome: &PassOutcome) -> WorkOutcome {
197 match outcome {
198 PassOutcome::Synced => WorkOutcome::Success,
199 PassOutcome::Pending(_)
200 | PassOutcome::Deferred { .. }
201 | PassOutcome::Unavailable(_)
202 | PassOutcome::Cancelled
203 | PassOutcome::Failed(_) => WorkOutcome::Retry,
204 PassOutcome::Disabled | PassOutcome::ConsentRequired(_) => WorkOutcome::Failure,
205 }
206}
207
208pub fn next_delay(
215 outcome: &PassOutcome,
216 retry_after_secs: Option<f64>,
217 failures: u32,
218 policy: &SchedulePolicy,
219) -> Option<f64> {
220 let engine = retry_after_secs.filter(|s| s.is_finite() && *s > 0.0);
221 let secs = match outcome {
222 PassOutcome::Disabled | PassOutcome::ConsentRequired(_) => return None,
223 PassOutcome::Synced => policy.idle_secs,
224 PassOutcome::Pending(_) => engine.unwrap_or(policy.backoff.pending_floor_secs),
225 PassOutcome::Deferred { secs } => {
226 if secs.is_finite() && *secs > 0.0 {
227 *secs
228 } else {
229 policy.min_secs
230 }
231 }
232 PassOutcome::Cancelled => engine.unwrap_or(policy.cancelled_secs),
233 PassOutcome::Unavailable(_) | PassOutcome::Failed(_) => {
234 engine.unwrap_or_else(|| policy.backoff.delay_secs(failures.max(1), None))
235 }
236 };
237 Some(secs.max(policy.min_secs))
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 fn p() -> SchedulePolicy {
245 SchedulePolicy::default()
246 }
247
248 #[test]
249 fn synced_waits_the_idle_period() {
250 assert_eq!(next_delay(&PassOutcome::Synced, None, 0, &p()), Some(900.0));
251 }
252
253 #[test]
254 fn disabled_and_consent_schedule_nothing() {
255 assert_eq!(next_delay(&PassOutcome::Disabled, None, 0, &p()), None);
256 let req = ConsentRequest {
257 from: "a".into(),
258 to: "b".into(),
259 };
260 assert_eq!(
261 next_delay(&PassOutcome::ConsentRequired(req.clone()), None, 0, &p()),
262 None
263 );
264 assert_eq!(work_outcome(&PassOutcome::Disabled), WorkOutcome::Failure);
265 assert_eq!(
266 work_outcome(&PassOutcome::ConsentRequired(req)),
267 WorkOutcome::Failure
268 );
269 }
270
271 #[test]
272 fn pending_uses_the_engine_figure_else_the_floor() {
273 let o = PassOutcome::Pending("x".into());
274 assert_eq!(next_delay(&o, Some(45.0), 0, &p()), Some(45.0));
275 assert_eq!(next_delay(&o, None, 0, &p()), Some(30.0));
276 assert_eq!(work_outcome(&o), WorkOutcome::Retry);
277 }
278
279 #[test]
280 fn deferred_keeps_the_remaining_window_and_never_goes_below_the_minimum() {
281 assert_eq!(
282 next_delay(&PassOutcome::Deferred { secs: 240.0 }, Some(240.0), 3, &p()),
283 Some(240.0)
284 );
285 assert_eq!(
286 next_delay(&PassOutcome::Deferred { secs: 0.4 }, Some(0.4), 3, &p()),
287 Some(15.0)
288 );
289 assert_eq!(
290 next_delay(&PassOutcome::Deferred { secs: f64::NAN }, None, 0, &p()),
291 Some(15.0)
292 );
293 }
294
295 #[test]
296 fn failures_prefer_the_engine_figure_and_fall_back_to_the_exponential() {
297 let f = PassOutcome::Failed("e".into());
298 assert_eq!(next_delay(&f, Some(600.0), 2, &p()), Some(600.0));
300 assert_eq!(next_delay(&f, None, 1, &p()), Some(15.0));
302 assert_eq!(next_delay(&f, None, 2, &p()), Some(30.0));
303 assert_eq!(next_delay(&f, None, 4, &p()), Some(120.0));
304 assert_eq!(next_delay(&f, None, 50, &p()), Some(900.0));
305 assert_eq!(next_delay(&f, None, 0, &p()), Some(15.0));
307 let u = PassOutcome::Unavailable("signed out".into());
308 assert_eq!(next_delay(&u, None, 3, &p()), Some(60.0));
309 assert_eq!(work_outcome(&u), WorkOutcome::Retry);
310 }
311
312 #[test]
313 fn non_finite_or_non_positive_engine_figures_are_ignored() {
314 let f = PassOutcome::Failed("e".into());
315 assert_eq!(next_delay(&f, Some(f64::INFINITY), 2, &p()), Some(30.0));
316 assert_eq!(next_delay(&f, Some(-5.0), 2, &p()), Some(30.0));
317 assert_eq!(next_delay(&f, Some(0.0), 2, &p()), Some(30.0));
318 }
319
320 #[test]
321 fn cancelled_retries_soon() {
322 assert_eq!(
323 next_delay(&PassOutcome::Cancelled, None, 0, &p()),
324 Some(30.0)
325 );
326 assert_eq!(work_outcome(&PassOutcome::Cancelled), WorkOutcome::Retry);
327 assert_eq!(work_outcome(&PassOutcome::Synced), WorkOutcome::Success);
328 }
329
330 #[test]
331 fn a_larger_minimum_lifts_every_delay() {
332 let mut pol = p();
333 pol.min_secs = 60.0;
334 assert_eq!(
335 next_delay(&PassOutcome::Pending("x".into()), Some(30.0), 0, &pol),
336 Some(60.0)
337 );
338 assert_eq!(
339 next_delay(&PassOutcome::Failed("e".into()), None, 1, &pol),
340 Some(60.0)
341 );
342 }
343
344 fn cont(
345 outcome: &PassOutcome,
346 retry: Option<f64>,
347 progress: usize,
348 passes: u32,
349 budget: &SyncBudget,
350 elapsed: Duration,
351 ) -> bool {
352 should_continue(
353 outcome,
354 retry,
355 progress,
356 passes,
357 budget.max_passes,
358 elapsed,
359 budget,
360 )
361 }
362
363 #[test]
364 fn the_default_budget_is_one_pass() {
365 let b = SyncBudget::default();
366 let pending = PassOutcome::Pending("x".into());
367 assert!(!cont(&pending, Some(30.0), 5, 1, &b, Duration::ZERO));
368 }
369
370 #[test]
371 fn a_drain_loop_needs_pending_progress_a_short_wait_and_budget_left() {
372 let b = SyncBudget {
373 max_passes: 3,
374 max_elapsed: Duration::from_secs(10),
375 max_inline_delay_secs: 1.0,
376 };
377 let pending = PassOutcome::Pending("x".into());
378 assert!(cont(&pending, Some(0.5), 2, 1, &b, Duration::from_secs(1)));
379 assert!(cont(&pending, None, 2, 1, &b, Duration::from_secs(1)));
380 assert!(!cont(
382 &pending,
383 Some(30.0),
384 2,
385 1,
386 &b,
387 Duration::from_secs(1)
388 ));
389 assert!(!cont(&pending, Some(0.5), 0, 1, &b, Duration::from_secs(1)));
391 assert!(!cont(&pending, Some(0.5), 2, 3, &b, Duration::from_secs(1)));
393 assert!(!cont(
394 &pending,
395 Some(0.5),
396 2,
397 1,
398 &b,
399 Duration::from_secs(10)
400 ));
401 assert!(!cont(&PassOutcome::Synced, None, 2, 1, &b, Duration::ZERO));
403 assert!(!cont(
404 &PassOutcome::Failed("e".into()),
405 Some(0.5),
406 2,
407 1,
408 &b,
409 Duration::ZERO
410 ));
411 assert!(!cont(
412 &PassOutcome::Deferred { secs: 0.5 },
413 Some(0.5),
414 2,
415 1,
416 &b,
417 Duration::ZERO
418 ));
419 }
420}