Skip to main content

ntex_util/services/
counter.rs

1use 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/// A shared count with an asynchronous capacity notification.
10///
11/// Clones use the same count and capacity, but each clone registers its own
12/// waiting task.
13#[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    /// Creates a counter with the specified capacity.
26    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    /// Acquires one count and returns a guard that releases it on drop.
42    ///
43    /// This does not check the capacity, so the count may exceed it. Use
44    /// [`acquire`](Self::acquire) or [`try_get`](Self::try_get) when the
45    /// capacity must not be exceeded.
46    pub fn get(&self) -> CounterGuard {
47        CounterGuard::new(self.1.clone())
48    }
49
50    /// Acquires one count if the counter has free capacity.
51    pub fn try_get(&self) -> Option<CounterGuard> {
52        if self.is_available() {
53            Some(self.get())
54        } else {
55            None
56        }
57    }
58
59    /// Waits until the counter has free capacity and acquires one count.
60    ///
61    /// The count is taken in the same poll that observes free capacity, so
62    /// tasks acquiring concurrently never exceed the capacity. Concurrent
63    /// waiters must use separate clones, each clone wakes only its most recent
64    /// waiting task. Cancelling the future acquires nothing.
65    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    /// Changes the capacity and wakes waiting tasks.
77    pub fn set_capacity(&self, cap: usize) {
78        self.1.capacity.set(cap);
79        self.1.notify();
80    }
81
82    /// Returns `true` if another count can be acquired without exceeding the capacity.
83    pub fn is_available(&self) -> bool {
84        self.1.count.get() < self.1.capacity.get()
85    }
86
87    /// Waits until the counter has free capacity.
88    ///
89    /// Returns immediately if there is capacity available. Otherwise,
90    /// registers the current task for wakeup and waits until a slot is freed.
91    ///
92    /// This does not reserve the slot: another task may take it before a
93    /// later [`get`](Self::get), unless `get` is called without awaiting in
94    /// between. Use [`acquire`](Self::acquire) to wait and take a slot at once.
95    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    /// Waits until the counter reaches its capacity (i.e., becomes unavailable).
107    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    /// Check if counter is not at capacity. If counter at capacity
120    /// it registers notification for current task.
121    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    /// Returns the number of currently held guards.
132    pub fn total(&self) -> usize {
133        self.1.count.get()
134    }
135
136    /// Subscribes `ctx` to capacity changes.
137    ///
138    /// Services whose readiness depends on this counter must call this in
139    /// [`Service::bind`](ntex_service::Service::bind), otherwise their cached
140    /// readiness is not invalidated when the counter fills or frees a slot.
141    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)]
160/// An acquired counter slot.
161///
162/// Dropping the guard releases the slot and wakes availability waiters.
163pub 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    /// STATEMENT: Unavailability waiters wake only when the counter reaches capacity.
219    ///
220    /// HOW:
221    /// - Spawn an unavailability waiter on a capacity-two counter.
222    /// - Acquire guards one at a time and verify completion only after the second.
223    #[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    /// STATEMENT: Releasing a guard wakes an availability waiter.
246    ///
247    /// HOW:
248    /// - Fill a capacity-one counter and verify an availability waiter stays pending.
249    /// - Drop the guard and observe the waiter complete.
250    #[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    /// STATEMENT: Increasing capacity wakes waiters without changing the active count.
270    ///
271    /// HOW:
272    /// - Hold the only slot and verify an availability task is pending.
273    /// - Raise capacity, await the task, and drop the guard to check the count returns to zero.
274    #[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        // raising the capacity wakes waiters
287        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    /// STATEMENT: Concurrent `acquire` calls never exceed the capacity, even when
299    /// the acquiring tasks yield while holding their guards.
300    ///
301    /// HOW:
302    /// - Hold the only slot of a capacity-one counter and spawn two tasks that `acquire`
303    ///   through their own clones, record `total()`, sleep, then release.
304    /// - Check `try_get` returns `None` while full, release the slot, and check both tasks
305    ///   acquired with a recorded maximum `total()` of one, and `try_get` succeeds afterwards.
306    #[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}