use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;
#[derive(Debug, Clone)]
pub struct CallControl {
cancellation: CancellationToken,
deadline: Option<Instant>,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum ControlError {
#[error("cancelled")]
Cancelled,
#[error("deadline exceeded")]
TimedOut,
}
impl CallControl {
pub fn new(cancellation: CancellationToken, deadline: Option<Instant>) -> Self {
Self {
cancellation,
deadline,
}
}
pub fn with_timeout(&self, timeout: Duration) -> Self {
let local = Instant::now().checked_add(timeout);
let deadline = match (self.deadline, local) {
(Some(parent), Some(local)) => Some(parent.min(local)),
(parent, None) => parent,
(None, local) => local,
};
Self::new(self.cancellation.clone(), deadline)
}
pub fn is_cancelled(&self) -> bool {
self.cancellation.is_cancelled()
}
pub fn deadline(&self) -> Option<Instant> {
self.deadline
}
pub fn cancellation_token(&self) -> &CancellationToken {
&self.cancellation
}
pub fn check(&self) -> Result<(), ControlError> {
if self.cancellation.is_cancelled() {
return Err(ControlError::Cancelled);
}
if self.deadline.map(|d| Instant::now() >= d).unwrap_or(false) {
return Err(ControlError::TimedOut);
}
Ok(())
}
}