Skip to main content

causa_runtime/
control.rs

1//! Turn-level run control — the driver's bundling of the shared
2//! cancellation token and the turn deadline. No port signature consumes this
3//! type (the gateway takes `AttemptControl`, tools take `CallControl`), so it
4//! lives here rather than in the kernel's `ports`.
5
6use std::time::{Duration, Instant};
7use tokio_util::sync::CancellationToken;
8
9use causa_kernel::{AttemptControl, effective_deadline};
10
11/// Turn-level run control: the shared cancellation token plus the turn
12/// deadline. The driver checks [`RunControl::should_stop`] at every loop
13/// top; attempts and tool calls get narrowed views via
14/// [`RunControl::for_attempt`].
15#[derive(Debug, Clone)]
16pub struct RunControl {
17    cancellation: CancellationToken,
18    turn_deadline: Option<Instant>,
19}
20impl RunControl {
21    /// Bundle the shared cancellation token with an optional turn deadline.
22    pub fn new(cancellation: CancellationToken, turn_deadline: Option<Instant>) -> Self {
23        Self {
24            cancellation,
25            turn_deadline,
26        }
27    }
28    /// Whether the shared cancellation token has fired.
29    pub fn is_cancelled(&self) -> bool {
30        self.cancellation.is_cancelled()
31    }
32    /// True when the turn is cancelled or the turn deadline has passed — the
33    /// driver checks this at every loop top.
34    pub fn should_stop(&self) -> bool {
35        self.is_cancelled()
36            || self
37                .turn_deadline
38                .map(|d| Instant::now() >= d)
39                .unwrap_or(false)
40    }
41    /// Narrow the turn-level control into an attempt-scoped one: the shared
42    /// token plus the attempt deadline (earlier of turn deadline and
43    /// attempt timeout).
44    pub fn for_attempt(&self, attempt_timeout: Option<Duration>) -> AttemptControl {
45        AttemptControl::new(
46            self.cancellation.clone(),
47            effective_deadline(self.turn_deadline, attempt_timeout),
48        )
49    }
50    /// Time left until the turn deadline, `Some(0)` once it has passed —
51    /// for driver-owned waits (retry backoff) that must not outlive the
52    /// turn.
53    pub fn remaining_turn_time(&self) -> Option<Duration> {
54        self.turn_deadline
55            .map(|d| d.saturating_duration_since(Instant::now()))
56    }
57}