relate_core/cancel.rs
1//! Cooperative query cancellation (ADR-0111).
2//!
3//! A [`CancelToken`] is a shared flag. A caller (for example a transport
4//! enforcing a query timeout or handling a disconnect) holds one handle and
5//! cancels it; the thread executing the query holds a cloned handle and stops
6//! at its next cancellation check with a typed error whose message contains
7//! `"query cancelled"`.
8
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::Arc;
11
12/// A cooperative cancellation flag shared between a query's caller and the
13/// worker executing it (ADR-0111).
14///
15/// Cloning shares the same underlying flag, so a transport can cancel a query
16/// it did not start. A `CancelToken` that is never cancelled lets a query run
17/// to completion, which is how [`crate::Error`]'s callers that do not care
18/// about cancellation use it.
19///
20/// ```
21/// use relate_core::CancelToken;
22///
23/// let token = CancelToken::new();
24/// assert!(!token.is_cancelled());
25/// let transport = token.clone();
26/// transport.cancel();
27/// assert!(token.is_cancelled());
28/// ```
29#[derive(Debug, Clone, Default)]
30pub struct CancelToken {
31 cancelled: Arc<AtomicBool>,
32 /// Set (before `cancelled`) only by the statement deadline
33 /// ([`crate::deadline`]): the cause that lets the engine answer
34 /// [`crate::Error::TimedOut`] rather than a plain cancellation.
35 timed_out: Arc<AtomicBool>,
36}
37
38impl CancelToken {
39 /// A fresh token that is not cancelled.
40 pub fn new() -> Self {
41 Self::default()
42 }
43
44 /// Cancel the query sharing this token. Idempotent.
45 pub fn cancel(&self) {
46 self.cancelled.store(true, Ordering::Release);
47 }
48
49 /// Whether [`Self::cancel`] has been called on this token or any clone.
50 pub fn is_cancelled(&self) -> bool {
51 self.cancelled.load(Ordering::Acquire)
52 }
53
54 /// Cancel because the statement deadline passed. The cause is stored
55 /// first, so an observer that sees the cancellation also sees why.
56 pub(crate) fn cancel_timed_out(&self) {
57 self.timed_out.store(true, Ordering::Release);
58 self.cancel();
59 }
60
61 /// Whether the cancellation (if any) came from the statement deadline.
62 pub fn timed_out(&self) -> bool {
63 self.timed_out.load(Ordering::Acquire)
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 #[test]
72 fn clones_share_the_flag() {
73 let token = CancelToken::new();
74 let clone = token.clone();
75 assert!(!clone.is_cancelled());
76 token.cancel();
77 assert!(clone.is_cancelled());
78 clone.cancel();
79 assert!(token.is_cancelled());
80 }
81}