Skip to main content

ntex_util/services/
ordered.rs

1//! Service that runs requests concurrently but enters a second service in ticket order.
2//!
3//! [`Ordered`] calls service `A` for every request concurrently, then passes each
4//! result to service `B` strictly in ticket order. Each caller receives its own
5//! `B` response. This keeps an ordered side effect in `B`, such as appending to a
6//! log or queue, in request order while slow `A` processing (authorization,
7//! payload reads) still overlaps.
8//!
9//! Tickets come from a [`Sequencer`]:
10//!
11//! - [`Arrival`] issues tickets in the order calls start, optionally only for
12//!   requests selected by a filter;
13//! - [`tickets()`] takes tickets assigned by an external system, for example a
14//!   protocol codec that numbers packets in decode order.
15//!
16//! [`Tickets::cancel()`] or [`Ticket::cancel()`] cancels every outstanding ticket
17//! of a sequence, their turn waits return [`Canceled`].
18//!
19//! # Example
20//!
21//! ```
22//! use ntex_service::{Pipeline, fn_service};
23//! use ntex_util::services::ordered::{Canceled, Ordered};
24//!
25//! # #[ntex::main]
26//! # async fn main() {
27//! let svc = Ordered::new(
28//!     fn_service(async |req: u32| Ok::<_, Canceled>(req * 2)),
29//!     fn_service(async |val: u32| Ok::<_, Canceled>(val.to_string())),
30//! );
31//! let pipeline = Pipeline::new((), svc);
32//! assert_eq!(pipeline.call(21).await, Ok("42".to_string()));
33//! # }
34//! ```
35use std::cell::{Cell, RefCell};
36use std::task::{Context, Poll};
37use std::{collections::VecDeque, error, fmt, future::Future, future::poll_fn, pin::pin, rc::Rc};
38
39use ntex_service::{BindCtx, Ctx, ReadyBinding, Service, ServiceFactory};
40
41use crate::task::LocalWaker;
42
43/// Error returned by a turn wait of a canceled ticket.
44#[derive(Copy, Clone, Debug, PartialEq, Eq)]
45pub struct Canceled;
46
47impl fmt::Display for Canceled {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.write_str("Ticket is canceled")
50    }
51}
52
53impl error::Error for Canceled {}
54
55/// Position of a request in an ordered sequence.
56///
57/// Dropping a ticket that holds the turn passes the turn to the next ticket;
58/// dropping a ticket before its turn skips its position.
59pub trait Turn {
60    /// Polls until this ticket holds the turn.
61    ///
62    /// Returns `Err(Canceled)` if the ticket is canceled.
63    fn poll_turn(&self, cx: &mut Context<'_>) -> Poll<Result<(), Canceled>>;
64}
65
66/// Source of tickets for [`Ordered`].
67pub trait Sequencer<Req> {
68    /// Ticket type.
69    type Ticket: Turn;
70
71    /// Returns the ticket of a request, `None` for a request that is not ordered.
72    ///
73    /// Called synchronously when [`Ordered`] starts handling the request.
74    fn ticket(&self, req: &mut Req) -> Option<Self::Ticket>;
75}
76
77/// Position in a sequence issued by [`Tickets`].
78///
79/// The oldest outstanding ticket holds the turn. Passing or dropping it hands
80/// the turn to the next ticket; a ticket dropped before its turn is skipped.
81///
82/// Holding a ticket blocks the turn of every later ticket of the sequence,
83/// pass or drop it once its ordered side effect is done.
84///
85/// A canceled ticket keeps its position: its turn wait returns [`Canceled`] and
86/// dropping it passes or skips its turn as usual.
87pub struct Ticket {
88    seq: u64,
89    turns: Rc<Turns>,
90    passed: bool,
91}
92
93impl Ticket {
94    #[inline]
95    /// Position in the sequence, starting from zero.
96    pub fn seq(&self) -> u64 {
97        self.seq
98    }
99
100    #[inline]
101    /// Returns `true` if this ticket holds the turn.
102    pub fn is_turn(&self) -> bool {
103        !self.passed && self.turns.turn.get() == self.seq
104    }
105
106    #[inline]
107    /// Returns `true` if this ticket is canceled.
108    ///
109    /// Returns `false` after [`pass()`](Self::pass).
110    pub fn is_canceled(&self) -> bool {
111        !self.passed && self.turns.is_canceled(self.seq)
112    }
113
114    #[inline]
115    /// Returns `true` if this ticket is passed.
116    pub fn is_passed(&self) -> bool {
117        self.passed
118    }
119
120    /// Polls until this ticket holds the turn.
121    ///
122    /// Returns `Err(Canceled)` if the ticket is canceled, even if it holds the turn,
123    /// or if it is passed.
124    pub fn poll_turn(&self, cx: &mut Context<'_>) -> Poll<Result<(), Canceled>> {
125        if self.passed {
126            Poll::Ready(Err(Canceled))
127        } else {
128            self.turns.poll_turn(self.seq, cx)
129        }
130    }
131
132    /// Waits until this ticket holds the turn.
133    ///
134    /// Returns `Err(Canceled)` if the ticket is canceled, even if it holds the turn,
135    /// or if it is passed.
136    pub async fn turn(&self) -> Result<(), Canceled> {
137        poll_fn(|cx| self.poll_turn(cx)).await
138    }
139
140    /// Releases the turn of this ticket, same as drop, but keeps the ticket.
141    ///
142    /// If the ticket holds the turn, the turn passes to the next outstanding
143    /// ticket, otherwise its turn is skipped. The passed ticket can still
144    /// [`cancel()`](Self::cancel) the sequence. Passing again does nothing.
145    pub fn pass(&mut self) {
146        if !self.passed {
147            self.passed = true;
148            self.turns.release(self.seq);
149        }
150    }
151
152    /// Cancels every ticket of the sequence that is outstanding now.
153    ///
154    /// Turn waits of canceled tickets return [`Canceled`], tasks waiting for the
155    /// turn are woken. A ticket that already got its turn keeps running. Tickets
156    /// issued later are not canceled.
157    pub fn cancel(&self) {
158        self.turns.cancel();
159    }
160}
161
162impl Turn for Ticket {
163    fn poll_turn(&self, cx: &mut Context<'_>) -> Poll<Result<(), Canceled>> {
164        Ticket::poll_turn(self, cx)
165    }
166}
167
168impl Drop for Ticket {
169    fn drop(&mut self) {
170        self.pass();
171    }
172}
173
174impl PartialEq for Ticket {
175    fn eq(&self, other: &Self) -> bool {
176        self.seq == other.seq && Rc::ptr_eq(&self.turns, &other.turns)
177    }
178}
179
180impl Eq for Ticket {}
181
182impl fmt::Debug for Ticket {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        f.debug_struct("Ticket").field("seq", &self.seq).finish()
185    }
186}
187
188/// Issuer of a [`Ticket`] sequence.
189#[derive(Default)]
190pub struct Tickets(Rc<Turns>);
191
192impl Tickets {
193    /// Creates a new sequence, the first ticket is `0`.
194    pub fn new() -> Self {
195        Self::default()
196    }
197
198    /// Issues the next ticket.
199    pub fn issue(&self) -> Ticket {
200        let turns = &self.0;
201        let seq = turns.next.get();
202        turns.next.set(seq.wrapping_add(1));
203        turns.slots.borrow_mut().push_back(Slot::default());
204        Ticket {
205            seq,
206            turns: turns.clone(),
207            passed: false,
208        }
209    }
210
211    /// Cancels every outstanding ticket, see [`Ticket::cancel()`].
212    pub fn cancel(&self) {
213        self.0.cancel();
214    }
215}
216
217impl fmt::Debug for Tickets {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        f.debug_struct("Tickets")
220            .field("next", &self.0.next.get())
221            .field("turn", &self.0.turn.get())
222            .finish()
223    }
224}
225
226/// Turn state shared by an issuer and its outstanding tickets.
227#[derive(Default)]
228struct Turns {
229    /// Sequence of the next issued ticket.
230    next: Cell<u64>,
231    /// Sequence holding the turn, matches the front of `slots`.
232    turn: Cell<u64>,
233    /// Outstanding tickets from `turn` to `next`, indexed by `seq - turn`.
234    slots: RefCell<VecDeque<Slot>>,
235}
236
237#[derive(Default)]
238struct Slot {
239    /// Ticket is dropped, its turn is skipped.
240    released: bool,
241    /// Ticket is canceled, its turn wait fails.
242    canceled: bool,
243    /// Task waiting for the turn.
244    waker: LocalWaker,
245}
246
247impl Turns {
248    #[allow(clippy::cast_possible_truncation)]
249    fn index(&self, seq: u64) -> usize {
250        // outstanding tickets fit in memory, so the distance fits `usize`
251        seq.wrapping_sub(self.turn.get()) as usize
252    }
253
254    fn is_canceled(&self, seq: u64) -> bool {
255        self.slots.borrow()[self.index(seq)].canceled
256    }
257
258    fn poll_turn(&self, seq: u64, cx: &Context<'_>) -> Poll<Result<(), Canceled>> {
259        let idx = self.index(seq);
260        let slots = self.slots.borrow();
261        let slot = &slots[idx];
262        if slot.canceled {
263            Poll::Ready(Err(Canceled))
264        } else if idx == 0 {
265            Poll::Ready(Ok(()))
266        } else {
267            slot.waker.register(cx.waker());
268            Poll::Pending
269        }
270    }
271
272    fn cancel(&self) {
273        let wakers: Vec<_> = self
274            .slots
275            .borrow_mut()
276            .iter_mut()
277            .filter_map(|slot| {
278                slot.canceled = true;
279                slot.waker.take()
280            })
281            .collect();
282        for waker in wakers {
283            waker.wake();
284        }
285    }
286
287    fn release(&self, seq: u64) {
288        let waker = {
289            let idx = self.index(seq);
290            let mut slots = self.slots.borrow_mut();
291            let mut turn = self.turn.get();
292            slots[idx].released = true;
293            while slots.front().is_some_and(|s| s.released) {
294                slots.pop_front();
295                turn = turn.wrapping_add(1);
296            }
297            self.turn.set(turn);
298            slots.front().and_then(|s| s.waker.take())
299        };
300        if let Some(waker) = waker {
301            waker.wake();
302        }
303    }
304}
305
306/// Sequencer that issues tickets in the order calls start.
307///
308/// Every service created by [`OrderedFactory`] and every clone starts its own
309/// sequence. Without a filter every request is ordered; with a filter, requests
310/// for which it returns `false` are not ordered.
311pub struct Arrival<F = ()> {
312    tickets: Tickets,
313    filter: F,
314}
315
316impl Arrival {
317    /// Creates a sequencer that orders every request.
318    pub fn new() -> Self {
319        Self {
320            tickets: Tickets::new(),
321            filter: (),
322        }
323    }
324}
325
326impl Default for Arrival {
327    fn default() -> Self {
328        Self::new()
329    }
330}
331
332impl<F> Arrival<F> {
333    /// Orders only requests for which `filter` returns `true`.
334    pub fn filter<Req, F2>(self, filter: F2) -> Arrival<F2>
335    where
336        F2: Fn(&Req) -> bool,
337    {
338        Arrival {
339            filter,
340            tickets: self.tickets,
341        }
342    }
343}
344
345impl<F: Clone> Clone for Arrival<F> {
346    fn clone(&self) -> Self {
347        Self {
348            tickets: Tickets::new(),
349            filter: self.filter.clone(),
350        }
351    }
352}
353
354impl<F> fmt::Debug for Arrival<F> {
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        f.debug_struct("Arrival")
357            .field("tickets", &self.tickets)
358            .finish()
359    }
360}
361
362impl<Req> Sequencer<Req> for Arrival {
363    type Ticket = Ticket;
364
365    fn ticket(&self, _: &mut Req) -> Option<Ticket> {
366        Some(self.tickets.issue())
367    }
368}
369
370impl<Req, F> Sequencer<Req> for Arrival<F>
371where
372    F: Fn(&Req) -> bool,
373{
374    type Ticket = Ticket;
375
376    fn ticket(&self, req: &mut Req) -> Option<Ticket> {
377        (self.filter)(req).then(|| self.tickets.issue())
378    }
379}
380
381/// Sequencer that takes tickets from requests, see [`tickets()`].
382#[derive(Clone)]
383pub struct External<F>(F);
384
385/// Creates a sequencer that takes tickets assigned by an external system.
386///
387/// `f` extracts the ticket from a request, `None` means the request is not ordered.
388/// Requests may enter [`Ordered`] in any order, they enter `B` in ticket order.
389///
390/// ```
391/// use ntex_util::services::ordered::{Ordered, Ticket, tickets};
392/// # let a = ntex_service::fn_service(async |req: (u32, Option<Ticket>)| Ok::<_, ()>(req.0));
393/// # let b = ntex_service::fn_service(async |val: u32| Ok::<_, ()>(val));
394///
395/// let svc = Ordered::new(a, b).sequencer(tickets(|req: &mut (u32, Option<Ticket>)| req.1.take()));
396/// ```
397pub fn tickets<F, Req, T>(f: F) -> External<F>
398where
399    F: Fn(&mut Req) -> Option<T>,
400    T: Turn,
401{
402    External(f)
403}
404
405impl<F> fmt::Debug for External<F> {
406    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407        f.debug_struct("External").finish()
408    }
409}
410
411impl<Req, F, T> Sequencer<Req> for External<F>
412where
413    F: Fn(&mut Req) -> Option<T>,
414    T: Turn,
415{
416    type Ticket = T;
417
418    fn ticket(&self, req: &mut Req) -> Option<T> {
419        (self.0)(req)
420    }
421}
422
423/// Runs `A` concurrently and enters `B` in ticket order.
424///
425/// For each request, [`Ordered`] takes a ticket from its [`Sequencer`], calls `A`,
426/// waits for the ticket's turn, waits for `B` readiness and enters `B::call`. The
427/// turn passes to the next ticket as soon as `B::call` is entered, so `B` calls run
428/// concurrently and each caller awaits its own `B` result. Requests without a
429/// ticket call `A` and `B` without waiting for a turn.
430///
431/// Errors from `A` and from `B` readiness are returned immediately and pass the
432/// turn. Dropping the call future at any stage passes or skips its turn. A
433/// canceled ticket returns [`Canceled`] converted to the error type instead of
434/// entering `B`.
435///
436/// Readiness requires both services to be ready, so `B` backpressure applies to
437/// new requests. `B` has its own readiness cache ([`ReadyBinding`]).
438///
439/// # Contracts
440///
441/// - `B::call` must perform its ordered side effect before its first `.await`;
442///   the turn passes once `B::call` is first polled.
443/// - `B` must notify readiness changes (see [`ntex_service::ReadyNotifier`]).
444/// - With [`Arrival`], the ticket is taken on the first poll of the call future,
445///   so callers must start calls in arrival order: layers above `Ordered` must not
446///   await before calling it. External tickets ([`tickets()`]) remove this
447///   requirement.
448/// - A held ticket blocks later turns, external tickets must be passed to
449///   `Ordered` or dropped.
450pub struct Ordered<A, B, S = Arrival> {
451    a: A,
452    b: ReadyBinding<B>,
453    seq: S,
454}
455
456impl<A, B> Ordered<A, B> {
457    /// Creates a service that orders every request by call start.
458    pub fn new(a: A, b: B) -> Self {
459        Self {
460            a,
461            b: ReadyBinding::new(b),
462            seq: Arrival::new(),
463        }
464    }
465}
466
467impl<A, B, F> Ordered<A, B, Arrival<F>> {
468    /// Orders only requests for which `filter` returns `true`.
469    pub fn filter<Req, F2>(self, filter: F2) -> Ordered<A, B, Arrival<F2>>
470    where
471        F2: Fn(&Req) -> bool,
472    {
473        Ordered {
474            a: self.a,
475            b: self.b,
476            seq: self.seq.filter(filter),
477        }
478    }
479}
480
481impl<A, B, S> Ordered<A, B, S> {
482    /// Replaces the ticket source.
483    pub fn sequencer<S2>(self, seq: S2) -> Ordered<A, B, S2> {
484        Ordered {
485            a: self.a,
486            b: self.b,
487            seq,
488        }
489    }
490}
491
492impl<A: Clone, B: Clone, S: Clone> Clone for Ordered<A, B, S> {
493    fn clone(&self) -> Self {
494        Self {
495            a: self.a.clone(),
496            b: self.b.clone(),
497            seq: self.seq.clone(),
498        }
499    }
500}
501
502impl<A: fmt::Debug, B: fmt::Debug, S: fmt::Debug> fmt::Debug for Ordered<A, B, S> {
503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504        f.debug_struct("Ordered")
505            .field("a", &self.a)
506            .field("b", self.b.get_ref())
507            .field("seq", &self.seq)
508            .finish()
509    }
510}
511
512impl<A, B, S, St, Req> Service<St, Req> for Ordered<A, B, S>
513where
514    A: Service<St, Req>,
515    A::Error: From<Canceled>,
516    B: Service<St, A::Res, Error = A::Error>,
517    S: Sequencer<Req>,
518{
519    type Res = B::Res;
520    type Error = A::Error;
521
522    fn bind(&self, ctx: BindCtx<'_>) {
523        ctx.bind(&self.a);
524        ctx.bind(&self.b);
525    }
526
527    async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), A::Error> {
528        let mut a = pin!(ctx.ready(&self.a));
529        let mut b = pin!(ctx.ready(&self.b));
530        let (mut a_ready, mut b_ready) = (false, false);
531        poll_fn(|cx| {
532            if !a_ready && let Poll::Ready(res) = a.as_mut().poll(cx) {
533                res?;
534                a_ready = true;
535            }
536            if !b_ready && let Poll::Ready(res) = b.as_mut().poll(cx) {
537                res?;
538                b_ready = true;
539            }
540            if a_ready && b_ready {
541                Poll::Ready(Ok(()))
542            } else {
543                Poll::Pending
544            }
545        })
546        .await
547    }
548
549    async fn call(&self, mut req: Req, ctx: Ctx<'_, Self, St>) -> Result<B::Res, A::Error> {
550        // taken before any await, drop passes or skips the turn
551        let Some(ticket) = self.seq.ticket(&mut req) else {
552            let res = ctx.call(&self.a, req).await?;
553            return ctx.call(&self.b, res).await;
554        };
555
556        let res = ctx.call(&self.a, req).await?;
557        poll_fn(|cx| ticket.poll_turn(cx)).await?;
558
559        // `ctx.call` enters `B::call` in the same poll as the successful
560        // readiness check, `B`'s binding cache is valid until then
561        let entered = Cell::new(false);
562        let mut fut = pin!(async {
563            ctx.ready(&self.b).await?;
564            entered.set(true);
565            ctx.call(&self.b, res).await
566        });
567        let mut ticket = Some(ticket);
568        poll_fn(|cx| {
569            let res = fut.as_mut().poll(cx);
570            if entered.get() {
571                ticket = None;
572            }
573            res
574        })
575        .await
576    }
577
578    async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
579        crate::future::join(ctx.shutdown(&self.a), ctx.shutdown(&self.b)).await;
580    }
581}
582
583/// Factory for [`Ordered`] services.
584///
585/// Creates `A` and then `B` with the same state. Each created service clones
586/// the sequencer, an [`Arrival`] sequencer starts a new sequence per service.
587pub struct OrderedFactory<A, B, S = Arrival> {
588    a: A,
589    b: B,
590    seq: S,
591}
592
593impl<A, B> OrderedFactory<A, B> {
594    /// Creates a factory that orders every request by call start.
595    pub fn new(a: A, b: B) -> Self {
596        Self {
597            a,
598            b,
599            seq: Arrival::new(),
600        }
601    }
602}
603
604impl<A, B, F> OrderedFactory<A, B, Arrival<F>> {
605    /// Orders only requests for which `filter` returns `true`.
606    pub fn filter<Req, F2>(self, filter: F2) -> OrderedFactory<A, B, Arrival<F2>>
607    where
608        F2: Fn(&Req) -> bool,
609    {
610        OrderedFactory {
611            a: self.a,
612            b: self.b,
613            seq: self.seq.filter(filter),
614        }
615    }
616}
617
618impl<A, B, S> OrderedFactory<A, B, S> {
619    /// Replaces the ticket source.
620    pub fn sequencer<S2>(self, seq: S2) -> OrderedFactory<A, B, S2> {
621        OrderedFactory {
622            a: self.a,
623            b: self.b,
624            seq,
625        }
626    }
627}
628
629impl<A: Clone, B: Clone, S: Clone> Clone for OrderedFactory<A, B, S> {
630    fn clone(&self) -> Self {
631        Self {
632            a: self.a.clone(),
633            b: self.b.clone(),
634            seq: self.seq.clone(),
635        }
636    }
637}
638
639impl<A: fmt::Debug, B: fmt::Debug, S: fmt::Debug> fmt::Debug for OrderedFactory<A, B, S> {
640    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641        f.debug_struct("OrderedFactory")
642            .field("a", &self.a)
643            .field("b", &self.b)
644            .field("seq", &self.seq)
645            .finish()
646    }
647}
648
649impl<A, B, S, St, Req> ServiceFactory<St, Req> for OrderedFactory<A, B, S>
650where
651    A: ServiceFactory<St, Req>,
652    A::Error: From<Canceled>,
653    B: ServiceFactory<St, A::Res, Error = A::Error, InitError = A::InitError>,
654    S: Sequencer<Req> + Clone,
655{
656    type Res = B::Res;
657    type Error = A::Error;
658    type Service = Ordered<A::Service, B::Service, S>;
659    type InitError = A::InitError;
660
661    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
662        let a = self.a.create(st).await?;
663        let b = self.b.create(st).await?;
664        Ok(Ordered {
665            a,
666            b: ReadyBinding::new(b),
667            seq: self.seq.clone(),
668        })
669    }
670}
671
672#[cfg(test)]
673mod tests {
674    use std::sync::atomic::{AtomicBool, Ordering};
675    use std::{convert::Infallible, sync::Arc, task::Wake, task::Waker};
676
677    use ntex::rt::{JoinHandle, spawn};
678    use ntex_service::{Pipeline, ReadyNotifier, fn_factory, fn_service, service};
679
680    use super::*;
681    use crate::services::inflight::InFlightService;
682    use crate::{time::Millis, time::sleep, time::timeout};
683
684    fn issue(tickets: &Tickets, n: usize) -> Vec<Ticket> {
685        (0..n).map(|_| tickets.issue()).collect()
686    }
687
688    /// STATEMENT: Tickets are issued in sequence and the oldest one holds the turn.
689    ///
690    /// HOW:
691    /// - Issue two tickets, check sequence, turn, `Debug` and equality.
692    #[test]
693    fn issue_in_sequence() {
694        let tickets = Tickets::new();
695        let t0 = tickets.issue();
696        let t1 = tickets.issue();
697        assert_eq!((t0.seq(), t1.seq()), (0, 1));
698        assert!(t0.is_turn());
699        assert!(!t1.is_turn());
700        assert_eq!(format!("{t1:?}"), "Ticket { seq: 1 }");
701        assert_ne!(t0, t1);
702        assert_eq!(t0, t0);
703
704        // another issuer has an independent sequence
705        let other = Tickets::new();
706        let o0 = other.issue();
707        assert_eq!(o0.seq(), 0);
708        assert!(o0.is_turn());
709        assert_ne!(o0, t0);
710    }
711
712    /// STATEMENT: `Tickets` `Debug` reports the next sequence and the current turn.
713    ///
714    /// HOW:
715    /// - Issue two tickets, check `next: 2, turn: 0`, drop the first one and check that the
716    ///   turn moves to `1`.
717    #[test]
718    fn tickets_debug() {
719        let tickets = Tickets::new();
720        assert_eq!(format!("{tickets:?}"), "Tickets { next: 0, turn: 0 }");
721        let t0 = tickets.issue();
722        let _t1 = tickets.issue();
723        assert_eq!(format!("{tickets:?}"), "Tickets { next: 2, turn: 0 }");
724        drop(t0);
725        assert_eq!(format!("{tickets:?}"), "Tickets { next: 2, turn: 1 }");
726    }
727
728    /// STATEMENT: Sequencer `Debug` output shows ticket state and hides filters and extractors.
729    ///
730    /// HOW:
731    /// - Format a plain and a filtered `Arrival` after issuing a ticket, and a `tickets()`
732    ///   sequencer; check the exact strings.
733    #[test]
734    fn sequencer_debug() {
735        let arrival = Arrival::new();
736        let _t = <Arrival as Sequencer<u32>>::ticket(&arrival, &mut 0);
737        assert_eq!(
738            format!("{arrival:?}"),
739            "Arrival { tickets: Tickets { next: 1, turn: 0 } }"
740        );
741
742        let filtered = Arrival::new().filter(|req: &u32| *req > 0);
743        assert_eq!(
744            format!("{filtered:?}"),
745            "Arrival { tickets: Tickets { next: 0, turn: 0 } }"
746        );
747
748        let external = tickets(|req: &mut Option<Ticket>| req.take());
749        assert_eq!(format!("{external:?}"), "External");
750    }
751
752    /// STATEMENT: `Ordered` and `OrderedFactory` `Debug` show both services and the sequencer.
753    ///
754    /// HOW:
755    /// - Build both with `Debug` stand-ins for `A` and `B`, with the default sequencer and with
756    ///   `tickets()`, and check the exact strings.
757    #[test]
758    fn ordered_debug() {
759        let svc = Ordered::new("a", 1u8);
760        assert_eq!(
761            format!("{svc:?}"),
762            "Ordered { a: \"a\", b: 1, seq: Arrival { tickets: Tickets { next: 0, turn: 0 } } }"
763        );
764        let svc = svc.sequencer(tickets(|req: &mut Option<Ticket>| req.take()));
765        assert_eq!(
766            format!("{svc:?}"),
767            "Ordered { a: \"a\", b: 1, seq: External }"
768        );
769
770        let factory = OrderedFactory::new("a", 1u8);
771        assert_eq!(
772            format!("{factory:?}"),
773            "OrderedFactory { a: \"a\", b: 1, seq: Arrival { tickets: Tickets { next: 0, turn: 0 } } }"
774        );
775        let factory = factory.sequencer(tickets(|req: &mut Option<Ticket>| req.take()));
776        assert_eq!(
777            format!("{factory:?}"),
778            "OrderedFactory { a: \"a\", b: 1, seq: External }"
779        );
780    }
781
782    /// STATEMENT: Passing the turn skips tickets dropped before their turn.
783    ///
784    /// HOW:
785    /// - Drop middle tickets out of order, pass the first, the last holds the turn.
786    #[test]
787    fn pass_and_skip() {
788        let tickets = Tickets::new();
789        let mut t = issue(&tickets, 5);
790        let t4 = t.pop().unwrap();
791        let t3 = t.pop().unwrap();
792        let t2 = t.pop().unwrap();
793        let t1 = t.pop().unwrap();
794        let mut t0 = t.pop().unwrap();
795
796        drop(t1);
797        drop(t3);
798        drop(t2);
799        assert!(t0.is_turn());
800        assert!(!t4.is_turn());
801
802        t0.pass();
803        assert!(t4.is_turn());
804        drop(t4);
805
806        let t5 = tickets.issue();
807        assert_eq!(t5.seq(), 5);
808        assert!(t5.is_turn());
809    }
810
811    struct Flag(AtomicBool);
812
813    impl Wake for Flag {
814        fn wake(self: Arc<Self>) {
815            self.0.store(true, Ordering::SeqCst);
816        }
817    }
818
819    /// STATEMENT: The next turn owner is woken only when it gets the turn.
820    ///
821    /// HOW:
822    /// - Wait for the turn of the third ticket, drop the second, pass the first.
823    #[test]
824    fn wake_next_owner() {
825        let tickets = Tickets::new();
826        let mut t = issue(&tickets, 3);
827        let t2 = t.pop().unwrap();
828        let t1 = t.pop().unwrap();
829        let mut t0 = t.pop().unwrap();
830
831        let flag = Arc::new(Flag(AtomicBool::new(false)));
832        let waker = Waker::from(flag.clone());
833        let mut cx = Context::from_waker(&waker);
834        let mut fut = pin!(t2.turn());
835        assert!(fut.as_mut().poll(&mut cx).is_pending());
836
837        drop(t1);
838        assert!(!flag.0.load(Ordering::SeqCst), "not woken before its turn");
839        t0.pass();
840        assert!(flag.0.load(Ordering::SeqCst));
841        assert_eq!(fut.as_mut().poll(&mut cx), Poll::Ready(Ok(())));
842    }
843
844    /// STATEMENT: Cancel fails the turn waits of outstanding tickets only and
845    /// keeps the sequence going.
846    /// HOW:
847    /// - Wait for the turn of the last of three tickets, cancel through a
848    ///   passed ticket that holds no slot anymore.
849    /// - Check the waiter is woken with `Canceled`, the turn owner is canceled too.
850    /// - Issue a ticket after the cancel, release the canceled ones and check it
851    ///   gets its turn; `Tickets::cancel()` cancels it.
852    #[test]
853    fn cancel_outstanding() {
854        let tickets = Tickets::new();
855        let mut t0 = tickets.issue();
856        t0.pass();
857        t0.pass();
858        assert!(t0.is_passed() && !t0.is_turn() && !t0.is_canceled());
859        let mut t = issue(&tickets, 3);
860        let t3 = t.pop().unwrap();
861        let t2 = t.pop().unwrap();
862        let t1 = t.pop().unwrap();
863
864        let flag = Arc::new(Flag(AtomicBool::new(false)));
865        let waker = Waker::from(flag.clone());
866        let mut cx = Context::from_waker(&waker);
867        {
868            let mut fut = pin!(t3.turn());
869            assert!(fut.as_mut().poll(&mut cx).is_pending());
870
871            t0.cancel();
872            assert!(flag.0.load(Ordering::SeqCst));
873            assert_eq!(fut.as_mut().poll(&mut cx), Poll::Ready(Err(Canceled)));
874        }
875        assert!(t1.is_turn() && t1.is_canceled() && t2.is_canceled());
876        assert_eq!(t1.poll_turn(&mut cx), Poll::Ready(Err(Canceled)));
877        assert_eq!(t0.poll_turn(&mut cx), Poll::Ready(Err(Canceled)));
878        assert!(!t0.is_canceled());
879        assert_eq!(Canceled.to_string(), "Ticket is canceled");
880
881        let t4 = tickets.issue();
882        assert!(!t4.is_canceled());
883        drop((t1, t2, t3));
884        assert_eq!(t4.poll_turn(&mut cx), Poll::Ready(Ok(())));
885
886        tickets.cancel();
887        assert_eq!(t4.poll_turn(&mut cx), Poll::Ready(Err(Canceled)));
888    }
889
890    #[derive(Debug)]
891    struct Msg {
892        id: u32,
893        delay: u32,
894        ordered: bool,
895        fail: bool,
896        ticket: Option<Ticket>,
897    }
898
899    impl Msg {
900        fn new(id: u32, delay: u32) -> Self {
901            Self {
902                id,
903                delay,
904                ordered: true,
905                fail: false,
906                ticket: None,
907            }
908        }
909
910        fn unordered(self) -> Self {
911            Self {
912                ordered: false,
913                ..self
914            }
915        }
916
917        fn failed(self) -> Self {
918            Self { fail: true, ..self }
919        }
920
921        fn ticket(self, ticket: Ticket) -> Self {
922            Self {
923                ticket: Some(ticket),
924                ..self
925            }
926        }
927    }
928
929    /// Error of a canceled ticket in `Ordered` tests.
930    const CANCELED: u32 = u32::MAX;
931
932    impl From<Canceled> for u32 {
933        fn from(_: Canceled) -> u32 {
934            CANCELED
935        }
936    }
937
938    async fn first(msg: Msg) -> Result<u32, u32> {
939        if msg.delay > 0 {
940            sleep(Millis(msg.delay)).await;
941        }
942        if msg.fail { Err(msg.id) } else { Ok(msg.id) }
943    }
944
945    #[derive(Clone, Default)]
946    struct Sink(Rc<SinkInner>);
947
948    #[derive(Default)]
949    struct SinkInner {
950        entered: RefCell<Vec<u32>>,
951        not_ready: Cell<bool>,
952        fail_ready: Cell<bool>,
953        delay: Cell<u32>,
954        shutdown: Cell<bool>,
955        waker: LocalWaker,
956        changed: ReadyNotifier,
957    }
958
959    impl Sink {
960        fn set_ready(&self, ready: bool) {
961            self.0.not_ready.set(!ready);
962            self.0.changed.notify();
963            self.0.waker.wake();
964        }
965
966        fn fail_ready(&self) {
967            self.0.fail_ready.set(true);
968            self.0.changed.notify();
969        }
970
971        fn entered(&self) -> Vec<u32> {
972            self.0.entered.borrow().clone()
973        }
974    }
975
976    impl Service<(), u32> for Sink {
977        type Res = u32;
978        type Error = u32;
979
980        fn bind(&self, ctx: BindCtx<'_>) {
981            ctx.subscribe(&self.0.changed);
982        }
983
984        async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), u32> {
985            poll_fn(|cx| {
986                if self.0.fail_ready.replace(false) {
987                    return Poll::Ready(Err(0));
988                }
989                self.0.waker.register(cx.waker());
990                if self.0.not_ready.get() {
991                    Poll::Pending
992                } else {
993                    Poll::Ready(Ok(()))
994                }
995            })
996            .await
997        }
998
999        async fn call(&self, id: u32, _: Ctx<'_, Self>) -> Result<u32, u32> {
1000            self.0.entered.borrow_mut().push(id);
1001            let delay = self.0.delay.get();
1002            if delay > 0 {
1003                sleep(Millis(delay)).await;
1004            }
1005            Ok(id * 10)
1006        }
1007
1008        async fn shutdown(&self, _: Ctx<'_, Self>) {
1009            self.0.shutdown.set(true);
1010        }
1011    }
1012
1013    /// `A` that records binding and shutdown and can fail readiness with `1`.
1014    #[derive(Clone, Default)]
1015    struct Probe(Rc<ProbeInner>);
1016
1017    #[derive(Default)]
1018    struct ProbeInner {
1019        bound: Cell<bool>,
1020        fail_ready: Cell<bool>,
1021        shutdown: Cell<bool>,
1022        changed: ReadyNotifier,
1023    }
1024
1025    impl Probe {
1026        fn fail_ready(&self, fail: bool) {
1027            self.0.fail_ready.set(fail);
1028            self.0.changed.notify();
1029        }
1030    }
1031
1032    impl Service<(), Msg> for Probe {
1033        type Res = u32;
1034        type Error = u32;
1035
1036        fn bind(&self, ctx: BindCtx<'_>) {
1037            self.0.bound.set(true);
1038            ctx.subscribe(&self.0.changed);
1039        }
1040
1041        async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), u32> {
1042            let fail = self.0.fail_ready.get();
1043            poll_fn(|_| Poll::Ready(if fail { Err(1) } else { Ok(()) })).await
1044        }
1045
1046        async fn call(&self, msg: Msg, _: Ctx<'_, Self>) -> Result<u32, u32> {
1047            first(msg).await
1048        }
1049
1050        async fn shutdown(&self, _: Ctx<'_, Self>) {
1051            self.0.shutdown.set(true);
1052        }
1053    }
1054
1055    type Svc = Pipeline<Msg, u32, u32>;
1056
1057    fn ordered(sink: &Sink) -> Svc {
1058        Pipeline::new(
1059            (),
1060            Ordered::new(fn_service(first), sink.clone()).filter(|m: &Msg| m.ordered),
1061        )
1062    }
1063
1064    fn with_inflight(sink: &Sink, limit: usize) -> Svc {
1065        let svc = Ordered::new(fn_service(first), sink.clone());
1066        Pipeline::new((), InFlightService::new(limit, svc))
1067    }
1068
1069    /// Polls the future once inline (as ntex dispatcher does), then spawns it.
1070    async fn start<F>(fut: F) -> JoinHandle<F::Output>
1071    where
1072        F: Future + 'static,
1073        F::Output: 'static,
1074    {
1075        let mut fut = Box::pin(fut);
1076        let first = poll_fn(|cx| Poll::Ready(fut.as_mut().poll(cx))).await;
1077        spawn(async move {
1078            match first {
1079                Poll::Ready(res) => res,
1080                Poll::Pending => fut.await,
1081            }
1082        })
1083    }
1084
1085    /// Dispatcher-like loop: waits for readiness, then calls the service.
1086    async fn dispatch(
1087        pl: &Svc,
1088        msgs: impl IntoIterator<Item = Msg>,
1089    ) -> Vec<JoinHandle<Result<u32, u32>>> {
1090        let mut handles = Vec::new();
1091        for msg in msgs {
1092            timeout(Millis(1000), pl.ready())
1093                .await
1094                .expect("dispatcher readiness stalled")
1095                .unwrap();
1096            handles.push(start(pl.call_static(msg)).await);
1097        }
1098        handles
1099    }
1100
1101    async fn results<T>(handles: Vec<JoinHandle<T>>) -> Vec<T> {
1102        let mut res = Vec::new();
1103        for h in handles {
1104            res.push(
1105                timeout(Millis(1000), h)
1106                    .await
1107                    .expect("call stalled")
1108                    .unwrap(),
1109            );
1110        }
1111        res
1112    }
1113
1114    /// STATEMENT: `B` is entered in arrival order and each caller gets its own result.
1115    ///
1116    /// HOW:
1117    /// - Later requests finish `A` first; check entry order and per-caller results.
1118    #[ntex::test]
1119    async fn enters_in_arrival_order() {
1120        let sink = Sink::default();
1121        let pl = ordered(&sink);
1122
1123        let msgs = [
1124            Msg::new(1, 30),
1125            Msg::new(2, 20),
1126            Msg::new(3, 10),
1127            Msg::new(4, 0),
1128        ];
1129        let handles = dispatch(&pl, msgs).await;
1130        assert_eq!(results(handles).await, vec![Ok(10), Ok(20), Ok(30), Ok(40)]);
1131        assert_eq!(sink.entered(), vec![1, 2, 3, 4]);
1132    }
1133
1134    /// STATEMENT: Requests waiting for `B` readiness enter it in arrival order.
1135    ///
1136    /// HOW:
1137    /// - Make `B` not ready while all requests wait, then make it ready.
1138    #[ntex::test]
1139    async fn b_not_ready_keeps_order() {
1140        let sink = Sink::default();
1141        let pl = ordered(&sink);
1142
1143        let handles = dispatch(&pl, [Msg::new(1, 20), Msg::new(2, 10), Msg::new(3, 0)]).await;
1144        sink.set_ready(false);
1145        sleep(Millis(40)).await;
1146        assert_eq!(sink.entered(), Vec::<u32>::new());
1147
1148        sink.set_ready(true);
1149        assert_eq!(results(handles).await, vec![Ok(10), Ok(20), Ok(30)]);
1150        assert_eq!(sink.entered(), vec![1, 2, 3]);
1151    }
1152
1153    /// STATEMENT: Order holds when `B` readiness changes repeatedly during turns.
1154    ///
1155    /// HOW:
1156    /// - Toggle `B` readiness through `ReadyNotifier` while requests wait for turns; the toggle
1157    ///   task ends with `B` ready.
1158    #[ntex::test]
1159    async fn b_readiness_toggles() {
1160        let sink = Sink::default();
1161        let pl = ordered(&sink);
1162
1163        let toggle = sink.clone();
1164        let toggler = spawn(async move {
1165            for i in 0..10 {
1166                sleep(Millis(4)).await;
1167                toggle.set_ready(i % 2 == 1);
1168            }
1169        });
1170
1171        let msgs = (1..=6).map(|id| Msg::new(id, 30 - id * 5));
1172        let handles = dispatch(&pl, msgs).await;
1173        let expected: Vec<_> = (1..=6).map(|id| Ok(id * 10)).collect();
1174        assert_eq!(results(handles).await, expected);
1175        assert_eq!(sink.entered(), vec![1, 2, 3, 4, 5, 6]);
1176        timeout(Millis(1000), toggler).await.unwrap().unwrap();
1177    }
1178
1179    /// STATEMENT: `Ordered` readiness waits for both services and returns
1180    /// readiness errors from either.
1181    ///
1182    /// HOW:
1183    /// - Fail `A` readiness and check `ready()` returns `A`'s error.
1184    /// - Make `B` not ready, check `ready()` stays pending, then make `B` ready
1185    ///   and check the same pending future completes.
1186    /// - Fail `B` readiness once and check `ready()` returns `B`'s error.
1187    #[ntex::test]
1188    async fn ready_waits_for_both() {
1189        let probe = Probe::default();
1190        let sink = Sink::default();
1191        let pl = Pipeline::new((), Ordered::new(probe.clone(), sink.clone()));
1192
1193        probe.fail_ready(true);
1194        assert_eq!(pl.ready().await, Err(1));
1195        probe.fail_ready(false);
1196        assert_eq!(pl.ready().await, Ok(()));
1197
1198        sink.set_ready(false);
1199        let mut ready = pin!(pl.ready());
1200        assert!(
1201            poll_fn(|cx| Poll::Ready(ready.as_mut().poll(cx)))
1202                .await
1203                .is_pending()
1204        );
1205        sleep(Millis(20)).await;
1206        assert!(
1207            poll_fn(|cx| Poll::Ready(ready.as_mut().poll(cx)))
1208                .await
1209                .is_pending()
1210        );
1211        sink.set_ready(true);
1212        assert_eq!(timeout(Millis(1000), ready).await, Ok(Ok(())));
1213
1214        sink.fail_ready();
1215        assert_eq!(pl.ready().await, Err(0));
1216    }
1217
1218    /// STATEMENT: `Ordered` forwards binding and shutdown to both services.
1219    ///
1220    /// HOW:
1221    /// - Wrap a recording `A` and `B` in a pipeline, check `A` is bound after `ready()` and a
1222    ///   call succeeds, then shut the pipeline down and check both saw the shutdown.
1223    #[ntex::test]
1224    async fn bind_and_shutdown_reach_both() {
1225        let probe = Probe::default();
1226        let sink = Sink::default();
1227        let pl = Pipeline::new((), Ordered::new(probe.clone(), sink.clone()));
1228
1229        pl.ready().await.unwrap();
1230        assert!(probe.0.bound.get());
1231        assert_eq!(pl.call(Msg::new(1, 0)).await, Ok(10));
1232        assert!(!probe.0.shutdown.get() && !sink.0.shutdown.get());
1233
1234        pl.shutdown().await;
1235        assert!(probe.0.shutdown.get());
1236        assert!(sink.0.shutdown.get());
1237    }
1238
1239    /// STATEMENT: A cloned `Ordered` starts its own arrival sequence.
1240    ///
1241    /// HOW:
1242    /// - Clone a service built with `Arrival::default()`; a slow request in the original does
1243    ///   not block a request in the clone.
1244    #[ntex::test]
1245    async fn clone_has_own_sequence() {
1246        let sink = Sink::default();
1247        let svc = Ordered::new(fn_service(first), sink.clone()).sequencer(Arrival::default());
1248        let pl1 = Pipeline::new((), svc.clone());
1249        let pl2 = Pipeline::new((), svc);
1250
1251        let h1 = dispatch(&pl1, [Msg::new(1, 30), Msg::new(2, 0)]).await;
1252        let h2 = dispatch(&pl2, [Msg::new(3, 0)]).await;
1253        assert_eq!(results(h2).await, vec![Ok(30)]);
1254        assert_eq!(results(h1).await, vec![Ok(10), Ok(20)]);
1255        assert_eq!(sink.entered(), vec![3, 1, 2]);
1256    }
1257
1258    /// STATEMENT: An `A` error is returned immediately and does not block later turns.
1259    ///
1260    /// HOW:
1261    /// - Fail the turn owner and a waiting request.
1262    #[ntex::test]
1263    async fn a_error() {
1264        let sink = Sink::default();
1265        let pl = ordered(&sink);
1266
1267        let msgs = [
1268            Msg::new(1, 30).failed(),
1269            Msg::new(2, 20),
1270            Msg::new(3, 0).failed(),
1271            Msg::new(4, 10),
1272        ];
1273        let handles = dispatch(&pl, msgs).await;
1274        assert_eq!(results(handles).await, vec![Err(1), Ok(20), Err(3), Ok(40)]);
1275        assert_eq!(sink.entered(), vec![2, 4]);
1276    }
1277
1278    /// STATEMENT: A `B` readiness error is returned to the turn owner and passes the turn.
1279    ///
1280    /// HOW:
1281    /// - Fail `B` readiness once while requests wait for turns.
1282    #[ntex::test]
1283    async fn b_ready_error() {
1284        let sink = Sink::default();
1285        let pl = ordered(&sink);
1286
1287        let handles = dispatch(&pl, [Msg::new(1, 10), Msg::new(2, 0), Msg::new(3, 0)]).await;
1288        sink.fail_ready();
1289        assert_eq!(results(handles).await, vec![Err(0), Ok(20), Ok(30)]);
1290        assert_eq!(sink.entered(), vec![2, 3]);
1291    }
1292
1293    /// STATEMENT: Cancelling a request before its turn skips it.
1294    ///
1295    /// HOW:
1296    /// - Time out the second request while the first is in `A`.
1297    #[ntex::test]
1298    async fn cancel_before_turn() {
1299        let sink = Sink::default();
1300        let pl = ordered(&sink);
1301
1302        let h1 = start(pl.call_static(Msg::new(1, 30))).await;
1303        let h2 = start(timeout(Millis(15), pl.call_static(Msg::new(2, 0)))).await;
1304        let h3 = start(pl.call_static(Msg::new(3, 0))).await;
1305
1306        assert_eq!(results(vec![h1, h3]).await, vec![Ok(10), Ok(30)]);
1307        assert!(results(vec![h2]).await[0].is_err());
1308        assert_eq!(sink.entered(), vec![1, 3]);
1309    }
1310
1311    /// STATEMENT: Cancelling the turn owner while it waits for `B` passes the turn.
1312    ///
1313    /// HOW:
1314    /// - Time out the first request while `B` is not ready.
1315    #[ntex::test]
1316    async fn cancel_turn_owner() {
1317        let sink = Sink::default();
1318        let pl = ordered(&sink);
1319
1320        sink.set_ready(false);
1321        let h1 = start(timeout(Millis(20), pl.call_static(Msg::new(1, 0)))).await;
1322        let h2 = start(pl.call_static(Msg::new(2, 0))).await;
1323        sleep(Millis(40)).await;
1324        assert!(results(vec![h1]).await[0].is_err());
1325        assert_eq!(sink.entered(), Vec::<u32>::new());
1326
1327        sink.set_ready(true);
1328        assert_eq!(results(vec![h2]).await, vec![Ok(20)]);
1329        assert_eq!(sink.entered(), vec![2]);
1330    }
1331
1332    /// STATEMENT: Cancelling a request inside `B` does not affect later turns.
1333    ///
1334    /// HOW:
1335    /// - Start the first request with a 10ms timeout; it enters `B::call`, which
1336    ///   sleeps far longer, so the timeout always wins even on a slow runner.
1337    /// - Start two more requests with a short `B` delay.
1338    /// - Confirm the first times out and the later ones complete in order.
1339    #[ntex::test]
1340    async fn cancel_in_b() {
1341        let sink = Sink::default();
1342        sink.0.delay.set(10_000);
1343        let pl = ordered(&sink);
1344
1345        let h1 = start(timeout(Millis(10), pl.call_static(Msg::new(1, 0)))).await;
1346        assert_eq!(sink.entered(), vec![1]);
1347        sink.0.delay.set(30);
1348        let h2 = start(pl.call_static(Msg::new(2, 20))).await;
1349        let h3 = start(pl.call_static(Msg::new(3, 0))).await;
1350
1351        assert!(results(vec![h1]).await[0].is_err());
1352        assert_eq!(results(vec![h2, h3]).await, vec![Ok(20), Ok(30)]);
1353        assert_eq!(sink.entered(), vec![1, 2, 3]);
1354    }
1355
1356    /// STATEMENT: Requests rejected by the filter bypass turns, and their `A` errors are
1357    /// returned without entering `B`.
1358    ///
1359    /// HOW:
1360    /// - An unordered request enters `B` while an earlier ordered one is in `A`; a failing
1361    ///   unordered request returns its `A` error.
1362    #[ntex::test]
1363    async fn unordered_bypass() {
1364        let sink = Sink::default();
1365        let pl = ordered(&sink);
1366
1367        let msgs = [
1368            Msg::new(1, 30),
1369            Msg::new(2, 0).unordered(),
1370            Msg::new(3, 0),
1371            Msg::new(4, 0).unordered().failed(),
1372        ];
1373        let handles = dispatch(&pl, msgs).await;
1374        assert_eq!(results(handles).await, vec![Ok(10), Ok(20), Ok(30), Err(4)]);
1375        assert_eq!(sink.entered(), vec![2, 1, 3]);
1376    }
1377
1378    /// STATEMENT: A full in-flight limit above `Ordered` does not stall turns.
1379    ///
1380    /// HOW:
1381    /// - Limits 1 and 2, with and without a `B` readiness stall.
1382    #[ntex::test]
1383    async fn inflight_limit() {
1384        for limit in [1, 2] {
1385            for b_stall in [false, true] {
1386                let sink = Sink::default();
1387                let pl = with_inflight(&sink, limit);
1388
1389                if b_stall {
1390                    let sink = sink.clone();
1391                    spawn(async move {
1392                        sleep(Millis(5)).await;
1393                        sink.set_ready(false);
1394                        sleep(Millis(60)).await;
1395                        sink.set_ready(true);
1396                    });
1397                }
1398
1399                let msgs = [
1400                    Msg::new(1, 30),
1401                    Msg::new(2, 20),
1402                    Msg::new(3, 10),
1403                    Msg::new(4, 0),
1404                ];
1405                let handles = dispatch(&pl, msgs).await;
1406                assert_eq!(
1407                    results(handles).await,
1408                    vec![Ok(10), Ok(20), Ok(30), Ok(40)],
1409                    "limit {limit}, stall {b_stall}"
1410                );
1411                assert_eq!(
1412                    sink.entered(),
1413                    vec![1, 2, 3, 4],
1414                    "limit {limit}, stall {b_stall}"
1415                );
1416            }
1417        }
1418    }
1419
1420    /// STATEMENT: In-call readiness checks in `A` do not stall turns.
1421    ///
1422    /// HOW:
1423    /// - `A` is an `and_then` chain under an in-flight limit of 2.
1424    #[ntex::test]
1425    async fn chained_a_with_inflight_limit() {
1426        let sink = Sink::default();
1427        let a = service(fn_service(first)).and_then(fn_service(async |id: u32| Ok::<_, u32>(id)));
1428        let pl = Pipeline::new((), InFlightService::new(2, Ordered::new(a, sink.clone())));
1429
1430        let msgs = [
1431            Msg::new(1, 30),
1432            Msg::new(2, 10),
1433            Msg::new(3, 0),
1434            Msg::new(4, 0),
1435        ];
1436        let handles = dispatch(&pl, msgs).await;
1437        assert_eq!(results(handles).await, vec![Ok(10), Ok(20), Ok(30), Ok(40)]);
1438        assert_eq!(sink.entered(), vec![1, 2, 3, 4]);
1439    }
1440
1441    /// STATEMENT: External tickets define the order, not the call order.
1442    ///
1443    /// HOW:
1444    /// - Call in reverse ticket order with a ticket dropped before its call.
1445    #[ntex::test]
1446    async fn external_tickets() {
1447        let sink = Sink::default();
1448        let svc = Ordered::new(fn_service(first), sink.clone())
1449            .sequencer(tickets(|m: &mut Msg| m.ticket.take()));
1450        let pl = Pipeline::new((), svc);
1451
1452        let tickets = Tickets::new();
1453        let mut t = issue(&tickets, 4);
1454        let t3 = t.pop().unwrap();
1455        let t2 = t.pop().unwrap();
1456        drop(t.pop());
1457        let t0 = t.pop().unwrap();
1458
1459        let msgs = [
1460            Msg::new(4, 0).ticket(t3),
1461            Msg::new(5, 0).unordered(),
1462            Msg::new(3, 10).ticket(t2),
1463            Msg::new(1, 20).ticket(t0),
1464        ];
1465        let handles = dispatch(&pl, msgs).await;
1466        assert_eq!(results(handles).await, vec![Ok(40), Ok(50), Ok(30), Ok(10)]);
1467        assert_eq!(sink.entered(), vec![5, 1, 3, 4]);
1468    }
1469
1470    /// STATEMENT: Requests with canceled tickets return `Canceled` without entering `B`, later
1471    /// tickets are not affected.
1472    ///
1473    /// HOW:
1474    /// - Cancel external tickets while one request is in `A` and others wait for the turn, then
1475    ///   call with a ticket issued after the cancel.
1476    #[ntex::test]
1477    async fn canceled_tickets() {
1478        let sink = Sink::default();
1479        let svc = Ordered::new(fn_service(first), sink.clone())
1480            .sequencer(tickets(|m: &mut Msg| m.ticket.take()));
1481        let pl = Pipeline::new((), svc);
1482
1483        let tickets = Tickets::new();
1484        let msgs = [
1485            Msg::new(1, 30).ticket(tickets.issue()),
1486            Msg::new(2, 0).ticket(tickets.issue()),
1487            Msg::new(3, 0).ticket(tickets.issue()),
1488        ];
1489        let handles = dispatch(&pl, msgs).await;
1490        sleep(Millis(10)).await;
1491        tickets.cancel();
1492        assert_eq!(results(handles).await, vec![Err(CANCELED); 3]);
1493        assert_eq!(sink.entered(), Vec::<u32>::new());
1494
1495        let handles = dispatch(&pl, [Msg::new(4, 0).ticket(tickets.issue())]).await;
1496        assert_eq!(results(handles).await, vec![Ok(40)]);
1497        assert_eq!(sink.entered(), vec![4]);
1498    }
1499
1500    /// STATEMENT: The factory creates services with independent arrival sequences.
1501    ///
1502    /// HOW:
1503    /// - A slow request in one service does not block a request in another.
1504    #[ntex::test]
1505    async fn factory() {
1506        let sink = Sink::default();
1507        let s = sink.clone();
1508        let factory = OrderedFactory::new(
1509            fn_factory(async |(): &()| Ok::<_, Infallible>(fn_service(first))),
1510            fn_factory(async move |(): &()| Ok::<_, Infallible>(s.clone())),
1511        )
1512        .filter(|m: &Msg| m.ordered);
1513        let pl1 = factory.pipeline(()).await.unwrap();
1514        let pl2 = factory.clone().pipeline(()).await.unwrap();
1515
1516        let h1 = dispatch(&pl1, [Msg::new(1, 30), Msg::new(2, 0)]).await;
1517        let h2 = dispatch(&pl2, [Msg::new(3, 0)]).await;
1518        assert_eq!(results(h2).await, vec![Ok(30)]);
1519        assert_eq!(results(h1).await, vec![Ok(10), Ok(20)]);
1520        assert_eq!(sink.entered(), vec![3, 1, 2]);
1521    }
1522
1523    /// STATEMENT: The factory returns the init error of `A` or `B`.
1524    ///
1525    /// HOW:
1526    /// - Create with a failing `A` factory and with a failing `B` factory, check each init
1527    ///   error.
1528    #[ntex::test]
1529    async fn factory_init_error() {
1530        let factory = OrderedFactory::new(
1531            fn_factory(async |(): &()| Err::<Probe, u32>(1)),
1532            fn_factory(async |(): &()| Ok::<_, u32>(Sink::default())),
1533        );
1534        assert_eq!(factory.pipeline(()).await.err(), Some(1));
1535
1536        let factory = OrderedFactory::new(
1537            fn_factory(async |(): &()| Ok::<_, u32>(Probe::default())),
1538            fn_factory(async |(): &()| Err::<Sink, u32>(2)),
1539        );
1540        assert_eq!(factory.pipeline(()).await.err(), Some(2));
1541    }
1542}