1use ntex_service::{BindCtx, Ctx, Middleware, ReadyBinding, Service};
3
4use super::counter::Counter;
5
6#[derive(Copy, Clone, Debug)]
11pub struct InFlight {
12 max_inflight: usize,
13}
14
15impl InFlight {
16 pub fn new(max: usize) -> Self {
20 Self { max_inflight: max }
21 }
22}
23
24impl Default for InFlight {
25 fn default() -> Self {
26 Self::new(15)
27 }
28}
29
30impl<S, St> Middleware<S, St> for InFlight {
31 type Service = InFlightService<S>;
32
33 fn create(&self, _: &St, service: S) -> Self::Service {
34 InFlightService::new(self.max_inflight, service)
35 }
36}
37
38#[derive(Debug)]
39pub struct InFlightService<S> {
44 count: Counter,
45 service: ReadyBinding<S>,
46}
47
48impl<S> InFlightService<S> {
49 pub fn new(max: usize, service: S) -> Self {
53 Self {
54 service: ReadyBinding::new(service),
55 count: Counter::new(max),
56 }
57 }
58}
59
60impl<S, St, Req> Service<St, Req> for InFlightService<S>
61where
62 S: Service<St, Req>,
63{
64 type Res = S::Res;
65 type Error = S::Error;
66
67 fn bind(&self, ctx: BindCtx<'_>) {
68 self.count.bind(&ctx);
69 ctx.bind(&self.service);
70 }
71
72 #[inline]
73 async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), S::Error> {
74 if self.count.is_available() {
75 ctx.ready(&self.service).await
76 } else {
77 crate::future::join(self.count.available(), ctx.ready(&self.service))
78 .await
79 .1?;
80 ctx.ready(&self.service).await
82 }
83 }
84
85 #[inline]
86 async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<S::Res, S::Error> {
87 let _guard = match self.count.try_get() {
88 Some(guard) => guard,
89 None => self.count.clone().acquire().await,
91 };
92 ctx.call(&self.service, req).await
93 }
94
95 #[inline]
96 async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
97 ctx.shutdown(&self.service).await;
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use std::{cell::Cell, cell::RefCell, future::Future, rc::Rc, task::Poll, time::Duration};
104
105 use async_channel as mpmc;
106 use ntex_service::{Pipeline, ReadyNotifier, apply, fn_factory};
107
108 use super::*;
109 use crate::{channel::oneshot, future::OnDropFn, future::lazy};
110
111 struct SleepService(mpmc::Receiver<()>);
112
113 impl Service<(), ()> for SleepService {
114 type Res = ();
115 type Error = ();
116
117 async fn call(&self, _r: (), _: Ctx<'_, Self>) -> Result<(), ()> {
118 let _ = self.0.recv().await;
119 Ok(())
120 }
121 }
122
123 #[ntex::test]
129 async fn test_service() {
130 let (tx, rx) = mpmc::unbounded();
131 let counter = Rc::new(Cell::new(0));
132
133 let srv = Pipeline::new((), InFlightService::new(1, SleepService(rx)));
134 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
135
136 let counter2 = counter.clone();
137 let fut = srv.call_static(());
138 ntex::rt::spawn(async move {
139 let _ = fut.await;
140 counter2.set(counter2.get() + 1);
141 });
142 crate::time::sleep(Duration::from_millis(25)).await;
143 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Pending);
144
145 let counter2 = counter.clone();
146 let fut = srv.call_static(());
147 ntex::rt::spawn(async move {
148 let _ = fut.await;
149 counter2.set(counter2.get() + 1);
150 });
151 crate::time::sleep(Duration::from_millis(25)).await;
152 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Pending);
153
154 let counter2 = counter.clone();
155 let fut = srv.call_static(());
156 let (stx, srx) = oneshot::channel::<()>();
157 ntex::rt::spawn(async move {
158 let _ = fut.await;
159 counter2.set(counter2.get() + 1);
160 let _ = stx.send(());
161 });
162 crate::time::sleep(Duration::from_millis(25)).await;
163 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Pending);
164
165 let _ = tx.send(()).await;
166 crate::time::sleep(Duration::from_millis(25)).await;
167 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Pending);
168 assert_eq!(counter.get(), 1);
169
170 let _ = tx.send(()).await;
171 crate::time::sleep(Duration::from_millis(25)).await;
172 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Pending);
173
174 let _ = tx.send(()).await;
175 let _ = srx.recv().await;
176 assert_eq!(counter.get(), 3);
177 srv.shutdown().await;
178 }
179
180 #[ntex::test]
186 async fn test_middleware() {
187 let (tx, rx) = mpmc::unbounded();
188 let rx = RefCell::new(Some(rx));
189 let sf = apply(
190 InFlight::new(1),
191 fn_factory(move |(): &()| {
192 let rx = rx.borrow_mut().take().unwrap();
193 async move { Ok::<_, ()>(SleepService(rx)) }
194 }),
195 );
196
197 let srv = sf.pipeline(()).await.unwrap();
198 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
199
200 let srv2 = srv.bind();
201 ntex::rt::spawn(async move {
202 let _ = srv2.call(()).await;
203 });
204 crate::time::sleep(Duration::from_millis(25)).await;
205 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Pending);
206
207 let _ = tx.send(()).await;
208 crate::time::sleep(Duration::from_millis(25)).await;
209 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
210 }
211
212 #[derive(Default)]
213 struct ProbeState {
214 active: Cell<usize>,
215 max: Cell<usize>,
216 checks: Cell<usize>,
217 waker: crate::task::LocalWaker,
218 changed: ReadyNotifier,
219 }
220
221 struct Probe(Rc<ProbeState>, usize, mpmc::Receiver<()>);
223
224 impl Service<(), ()> for Probe {
225 type Res = ();
226 type Error = ();
227
228 fn bind(&self, ctx: BindCtx<'_>) {
229 ctx.subscribe(&self.0.changed);
230 }
231
232 async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), ()> {
233 self.0.checks.set(self.0.checks.get() + 1);
234 std::future::poll_fn(|cx| {
235 if self.0.active.get() < self.1 {
236 Poll::Ready(Ok(()))
237 } else {
238 self.0.waker.register(cx.waker());
239 Poll::Pending
240 }
241 })
242 .await
243 }
244
245 async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<(), ()> {
246 let st = &self.0;
247 st.active.set(st.active.get() + 1);
248 let _release = OnDropFn::new(|| {
249 let active = st.active.get();
250 st.active.set(active - 1);
251 let _wake = OnDropFn::new(|| st.waker.wake());
252 if active == self.1 {
253 st.changed.notify();
254 }
255 });
256 if st.active.get() == self.1 {
257 st.changed.notify();
258 }
259 st.max.set(st.max.get().max(st.active.get()));
260 let _ = self.2.recv().await;
261 Ok(())
262 }
263 }
264
265 #[ntex::test]
271 async fn test_inner_readiness_cached_until_notification() {
272 let (tx, rx) = mpmc::unbounded();
273 let st = Rc::new(ProbeState::default());
274 let srv = Pipeline::new((), InFlightService::new(4, Probe(st.clone(), 4, rx)));
275 for _ in 0..3 {
276 let _ = tx.send(()).await;
277 srv.call(()).await.unwrap();
278 }
279 assert_eq!(st.checks.get(), 1);
280
281 for _ in 0..3 {
282 let _ = tx.send(()).await;
283 srv.ready().await.unwrap();
284 srv.call(()).await.unwrap();
285 }
286 assert_eq!(st.checks.get(), 1);
287
288 st.changed.notify();
289 srv.ready().await.unwrap();
290 assert_eq!(st.checks.get(), 2);
291 }
292
293 struct NoWait<S>(S);
296
297 impl<S: Service<(), (), Res = (), Error = ()>> Service<(), ()> for NoWait<S> {
298 type Res = ();
299 type Error = ();
300
301 #[inline]
302 fn bind(&self, ctx: BindCtx<'_>) {
303 ctx.bind(&self.0);
304 }
305
306 async fn call(&self, req: (), ctx: Ctx<'_, Self>) -> Result<(), ()> {
308 ctx.call(&self.0, req).await
309 }
310 }
311
312 async fn run_concurrent(max: usize, inner: usize) -> usize {
314 let (tx, rx) = mpmc::unbounded();
315 let st = Rc::new(ProbeState::default());
316 let srv = Pipeline::new(
317 (),
318 NoWait(InFlightService::new(max, Probe(st.clone(), inner, rx))),
319 );
320 let mut futs = Vec::new();
321 for _ in 0..4 {
322 futs.push(ntex::rt::spawn(srv.call_static(())));
323 }
324 crate::time::sleep(Duration::from_millis(20)).await;
325 for _ in 0..4 {
326 let _ = tx.send(()).await;
327 }
328 for f in futs {
329 let _ = f.await;
330 }
331 st.max.get()
332 }
333
334 #[ntex::test]
340 async fn test_limits_without_readiness_check() {
341 assert_eq!(run_concurrent(1, 4).await, 1, "inflight limit");
342 assert_eq!(run_concurrent(2, 1).await, 1, "inner limit");
343 assert_eq!(run_concurrent(2, 4).await, 2, "inflight limit 2");
344 }
345
346 #[ntex::test]
352 async fn test_zero_limit() {
353 let (_tx, rx) = mpmc::unbounded();
354 let srv = Pipeline::new((), InFlightService::new(0, SleepService(rx.clone())));
355 assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Pending);
356 let mut call = Box::pin(srv.call(()));
357 assert_eq!(lazy(|cx| call.as_mut().poll(cx)).await, Poll::Pending);
358
359 let srv = Pipeline::new((), NoWait(InFlightService::new(0, SleepService(rx))));
360 let mut call = Box::pin(srv.call(()));
361 assert_eq!(lazy(|cx| call.as_mut().poll(cx)).await, Poll::Pending);
362 }
363}