use crate::errors::{ErrorKind, Result};
use std::thread;
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy)]
pub enum Status {
NotFound,
InProgress,
Complete,
}
static POLL_INTERVAL: Duration = Duration::from_secs(1);
pub trait Task {
fn query_status(&self) -> Result<Status>;
fn wait_till_complete(&self, timeout: Option<Duration>) -> Result<Status> {
let now = Instant::now();
let timeout_elapsed = |deadline| now.elapsed() + POLL_INTERVAL > deadline;
loop {
thread::sleep(POLL_INTERVAL);
match self.query_status() {
Ok(Status::NotFound) => {
bail!(ErrorKind::BadResponse("task status not found".to_string()))
}
Ok(Status::InProgress) => {} error_or_complete => return error_or_complete,
}
if timeout.map_or(false, timeout_elapsed) {
bail!(ErrorKind::Timeout("Task timeout reached".to_string()))
}
}
}
}