use std::time::{Duration, Instant};
use crate::domain::Board;
use crate::sync::{Error, JobOutcome};
use super::model::{Problem, SyncStatus};
const DEBOUNCE: Duration = Duration::from_secs(3);
const RETRY: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, Copy)]
pub(crate) struct SyncState {
pub dirty: bool,
pub in_flight: usize,
pub since_change: Duration,
pub retry_pending: bool,
pub needs_pull: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Due {
Nothing,
Push,
PullThenPush,
}
pub(crate) fn due(state: &SyncState, debounce: Duration) -> Due {
if !state.dirty || state.in_flight > 0 || state.since_change < debounce || state.retry_pending {
return Due::Nothing;
}
if state.needs_pull {
Due::PullThenPush
} else {
Due::Push
}
}
#[derive(Debug)]
pub struct SyncTracker {
status: SyncStatus,
problem: Option<Problem>,
dirty: bool,
last_change: Instant,
retry_at: Option<Instant>,
in_flight: usize,
needs_pull: bool,
}
impl SyncTracker {
pub fn new(enabled: bool, now: Instant) -> Self {
Self {
status: if enabled {
SyncStatus::Idle
} else {
SyncStatus::Local
},
problem: None,
dirty: false,
last_change: now,
retry_at: None,
in_flight: 0,
needs_pull: false,
}
}
pub fn status(&self) -> SyncStatus {
self.status
}
pub fn problem(&self) -> Option<&Problem> {
self.problem.as_ref()
}
pub fn needs_flush(&self) -> bool {
self.dirty || self.in_flight > 0 || self.needs_pull
}
pub fn changed(&mut self, now: Instant) {
self.dirty = true;
self.last_change = now;
}
pub fn pull_queued(&mut self) {
self.in_flight += 1;
self.needs_pull = false;
self.status = SyncStatus::Syncing;
}
pub fn push_queued(&mut self) {
self.in_flight += 1;
self.dirty = false;
self.retry_at = None;
self.status = SyncStatus::Syncing;
}
pub fn failed(&mut self, error: &Error) {
self.status = SyncStatus::Idle;
self.problem = Some(
Problem::new(error.kind().footer(), error.detail())
.with_hint("run `tasu sync` to retry now"),
);
}
pub fn on_outcome(&mut self, outcome: JobOutcome, now: Instant) -> Option<Board> {
self.in_flight = self.in_flight.saturating_sub(1);
match outcome {
JobOutcome::UpToDate | JobOutcome::Pushed => {
self.status = SyncStatus::Idle;
self.problem = None;
None
}
JobOutcome::Merged(board) => {
self.status = SyncStatus::Idle;
self.problem = None;
board
}
JobOutcome::Failed(error) => {
self.dirty = true;
self.needs_pull = true;
self.retry_at = Some(now + RETRY);
self.failed(&error);
None
}
}
}
pub fn due(&self, now: Instant) -> Due {
due(
&SyncState {
dirty: self.dirty,
in_flight: self.in_flight,
since_change: now.saturating_duration_since(self.last_change),
retry_pending: self.retry_at.is_some_and(|at| now < at),
needs_pull: self.needs_pull,
},
DEBOUNCE,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn state(
dirty: bool,
in_flight: usize,
since_secs: u64,
retry_pending: bool,
needs_pull: bool,
) -> SyncState {
SyncState {
dirty,
in_flight,
since_change: Duration::from_secs(since_secs),
retry_pending,
needs_pull,
}
}
#[test]
fn a_clean_board_is_never_pushed() {
assert_eq!(
due(&state(false, 0, 10, false, false), DEBOUNCE),
Due::Nothing
);
}
#[test]
fn a_push_waits_out_the_debounce_window() {
assert_eq!(
due(&state(true, 0, 1, false, false), DEBOUNCE),
Due::Nothing,
"too soon after the change"
);
assert_eq!(
due(&state(true, 0, 3, false, false), DEBOUNCE),
Due::Push,
"at the boundary the push is due"
);
assert_eq!(due(&state(true, 0, 9, false, false), DEBOUNCE), Due::Push);
}
#[test]
fn nothing_is_scheduled_while_a_job_is_in_flight() {
assert_eq!(
due(&state(true, 1, 10, false, true), DEBOUNCE),
Due::Nothing
);
}
#[test]
fn the_retry_backoff_holds_the_push() {
assert_eq!(
due(&state(true, 0, 10, true, false), DEBOUNCE),
Due::Nothing,
"still inside the backoff window"
);
}
#[test]
fn after_a_failure_the_push_pulls_first() {
assert_eq!(
due(&state(true, 0, 10, false, true), DEBOUNCE),
Due::PullThenPush
);
}
#[test]
fn a_failed_job_backs_off_then_pulls_before_pushing() {
let t0 = Instant::now();
let mut tracker = SyncTracker::new(true, t0);
tracker.changed(t0);
tracker.push_queued();
let board = tracker.on_outcome(
JobOutcome::Failed(Error::new(
"fatal: unable to access: Could not resolve host",
)),
t0,
);
assert!(board.is_none());
let problem = tracker.problem().expect("a failed push is shown");
assert_eq!(problem.summary, "offline");
assert!(
problem.detail.contains("Could not resolve host"),
"the git error is kept whole: {}",
problem.detail
);
assert_eq!(tracker.status(), SyncStatus::Idle);
assert!(tracker.needs_flush(), "a failed push is still owed");
assert_eq!(tracker.due(t0 + Duration::from_secs(10)), Due::Nothing);
assert_eq!(tracker.due(t0 + Duration::from_secs(40)), Due::PullThenPush);
}
#[test]
fn a_pulled_remote_board_is_handed_back_and_the_change_stays_owed() {
let t0 = Instant::now();
let mut tracker = SyncTracker::new(true, t0);
tracker.changed(t0);
tracker.pull_queued();
let board = tracker.on_outcome(JobOutcome::Merged(Some(Board::new())), t0);
assert!(board.is_some());
assert_eq!(tracker.status(), SyncStatus::Idle);
assert!(tracker.needs_flush(), "the local change is not pushed yet");
}
#[test]
fn a_push_confirmed_by_the_worker_clears_the_debt() {
let t0 = Instant::now();
let mut tracker = SyncTracker::new(true, t0);
tracker.changed(t0);
tracker.push_queued();
assert_eq!(tracker.status(), SyncStatus::Syncing);
tracker.on_outcome(JobOutcome::Pushed, t0);
assert_eq!(tracker.status(), SyncStatus::Idle);
assert!(!tracker.needs_flush());
}
#[test]
fn a_local_board_never_reports_sync_state() {
let tracker = SyncTracker::new(false, Instant::now());
assert_eq!(tracker.status(), SyncStatus::Local);
assert!(!tracker.needs_flush());
}
#[test]
fn a_successful_push_clears_the_problem() {
let t0 = Instant::now();
let mut tracker = SyncTracker::new(true, t0);
tracker.changed(t0);
tracker.push_queued();
tracker.on_outcome(
JobOutcome::Failed(Error::new("fatal: could not resolve host")),
t0,
);
assert!(tracker.problem().is_some());
tracker.on_outcome(JobOutcome::Pushed, t0);
assert!(tracker.problem().is_none(), "recovery clears the footer");
}
#[test]
fn a_setup_failure_is_classified_for_the_footer() {
let mut tracker = SyncTracker::new(true, Instant::now());
tracker.failed(&Error::new("sync worker stopped"));
let problem = tracker.problem().expect("the setup failure is shown");
assert_eq!(problem.summary, "sync failed");
assert_eq!(
problem.hint.as_deref(),
Some("run `tasu sync` to retry now")
);
}
}