causa_kernel/ports/
control.rs1use std::time::{Duration, Instant};
4use tokio_util::sync::CancellationToken;
5
6#[derive(Debug, Clone)]
8pub struct CallControl {
9 cancellation: CancellationToken,
10 deadline: Option<Instant>,
11}
12
13#[derive(Debug, Clone, thiserror::Error)]
17pub enum ControlError {
18 #[error("cancelled")]
20 Cancelled,
21 #[error("deadline exceeded")]
23 TimedOut,
24}
25impl CallControl {
26 pub fn new(cancellation: CancellationToken, deadline: Option<Instant>) -> Self {
28 Self {
29 cancellation,
30 deadline,
31 }
32 }
33
34 pub fn with_timeout(&self, timeout: Duration) -> Self {
39 let local = Instant::now().checked_add(timeout);
40 let deadline = match (self.deadline, local) {
41 (Some(parent), Some(local)) => Some(parent.min(local)),
42 (parent, None) => parent,
43 (None, local) => local,
44 };
45 Self::new(self.cancellation.clone(), deadline)
46 }
47
48 pub fn is_cancelled(&self) -> bool {
50 self.cancellation.is_cancelled()
51 }
52 pub fn deadline(&self) -> Option<Instant> {
54 self.deadline
55 }
56 pub fn cancellation_token(&self) -> &CancellationToken {
59 &self.cancellation
60 }
61 pub fn check(&self) -> Result<(), ControlError> {
64 if self.cancellation.is_cancelled() {
65 return Err(ControlError::Cancelled);
66 }
67 if self.deadline.map(|d| Instant::now() >= d).unwrap_or(false) {
68 return Err(ControlError::TimedOut);
69 }
70 Ok(())
71 }
72}