Skip to main content

deq_runtime/misc/
sync.rs

1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
3use tokio::sync::{Notify, watch};
4use tokio::task::JoinHandle;
5use tokio_util::sync::CancellationToken;
6
7pub fn get_or_receiver<T: Send + Sync + Clone + 'static>(
8    sender: &watch::Sender<Option<T>>,
9    token: CancellationToken,
10) -> Result<T, JoinHandle<Option<T>>> {
11    if let Some(value) = sender.borrow().as_ref() {
12        Ok(value.clone())
13    } else {
14        let mut rx = sender.subscribe();
15        Err(tokio::spawn(async move {
16            tokio::select! {
17                result = rx.wait_for(|v| v.is_some()) => {
18                    result.ok().and_then(|v| v.clone())
19                }
20                _ = token.cancelled() => None,
21            }
22        }))
23    }
24}
25
26pub async fn get_value<T: Send + Sync + Clone + 'static>(
27    sender: &watch::Sender<Option<T>>,
28    token: CancellationToken,
29) -> Option<T> {
30    match get_or_receiver(sender, token) {
31        Ok(value) => Some(value),
32        Err(handle) => handle.await.unwrap_or(None),
33    }
34}
35
36/// Returns `Ok(())` if the value already exists, or spawns a task that waits
37/// for it (or cancellation). The spawned task returns `true` if the value
38/// arrived and `false` if cancelled.
39pub fn check_or_receiver<T: Send + Sync + Clone + 'static>(
40    sender: &watch::Sender<Option<T>>,
41    token: CancellationToken,
42) -> Result<(), JoinHandle<bool>> {
43    if sender.borrow().as_ref().is_some() {
44        Ok(())
45    } else {
46        let mut rx = sender.subscribe();
47        Err(tokio::spawn(async move {
48            tokio::select! {
49                result = rx.wait_for(|v| v.is_some()) => result.is_ok(),
50                _ = token.cancelled() => false,
51            }
52        }))
53    }
54}
55
56// ============================================================================
57// TaskCounter / TaskGuard — track active spawned tasks for barrier-based reset
58// ============================================================================
59
60/// Tracks the number of active background tasks. `reset()` cancels the token
61/// then calls `wait_for_zero()` to ensure all tasks have exited before clearing
62/// shared state.
63pub struct TaskCounter {
64    count: AtomicUsize,
65    accepting: AtomicBool,
66    notify: Notify,
67}
68
69impl TaskCounter {
70    pub fn new() -> Arc<Self> {
71        Arc::new(Self {
72            count: AtomicUsize::new(0),
73            accepting: AtomicBool::new(true),
74            notify: Notify::new(),
75        })
76    }
77
78    /// Wait until the active task count reaches zero.
79    pub async fn wait_for_zero(self: &Arc<Self>) {
80        loop {
81            let notified = self.notify.notified();
82            // Acquire pairs with the Release in TaskGuard::drop, ensuring
83            // all writes made by finished tasks are visible after we return.
84            if self.count.load(Ordering::Acquire) == 0 {
85                return;
86            }
87            // The `Notified` future is registered before we re-check, so if
88            // a guard is dropped between `load` and here, the notification
89            // is captured by the already-registered waiter — no lost wakeup.
90            notified.await;
91        }
92    }
93
94    /// Create a guard that increments the counter now and decrements on drop.
95    pub fn guard(self: &Arc<Self>) -> TaskGuard {
96        self.count.fetch_add(1, Ordering::Relaxed);
97        TaskGuard {
98            counter: Arc::clone(self),
99        }
100    }
101
102    /// Admit a new top-level operation unless reset has paused admission.
103    /// A second acceptance check closes the race with [`Self::try_pause`].
104    pub fn try_guard(self: &Arc<Self>) -> Option<TaskGuard> {
105        if !self.accepting.load(Ordering::Acquire) {
106            return None;
107        }
108        let guard = self.guard();
109        if self.accepting.load(Ordering::Acquire) {
110            Some(guard)
111        } else {
112            drop(guard);
113            None
114        }
115    }
116
117    /// Stop admitting top-level operations until the returned guard is dropped.
118    /// Returns `None` when another reset already owns the pause.
119    pub fn try_pause(self: &Arc<Self>) -> Option<TaskCounterPause> {
120        self.accepting
121            .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
122            .ok()
123            .map(|_| TaskCounterPause {
124                counter: Arc::clone(self),
125            })
126    }
127}
128
129/// RAII guard that decrements the [`TaskCounter`] when dropped.
130/// Move this into each spawned task to track its lifetime.
131pub struct TaskGuard {
132    counter: Arc<TaskCounter>,
133}
134
135impl Drop for TaskGuard {
136    fn drop(&mut self) {
137        // Release ensures all writes made by this task are visible to the
138        // thread that later observes count == 0 with an Acquire load.
139        if self.counter.count.fetch_sub(1, Ordering::Release) == 1 {
140            self.counter.notify.notify_waiters();
141        }
142    }
143}
144
145/// RAII admission pause used by reset. Dropping it reopens the coordinator even
146/// when reset returns early with an error.
147pub struct TaskCounterPause {
148    counter: Arc<TaskCounter>,
149}
150
151impl Drop for TaskCounterPause {
152    fn drop(&mut self) {
153        self.counter.accepting.store(true, Ordering::Release);
154    }
155}