causa_kernel/ports/control/
state.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)]
15pub enum ControlError {
16 #[error("cancelled")]
18 Cancelled,
19 #[error("deadline exceeded")]
21 TimedOut,
22}
23impl CallControl {
24 pub fn new(cancellation: CancellationToken, deadline: Option<Instant>) -> Self {
26 Self {
27 cancellation,
28 deadline,
29 }
30 }
31
32 pub fn with_timeout(&self, timeout: Duration) -> Self {
37 let local = Instant::now().checked_add(timeout);
38 let deadline = match (self.deadline, local) {
39 (Some(parent), Some(local)) => Some(parent.min(local)),
40 (parent, None) => parent,
41 (None, local) => local,
42 };
43 Self::new(self.cancellation.clone(), deadline)
44 }
45
46 pub fn is_cancelled(&self) -> bool {
48 self.cancellation.is_cancelled()
49 }
50 pub fn deadline(&self) -> Option<Instant> {
52 self.deadline
53 }
54 pub fn cancellation_token(&self) -> &CancellationToken {
57 &self.cancellation
58 }
59 pub fn check(&self) -> Result<(), ControlError> {
62 if self.cancellation.is_cancelled() {
63 return Err(ControlError::Cancelled);
64 }
65 if self.deadline.map(|d| Instant::now() >= d).unwrap_or(false) {
66 return Err(ControlError::TimedOut);
67 }
68 Ok(())
69 }
70}