Skip to main content

open_net/api/ws/
cancellation.rs

1use crate::common::log::log_def::LogType;
2use crate::NetError;
3use std::collections::HashMap;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex, MutexGuard, Weak};
6use tokio_util::sync::CancellationToken;
7
8/// A cancellation control handle shared by a group of operations.
9///
10/// Cancelling a parent group prevents all descendants from admitting further
11/// operations; cancelling a child does not affect its parent or sibling groups.
12/// Dropping this handle only releases a reference. Use
13/// [`Self::cancel_on_drop`] to cancel when a guard is dropped.
14#[derive(Clone)]
15pub struct CancellationGroup {
16    /// Cancellation status and parent-child relationship shared by multiple handles.
17    pub(crate) inner: Arc<CancellationState>,
18}
19
20impl CancellationGroup {
21    /// Creates an active cancellation group with no parent.
22    pub fn new() -> Self {
23        Self {
24            inner: CancellationState::new(),
25        }
26    }
27
28    /// Creates a child group whose cancellation is independent unless the parent is cancelled.
29    pub fn child(&self) -> Self {
30        Self {
31            inner: self.inner.child(),
32        }
33    }
34
35    /// Irreversibly close admission, then wake waiters outside internal locks.
36    /// This needs no runtime and does not wait for network or callback cleanup.
37    pub fn cancel(&self) {
38        self.inner.cancel();
39    }
40
41    /// Returns whether cancellation has been requested for this group or an ancestor.
42    pub fn is_cancelled(&self) -> bool {
43        self.inner.is_cancelled()
44    }
45
46    /// Wait for cancellation without creating a worker or requiring a runtime.
47    pub async fn cancelled(&self) {
48        self.inner.notification.cancelled().await;
49    }
50
51    /// Returns a guard that cancels this group when dropped unless disarmed.
52    pub fn cancel_on_drop(&self) -> CancellationGuard {
53        CancellationGuard {
54            group: self.clone(),
55            armed: true,
56        }
57    }
58}
59
60impl Default for CancellationGroup {
61    fn default() -> Self {
62        Self::new()
63    }
64}
65
66impl std::fmt::Debug for CancellationGroup {
67    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        formatter
69            .debug_struct("CancellationGroup")
70            .field("cancelled", &self.is_cancelled())
71            .finish_non_exhaustive()
72    }
73}
74
75/// Cancels the associated group when dropped; call [`Self::disarm`] to disable
76/// automatic cancellation.
77#[must_use]
78#[derive(Debug)]
79pub struct CancellationGuard {
80    /// Group cancelled by this guard when it remains armed.
81    group: CancellationGroup,
82    /// Whether cancellation still needs to be performed on destruction; `false` after removing the guard.
83    armed: bool,
84}
85
86impl CancellationGuard {
87    /// Disarms automatic cancellation and returns the associated group.
88    pub fn disarm(mut self) -> CancellationGroup {
89        self.armed = false;
90        self.group.clone()
91    }
92}
93
94impl Drop for CancellationGuard {
95    fn drop(&mut self) {
96        if self.armed {
97            self.group.cancel();
98        }
99    }
100}
101
102/// Internal state for one cancellation-tree node, coordinating operation
103/// admission, cancellation propagation, and cleanup callbacks.
104pub(crate) struct CancellationState {
105    /// Mutex gate shared by the cancellation tree to order admission and
106    /// cancellation deterministically.
107    gate: Arc<Mutex<()>>,
108    /// Whether this node has been canceled; once set to `true` it will not be restored.
109    cancelled: AtomicBool,
110    /// Used to wake up asynchronous tasks waiting for cancellation by this node.
111    notification: CancellationToken,
112    /// Strong reference to the parent. It keeps an intermediate node alive while
113    /// descendants remain; the root has `None`.
114    parent: Option<Arc<CancellationState>>,
115    /// Weak references to child nodes indexed by allocation address, used to propagate cancellation downward without forming a reference cycle.
116    pub(crate) children: Mutex<HashMap<usize, Weak<CancellationState>>>,
117    /// Weak references to cancellation hooks. Hooks are removed on cancellation
118    /// and invoked after releasing the gate lock.
119    pub(crate) hooks: Mutex<HashMap<usize, Weak<CancelHook>>>,
120}
121
122/// Internal cleanup action performed when its cancellation domain is cancelled.
123pub(crate) struct CancelHook {
124    /// Shared cleanup callback invoked after the tree gate is released.
125    action: Arc<dyn Fn() + Send + Sync>,
126}
127
128/// Holds an internal cleanup-callback registration. Dropping it unregisters the
129/// callback without cancelling the domain. If the callback owner also holds
130/// this guard, its back-reference must be weak.
131pub(crate) struct CancelHookGuard {
132    /// Cancellation domain for the registration; keeps it accessible while the
133    /// guard is alive.
134    owner: Arc<CancellationState>,
135    /// Cleanup callback removed from the domain when this guard is dropped.
136    hook: Arc<CancelHook>,
137}
138
139impl CancellationState {
140    pub(crate) fn new() -> Arc<Self> {
141        Arc::new(Self {
142            gate: Arc::new(Mutex::new(())),
143            cancelled: AtomicBool::new(false),
144            notification: CancellationToken::new(),
145            parent: None,
146            children: Mutex::new(HashMap::new()),
147            hooks: Mutex::new(HashMap::new()),
148        })
149    }
150
151    /// Create a separately cancellable child. A cancelled parent creates a cancelled child.
152    pub(crate) fn child(self: &Arc<Self>) -> Arc<Self> {
153        let gate = lock_recover(&self.gate);
154        let cancelled = self.is_cancelled();
155        let child = Arc::new(CancellationState {
156            gate: self.gate.clone(),
157            cancelled: AtomicBool::new(cancelled),
158            notification: CancellationToken::new(),
159            parent: Some(self.clone()),
160            children: Mutex::new(HashMap::new()),
161            hooks: Mutex::new(HashMap::new()),
162        });
163        lock_recover(&self.children).insert(Arc::as_ptr(&child) as usize, Arc::downgrade(&child));
164        drop(gate);
165        if cancelled {
166            child.notification.cancel();
167        }
168        child
169    }
170
171    /// Close this domain and all descendants, then notify waiters and internal cleanup.
172    ///
173    /// This is synchronous and needs no runtime. Cleanup callbacks run after the shared
174    /// admission lock is released; cancellation does not wait for user response handlers.
175    pub(crate) fn cancel(self: &Arc<Self>) {
176        let gate = lock_recover(&self.gate);
177        let mut pending = vec![self.clone()];
178        let mut cancelled = Vec::new();
179        let mut hooks = Vec::new();
180        while let Some(domain) = pending.pop() {
181            domain.cancelled.store(true, Ordering::Release);
182            pending.extend(
183                lock_recover(&domain.children)
184                    .values()
185                    .filter_map(Weak::upgrade),
186            );
187            hooks.extend(
188                lock_recover(&domain.hooks)
189                    .drain()
190                    .filter_map(|(_, hook)| hook.upgrade()),
191            );
192            cancelled.push(domain);
193        }
194        drop(gate);
195        // Even custom wake implementations must not execute while the gate is held.
196        for domain in cancelled {
197            domain.notification.cancel();
198        }
199        for hook in hooks {
200            (hook.action)();
201        }
202    }
203
204    /// Read the irreversible local cancellation state without taking the admission lock.
205    pub(crate) fn is_cancelled(&self) -> bool {
206        self.cancelled.load(Ordering::Acquire)
207    }
208
209    /// Lock a single synchronous admission step. Do not hold the guard across an await,
210    /// invoke cancellation/binding, or reacquire this tree's gate from the guarded code.
211    pub(crate) fn lock_if_active(&self) -> Result<MutexGuard<'_, ()>, NetError> {
212        let gate = self.gate.lock().map_err(|_| {
213            crate::log_e!(LogType::WSC; "cancel_domain_admission", "error", "gate_lock_poisoned");
214            NetError::from(crate::error::ErrorKind::Internal)
215        })?;
216        if self.is_cancelled() {
217            return Err(NetError::from(crate::error::ErrorKind::Cancelled));
218        }
219        Ok(gate)
220    }
221
222    /// Register before publishing the operation through `lock_if_active`/`run_if_active`.
223    /// A cancellation winning before publication runs the hook and rejects publication.
224    pub(crate) fn bind_cancel_hook(
225        self: &Arc<Self>,
226        action: Arc<dyn Fn() + Send + Sync>,
227    ) -> Result<CancelHookGuard, NetError> {
228        // Declare the capture before every guard so failed reservation releases
229        // user-owned captures only after the admission gate has been unlocked.
230        let hook = Arc::new(CancelHook { action });
231        let _gate = self.lock_if_active()?;
232        let mut hooks = lock_recover(&self.hooks);
233        hooks
234            .try_reserve(1)
235            .map_err(|_| NetError::from(crate::error::ErrorKind::Internal))?;
236        hooks.insert(Arc::as_ptr(&hook) as usize, Arc::downgrade(&hook));
237        Ok(CancelHookGuard {
238            owner: self.clone(),
239            hook,
240        })
241    }
242}
243
244impl Drop for CancelHookGuard {
245    fn drop(&mut self) {
246        // No tree gate here: completion may drop this guard while holding that gate.
247        lock_recover(&self.owner.hooks).remove(&(Arc::as_ptr(&self.hook) as usize));
248    }
249}
250
251impl Drop for CancellationState {
252    fn drop(&mut self) {
253        let Some(mut ancestor) = self.parent.take() else {
254            return;
255        };
256        lock_recover(&ancestor.children).remove(&(self as *const Self as usize));
257        loop {
258            // Weak child keys use the original Arc allocation, not the address of
259            // the CancellationState value after try_unwrap moves it onto this stack.
260            let identity = Arc::as_ptr(&ancestor) as usize;
261            match Arc::try_unwrap(ancestor) {
262                Ok(mut state) => {
263                    let Some(parent) = state.parent.take() else {
264                        return;
265                    };
266                    lock_recover(&parent.children).remove(&identity);
267                    ancestor = parent;
268                    // state now has no parent: its own Drop cannot recurse.
269                }
270                Err(shared) => {
271                    drop(shared);
272                    return;
273                }
274            }
275        }
276    }
277}
278
279pub(crate) fn lock_recover<T>(lock: &Mutex<T>) -> MutexGuard<'_, T> {
280    match lock.lock() {
281        Ok(guard) => guard,
282        Err(poisoned) => {
283            crate::log_e!(LogType::WSC; "ws.cancellation.lock_recover", "arg_lock_present|error", true, "lock_poisoned_recovered");
284            poisoned.into_inner()
285        }
286    }
287}
288
289#[cfg(test)]
290#[path = "cancellation_tests.rs"]
291mod tests;