use std::collections::VecDeque;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::{Mutex, PoisonError};
use std::time::Duration;
use tokio::time::Instant;
use super::step::{cut, process_error};
use crate::Result;
use crate::error::{Error, TimedOut};
use crate::process::{Captured, ProcessError, ProcessRunner, ProcessSpec, capture_echoing};
pub(crate) const CEILING: Duration = Duration::from_secs(6 * 3600);
pub(crate) const DOWNLOAD_STALL: Duration = Duration::from_secs(15 * 60);
const RECENT: usize = 64;
const LAST_LINE_MAX: usize = 300;
#[derive(Debug)]
pub(crate) struct Progress(Mutex<Seen>);
#[derive(Debug)]
struct Seen {
at: Instant,
recent: VecDeque<u64>,
last: Option<String>,
}
impl Progress {
pub(crate) fn new() -> Progress {
Progress(Mutex::new(Seen {
at: Instant::now(),
recent: VecDeque::with_capacity(RECENT),
last: None,
}))
}
pub(crate) fn saw(&self, line: &str) {
let line = line.trim();
if line.is_empty() {
return;
}
let mut hasher = DefaultHasher::new();
line.hash(&mut hasher);
let hash = hasher.finish();
let mut seen = self.seen();
seen.last = Some(line.to_owned());
if seen.recent.contains(&hash) {
return;
}
if seen.recent.len() == RECENT {
seen.recent.pop_front();
}
seen.recent.push_back(hash);
seen.at = Instant::now();
}
pub(crate) async fn capture(&self, runner: &dyn ProcessRunner, spec: &ProcessSpec) -> Result<Captured, ProcessError> {
capture_echoing(runner, spec, &mut |_, line| self.saw(line)).await
}
fn seen(&self) -> std::sync::MutexGuard<'_, Seen> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
pub(crate) async fn within<T>(id: &str, limit: Duration, progress: &Progress, run: impl Future<Output = Result<T, ProcessError>>) -> Result<T> {
match watched(limit, Some(limit.max(CEILING)), progress, run).await {
Ok(done) => done.map_err(|e| process_error(id, e)),
Err(timed_out) => Err(Error::Timeout {
step: id.to_owned(),
timed_out,
}),
}
}
pub(crate) async fn downloading<T>(id: &str, stall: Duration, progress: &Progress, run: impl Future<Output = Result<T, ProcessError>>) -> Result<T> {
match watched(stall, None, progress, run).await {
Ok(done) => done.map_err(|e| process_error(id, e)),
Err(TimedOut::NoProgress { after_s, last_line }) => Err(Error::DownloadStalled {
step: id.to_owned(),
after_s,
last_line,
}),
Err(other) => Err(Error::Timeout {
step: id.to_owned(),
timed_out: other,
}),
}
}
async fn watched<T>(limit: Duration, ceiling: Option<Duration>, progress: &Progress, run: impl Future<Output = T>) -> Result<T, TimedOut> {
let deadline = ceiling.map(|c| (Instant::now() + c, c));
tokio::pin!(run);
loop {
let stalled = progress.seen().at + limit;
let wake = deadline.map_or(stalled, |(at, _)| stalled.min(at));
tokio::select! {
biased;
done = &mut run => return Ok(done),
() = tokio::time::sleep_until(wake) => {}
}
let now = Instant::now();
let seen = progress.seen();
if seen.at + limit <= now {
return Err(TimedOut::NoProgress {
after_s: limit.as_secs(),
last_line: seen.last.as_deref().map(|l| cut(l, LAST_LINE_MAX)),
});
}
if let Some((at, after)) = deadline
&& now >= at
{
return Err(TimedOut::Ceiling { after_s: after.as_secs() });
}
}
}
#[cfg(test)]
#[path = "progress_tests.rs"]
mod tests;