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}
33
34impl CancelToken {
35 /// A fresh token that is not cancelled.
36 pub fn new() -> Self {
37 Self::default()
38 }
39
40 /// Cancel the query sharing this token. Idempotent.
41 pub fn cancel(&self) {
42 self.cancelled.store(true, Ordering::Release);
43 }
44
45 /// Whether [`Self::cancel`] has been called on this token or any clone.
46 pub fn is_cancelled(&self) -> bool {
47 self.cancelled.load(Ordering::Acquire)
48 }
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[test]
56 fn clones_share_the_flag() {
57 let token = CancelToken::new();
58 let clone = token.clone();
59 assert!(!clone.is_cancelled());
60 token.cancel();
61 assert!(clone.is_cancelled());
62 clone.cancel();
63 assert!(token.is_cancelled());
64 }
65}