use std::time::{Duration, Instant};
pub struct ConnectionStallTracker {
last_progress_time: Instant,
last_bytes_received: u64,
stalled: bool,
}
impl ConnectionStallTracker {
pub fn new() -> Self {
Self {
last_progress_time: Instant::now(),
last_bytes_received: 0,
stalled: false,
}
}
pub fn new_at(now: Instant) -> Self {
Self {
last_progress_time: now,
last_bytes_received: 0,
stalled: false,
}
}
pub fn update_progress(&mut self, bytes_received: u64) {
if bytes_received > self.last_bytes_received {
self.last_progress_time = Instant::now();
self.last_bytes_received = bytes_received;
self.stalled = false;
}
}
pub fn update_progress_at(&mut self, bytes_received: u64, now: Instant) {
if bytes_received > self.last_bytes_received {
self.last_progress_time = now;
self.last_bytes_received = bytes_received;
self.stalled = false;
}
}
pub fn check_stalled(&mut self, timeout: Duration) -> bool {
let elapsed = self.last_progress_time.elapsed();
self.stalled = elapsed >= timeout;
self.stalled
}
pub fn check_stalled_at(&mut self, timeout: Duration, now: Instant) -> bool {
let elapsed = now.saturating_duration_since(self.last_progress_time);
self.stalled = elapsed >= timeout;
self.stalled
}
pub fn is_stalled(&self) -> bool {
self.stalled
}
pub fn last_progress_time(&self) -> Instant {
self.last_progress_time
}
pub fn last_bytes_received(&self) -> u64 {
self.last_bytes_received
}
pub fn reset(&mut self) {
self.last_progress_time = Instant::now();
self.last_bytes_received = 0;
self.stalled = false;
}
}
impl Default for ConnectionStallTracker {
fn default() -> Self {
Self::new()
}
}