Skip to main content

causa_kernel/ports/control/
state.rs

1//! Cooperative cancellation and absolute deadline control for ports.
2
3use std::time::{Duration, Instant};
4use tokio_util::sync::CancellationToken;
5
6/// Cooperative control for a logical model invocation, preparation or tool work.
7#[derive(Debug, Clone)]
8pub struct CallControl {
9    cancellation: CancellationToken,
10    deadline: Option<Instant>,
11}
12
13/// Why a control check failed.
14#[derive(Debug, Clone, thiserror::Error)]
15pub enum ControlError {
16    /// The turn was cancelled.
17    #[error("cancelled")]
18    Cancelled,
19    /// The effective deadline has passed.
20    #[error("deadline exceeded")]
21    TimedOut,
22}
23impl CallControl {
24    /// Builds control from a cancellation token and an absolute deadline.
25    pub fn new(cancellation: CancellationToken, deadline: Option<Instant>) -> Self {
26        Self {
27            cancellation,
28            deadline,
29        }
30    }
31
32    /// Inherits cancellation and narrows the deadline by a local timeout.
33    ///
34    /// The local clock starts now. An unrepresentably distant timeout adds no
35    /// earlier constraint, and this operation never cancels the parent token.
36    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    /// Whether the turn's cancellation has fired.
47    pub fn is_cancelled(&self) -> bool {
48        self.cancellation.is_cancelled()
49    }
50    /// The effective call deadline, if any.
51    pub fn deadline(&self) -> Option<Instant> {
52        self.deadline
53    }
54    /// The turn-shared primitive — race it against in-flight tool work
55    /// instead of polling.
56    pub fn cancellation_token(&self) -> &CancellationToken {
57        &self.cancellation
58    }
59    /// Sync guard for tool loops: `Err` when the turn is cancelled or the
60    /// effective deadline has passed.
61    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}