Skip to main content

ratify_protocol/v2/
context.rs

1//! Cancellation and deadlines for Protocol v2 operations (the Go reference's
2//! `context.Context`). A context is cheap to clone and safe to share between
3//! threads. Cancelling a parent cancels every context derived from it.
4
5use std::fmt;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10struct Node {
11    cancelled: AtomicBool,
12    deadline: Option<Instant>,
13    parent: Option<Arc<Node>>,
14}
15
16impl Node {
17    fn done(&self) -> bool {
18        if self.cancelled.load(Ordering::SeqCst) {
19            return true;
20        }
21        if self.deadline.is_some_and(|d| Instant::now() >= d) {
22            return true;
23        }
24        self.parent.as_ref().is_some_and(|p| p.done())
25    }
26}
27
28/// A cancellation context. [`V2Context::background`] is never done.
29#[derive(Clone, Default)]
30pub struct V2Context {
31    node: Option<Arc<Node>>,
32}
33
34/// Cancels the context it was created with (and every context derived from
35/// that one). Dropping the handle does not cancel.
36#[derive(Clone)]
37pub struct V2CancelHandle {
38    node: Arc<Node>,
39}
40
41impl V2Context {
42    /// A context that is never cancelled.
43    pub fn background() -> Self {
44        V2Context { node: None }
45    }
46
47    fn child(&self, deadline: Option<Instant>) -> (V2Context, V2CancelHandle) {
48        let node = Arc::new(Node {
49            cancelled: AtomicBool::new(false),
50            deadline,
51            parent: self.node.clone(),
52        });
53        (
54            V2Context {
55                node: Some(node.clone()),
56            },
57            V2CancelHandle { node },
58        )
59    }
60
61    /// A child context cancelled by the returned handle or by this context.
62    pub fn with_cancel(&self) -> (V2Context, V2CancelHandle) {
63        self.child(None)
64    }
65
66    /// A child context that is also done once `timeout` has elapsed.
67    pub fn with_timeout(&self, timeout: Duration) -> (V2Context, V2CancelHandle) {
68        self.child(Instant::now().checked_add(timeout))
69    }
70
71    /// Whether the context is cancelled or past its deadline.
72    pub fn is_done(&self) -> bool {
73        self.node.as_ref().is_some_and(|n| n.done())
74    }
75}
76
77impl V2CancelHandle {
78    /// Cancel the context. Idempotent.
79    pub fn cancel(&self) {
80        self.node.cancelled.store(true, Ordering::SeqCst);
81    }
82}
83
84impl fmt::Debug for V2Context {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.debug_struct("V2Context")
87            .field("done", &self.is_done())
88            .finish()
89    }
90}
91
92impl fmt::Debug for V2CancelHandle {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.write_str("V2CancelHandle")
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn cancellation_propagates_to_children_only() {
104        let root = V2Context::background();
105        assert!(!root.is_done());
106        let (parent, cancel_parent) = root.with_cancel();
107        let (child, cancel_child) = parent.with_cancel();
108        cancel_child.cancel();
109        assert!(child.is_done());
110        assert!(!parent.is_done());
111        let (other, _) = parent.with_cancel();
112        cancel_parent.cancel();
113        assert!(other.is_done());
114        assert!(!root.is_done());
115    }
116
117    #[test]
118    fn timeout_marks_done() {
119        let (ctx, _) = V2Context::background().with_timeout(Duration::from_millis(0));
120        assert!(ctx.is_done());
121    }
122}