ntex_util/services/
counter.rs1use std::{
2 cell::Cell, cell::OnceCell, cell::RefCell, future::poll_fn, rc::Rc, task::Context, task::Poll,
3};
4
5use ntex_service::{BindCtx, ReadyNotifier};
6
7use crate::{future::OnDropFn, task::LocalWaker};
8
9#[derive(Debug)]
14pub struct Counter(usize, Rc<CounterInner>);
15
16#[derive(Debug)]
17struct CounterInner {
18 count: Cell<usize>,
19 capacity: Cell<usize>,
20 tasks: RefCell<slab::Slab<LocalWaker>>,
21 changed: OnceCell<ReadyNotifier>,
22}
23
24impl Counter {
25 pub fn new(capacity: usize) -> Self {
27 let mut tasks = slab::Slab::new();
28 let idx = tasks.insert(LocalWaker::new());
29
30 Counter(
31 idx,
32 Rc::new(CounterInner {
33 count: Cell::new(0),
34 capacity: Cell::new(capacity),
35 tasks: RefCell::new(tasks),
36 changed: OnceCell::new(),
37 }),
38 )
39 }
40
41 pub fn get(&self) -> CounterGuard {
47 CounterGuard::new(self.1.clone())
48 }
49
50 pub fn try_get(&self) -> Option<CounterGuard> {
52 if self.is_available() {
53 Some(self.get())
54 } else {
55 None
56 }
57 }
58
59 pub async fn acquire(&self) -> CounterGuard {
66 poll_fn(|cx| {
67 if self.poll_available(cx) {
68 Poll::Ready(self.get())
69 } else {
70 Poll::Pending
71 }
72 })
73 .await
74 }
75
76 pub fn set_capacity(&self, cap: usize) {
78 self.1.capacity.set(cap);
79 self.1.notify();
80 }
81
82 pub fn is_available(&self) -> bool {
84 self.1.count.get() < self.1.capacity.get()
85 }
86
87 pub async fn available(&self) {
96 poll_fn(|cx| {
97 if self.poll_available(cx) {
98 Poll::Ready(())
99 } else {
100 Poll::Pending
101 }
102 })
103 .await;
104 }
105
106 pub async fn unavailable(&self) {
108 poll_fn(|cx| {
109 if self.is_available() {
110 self.1.tasks.borrow()[self.0].register(cx.waker());
111 Poll::Pending
112 } else {
113 Poll::Ready(())
114 }
115 })
116 .await;
117 }
118
119 fn poll_available(&self, cx: &mut Context<'_>) -> bool {
122 if self.1.count.get() < self.1.capacity.get() {
123 true
124 } else {
125 let tasks = self.1.tasks.borrow();
126 tasks[self.0].register(cx.waker());
127 false
128 }
129 }
130
131 pub fn total(&self) -> usize {
133 self.1.count.get()
134 }
135
136 pub fn bind(&self, ctx: &BindCtx<'_>) {
142 ctx.subscribe(self.1.changed.get_or_init(ReadyNotifier::new));
143 }
144}
145
146impl Clone for Counter {
147 fn clone(&self) -> Self {
148 let idx = self.1.tasks.borrow_mut().insert(LocalWaker::new());
149 Self(idx, self.1.clone())
150 }
151}
152
153impl Drop for Counter {
154 fn drop(&mut self) {
155 self.1.tasks.borrow_mut().remove(self.0);
156 }
157}
158
159#[derive(Debug)]
160pub struct CounterGuard(Rc<CounterInner>);
164
165impl CounterGuard {
166 fn new(inner: Rc<CounterInner>) -> Self {
167 let guard = CounterGuard(inner);
168 guard.0.inc();
169 guard
170 }
171}
172
173impl Unpin for CounterGuard {}
174
175impl Drop for CounterGuard {
176 fn drop(&mut self) {
177 self.0.dec();
178 }
179}
180
181impl CounterInner {
182 fn inc(&self) {
183 let num = self.count.get() + 1;
184 self.count.set(num);
185 if num == self.capacity.get() {
186 self.notify();
187 }
188 }
189
190 fn dec(&self) {
191 let num = self.count.get();
192 self.count.set(num - 1);
193 if num == self.capacity.get() {
194 self.notify();
195 }
196 }
197
198 fn notify(&self) {
199 let _wake = OnDropFn::new(|| {
200 let tasks = self.tasks.borrow();
201 for (_, task) in &*tasks {
202 task.wake();
203 }
204 });
205 if let Some(changed) = self.changed.get() {
206 changed.notify();
207 }
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use std::time::Duration;
214
215 use super::*;
216 use crate::time::sleep;
217
218 #[ntex::test]
224 async fn test_unavailable_is_woken() {
225 let counter = Counter::new(2);
226 let done = Rc::new(Cell::new(false));
227
228 let (c, d) = (counter.clone(), done.clone());
229 crate::spawn(async move {
230 c.unavailable().await;
231 d.set(true);
232 });
233 sleep(Duration::from_millis(10)).await;
234 assert!(!done.get());
235
236 let _g1 = counter.get();
237 sleep(Duration::from_millis(10)).await;
238 assert!(!done.get());
239
240 let _g2 = counter.get();
241 sleep(Duration::from_millis(10)).await;
242 assert!(done.get());
243 }
244
245 #[ntex::test]
251 async fn test_available_is_woken() {
252 let counter = Counter::new(1);
253 let guard = counter.get();
254 let done = Rc::new(Cell::new(false));
255
256 let (c, d) = (counter.clone(), done.clone());
257 crate::spawn(async move {
258 c.available().await;
259 d.set(true);
260 });
261 sleep(Duration::from_millis(10)).await;
262 assert!(!done.get());
263
264 drop(guard);
265 sleep(Duration::from_millis(10)).await;
266 assert!(done.get());
267 }
268
269 #[ntex::test]
275 async fn test_set_capacity() {
276 let counter = Counter::new(1);
277 let guard = counter.get();
278 assert_eq!(counter.total(), 1);
279 assert!(!counter.is_available());
280
281 let counter2 = counter.clone();
282 let hnd = crate::spawn(async move { counter2.available().await });
283 sleep(Duration::from_millis(10)).await;
284 assert!(!hnd.is_finished());
285
286 counter.set_capacity(2);
288 assert!(counter.is_available());
289 crate::time::timeout(Duration::from_secs(1), hnd)
290 .await
291 .unwrap()
292 .unwrap();
293
294 drop(guard);
295 assert_eq!(counter.total(), 0);
296 }
297
298 #[ntex::test]
307 async fn acquire_reserves_slot() {
308 let counter = Counter::new(1);
309 let guard = counter.get();
310 assert!(counter.try_get().is_none());
311 assert_eq!(counter.total(), 1);
312
313 let max = Rc::new(Cell::new(0));
314 let mut handles = Vec::new();
315 for _ in 0..2 {
316 let (c, max) = (counter.clone(), max.clone());
317 handles.push(crate::spawn(async move {
318 let _guard = c.acquire().await;
319 max.set(max.get().max(c.total()));
320 sleep(Duration::from_millis(10)).await;
321 }));
322 }
323 sleep(Duration::from_millis(10)).await;
324 assert_eq!(max.get(), 0);
325
326 drop(guard);
327 for hnd in handles {
328 crate::time::timeout(Duration::from_secs(1), hnd)
329 .await
330 .unwrap()
331 .unwrap();
332 }
333 assert_eq!(max.get(), 1);
334 assert_eq!(counter.total(), 0);
335
336 let guard = counter.try_get().unwrap();
337 assert_eq!(counter.total(), 1);
338 drop(guard);
339 assert_eq!(counter.total(), 0);
340 }
341}