1use std::cell::RefCell;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::sync::{Arc, Mutex, Weak};
13
14pub(crate) const CANCELLED_SENTINEL: &str = "__isle_cancelled__";
16
17#[derive(Clone)]
44pub struct CancelToken {
45 inner: Arc<Inner>,
46}
47
48struct Inner {
49 flag: AtomicBool,
50 #[cfg(feature = "tokio")]
51 notify: tokio::sync::Notify,
52 _parent: Option<Arc<Inner>>,
54 children: Mutex<Children>,
55}
56
57#[derive(Default)]
58struct Children {
59 list: Vec<Weak<Inner>>,
60 sweep_at: usize,
62}
63
64impl Inner {
65 fn new(parent: Option<Arc<Inner>>) -> Self {
66 Self {
67 flag: AtomicBool::new(false),
68 #[cfg(feature = "tokio")]
69 notify: tokio::sync::Notify::new(),
70 _parent: parent,
71 children: Mutex::new(Children::default()),
72 }
73 }
74
75 fn cancel(&self) {
76 if self.flag.swap(true, Ordering::AcqRel) {
77 return;
78 }
79 #[cfg(feature = "tokio")]
80 self.notify.notify_waiters();
81 let children = std::mem::take(&mut lock(&self.children).list);
82 for child in children.iter().filter_map(Weak::upgrade) {
83 child.cancel();
84 }
85 }
86}
87
88fn lock(m: &Mutex<Children>) -> std::sync::MutexGuard<'_, Children> {
89 m.lock().unwrap_or_else(|e| e.into_inner())
92}
93
94impl CancelToken {
95 pub fn new() -> Self {
97 Self {
98 inner: Arc::new(Inner::new(None)),
99 }
100 }
101
102 pub fn child_token(&self) -> CancelToken {
108 let child = Arc::new(Inner::new(Some(self.inner.clone())));
109 let mut children = lock(&self.inner.children);
110 if self.is_cancelled() {
113 drop(children);
114 child.cancel();
115 } else {
116 if children.list.len() >= children.sweep_at {
117 children.list.retain(|w| w.strong_count() > 0);
118 children.sweep_at = (children.list.len() * 2).max(16);
119 }
120 children.list.push(Arc::downgrade(&child));
121 }
122 CancelToken { inner: child }
123 }
124
125 pub fn cancel(&self) {
132 self.inner.cancel();
133 }
134
135 pub fn is_cancelled(&self) -> bool {
137 self.inner.flag.load(Ordering::Acquire)
138 }
139
140 #[cfg(feature = "tokio")]
153 pub async fn cancelled(&self) {
154 if self.is_cancelled() {
155 return;
156 }
157 let notified = self.inner.notify.notified();
158 tokio::pin!(notified);
159 notified.as_mut().enable();
160 if self.is_cancelled() {
165 return;
166 }
167 notified.await;
168 }
169
170 #[cfg(test)]
171 fn live_children(&self) -> usize {
172 lock(&self.inner.children)
173 .list
174 .iter()
175 .filter(|w| w.strong_count() > 0)
176 .count()
177 }
178
179 #[cfg(test)]
180 fn stored_children(&self) -> usize {
181 lock(&self.inner.children).list.len()
182 }
183}
184
185impl Default for CancelToken {
186 fn default() -> Self {
187 Self::new()
188 }
189}
190
191impl std::fmt::Debug for CancelToken {
192 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 f.debug_struct("CancelToken")
194 .field("cancelled", &self.is_cancelled())
195 .finish()
196 }
197}
198
199thread_local! {
200 static CURRENT: RefCell<Option<CancelToken>> = const { RefCell::new(None) };
203}
204
205pub fn current_token() -> Option<CancelToken> {
213 CURRENT.with(|c| c.borrow().clone())
214}
215
216pub(crate) fn current_is_cancelled() -> bool {
218 CURRENT.with(|c| c.borrow().as_ref().is_some_and(CancelToken::is_cancelled))
219}
220
221pub(crate) struct EnterGuard {
225 prev: Option<CancelToken>,
226}
227
228impl EnterGuard {
229 pub(crate) fn new(token: &CancelToken) -> Self {
230 let prev = CURRENT.with(|c| c.replace(Some(token.clone())));
231 Self { prev }
232 }
233}
234
235impl Drop for EnterGuard {
236 fn drop(&mut self) {
237 let prev = self.prev.take();
238 CURRENT.with(|c| *c.borrow_mut() = prev);
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 #[test]
247 fn token_default_not_cancelled() {
248 let token = CancelToken::new();
249 assert!(!token.is_cancelled());
250 }
251
252 #[test]
253 fn token_cancel_sets_flag() {
254 let token = CancelToken::new();
255 let clone = token.clone();
256 token.cancel();
257 assert!(clone.is_cancelled());
258 }
259
260 #[test]
261 fn cancel_reaches_descendants_not_ancestors() {
262 let root = CancelToken::new();
263 let child = root.child_token();
264 let grandchild = child.child_token();
265 let sibling = root.child_token();
266
267 child.cancel();
268 assert!(child.is_cancelled());
269 assert!(grandchild.is_cancelled());
270 assert!(!root.is_cancelled());
271 assert!(!sibling.is_cancelled());
272
273 root.cancel();
274 assert!(sibling.is_cancelled());
275 }
276
277 #[test]
278 fn child_of_cancelled_token_starts_cancelled() {
279 let root = CancelToken::new();
280 root.cancel();
281 assert!(root.child_token().is_cancelled());
282 }
283
284 #[test]
285 fn grandchild_stays_reachable_after_middle_handle_is_dropped() {
286 let root = CancelToken::new();
287 let grandchild = root.child_token().child_token();
288 root.cancel();
289 assert!(grandchild.is_cancelled());
290 }
291
292 #[test]
293 fn dropped_children_are_swept() {
294 let root = CancelToken::new();
295 let keep = root.child_token();
296 for _ in 0..10_000 {
297 let _ = root.child_token();
298 }
299 assert_eq!(root.live_children(), 1);
300 assert!(
301 root.stored_children() <= 32,
302 "dead children were not swept: {}",
303 root.stored_children()
304 );
305 root.cancel();
306 assert!(keep.is_cancelled());
307 }
308
309 #[test]
310 fn current_token_follows_enter_guards() {
311 assert!(current_token().is_none());
312 let outer = CancelToken::new();
313 let inner = CancelToken::new();
314 {
315 let _o = EnterGuard::new(&outer);
316 {
317 let _i = EnterGuard::new(&inner);
318 inner.cancel();
319 assert!(current_is_cancelled());
320 }
321 assert!(!current_is_cancelled());
322 }
323 assert!(current_token().is_none());
324 }
325}