Skip to main content

causa_runtime/control/
run.rs

1use causa_kernel::CallControl;
2use std::time::{Duration, Instant};
3use tokio_util::sync::CancellationToken;
4
5/// Shared cancellation and an optional absolute execution deadline.
6#[derive(Debug, Clone)]
7pub struct RunControl {
8    cancellation: CancellationToken,
9    deadline: Option<Instant>,
10}
11impl RunControl {
12    /// Combine a caller-owned cancellation token and absolute deadline.
13    pub fn new(cancellation: CancellationToken, deadline: Option<Instant>) -> Self {
14        Self {
15            cancellation,
16            deadline,
17        }
18    }
19    /// Whether cancellation has been requested.
20    pub fn is_cancelled(&self) -> bool {
21        self.cancellation.is_cancelled()
22    }
23    /// The caller-owned cancellation token.
24    pub fn cancellation_token(&self) -> &CancellationToken {
25        &self.cancellation
26    }
27    /// The absolute execution deadline.
28    pub fn deadline(&self) -> Option<Instant> {
29        self.deadline
30    }
31    /// Whether cancellation or the absolute deadline requires stopping.
32    pub fn should_stop(&self) -> bool {
33        self.is_cancelled() || self.deadline.is_some_and(|d| Instant::now() >= d)
34    }
35    /// Inherit the exact token and deadline without starting a local timeout.
36    pub fn call_control(&self) -> CallControl {
37        CallControl::new(self.cancellation.clone(), self.deadline)
38    }
39    /// Remaining execution time, saturating at zero.
40    pub fn remaining_turn_time(&self) -> Option<Duration> {
41        self.deadline
42            .map(|d| d.saturating_duration_since(Instant::now()))
43    }
44}