open_net/api/ws/
cancellation.rs1use 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#[derive(Clone)]
15pub struct CancellationGroup {
16 pub(crate) inner: Arc<CancellationState>,
18}
19
20impl CancellationGroup {
21 pub fn new() -> Self {
23 Self {
24 inner: CancellationState::new(),
25 }
26 }
27
28 pub fn child(&self) -> Self {
30 Self {
31 inner: self.inner.child(),
32 }
33 }
34
35 pub fn cancel(&self) {
38 self.inner.cancel();
39 }
40
41 pub fn is_cancelled(&self) -> bool {
43 self.inner.is_cancelled()
44 }
45
46 pub async fn cancelled(&self) {
48 self.inner.notification.cancelled().await;
49 }
50
51 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#[must_use]
78#[derive(Debug)]
79pub struct CancellationGuard {
80 group: CancellationGroup,
82 armed: bool,
84}
85
86impl CancellationGuard {
87 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
102pub(crate) struct CancellationState {
105 gate: Arc<Mutex<()>>,
108 cancelled: AtomicBool,
110 notification: CancellationToken,
112 parent: Option<Arc<CancellationState>>,
115 pub(crate) children: Mutex<HashMap<usize, Weak<CancellationState>>>,
117 pub(crate) hooks: Mutex<HashMap<usize, Weak<CancelHook>>>,
120}
121
122pub(crate) struct CancelHook {
124 action: Arc<dyn Fn() + Send + Sync>,
126}
127
128pub(crate) struct CancelHookGuard {
132 owner: Arc<CancellationState>,
135 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 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 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 for domain in cancelled {
197 domain.notification.cancel();
198 }
199 for hook in hooks {
200 (hook.action)();
201 }
202 }
203
204 pub(crate) fn is_cancelled(&self) -> bool {
206 self.cancelled.load(Ordering::Acquire)
207 }
208
209 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 pub(crate) fn bind_cancel_hook(
225 self: &Arc<Self>,
226 action: Arc<dyn Fn() + Send + Sync>,
227 ) -> Result<CancelHookGuard, NetError> {
228 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 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 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 }
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;