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
36pub 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
56pub 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 pub async fn wait_for_zero(self: &Arc<Self>) {
80 loop {
81 let notified = self.notify.notified();
82 if self.count.load(Ordering::Acquire) == 0 {
85 return;
86 }
87 notified.await;
91 }
92 }
93
94 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 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 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
129pub struct TaskGuard {
132 counter: Arc<TaskCounter>,
133}
134
135impl Drop for TaskGuard {
136 fn drop(&mut self) {
137 if self.counter.count.fetch_sub(1, Ordering::Release) == 1 {
140 self.counter.notify.notify_waiters();
141 }
142 }
143}
144
145pub 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}