Skip to main content

ntex_util/services/
mod.rs

1//! Reusable services and middleware.
2//!
3//! This module includes request buffering, in-flight request limits,
4//! keep-alive handling, ordered processing, retries, reconnects, per-request
5//! extensions, and timeouts.
6
7pub mod buffer;
8mod extensions;
9pub mod inflight;
10pub mod keepalive;
11pub mod onerequest;
12pub mod ordered;
13pub mod reconnect;
14pub mod retry;
15pub mod timeout;
16
17#[doc(hidden)]
18pub mod counter;
19
20pub use self::counter::{Counter, CounterGuard};
21pub use self::extensions::Extensions;
22
23#[cfg(test)]
24mod tests {
25    use std::sync::{Arc, atomic::AtomicUsize, atomic::Ordering};
26    use std::task::{Context, Poll, Wake};
27    use std::{cell::Cell, future::Future, future::poll_fn, rc::Rc};
28    use std::{panic::AssertUnwindSafe, panic::catch_unwind};
29
30    use ntex_service::{BindCtx, Ctx, Pipeline, ReadyCallback, ReadyNotifier, Service};
31
32    use super::{inflight::InFlightService, onerequest::OneRequestService};
33    use crate::{future::OnDropFn, task::LocalWaker};
34
35    #[derive(Clone, Copy)]
36    enum Outcome {
37        Pending,
38        Ok,
39        Error,
40        Panic,
41    }
42
43    struct Probe {
44        changed: ReadyNotifier,
45        checks: Cell<usize>,
46        ready: Cell<Outcome>,
47        call: Cell<Outcome>,
48        active: Cell<usize>,
49        waker: LocalWaker,
50        panic_on_notify: Cell<bool>,
51    }
52
53    impl Service<(), ()> for Probe {
54        type Res = ();
55        type Error = ();
56
57        fn bind(&self, ctx: BindCtx<'_>) {
58            ctx.subscribe(&self.changed);
59        }
60
61        async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), ()> {
62            self.checks.set(self.checks.get() + 1);
63            poll_fn(|_| match self.ready.get() {
64                Outcome::Pending => Poll::Pending,
65                Outcome::Ok => Poll::Ready(Ok(())),
66                Outcome::Error => Poll::Ready(Err(())),
67                Outcome::Panic => panic!("inner readiness panic"),
68            })
69            .await
70        }
71
72        async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<(), ()> {
73            let active = self.active.replace(self.active.get() + 1);
74            let _release = OnDropFn::new(|| self.active.set(self.active.get() - 1));
75            assert_eq!(active, 0, "limiter allowed overlapping calls");
76            poll_fn(|cx| match self.call.get() {
77                Outcome::Pending => {
78                    self.waker.register(cx.waker());
79                    Poll::Pending
80                }
81                Outcome::Ok => Poll::Ready(Ok(())),
82                Outcome::Error => Poll::Ready(Err(())),
83                Outcome::Panic => panic!("inner call panic"),
84            })
85            .await
86        }
87    }
88
89    struct Dispatch<S> {
90        service: S,
91        bypass: bool,
92        callback: ReadyCallback,
93    }
94
95    impl<S: Service<(), (), Res = (), Error = ()>> Service<(), ()> for Dispatch<S> {
96        type Res = ();
97        type Error = ();
98
99        fn bind(&self, ctx: BindCtx<'_>) {
100            ctx.on_notify(&self.callback);
101            ctx.bind(&self.service);
102        }
103
104        async fn ready(&self, ctx: Ctx<'_, Self>) -> Result<(), ()> {
105            if self.bypass {
106                Ok(())
107            } else {
108                ctx.ready(&self.service).await
109            }
110        }
111
112        // with `bypass`, calls reuse this scope's cached readiness
113        async fn call(&self, req: (), ctx: Ctx<'_, Self>) -> Result<(), ()> {
114            ctx.call(&self.service, req).await
115        }
116    }
117
118    struct SharedPipeline(Pipeline<(), (), ()>);
119
120    impl Service<(), ()> for SharedPipeline {
121        type Res = ();
122        type Error = ();
123
124        fn bind(&self, ctx: BindCtx<'_>) {
125            self.0.bind_to(&ctx);
126        }
127
128        async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), ()> {
129            self.0.ready().await
130        }
131
132        async fn call(&self, req: (), _: Ctx<'_, Self>) -> Result<(), ()> {
133            self.0.call(req).await
134        }
135    }
136
137    fn shared<S>(service: S, bypass: bool, probe: Rc<Probe>) -> [Pipeline<(), (), ()>; 2]
138    where
139        S: Service<(), (), Res = (), Error = ()> + 'static,
140    {
141        let service = Rc::new(SharedPipeline(Pipeline::new(
142            (),
143            Dispatch {
144                service,
145                bypass,
146                callback: ReadyCallback::new(move |_| {
147                    assert!(!probe.panic_on_notify.replace(false), "notification panic");
148                }),
149            },
150        )));
151        [
152            Pipeline::new((), service.clone()),
153            Pipeline::new((), service),
154        ]
155    }
156
157    type SharedLimiter = (Rc<Probe>, [Pipeline<(), (), ()>; 2]);
158
159    fn limiters(bypass: bool) -> [SharedLimiter; 2] {
160        [false, true].map(|one_request| {
161            let probe = Rc::new(Probe {
162                changed: ReadyNotifier::new(),
163                checks: Cell::new(0),
164                ready: Cell::new(Outcome::Ok),
165                call: Cell::new(Outcome::Ok),
166                active: Cell::new(0),
167                waker: LocalWaker::new(),
168                panic_on_notify: Cell::new(false),
169            });
170            let services = if one_request {
171                shared(OneRequestService::new(probe.clone()), bypass, probe.clone())
172            } else {
173                shared(
174                    InFlightService::new(1, probe.clone()),
175                    bypass,
176                    probe.clone(),
177                )
178            };
179            (probe, services)
180        })
181    }
182
183    #[derive(Default)]
184    struct WakeCount(AtomicUsize);
185
186    impl Wake for WakeCount {
187        fn wake(self: Arc<Self>) {
188            self.0.fetch_add(1, Ordering::Relaxed);
189        }
190    }
191
192    /// STATEMENT: Limiter capacity notifications do not discard independent inner readiness.
193    ///
194    /// HOW:
195    /// - Link two roots to one owning pipeline for each limiter and count readiness checks across calls.
196    /// - Notify inner pending and ready transitions and verify each causes a new shared check.
197    #[ntex::test]
198    async fn inner_cache_survives_capacity_notifications() {
199        for (probe, services) in limiters(false) {
200            for service in &services {
201                for _ in 0..3 {
202                    service.ready().await.unwrap();
203                    service.call(()).await.unwrap();
204                }
205            }
206            assert_eq!(probe.checks.get(), 1);
207
208            probe.ready.set(Outcome::Pending);
209            probe.changed.notify();
210            let mut cx = Context::from_waker(std::task::Waker::noop());
211            for service in &services {
212                assert!(service.poll_ready(&mut cx).is_pending());
213            }
214            assert_eq!(probe.checks.get(), 2);
215
216            probe.ready.set(Outcome::Ok);
217            probe.changed.notify();
218            for service in &services {
219                service.ready().await.unwrap();
220                service.call(()).await.unwrap();
221            }
222            assert_eq!(probe.checks.get(), 3);
223        }
224    }
225
226    /// STATEMENT: Shared limiter capacity wakes all roots and is released on cancellation or error.
227    ///
228    /// HOW:
229    /// - Link two roots to one limiter pipeline and park a call on each.
230    /// - Cancel the active call and verify both registered wakers fire.
231    /// - Complete the successor and an erroring call while checking active counts and cached readiness.
232    #[ntex::test]
233    async fn shared_capacity_wakes_all_roots_and_releases() {
234        for (probe, [first, second]) in limiters(false) {
235            first.ready().await.unwrap();
236            second.ready().await.unwrap();
237            probe.call.set(Outcome::Pending);
238            let wakes1 = Arc::new(WakeCount::default());
239            let wakes2 = Arc::new(WakeCount::default());
240            let waker1 = wakes1.clone().into();
241            let waker2 = wakes2.clone().into();
242            let mut cx1 = Context::from_waker(&waker1);
243            let mut cx2 = Context::from_waker(&waker2);
244
245            let mut active = Box::pin(first.call(()));
246            assert!(active.as_mut().poll(&mut cx1).is_pending());
247            let mut waiting = Box::pin(second.call(()));
248            assert!(waiting.as_mut().poll(&mut cx2).is_pending());
249            assert_eq!(probe.active.get(), 1);
250            assert!(first.poll_ready(&mut cx1).is_pending());
251            assert!(second.poll_ready(&mut cx2).is_pending());
252            let before1 = wakes1.0.load(Ordering::Relaxed);
253            let before2 = wakes2.0.load(Ordering::Relaxed);
254
255            drop(active);
256            assert_eq!(probe.active.get(), 0);
257            assert!(wakes1.0.load(Ordering::Relaxed) > before1);
258            assert!(wakes2.0.load(Ordering::Relaxed) > before2);
259            assert!(waiting.as_mut().poll(&mut cx2).is_pending());
260            assert_eq!(probe.active.get(), 1);
261            assert!(first.poll_ready(&mut cx1).is_pending());
262
263            probe.call.set(Outcome::Ok);
264            probe.waker.wake();
265            assert_eq!(waiting.as_mut().poll(&mut cx2), Poll::Ready(Ok(())));
266            assert_eq!(probe.active.get(), 0);
267            first.ready().await.unwrap();
268            second.ready().await.unwrap();
269
270            probe.call.set(Outcome::Error);
271            assert_eq!(first.call(()).await, Err(()));
272            assert_eq!(probe.active.get(), 0);
273            second.ready().await.unwrap();
274            assert_eq!(probe.checks.get(), 1);
275        }
276    }
277
278    /// STATEMENT: Skipping outer readiness still checks inner readiness and releases limiter permits.
279    ///
280    /// HOW:
281    /// - Keep the bypass inside the shared limiter pipeline reached by two linked roots.
282    /// - Cancel a call waiting on inner readiness and verify a second root can proceed.
283    /// - Exercise inner readiness errors and panics, then verify subsequent calls succeed.
284    #[ntex::test]
285    async fn bypass_still_checks_inner_and_releases_pending_permit() {
286        for (probe, [first, second]) in limiters(true) {
287            probe.ready.set(Outcome::Pending);
288            let mut cx = Context::from_waker(std::task::Waker::noop());
289            let mut active = Box::pin(first.call(()));
290            assert!(active.as_mut().poll(&mut cx).is_pending());
291            assert_eq!(probe.checks.get(), 1);
292            assert_eq!(probe.active.get(), 0);
293            let mut waiting = Box::pin(second.call(()));
294            assert!(waiting.as_mut().poll(&mut cx).is_pending());
295            drop(active);
296
297            probe.ready.set(Outcome::Ok);
298            probe.changed.notify();
299            assert_eq!(waiting.as_mut().poll(&mut cx), Poll::Ready(Ok(())));
300
301            probe.ready.set(Outcome::Error);
302            probe.changed.notify();
303            assert_eq!(first.call(()).await, Err(()));
304            assert_eq!(probe.active.get(), 0);
305            probe.ready.set(Outcome::Ok);
306            probe.changed.notify();
307            second.call(()).await.unwrap();
308
309            probe.ready.set(Outcome::Panic);
310            probe.changed.notify();
311            let mut call = Box::pin(first.call(()));
312            assert!(catch_unwind(AssertUnwindSafe(|| call.as_mut().poll(&mut cx))).is_err());
313            drop(call);
314            probe.ready.set(Outcome::Ok);
315            probe.changed.notify();
316            second.call(()).await.unwrap();
317        }
318    }
319
320    /// STATEMENT: Notification and inner-call panics cannot leak limiter permits or strand waiters.
321    ///
322    /// HOW:
323    /// - Share each limiter through one owning pipeline linked to two outer roots.
324    /// - Catch entry-notification and call panics for both limiters and verify later calls succeed.
325    /// - Panic during active-call cancellation with skipped readiness and verify release and waiter wakeup.
326    #[ntex::test]
327    async fn panicking_notification_or_inner_call_releases_permit() {
328        for (probe, [first, second]) in limiters(false) {
329            first.ready().await.unwrap();
330            second.ready().await.unwrap();
331            let mut cx = Context::from_waker(std::task::Waker::noop());
332
333            probe.panic_on_notify.set(true);
334            let mut call = Box::pin(first.call(()));
335            assert!(catch_unwind(AssertUnwindSafe(|| call.as_mut().poll(&mut cx))).is_err());
336            drop(call);
337            assert_eq!(probe.active.get(), 0);
338            second.call(()).await.unwrap();
339
340            probe.call.set(Outcome::Panic);
341            let mut call = Box::pin(first.call(()));
342            assert!(catch_unwind(AssertUnwindSafe(|| call.as_mut().poll(&mut cx))).is_err());
343            drop(call);
344            assert_eq!(probe.active.get(), 0);
345            probe.call.set(Outcome::Ok);
346            second.call(()).await.unwrap();
347        }
348
349        for (probe, [first, second]) in limiters(true) {
350            probe.call.set(Outcome::Pending);
351            let wakes = Arc::new(WakeCount::default());
352            let waker = wakes.clone().into();
353            let mut cx = Context::from_waker(&waker);
354            let mut active = Box::pin(first.call(()));
355            assert!(active.as_mut().poll(&mut cx).is_pending());
356            let mut waiting = Box::pin(second.call(()));
357            assert!(waiting.as_mut().poll(&mut cx).is_pending());
358            let before = wakes.0.load(Ordering::Relaxed);
359
360            probe.panic_on_notify.set(true);
361            assert!(catch_unwind(AssertUnwindSafe(|| drop(active))).is_err());
362            assert_eq!(probe.active.get(), 0);
363            assert!(wakes.0.load(Ordering::Relaxed) > before);
364            probe.call.set(Outcome::Ok);
365            assert_eq!(waiting.as_mut().poll(&mut cx), Poll::Ready(Ok(())));
366        }
367    }
368}