use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;
use causa_kernel::{AttemptControl, effective_deadline};
#[derive(Debug, Clone)]
pub struct RunControl {
cancellation: CancellationToken,
turn_deadline: Option<Instant>,
}
impl RunControl {
pub fn new(cancellation: CancellationToken, turn_deadline: Option<Instant>) -> Self {
Self {
cancellation,
turn_deadline,
}
}
pub fn is_cancelled(&self) -> bool {
self.cancellation.is_cancelled()
}
pub fn should_stop(&self) -> bool {
self.is_cancelled()
|| self
.turn_deadline
.map(|d| Instant::now() >= d)
.unwrap_or(false)
}
pub fn for_attempt(&self, attempt_timeout: Option<Duration>) -> AttemptControl {
AttemptControl::new(
self.cancellation.clone(),
effective_deadline(self.turn_deadline, attempt_timeout),
)
}
pub fn remaining_turn_time(&self) -> Option<Duration> {
self.turn_deadline
.map(|d| d.saturating_duration_since(Instant::now()))
}
}