use std::{
future::Future,
sync::{Arc, Mutex},
time::Duration,
};
use tokio::time::Instant;
use super::{Result, WorkerContext};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PollOutcome {
Worked,
Idle,
RetryAfter(Duration),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PollShutdown {
CancelAttempt,
FinishAttempt,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PollPolicy {
pub idle_interval: Duration,
pub shutdown: PollShutdown,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PollSnapshot {
pub last_success: Option<Instant>,
pub last_work: Option<Instant>,
pub idle_polls: u64,
pub retries: u64,
}
#[derive(Clone, Debug, Default)]
pub struct PollProgress {
state: Arc<Mutex<PollSnapshot>>,
}
impl PollProgress {
pub fn snapshot(&self) -> PollSnapshot {
*self.state.lock().unwrap_or_else(|error| error.into_inner())
}
fn record(&self, outcome: PollOutcome) {
let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
match outcome {
PollOutcome::Worked => {
let now = Instant::now();
state.last_success = Some(now);
state.last_work = Some(now);
}
PollOutcome::Idle => {
state.last_success = Some(Instant::now());
state.idle_polls = state.idle_polls.saturating_add(1);
}
PollOutcome::RetryAfter(_) => state.retries = state.retries.saturating_add(1),
}
}
}
impl WorkerContext {
pub async fn poll<F, Fut>(
&self,
policy: PollPolicy,
progress: Option<&PollProgress>,
mut attempt: F,
) -> Result
where
F: FnMut() -> Fut,
Fut: Future<Output = std::result::Result<PollOutcome, super::BoxError>>,
{
self.ready();
let shutdown = self.shutdown();
while !shutdown.is_requested() {
let outcome = match policy.shutdown {
PollShutdown::CancelAttempt => tokio::select! {
biased;
() = shutdown.cancelled() => return Ok(()),
outcome = async { attempt().await } => outcome?,
},
PollShutdown::FinishAttempt => attempt().await?,
};
if let Some(progress) = progress {
progress.record(outcome);
}
let delay = match outcome {
PollOutcome::Worked => Duration::ZERO,
PollOutcome::Idle => policy.idle_interval,
PollOutcome::RetryAfter(delay) => delay,
};
if delay.is_zero() {
tokio::task::yield_now().await;
} else {
tokio::select! {
biased;
() = shutdown.cancelled() => return Ok(()),
() = tokio::time::sleep(delay) => {}
}
}
}
Ok(())
}
}
#[cfg(test)]
#[path = "poll_test.rs"]
mod tests;