Skip to main content

causa_kernel/ports/
control.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///
15/// Exhaustive on purpose: a stop is a cancellation or a deadline, and callers map each to their own result.
16#[derive(Debug, Clone, thiserror::Error)]
17pub enum ControlError {
18    /// The turn was cancelled.
19    #[error("cancelled")]
20    Cancelled,
21    /// The effective deadline has passed.
22    #[error("deadline exceeded")]
23    TimedOut,
24}
25impl CallControl {
26    /// Builds control from a cancellation token and an absolute deadline.
27    pub fn new(cancellation: CancellationToken, deadline: Option<Instant>) -> Self {
28        Self {
29            cancellation,
30            deadline,
31        }
32    }
33
34    /// Inherits cancellation and narrows the deadline by a local timeout.
35    ///
36    /// The local clock starts now. An unrepresentably distant timeout adds no
37    /// earlier constraint, and this operation never cancels the parent token.
38    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    /// Whether the turn's cancellation has fired.
49    pub fn is_cancelled(&self) -> bool {
50        self.cancellation.is_cancelled()
51    }
52    /// The effective call deadline, if any.
53    pub fn deadline(&self) -> Option<Instant> {
54        self.deadline
55    }
56    /// The turn-shared primitive — race it against in-flight tool work
57    /// instead of polling.
58    pub fn cancellation_token(&self) -> &CancellationToken {
59        &self.cancellation
60    }
61    /// Sync guard for tool loops: `Err` when the turn is cancelled or the
62    /// effective deadline has passed.
63    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}