Skip to main content

ntex_util/services/
reconnect.rs

1//! Lazy service creation and policy-controlled reconnection.
2//!
3//! [`Reconnect`] creates independent [`ReconnectService`] instances. Each instance
4//! owns one pipeline-local readiness scope and creates its child on demand.
5//! Failed requests are returned to the caller, never replayed automatically.
6
7use std::{
8    cell::Cell, cell::RefCell, error::Error, fmt, marker::PhantomData, rc::Rc, time::Instant,
9};
10
11use backoff::{Clock, ExponentialBackoff, backoff::Backoff};
12use ntex_error::fmt_err_string;
13use ntex_service::{BindCtx, Ctx, ReadyBinding, ReadyNotifier, Service, ServiceFactory};
14
15use crate::time;
16
17/// Factory for independent, lazily connected [`ReconnectService`] instances.
18///
19/// Each [`ServiceFactory::create`] call returns a disconnected wrapper without
20/// invoking the wrapped factory. The child is created when readiness is first
21/// needed, using the state supplied by that operation's context.
22///
23/// The wrapped factory is shared through [`Rc`]; policy and retry settings are
24/// copied into each service. The default policy permits reconnection after any
25/// error, with a budget of three retries.
26#[derive(Debug)]
27pub struct Reconnect<P, Sf, St> {
28    name: &'static str,
29    policy: P,
30    factory: Rc<Sf>,
31    retry: usize,
32    max_retry: usize,
33    ph: PhantomData<St>,
34}
35
36/// Decides whether a service error permits retrying or replacing a connection.
37///
38/// Cloneable `Fn(&E) -> bool` closures implement this trait. Factory initialization
39/// errors are converted to the service error type before the policy is consulted.
40pub trait ReconnectPolicy<E>: Clone + Sized + 'static {
41    /// Returns whether `err` permits reconnection.
42    ///
43    /// For creation or readiness errors, `true` permits another attempt if retry
44    /// budget and backoff remain; `false` returns the error without retrying.
45    /// A readiness-failed child is removed regardless of this decision.
46    ///
47    /// For a call error from the current child, `true` invalidates readiness and
48    /// schedules replacement on the next readiness check; `false` keeps the
49    /// child. The failed request is never replayed. Errors from retired children
50    /// do not consult the policy or invalidate a replacement.
51    fn reconnect(&self, err: &E) -> bool;
52}
53
54/// Policy that permits reconnection after every error.
55///
56/// Retry budgets and backoff still limit creation and readiness retries.
57#[derive(Copy, Clone, Debug)]
58pub struct DefaultPolicy;
59
60impl<E> ReconnectPolicy<E> for DefaultPolicy {
61    /// Permits reconnection without inspecting the error.
62    fn reconnect(&self, _: &E) -> bool {
63        true
64    }
65}
66
67impl<T, E> ReconnectPolicy<E> for T
68where
69    T: Fn(&E) -> bool + Clone + 'static,
70{
71    /// Delegates the reconnection decision to this closure.
72    fn reconnect(&self, err: &E) -> bool {
73        (*self)(err)
74    }
75}
76
77impl<Sf, St> Reconnect<DefaultPolicy, Sf, St>
78where
79    St: 'static,
80    Sf: 'static,
81{
82    /// Wraps `factory` with [`DefaultPolicy`] and a budget of three retries.
83    ///
84    /// `name` identifies the service in diagnostic messages. Construction does
85    /// not invoke the factory or establish a connection.
86    pub fn new<Req>(name: &'static str, factory: Sf) -> Self
87    where
88        Sf: ServiceFactory<St, Req> + 'static,
89        Sf::InitError: Into<Sf::Error>,
90    {
91        Self {
92            name,
93            factory: Rc::new(factory),
94            policy: DefaultPolicy,
95            retry: 3,
96            max_retry: 3,
97            ph: PhantomData,
98        }
99    }
100}
101
102impl<P, Sf, St> Reconnect<P, Sf, St> {
103    /// Sets the number of additional attempts after creation or readiness errors.
104    ///
105    /// Zero permits the initial attempt but no retries. Each created service
106    /// restores this budget after successful child readiness. A rejecting policy
107    /// or exhausted backoff can stop retries before the budget is consumed.
108    #[must_use]
109    pub fn retry(mut self, retry: usize) -> Self {
110        self.retry = retry;
111        self.max_retry = retry;
112        self
113    }
114
115    /// Replaces the error policy while preserving the factory and retry settings.
116    ///
117    /// The new policy is cloned into services created by this factory.
118    pub fn policy<T, Req>(self, policy: T) -> Reconnect<T, Sf, St>
119    where
120        T: ReconnectPolicy<Sf::Error>,
121        Sf: ServiceFactory<St, Req>,
122    {
123        Reconnect {
124            policy,
125            name: self.name,
126            factory: self.factory,
127            retry: self.retry,
128            max_retry: self.max_retry,
129            ph: PhantomData,
130        }
131    }
132}
133
134impl<P, Sf, St> Clone for Reconnect<P, Sf, St>
135where
136    P: Clone,
137{
138    /// Shares the wrapped factory and copies configuration without creating a child.
139    fn clone(&self) -> Self {
140        Self {
141            name: self.name,
142            policy: self.policy.clone(),
143            factory: self.factory.clone(),
144            retry: self.retry,
145            max_retry: self.max_retry,
146            ph: PhantomData,
147        }
148    }
149}
150
151impl<P, Sf, St, Req> ServiceFactory<St, Req> for Reconnect<P, Sf, St>
152where
153    P: ReconnectPolicy<Sf::Error>,
154    Sf: ServiceFactory<St, Req>,
155    Sf::Error: Error,
156    Sf::InitError: Into<Sf::Error> + Error,
157    St: 'static,
158{
159    type Res = Sf::Res;
160    type Error = Sf::Error;
161
162    type Service = ReconnectService<P, Sf, Sf::Service, St>;
163    type InitError = Sf::Error;
164
165    /// Creates a disconnected service with independent readiness and retry state.
166    ///
167    /// The supplied state is not retained and the wrapped factory is not called.
168    /// Child creation, including initialization errors, is deferred until readiness
169    /// is needed and uses that operation's [`Ctx::st`].
170    async fn create(&self, _: &St) -> Result<Self::Service, Self::InitError> {
171        Ok(ReconnectService {
172            inner: ReadyBinding::new(ReconnectServiceInner {
173                name: self.name,
174                policy: self.policy.clone(),
175                factory: self.factory.clone(),
176                service: Cell::new(None),
177                err: Cell::new(false),
178                changed: ReadyNotifier::new(),
179                retry: Cell::new(self.retry),
180                max_retry: self.max_retry,
181                backoff: RefCell::new(ExponentialBackoff::default()),
182                backoff_active: Cell::new(false),
183                retry_at: Cell::new(None),
184                ph: PhantomData,
185            }),
186        })
187    }
188}
189
190/// Lazily creates a child service and replaces it after policy-approved errors.
191///
192/// Creation and readiness failures can retry within the configured budget using
193/// exponential backoff. Successful creation resets backoff, even if the new
194/// child's readiness later fails; successful readiness restores the retry budget.
195/// Unused and healthy time do not count toward the backoff time limit. Once
196/// recovery starts, its elapsed-time window and retry deadlines survive cancellation.
197///
198/// Call errors are returned without replaying the request. If the policy permits
199/// reconnection, an error from the current child invalidates readiness so a later
200/// operation can replace it. Shutdown awaits the stored child without reconnecting.
201///
202/// Each child has its own readiness scope. Retired children's callbacks are
203/// released and their notifier subscriptions become inert when the last child
204/// handle is dropped, including handles held by outstanding calls.
205///
206/// Clones start disconnected and create their own inner service on the next
207/// readiness check. They copy the policy, remaining and configured retry budgets,
208/// and backoff settings and interval, but not the connection, elapsed-time window,
209/// or a pending retry deadline.
210///
211/// Each instance belongs to the first pipeline that binds it. Sharing an
212/// `Rc<ReconnectService>` within that pipeline shares its connection and readiness;
213/// binding the same instance to another pipeline panics, even after the owner
214/// is dropped. Clone the service itself for independent connections, or share
215/// bindings to one [`ntex_service::Pipeline`] for a shared connection.
216///
217/// # Examples
218///
219/// ```
220/// use std::io;
221/// use ntex_service::{Pipeline, fn_factory, fn_service};
222/// use ntex_util::services::reconnect::ReconnectService;
223///
224/// # async fn example() -> Result<(), io::Error> {
225/// let factory = fn_factory(|_: &()| async {
226///     Ok::<_, io::Error>(fn_service(|req: u32| async move {
227///         Ok::<_, io::Error>(req)
228///     }))
229/// });
230/// let service = ReconnectService::new("upstream", factory).retry(2);
231/// let first = Pipeline::new((), service.clone());
232/// let second = Pipeline::new((), service);
233///
234/// assert_eq!(first.call(1).await?, 1);
235/// assert_eq!(second.call(2).await?, 2);
236/// # Ok(())
237/// # }
238/// ```
239pub struct ReconnectService<P, Sf, S, St> {
240    inner: ReadyBinding<ReconnectServiceInner<P, Sf, S, St>>,
241}
242
243/// Connection and retry state driven inside the wrapper's owned readiness scope.
244///
245/// The enclosing [`ReadyBinding`] serializes readiness checks and propagates child
246/// invalidations to every parent within the owning pipeline. Each child binding
247/// keeps its readiness registrations separate from this long-lived scope.
248struct ReconnectServiceInner<P, Sf, S, St> {
249    name: &'static str,
250    policy: P,
251    factory: Rc<Sf>,
252    service: Cell<Option<Rc<ReadyBinding<S>>>>,
253    err: Cell<bool>,
254    changed: ReadyNotifier,
255    retry: Cell<usize>,
256    max_retry: usize,
257    backoff: RefCell<ExponentialBackoff>,
258    backoff_active: Cell<bool>,
259    // Keep the retry deadline when a readiness check is cancelled.
260    retry_at: Cell<Option<Instant>>,
261    ph: PhantomData<St>,
262}
263
264impl<P, Sf, S, St> fmt::Debug for ReconnectService<P, Sf, S, St> {
265    /// Formats connection metadata without requiring the factory or policy to implement `Debug`.
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        self.inner.get_ref().fmt(f)
268    }
269}
270
271impl<P: Clone, Sf, S, St> Clone for ReconnectService<P, Sf, S, St> {
272    /// Creates a disconnected clone with a fresh, unbound readiness scope.
273    ///
274    /// The factory is shared, but the original connection and pipeline ownership
275    /// are not. No child is created until the clone needs readiness.
276    fn clone(&self) -> Self {
277        Self {
278            inner: self.inner.clone(),
279        }
280    }
281}
282
283impl<P, Sf, S, St> fmt::Debug for ReconnectServiceInner<P, Sf, S, St> {
284    /// Formats type names, error state, retry counters, backoff activity, and the pending deadline.
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        f.debug_struct("ReconnectService")
287            .field("name", &self.name)
288            .field("policy", &std::any::type_name::<P>())
289            .field("factory", &std::any::type_name::<Sf>())
290            .field("service", &std::any::type_name::<S>())
291            .field("err", &self.err)
292            .field("retry", &self.retry)
293            .field("max_retry", &self.max_retry)
294            .field("backoff_active", &self.backoff_active)
295            .field("retry_at", &self.retry_at)
296            .finish()
297    }
298}
299
300impl<P: Clone, Sf, S, St> Clone for ReconnectServiceInner<P, Sf, S, St> {
301    /// Copies policy, retry counters, and backoff without sharing a child or notifier.
302    ///
303    /// The clone starts without an error flag, active backoff window, or pending retry deadline.
304    fn clone(&self) -> Self {
305        Self {
306            name: self.name,
307            policy: self.policy.clone(),
308            factory: self.factory.clone(),
309            service: Cell::new(None),
310            err: Cell::new(false),
311            changed: ReadyNotifier::new(),
312            retry: Cell::new(self.retry.get()),
313            max_retry: self.max_retry,
314            backoff: RefCell::new(self.backoff.borrow().clone()),
315            backoff_active: Cell::new(false),
316            retry_at: Cell::new(None),
317            ph: PhantomData,
318        }
319    }
320}
321
322impl<Sf, S, St> ReconnectService<DefaultPolicy, Sf, S, St>
323where
324    St: 'static,
325    Sf: 'static,
326{
327    /// Creates a disconnected service with [`DefaultPolicy`] and three retries.
328    ///
329    /// `name` is used in diagnostics. The factory is retained without being called;
330    /// binding to a pipeline is also lazy with respect to child creation.
331    pub fn new<Req>(name: &'static str, factory: Sf) -> Self
332    where
333        Sf: ServiceFactory<St, Req, Service = S, Error = S::Error> + 'static,
334        Sf::Error: Error,
335        Sf::InitError: Into<Sf::Error> + Error,
336        S: Service<St, Req>,
337    {
338        Self {
339            inner: ReadyBinding::new(ReconnectServiceInner {
340                name,
341                policy: DefaultPolicy,
342                factory: Rc::new(factory),
343                service: Cell::new(None),
344                err: Cell::new(false),
345                changed: ReadyNotifier::new(),
346                retry: Cell::new(3),
347                max_retry: 3,
348                backoff: RefCell::new(ExponentialBackoff::default()),
349                backoff_active: Cell::new(false),
350                retry_at: Cell::new(None),
351                ph: PhantomData,
352            }),
353        }
354    }
355}
356
357impl<P, Sf, S, St> ReconnectService<P, Sf, S, St> {
358    /// Sets both the remaining and configured budget for additional attempts.
359    ///
360    /// Zero permits the initial attempt but no retries after creation or readiness
361    /// errors. Successful child readiness restores this budget; policy rejection
362    /// or backoff exhaustion can stop retries earlier.
363    ///
364    /// Preserves the current child, pending deadline, backoff, and pipeline owner.
365    #[must_use]
366    pub fn retry(self, retry: usize) -> Self {
367        Self {
368            inner: self.inner.map(|mut inner| {
369                inner.retry.set(retry);
370                inner.max_retry = retry;
371                inner
372            }),
373        }
374    }
375
376    /// Replaces the error policy without reconnecting or resetting readiness.
377    ///
378    /// The connection, retry state, backoff, pending deadline, and pipeline owner
379    /// are preserved. Changing policy does not undo an already scheduled retry.
380    pub fn policy<T, Req>(self, policy: T) -> ReconnectService<T, Sf, S, St>
381    where
382        T: ReconnectPolicy<Sf::Error>,
383        Sf: ServiceFactory<St, Req>,
384    {
385        ReconnectService {
386            inner: self.inner.map(|inner| ReconnectServiceInner {
387                policy,
388                name: inner.name,
389                factory: inner.factory,
390                service: inner.service,
391                err: inner.err,
392                changed: inner.changed,
393                retry: inner.retry,
394                max_retry: inner.max_retry,
395                backoff: inner.backoff,
396                backoff_active: inner.backoff_active,
397                retry_at: inner.retry_at,
398                ph: PhantomData,
399            }),
400        }
401    }
402}
403
404impl<P, Sf, S, St> ReconnectServiceInner<P, Sf, S, St> {
405    /// Clones the stored child handle without removing it or checking readiness.
406    ///
407    /// Includes a child marked errored so shutdown can still reach it.
408    fn current(&self) -> Option<Rc<ReadyBinding<S>>> {
409        let svc = self.service.take();
410        self.service.set(svc.clone());
411        svc
412    }
413
414    /// Removes `svc` only if it is still the current child, preserving any replacement.
415    ///
416    /// Other handles keep a retired child and its readiness scope alive until they
417    /// are dropped. This does not invoke the child's shutdown.
418    fn remove(&self, svc: &Rc<ReadyBinding<S>>) {
419        if let Some(current) = self.service.take()
420            && !Rc::ptr_eq(&current, svc)
421        {
422            self.service.set(Some(current));
423        }
424    }
425
426    /// Starts elapsed-time accounting once per recovery, preserving the retry interval.
427    ///
428    /// Pending and failed attempts retain this window until child readiness succeeds.
429    fn start_backoff(&self) {
430        if !self.backoff_active.replace(true) {
431            let mut backoff = self.backoff.borrow_mut();
432            backoff.start_time = backoff.clock.now();
433        }
434    }
435
436    /// Returns a ready child, replacing an errored or missing connection as needed.
437    ///
438    /// Waits for any retained retry deadline before creating a child wrapped in
439    /// [`ReadyBinding`] through [`Ctx::create`], so binding uses the child's own
440    /// scope. The child stays stored while readiness is checked.
441    /// Creation success resets backoff and clears the deadline; readiness success
442    /// restores the configured retry budget and ends the recovery window.
443    ///
444    /// # Errors
445    ///
446    /// Returns the current creation or readiness error when the policy rejects a
447    /// retry, the retry budget is exhausted, or backoff produces no further delay.
448    /// Creation errors are converted to the service error type.
449    ///
450    /// # Cancellation
451    ///
452    /// The remaining retry budget, recovery window, and absolute deadline are stored
453    /// on the service, so restarting a cancelled check does not renew the time limit
454    /// or skip an outstanding delay.
455    async fn ensure<Req>(&self, ctx: Ctx<'_, Self, St>) -> Result<Rc<ReadyBinding<S>>, S::Error>
456    where
457        P: ReconnectPolicy<Sf::Error>,
458        Sf: ServiceFactory<St, Req, Service = S, Error = S::Error>,
459        Sf::Error: Error,
460        Sf::InitError: Into<Sf::Error> + Error,
461        S: Service<St, Req>,
462        St: 'static,
463    {
464        if self.err.get() {
465            log::trace!("State marked as errored, reconnecting: {:?}", self.name);
466            self.err.set(false);
467            let _ = self.service.take();
468        }
469
470        loop {
471            let svc = if let Some(svc) = self.current() {
472                svc
473            } else {
474                if let Some(retry_at) = self.retry_at.get() {
475                    let now = time::now();
476                    if now < retry_at {
477                        time::sleep(retry_at - now).await;
478                        continue;
479                    }
480                    self.retry_at.set(None);
481                }
482
483                // construct new service
484                self.start_backoff();
485                let factory = ntex_service::fn_factory(async |st: &St| {
486                    self.factory.create(st).await.map(ReadyBinding::new)
487                });
488                match ctx.create(&factory).await {
489                    Ok(service) => {
490                        // reset backoff and retry
491                        log::trace!("Re-connect is done, service '{}' is creates", self.name);
492                        self.backoff.borrow_mut().reset();
493                        self.retry_at.set(None);
494                        let svc = Rc::new(service);
495                        self.service.set(Some(svc.clone()));
496                        svc
497                    }
498                    Err(err) => {
499                        let s = fmt_err_string(&err);
500                        log::trace!("Failed to create service: {s}");
501
502                        // check policy
503                        let err = err.into();
504                        if self.policy.reconnect(&err) {
505                            // start backoff sleep
506                            let retry = self.retry.get();
507                            if retry > 0 {
508                                let timeout = self.backoff.borrow_mut().next_backoff();
509                                if let Some(timeout) = timeout {
510                                    self.retry.set(retry - 1);
511                                    log::trace!(
512                                        "Error during re-connecting '{}': {s}, sleep: {timeout:?}",
513                                        self.name
514                                    );
515                                    self.retry_at.set(Some(Instant::now() + timeout));
516                                    log::trace!(
517                                        "Re-connecting, checking service '{}' readiness",
518                                        self.name
519                                    );
520                                    continue;
521                                }
522                            }
523                        }
524                        self.err.set(true);
525                        return Err(err);
526                    }
527                }
528            };
529
530            // connected
531            break if let Err(err) = ctx.ready(svc.as_ref()).await {
532                log::trace!(
533                    "Error during service '{}' readiness check: {}",
534                    self.name,
535                    fmt_err_string(&err)
536                );
537                self.remove(&svc);
538                self.start_backoff();
539
540                // check policy
541                if self.policy.reconnect(&err) {
542                    // start backoff sleep
543                    let retry = self.retry.get();
544                    if retry > 0 {
545                        let timeout = self.backoff.borrow_mut().next_backoff();
546                        if let Some(timeout) = timeout {
547                            self.retry.set(retry - 1);
548                            log::trace!(
549                                "Error during checking '{}' readiness: {}, sleep: {timeout:?}",
550                                self.name,
551                                fmt_err_string(&err)
552                            );
553                            self.retry_at.set(Some(Instant::now() + timeout));
554                            continue;
555                        }
556                    }
557                }
558
559                self.err.set(true);
560                Err(err)
561            } else {
562                self.retry.set(self.max_retry);
563                self.backoff_active.set(false);
564                Ok(svc)
565            };
566        }
567    }
568}
569
570impl<P, Sf, S, St, Req> Service<St, Req> for ReconnectService<P, Sf, S, St>
571where
572    P: ReconnectPolicy<Sf::Error>,
573    Sf: ServiceFactory<St, Req, Service = S, Error = S::Error>,
574    Sf::Error: Error,
575    Sf::InitError: Into<Sf::Error> + Error,
576    S: Service<St, Req>,
577    St: 'static,
578{
579    type Res = S::Res;
580    type Error = S::Error;
581
582    /// Registers the owned readiness scope without creating a child.
583    ///
584    /// Repeated binding within the same pipeline shares this scope.
585    ///
586    /// # Panics
587    ///
588    /// Panics if this instance was already bound to another pipeline, even if
589    /// that pipeline has been dropped.
590    fn bind(&self, ctx: BindCtx<'_>) {
591        ctx.bind(&self.inner);
592    }
593
594    /// Waits for the owned readiness gate, lazily connecting or recovering as needed.
595    ///
596    /// Successful readiness is cached until a subscribed notification invalidates
597    /// it. Returns creation or readiness errors that cannot be retried.
598    ///
599    /// # Panics
600    ///
601    /// Panics if the caller's scope has not bound this instance.
602    async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
603        ctx.ready(&self.inner).await
604    }
605
606    /// Dispatches through the owned readiness gate without replaying failed requests.
607    ///
608    /// Returns readiness or child call errors. A policy-approved call error marks
609    /// the current connection for replacement by a later operation.
610    ///
611    /// # Panics
612    ///
613    /// Panics if the caller's scope has not bound this instance.
614    async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error> {
615        ctx.call(&self.inner, req).await
616    }
617
618    /// Awaits shutdown of the stored child, or completes immediately if disconnected.
619    ///
620    /// Does not check readiness, create a child, or reconnect an errored child.
621    ///
622    /// # Panics
623    ///
624    /// Panics if the caller's scope has not bound this instance.
625    async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
626        ctx.shutdown(&self.inner).await;
627    }
628}
629
630impl<P, Sf, S, St, Req> Service<St, Req> for ReconnectServiceInner<P, Sf, S, St>
631where
632    P: ReconnectPolicy<Sf::Error>,
633    Sf: ServiceFactory<St, Req, Service = S, Error = S::Error>,
634    Sf::Error: Error,
635    Sf::InitError: Into<Sf::Error> + Error,
636    S: Service<St, Req>,
637    St: 'static,
638{
639    type Res = S::Res;
640    type Error = S::Error;
641
642    /// Subscribes the owned scope to reconnect changes and binds any existing child.
643    ///
644    /// Missing children are bound later by [`Ctx::create`], not created here.
645    fn bind(&self, ctx: BindCtx<'_>) {
646        ctx.subscribe(&self.changed);
647        if let Some(svc) = self.current() {
648            ctx.bind(svc.as_ref());
649        }
650    }
651
652    /// Ensures a ready child, returning any terminal error from the current attempt.
653    async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
654        self.ensure(ctx).await.map(|_| ())
655    }
656
657    /// Shuts down the stored child, including one marked errored, without replacement.
658    async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
659        if let Some(svc) = self.current() {
660            ctx.shutdown(svc.as_ref()).await;
661        }
662    }
663
664    /// Uses the current child or restores one, then dispatches the request once.
665    ///
666    /// Only a policy-approved error from the still-current child invalidates
667    /// readiness. Late errors from retired children are returned unchanged.
668    async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error> {
669        // pipeline readiness is cached, the service could fail after the last readiness check
670        let svc = match self.current() {
671            Some(svc) if !self.err.get() => svc,
672            _ => self.ensure(ctx).await?,
673        };
674        let result = ctx.call(svc.as_ref(), req).await;
675
676        if let Err(ref err) = result {
677            log::trace!("Service failed: {}", fmt_err_string(err));
678            // make sure current service is the same
679            if self
680                .current()
681                .is_some_and(|current| Rc::ptr_eq(&current, &svc))
682                && self.policy.reconnect(err)
683            {
684                self.err.set(true);
685                self.changed.notify();
686            }
687        }
688        result
689    }
690}
691
692#[cfg(test)]
693mod tests {
694    use std::time::Duration;
695    use std::{future::Future, future::poll_fn, io, pin::pin, task::Context, task::Poll};
696
697    use ntex_service::{Pipeline, ReadyBinding, ReadyCallback, fn_factory, fn_service};
698
699    use super::*;
700    use crate::channel::oneshot;
701
702    struct Probe {
703        id: usize,
704        ready: Cell<bool>,
705        fail: Cell<bool>,
706        changed: ReadyNotifier,
707    }
708
709    impl Service<(), ()> for Probe {
710        type Res = usize;
711        type Error = io::Error;
712
713        /// Subscribes the caller to this probe's availability changes.
714        fn bind(&self, ctx: BindCtx<'_>) {
715            ctx.subscribe(&self.changed);
716        }
717
718        /// Waits until the test marks the probe ready.
719        async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), io::Error> {
720            poll_fn(|_| {
721                if self.ready.get() {
722                    Poll::Ready(Ok(()))
723                } else {
724                    Poll::Pending
725                }
726            })
727            .await
728        }
729
730        /// Returns the child identity or the call failure configured by the test.
731        async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<usize, io::Error> {
732            if self.fail.get() {
733                Err(io::Error::other("call failed"))
734            } else {
735                Ok(self.id)
736            }
737        }
738    }
739
740    struct Branches<S> {
741        first: ReadyBinding<S>,
742        second: ReadyBinding<S>,
743    }
744
745    impl<S> Service<(), bool> for Branches<S>
746    where
747        S: Service<(), (), Res = usize, Error = io::Error>,
748    {
749        type Res = usize;
750        type Error = io::Error;
751
752        /// Registers both branch caches as dependencies of the enclosing scope.
753        fn bind(&self, ctx: BindCtx<'_>) {
754            ctx.bind(&self.first);
755            ctx.bind(&self.second);
756        }
757
758        /// Selects a branch and dispatches through its independent readiness cache.
759        async fn call(&self, second: bool, ctx: Ctx<'_, Self>) -> Result<usize, io::Error> {
760            if second {
761                ctx.call(&self.second, ()).await
762            } else {
763                ctx.call(&self.first, ()).await
764            }
765        }
766    }
767
768    /// STATEMENT: Reconnect diagnostics delegate to the inner state without requiring child or policy `Debug`.
769    ///
770    /// HOW:
771    /// - Create a lazy wrapper with a closure policy and a non-`Debug` child.
772    /// - Compare wrapper and inner formatting, then change retry state and check the reported fields.
773    /// - Verify formatting never initializes the child.
774    #[ntex::test]
775    async fn debug_reconnect_state() {
776        let service = Reconnect::new(
777            "debug-reconnect",
778            fn_factory(async |(): &()| {
779                Ok::<_, io::Error>(Probe {
780                    id: 1,
781                    ready: Cell::new(true),
782                    fail: Cell::new(false),
783                    changed: ReadyNotifier::new(),
784                })
785            }),
786        )
787        .retry(7)
788        .policy(|_: &io::Error| true)
789        .create(&())
790        .await
791        .unwrap();
792        let inner = service.inner.get_ref();
793        let initial = format!("{service:?}");
794        assert_eq!(initial, format!("{inner:?}"));
795        assert!(initial.starts_with("ReconnectService { name: \"debug-reconnect\","));
796        assert!(initial.contains(std::any::type_name::<Probe>()));
797        assert!(initial.contains(std::any::type_name_of_val(&inner.policy)));
798        assert!(initial.contains(std::any::type_name_of_val(inner.factory.as_ref())));
799        assert!(initial.contains("err: Cell { value: false }"));
800        assert!(initial.contains("retry: Cell { value: 7 }, max_retry: 7"));
801        assert!(initial.contains("backoff_active: Cell { value: false }"));
802        assert!(initial.contains("retry_at: Cell { value: None }"));
803
804        inner.err.set(true);
805        inner.retry.set(6);
806        inner.backoff_active.set(true);
807        inner.retry_at.set(Some(Instant::now()));
808        let retrying = format!("{service:?}");
809        assert_eq!(retrying, format!("{inner:?}"));
810        assert!(retrying.contains("err: Cell { value: true }"));
811        assert!(retrying.contains("retry: Cell { value: 6 }, max_retry: 7"));
812        assert!(retrying.contains("backoff_active: Cell { value: true }"));
813        assert!(retrying.contains("retry_at: Cell { value: Some("));
814        assert!(inner.service.take().is_none());
815    }
816
817    /// STATEMENT: Cloned reconnect factories preserve policy and retries while deferring child state.
818    ///
819    /// HOW:
820    /// - Clone a factory with one retry and a policy inspecting converted initialization errors.
821    /// - Create disconnected wrappers with different state from their eventual pipelines.
822    /// - Verify retryable errors get two attempts and rejected errors get only one.
823    /// - Recover both pipelines and verify their independent children use the pipeline state.
824    #[ntex::test]
825    async fn factory_clones_preserve_configuration_and_defer_state() {
826        #[derive(Debug)]
827        struct InitError(io::ErrorKind);
828
829        impl fmt::Display for InitError {
830            /// Formats the factory-specific initialization error.
831            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
832                write!(f, "initialization failed: {:?}", self.0)
833            }
834        }
835
836        impl Error for InitError {}
837
838        impl From<InitError> for io::Error {
839            /// Preserves the error kind when converting to the child's error type.
840            fn from(err: InitError) -> Self {
841                err.0.into()
842            }
843        }
844
845        let attempts = Rc::new(RefCell::new(Vec::new()));
846        let failure = Rc::new(Cell::new(Some(io::ErrorKind::Interrupted)));
847        let decisions = Rc::new(RefCell::new(Vec::new()));
848        let factory = fn_factory({
849            let attempts = attempts.clone();
850            let failure = failure.clone();
851            move |state: &usize| {
852                let state = *state;
853                attempts.borrow_mut().push(state);
854                let failure = failure.get();
855                async move {
856                    if let Some(kind) = failure {
857                        Err(InitError(kind))
858                    } else {
859                        Ok(fn_service(move |(): ()| async move {
860                            Ok::<_, io::Error>(state)
861                        }))
862                    }
863                }
864            }
865        });
866        let factory = Reconnect::new("factory-clone", factory).retry(1).policy({
867            let decisions = decisions.clone();
868            move |err: &io::Error| {
869                decisions.borrow_mut().push(err.kind());
870                err.kind() == io::ErrorKind::Interrupted
871            }
872        });
873        let cloned = factory.clone();
874        let first = factory.create(&100).await.unwrap();
875        let second = cloned.create(&200).await.unwrap();
876        for service in [&first, &second] {
877            let mut backoff = service.inner.get_ref().backoff.borrow_mut();
878            backoff.initial_interval = Duration::ZERO;
879            backoff.reset();
880        }
881        let first = Pipeline::new(1, first);
882        let second = Pipeline::new(2, second);
883        assert!(attempts.borrow().is_empty());
884
885        assert_eq!(
886            first.ready().await.unwrap_err().kind(),
887            io::ErrorKind::Interrupted
888        );
889        assert_eq!(*attempts.borrow(), [1, 1]);
890        failure.set(Some(io::ErrorKind::PermissionDenied));
891        assert_eq!(
892            second.ready().await.unwrap_err().kind(),
893            io::ErrorKind::PermissionDenied
894        );
895        assert_eq!(*attempts.borrow(), [1, 1, 2]);
896        failure.set(Some(io::ErrorKind::Interrupted));
897        assert_eq!(
898            second.ready().await.unwrap_err().kind(),
899            io::ErrorKind::Interrupted
900        );
901        assert_eq!(*attempts.borrow(), [1, 1, 2, 2, 2]);
902        assert_eq!(
903            *decisions.borrow(),
904            [
905                io::ErrorKind::Interrupted,
906                io::ErrorKind::Interrupted,
907                io::ErrorKind::PermissionDenied,
908                io::ErrorKind::Interrupted,
909                io::ErrorKind::Interrupted,
910            ]
911        );
912
913        failure.set(None);
914        assert_eq!(first.call(()).await.unwrap(), 1);
915        assert_eq!(second.call(()).await.unwrap(), 2);
916        assert_eq!(first.call(()).await.unwrap(), 1);
917        assert_eq!(*attempts.borrow(), [1, 1, 2, 2, 2, 1, 2]);
918    }
919
920    /// STATEMENT: Rejecting a readiness retry still removes the failed child.
921    ///
922    /// HOW:
923    /// - Fail the first child's readiness with retries available and a rejecting policy.
924    /// - Verify the error reaches the caller without another attempt and the child is dropped.
925    /// - Call again and verify a fresh, healthy child serves the request.
926    #[ntex::test]
927    async fn rejected_readiness_retry_discards_child() {
928        struct RejectReady(usize);
929
930        impl Service<(), ()> for RejectReady {
931            type Res = usize;
932            type Error = io::Error;
933
934            /// Rejects readiness only for the first child.
935            async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), io::Error> {
936                if self.0 == 0 {
937                    Err(io::ErrorKind::PermissionDenied.into())
938                } else {
939                    Ok(())
940                }
941            }
942
943            /// Returns the identity of the child that received the request.
944            async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<usize, io::Error> {
945                Ok(self.0)
946            }
947        }
948
949        let children = Rc::new(RefCell::new(Vec::new()));
950        let decisions = Rc::new(Cell::new(0));
951        let factory = fn_factory({
952            let children = children.clone();
953            move |(): &()| {
954                let id = children.borrow().len();
955                let child = Rc::new(RejectReady(id));
956                children.borrow_mut().push(Rc::downgrade(&child));
957                async move { Ok::<_, io::Error>(child) }
958            }
959        });
960        let service = ReconnectService::new("reject-readiness", factory).policy({
961            let decisions = decisions.clone();
962            move |err: &io::Error| {
963                assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
964                decisions.set(decisions.get() + 1);
965                false
966            }
967        });
968        let pipeline = Pipeline::new((), service);
969        assert_eq!(
970            pipeline.call(()).await.unwrap_err().kind(),
971            io::ErrorKind::PermissionDenied
972        );
973        assert_eq!(children.borrow().len(), 1);
974        assert!(children.borrow()[0].upgrade().is_none());
975        assert_eq!(decisions.get(), 1);
976        assert_eq!(pipeline.call(()).await.unwrap(), 1);
977        assert_eq!(children.borrow().len(), 2);
978        assert!(children.borrow()[1].upgrade().is_some());
979        assert_eq!(decisions.get(), 1);
980    }
981
982    /// STATEMENT: Call policy rejection retains the child, and approved failures are never replayed.
983    ///
984    /// HOW:
985    /// - Reject reconnection after a call error and verify readiness and child identity are retained.
986    /// - Allow reconnection after another error and verify readiness is invalidated.
987    /// - Record every child call to verify failures are not replayed, then call the replacement.
988    #[ntex::test]
989    async fn call_policy_controls_replacement_without_replaying() {
990        let created = Rc::new(Cell::new(0));
991        let calls = Rc::new(RefCell::new(Vec::new()));
992        let allow = Rc::new(Cell::new(false));
993        let decisions = Rc::new(Cell::new(0));
994        let factory = fn_factory({
995            let created = created.clone();
996            let calls = calls.clone();
997            move |(): &()| {
998                let id = created.get();
999                created.set(id + 1);
1000                let calls = calls.clone();
1001                async move {
1002                    Ok::<_, io::Error>(fn_service(move |fail: bool| {
1003                        calls.borrow_mut().push((id, fail));
1004                        async move {
1005                            if fail {
1006                                Err(io::ErrorKind::BrokenPipe.into())
1007                            } else {
1008                                Ok(id)
1009                            }
1010                        }
1011                    }))
1012                }
1013            }
1014        });
1015        let service = ReconnectService::new("call-policy", factory).policy({
1016            let allow = allow.clone();
1017            let decisions = decisions.clone();
1018            move |err: &io::Error| {
1019                assert_eq!(err.kind(), io::ErrorKind::BrokenPipe);
1020                decisions.set(decisions.get() + 1);
1021                allow.get()
1022            }
1023        });
1024        let pipeline = Pipeline::new((), service);
1025        assert_eq!(pipeline.call(false).await.unwrap(), 0);
1026        assert_eq!(
1027            pipeline.call(true).await.unwrap_err().kind(),
1028            io::ErrorKind::BrokenPipe
1029        );
1030        assert!(pipeline.is_ready());
1031        assert_eq!(pipeline.call(false).await.unwrap(), 0);
1032        assert_eq!(created.get(), 1);
1033        assert_eq!(decisions.get(), 1);
1034
1035        allow.set(true);
1036        assert!(pipeline.call(true).await.is_err());
1037        assert!(!pipeline.is_ready());
1038        assert_eq!(created.get(), 1);
1039        assert_eq!(
1040            *calls.borrow(),
1041            [(0, false), (0, true), (0, false), (0, true)]
1042        );
1043        assert_eq!(pipeline.call(false).await.unwrap(), 1);
1044        assert_eq!(
1045            *calls.borrow(),
1046            [(0, false), (0, true), (0, false), (0, true), (1, false)]
1047        );
1048        assert_eq!(created.get(), 2);
1049        assert_eq!(decisions.get(), 2);
1050    }
1051
1052    /// STATEMENT: A reconnect instance rejects other pipelines without losing its original owner.
1053    ///
1054    /// HOW:
1055    /// - Bind an `Rc<ReconnectService>` before or after connecting and reject a second pipeline.
1056    /// - Verify the original pipeline still works and rejection does not invoke the factory.
1057    /// - Drop the owner, change retry and policy settings, and verify ownership is not transferred.
1058    #[ntex::test]
1059    async fn shared_service_rejects_another_pipeline() {
1060        use std::panic::{AssertUnwindSafe, catch_unwind};
1061
1062        for connected in [false, true] {
1063            let created = Rc::new(Cell::new(0));
1064            let factory = fn_factory({
1065                let created = created.clone();
1066                move |(): &()| {
1067                    created.set(created.get() + 1);
1068                    async {
1069                        Ok::<_, io::Error>(fn_service(|(): ()| async { Ok::<_, io::Error>(()) }))
1070                    }
1071                }
1072            });
1073            let service = Rc::new(ReconnectService::new("single-owner", factory));
1074            let original = Pipeline::new((), service.clone());
1075            if connected {
1076                original.ready().await.unwrap();
1077            }
1078            assert!(catch_unwind(AssertUnwindSafe(|| Pipeline::new((), service.clone()))).is_err());
1079            assert_eq!(created.get(), usize::from(connected));
1080            original.call(()).await.unwrap();
1081            assert_eq!(created.get(), 1);
1082
1083            drop(original);
1084            let service = Rc::try_unwrap(service)
1085                .unwrap()
1086                .retry(5)
1087                .policy(|_: &io::Error| true);
1088            assert!(catch_unwind(AssertUnwindSafe(|| Pipeline::new((), service))).is_err());
1089            assert_eq!(created.get(), 1);
1090        }
1091    }
1092
1093    /// STATEMENT: Parents within one pipeline share reconnect creation and child invalidations.
1094    ///
1095    /// HOW:
1096    /// - Share a reconnect instance between two call-only branches with separate readiness caches.
1097    /// - Gate initial creation and verify concurrent branch calls create only one child.
1098    /// - Exercise raw and `ReadyBinding` children, blocking readiness after both branches are cached.
1099    /// - Verify the second branch waits, then repeat after a call error replaces the child.
1100    #[ntex::test]
1101    async fn same_pipeline_parents_share_reconnect_scope() {
1102        for bound_child in [false, true] {
1103            let created = Rc::new(Cell::new(0));
1104            let children = Rc::new(RefCell::new(Vec::new()));
1105            let (release, gate) = oneshot::channel();
1106            let gate = Rc::new(gate);
1107            let factory = fn_factory({
1108                let created = created.clone();
1109                let children = children.clone();
1110                move |(): &()| {
1111                    let id = created.get();
1112                    created.set(id + 1);
1113                    let children = children.clone();
1114                    let gate = gate.clone();
1115                    async move {
1116                        if id == 0 {
1117                            gate.recv().await.unwrap();
1118                        }
1119                        let child = Rc::new(Probe {
1120                            id,
1121                            ready: Cell::new(true),
1122                            fail: Cell::new(false),
1123                            changed: ReadyNotifier::new(),
1124                        });
1125                        children.borrow_mut().push(child.clone());
1126                        Ok::<_, io::Error>(if bound_child {
1127                            ntex_service::boxed::service(ReadyBinding::new(child))
1128                        } else {
1129                            ntex_service::boxed::service(child)
1130                        })
1131                    }
1132                }
1133            });
1134            let service = Rc::new(ReconnectService::new("shared-scope", factory));
1135            let pipeline = Pipeline::new(
1136                (),
1137                Branches {
1138                    first: ReadyBinding::new(service.clone()),
1139                    second: ReadyBinding::new(service),
1140                },
1141            );
1142            assert_eq!(created.get(), 0);
1143            let mut cx = Context::from_waker(std::task::Waker::noop());
1144            {
1145                let mut first = pin!(pipeline.call(false));
1146                let mut second = pin!(pipeline.call(true));
1147                assert!(first.as_mut().poll(&mut cx).is_pending());
1148                assert!(second.as_mut().poll(&mut cx).is_pending());
1149                assert_eq!(created.get(), 1);
1150                release.send(()).unwrap();
1151                assert_eq!(first.await.unwrap(), 0);
1152                assert_eq!(second.await.unwrap(), 0);
1153            }
1154
1155            for id in 0..2 {
1156                assert_eq!(pipeline.call(false).await.unwrap(), id);
1157                assert_eq!(pipeline.call(true).await.unwrap(), id);
1158                let child = children.borrow()[id].clone();
1159                child.ready.set(false);
1160                child.changed.notify();
1161                assert!(!pipeline.is_ready());
1162                let mut call = pin!(pipeline.call(true));
1163                assert!(call.as_mut().poll(&mut cx).is_pending());
1164                child.ready.set(true);
1165                child.changed.notify();
1166                assert_eq!(call.await.unwrap(), id);
1167
1168                if id == 0 {
1169                    child.fail.set(true);
1170                    assert!(pipeline.call(false).await.is_err());
1171                }
1172            }
1173            assert_eq!(created.get(), 2);
1174        }
1175    }
1176
1177    /// STATEMENT: Binding a connected reconnect service to a new parent reuses its live child.
1178    ///
1179    /// HOW:
1180    /// - Connect through one parent, then create another bound parent in the same pipeline.
1181    /// - Make the existing child unavailable and verify a newly bound parent's call waits.
1182    /// - Restore readiness and verify both paths still use the original child without recreation.
1183    #[ntex::test]
1184    async fn late_parent_binding_reuses_connected_child() {
1185        struct Rebind<S>(Rc<S>);
1186
1187        impl<S> Service<(), bool> for Rebind<S>
1188        where
1189            S: Service<(), (), Res = usize, Error = io::Error>,
1190        {
1191            type Res = usize;
1192            type Error = io::Error;
1193
1194            /// Registers the original parent before the reconnect service has a child.
1195            fn bind(&self, ctx: BindCtx<'_>) {
1196                ctx.bind(self.0.as_ref());
1197            }
1198
1199            /// Optionally creates a new parent binding before forwarding the call.
1200            async fn call(&self, rebind: bool, ctx: Ctx<'_, Self>) -> Result<usize, io::Error> {
1201                if rebind {
1202                    let factory = fn_factory(async |(): &()| {
1203                        Ok::<_, io::Error>(ReadyBinding::new(self.0.clone()))
1204                    });
1205                    let parent = ctx.create(&factory).await?;
1206                    ctx.call(&parent, ()).await
1207                } else {
1208                    ctx.call(self.0.as_ref(), ()).await
1209                }
1210            }
1211        }
1212
1213        let created = Rc::new(Cell::new(0));
1214        let child = Rc::new(Probe {
1215            id: 0,
1216            ready: Cell::new(true),
1217            fail: Cell::new(false),
1218            changed: ReadyNotifier::new(),
1219        });
1220        let factory = fn_factory({
1221            let created = created.clone();
1222            let child = child.clone();
1223            move |(): &()| {
1224                created.set(created.get() + 1);
1225                let child = child.clone();
1226                async move { Ok::<_, io::Error>(child) }
1227            }
1228        });
1229        let service = Rc::new(ReconnectService::new("late-parent", factory));
1230        let pipeline = Pipeline::new((), Rebind(service));
1231        assert_eq!(pipeline.call(false).await.unwrap(), 0);
1232        assert_eq!(pipeline.call(true).await.unwrap(), 0);
1233
1234        child.ready.set(false);
1235        child.changed.notify();
1236        let mut call = pin!(pipeline.call(true));
1237        let mut cx = Context::from_waker(std::task::Waker::noop());
1238        assert!(call.as_mut().poll(&mut cx).is_pending());
1239        assert_eq!(created.get(), 1);
1240        child.ready.set(true);
1241        child.changed.notify();
1242        assert_eq!(call.await.unwrap(), 0);
1243        assert_eq!(pipeline.call(false).await.unwrap(), 0);
1244        assert_eq!(created.get(), 1);
1245    }
1246
1247    /// STATEMENT: Retired children release readiness registrations after their last call completes.
1248    ///
1249    /// HOW:
1250    /// - Register a raw child's callback with a weakly observed resource and retain its notifier.
1251    /// - Replace the child while holding a call, then verify the resource outlives that call only.
1252    /// - Repeat replacement and verify retired notifiers do not invalidate the current child.
1253    /// - Fail the current child's readiness and verify its callback resource is also released.
1254    #[ntex::test]
1255    async fn retired_children_release_registrations() {
1256        struct ScopedProbe {
1257            id: usize,
1258            fail_ready: Rc<Cell<bool>>,
1259            changed: ReadyNotifier,
1260            callback: ReadyCallback,
1261        }
1262
1263        impl Service<(), (bool, Option<oneshot::Receiver<()>>)> for ScopedProbe {
1264            type Res = usize;
1265            type Error = io::Error;
1266
1267            /// Registers this child's notification source and resource-owning callback.
1268            fn bind(&self, ctx: BindCtx<'_>) {
1269                ctx.subscribe(&self.changed);
1270                ctx.on_notify(&self.callback);
1271            }
1272
1273            /// Fails readiness when the test retires the final child.
1274            async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), io::Error> {
1275                if self.fail_ready.get() {
1276                    Err(io::Error::other("readiness failed"))
1277                } else {
1278                    Ok(())
1279                }
1280            }
1281
1282            /// Holds an optional in-flight call, then returns its identity or a replacement trigger.
1283            async fn call(
1284                &self,
1285                (fail, gate): (bool, Option<oneshot::Receiver<()>>),
1286                _: Ctx<'_, Self>,
1287            ) -> Result<usize, io::Error> {
1288                if let Some(gate) = gate {
1289                    gate.await.unwrap();
1290                }
1291                if fail {
1292                    Err(io::Error::other("call failed"))
1293                } else {
1294                    Ok(self.id)
1295                }
1296            }
1297        }
1298
1299        let registrations = Rc::new(RefCell::new(Vec::new()));
1300        let fail_ready = Rc::new(Cell::new(false));
1301        let factory = fn_factory({
1302            let registrations = registrations.clone();
1303            let fail_ready = fail_ready.clone();
1304            move |(): &()| {
1305                let id = registrations.borrow().len();
1306                let changed = ReadyNotifier::new();
1307                let notifications = Rc::new(Cell::new(0));
1308                registrations
1309                    .borrow_mut()
1310                    .push((changed.clone(), Rc::downgrade(&notifications)));
1311                let fail_ready = fail_ready.clone();
1312                async move {
1313                    Ok::<_, io::Error>(ScopedProbe {
1314                        id,
1315                        fail_ready,
1316                        changed,
1317                        callback: ReadyCallback::new(move |_| {
1318                            notifications.set(notifications.get() + 1);
1319                        }),
1320                    })
1321                }
1322            }
1323        });
1324        let pipeline = Pipeline::new(
1325            (),
1326            ReconnectService::new("child-registrations", factory).retry(0),
1327        );
1328        let (release, gate) = oneshot::channel();
1329        let mut held = pin!(pipeline.call((false, Some(gate))));
1330        let mut cx = Context::from_waker(std::task::Waker::noop());
1331        assert!(held.as_mut().poll(&mut cx).is_pending());
1332        assert!(pipeline.call((true, None)).await.is_err());
1333        assert_eq!(pipeline.call((false, None)).await.unwrap(), 1);
1334        assert!(registrations.borrow()[0].1.upgrade().is_some());
1335
1336        release.send(()).unwrap();
1337        assert_eq!(held.await.unwrap(), 0);
1338        assert!(registrations.borrow()[0].1.upgrade().is_none());
1339        registrations.borrow()[0].0.notify();
1340        assert!(pipeline.is_ready());
1341
1342        for id in 1..4 {
1343            assert!(pipeline.call((true, None)).await.is_err());
1344            assert_eq!(pipeline.call((false, None)).await.unwrap(), id + 1);
1345            assert!(registrations.borrow()[id].1.upgrade().is_none());
1346            registrations.borrow()[id].0.notify();
1347            assert!(pipeline.is_ready());
1348        }
1349        fail_ready.set(true);
1350        registrations.borrow()[4].0.notify();
1351        assert_eq!(registrations.borrow()[4].1.upgrade().unwrap().get(), 1);
1352        assert!(!pipeline.is_ready());
1353        assert_eq!(
1354            pipeline.ready().await.unwrap_err().to_string(),
1355            "readiness failed"
1356        );
1357        assert!(registrations.borrow()[4].1.upgrade().is_none());
1358    }
1359
1360    /// STATEMENT: Retired child notifications cannot cancel replacement creation.
1361    ///
1362    /// HOW:
1363    /// - Fail a raw child and suspend creation of its replacement behind a channel.
1364    /// - Notify the retired source and verify the factory is not restarted.
1365    /// - Complete creation and verify the retired source no longer invalidates readiness.
1366    #[ntex::test]
1367    async fn retired_notifications_preserve_replacement_creation() {
1368        let attempts = Rc::new(Cell::new(0));
1369        let retired_source = ReadyNotifier::new();
1370        let (release, gate) = oneshot::channel();
1371        let gate = Rc::new(gate);
1372        let factory = fn_factory({
1373            let attempts = attempts.clone();
1374            let retired_source = retired_source.clone();
1375            move |(): &()| {
1376                let id = attempts.get();
1377                attempts.set(id + 1);
1378                let gate = gate.clone();
1379                let changed = if id == 0 {
1380                    retired_source.clone()
1381                } else {
1382                    ReadyNotifier::new()
1383                };
1384                async move {
1385                    if id > 0 {
1386                        gate.recv().await.unwrap();
1387                    }
1388                    Ok::<_, io::Error>(Probe {
1389                        id,
1390                        ready: Cell::new(true),
1391                        fail: Cell::new(id == 0),
1392                        changed,
1393                    })
1394                }
1395            }
1396        });
1397        let pipeline = Pipeline::new((), ReconnectService::new("retired-source", factory));
1398        assert!(pipeline.call(()).await.is_err());
1399        assert_eq!(attempts.get(), 1);
1400        let mut ready = pin!(pipeline.ready());
1401        let mut cx = Context::from_waker(std::task::Waker::noop());
1402        assert!(ready.as_mut().poll(&mut cx).is_pending());
1403        assert_eq!(attempts.get(), 2);
1404        retired_source.notify();
1405        assert!(ready.as_mut().poll(&mut cx).is_pending());
1406        assert_eq!(attempts.get(), 2);
1407
1408        release.send(()).unwrap();
1409        ready.await.unwrap();
1410        assert_eq!(pipeline.call(()).await.unwrap(), 1);
1411        retired_source.notify();
1412        assert!(pipeline.is_ready());
1413        assert_eq!(attempts.get(), 2);
1414    }
1415
1416    /// STATEMENT: Cloned reconnect services lazily create independent children and readiness gates.
1417    ///
1418    /// HOW:
1419    /// - Clone before and after the original connects, counting factory calls and child identities.
1420    /// - Wrap each child in `ReadyBinding` and place the reconnect services in separate pipelines.
1421    /// - Verify cloning is lazy and both pipelines retain their own child across calls.
1422    /// - Make each child unavailable and verify only its pipeline waits until readiness is restored.
1423    #[ntex::test]
1424    async fn clones_create_independent_children() {
1425        for connected in [false, true] {
1426            let children = Rc::new(RefCell::new(Vec::new()));
1427            let factory = fn_factory({
1428                let children = children.clone();
1429                move |(): &()| {
1430                    let mut children = children.borrow_mut();
1431                    let child = Rc::new(Probe {
1432                        id: children.len(),
1433                        ready: Cell::new(true),
1434                        fail: Cell::new(false),
1435                        changed: ReadyNotifier::new(),
1436                    });
1437                    children.push(child.clone());
1438                    async move { Ok::<_, io::Error>(ReadyBinding::new(child)) }
1439                }
1440            });
1441            let service = Rc::new(ReconnectService::new("clone", factory));
1442            let original = Pipeline::new((), service.clone());
1443            if connected {
1444                original.ready().await.unwrap();
1445            }
1446
1447            let cloned = Pipeline::new((), service.as_ref().clone());
1448            assert_eq!(children.borrow().len(), usize::from(connected));
1449            original.ready().await.unwrap();
1450            cloned.ready().await.unwrap();
1451            assert_eq!(children.borrow().len(), 2);
1452            assert_eq!(original.call(()).await.unwrap(), 0);
1453            assert_eq!(cloned.call(()).await.unwrap(), 1);
1454
1455            let mut cx = Context::from_waker(std::task::Waker::noop());
1456            for (id, pipeline, other) in [(0, &original, &cloned), (1, &cloned, &original)] {
1457                let child = children.borrow()[id].clone();
1458                child.ready.set(false);
1459                child.changed.notify();
1460                assert!(!pipeline.is_ready());
1461                assert!(other.is_ready());
1462
1463                let mut call = pin!(pipeline.call(()));
1464                assert!(call.as_mut().poll(&mut cx).is_pending());
1465                assert_eq!(other.call(()).await.unwrap(), 1 - id);
1466
1467                child.ready.set(true);
1468                child.changed.notify();
1469                assert_eq!(call.await.unwrap(), id);
1470            }
1471            assert_eq!(children.borrow().len(), 2);
1472        }
1473    }
1474
1475    /// STATEMENT: A late error from a retired child does not invalidate its healthy replacement.
1476    ///
1477    /// HOW:
1478    /// - Hold a call on the first child, then fail another call to trigger reconnection.
1479    /// - Establish the replacement and release the held call with an error.
1480    /// - Verify the error is returned without consulting the policy again, invalidating readiness,
1481    ///   or creating another child.
1482    #[ntex::test]
1483    async fn late_call_error_preserves_replacement() {
1484        let created = Rc::new(Cell::new(0));
1485        let decisions = Rc::new(Cell::new(0));
1486        let factory = fn_factory({
1487            let created = created.clone();
1488            move |(): &()| {
1489                let id = created.get();
1490                created.set(id + 1);
1491                async move {
1492                    Ok::<_, io::Error>(fn_service(
1493                        move |fail: Option<oneshot::Receiver<()>>| async move {
1494                            if let Some(fail) = fail {
1495                                fail.await.unwrap();
1496                                Err(io::Error::other("call failed"))
1497                            } else {
1498                                Ok(id)
1499                            }
1500                        },
1501                    ))
1502                }
1503            }
1504        });
1505        let service = ReconnectService::new("late-error", factory).policy({
1506            let decisions = decisions.clone();
1507            move |_: &io::Error| {
1508                decisions.set(decisions.get() + 1);
1509                true
1510            }
1511        });
1512        let pipeline = Pipeline::new((), service);
1513        let (late_tx, late_rx) = oneshot::channel();
1514        let mut late_call = pin!(pipeline.call(Some(late_rx)));
1515        let mut cx = Context::from_waker(std::task::Waker::noop());
1516        assert!(late_call.as_mut().poll(&mut cx).is_pending());
1517        assert_eq!(created.get(), 1);
1518
1519        let (fail_tx, fail_rx) = oneshot::channel();
1520        fail_tx.send(()).unwrap();
1521        assert!(pipeline.call(Some(fail_rx)).await.is_err());
1522        assert!(!pipeline.is_ready());
1523        assert_eq!(pipeline.call(None).await.unwrap(), 1);
1524        assert!(pipeline.is_ready());
1525        assert_eq!(decisions.get(), 1);
1526
1527        late_tx.send(()).unwrap();
1528        assert!(late_call.await.is_err());
1529        assert_eq!(decisions.get(), 1);
1530        assert!(pipeline.is_ready());
1531        assert_eq!(pipeline.call(None).await.unwrap(), 1);
1532        assert_eq!(created.get(), 2);
1533    }
1534
1535    /// STATEMENT: Retry delays survive readiness invalidation and cancellation.
1536    ///
1537    /// HOW:
1538    /// - Fail creation or initial child readiness with a deterministic thirty-second backoff.
1539    /// - Repeatedly poll, invalidate readiness, and replace the pending readiness future.
1540    /// - Make the factory healthy and verify no new creation occurs before the retry delay expires.
1541    /// - Confirm a clone connects independently without inheriting the pending delay.
1542    /// - Shorten the original deadline and verify it reconnects and resets backoff after expiry.
1543    #[ntex::test]
1544    async fn retry_delay_survives_readiness_restarts() {
1545        struct FailReady(Rc<Cell<bool>>);
1546
1547        impl Service<(), ()> for FailReady {
1548            type Res = ();
1549            type Error = io::Error;
1550
1551            /// Fails readiness until the test clears the shared failure flag.
1552            async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), io::Error> {
1553                if self.0.get() {
1554                    Err(io::Error::other("readiness failed"))
1555                } else {
1556                    Ok(())
1557                }
1558            }
1559
1560            /// Completes a request after readiness recovery.
1561            async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<(), io::Error> {
1562                Ok(())
1563            }
1564        }
1565
1566        for fail_creation in [false, true] {
1567            let created = Rc::new(Cell::new(0));
1568            let failing = Rc::new(Cell::new(true));
1569            let factory = fn_factory({
1570                let created = created.clone();
1571                let failing = failing.clone();
1572                move |(): &()| {
1573                    created.set(created.get() + 1);
1574                    let failing = failing.clone();
1575                    async move {
1576                        if fail_creation && failing.get() {
1577                            Err(io::Error::other("creation failed"))
1578                        } else {
1579                            Ok(FailReady(failing))
1580                        }
1581                    }
1582                }
1583            });
1584            let service = Rc::new(ReconnectService::new("retry-delay", factory));
1585            let inner = service.inner.get_ref();
1586            {
1587                let mut backoff = inner.backoff.borrow_mut();
1588                backoff.initial_interval = Duration::from_secs(30);
1589                backoff.randomization_factor = 0.0;
1590                backoff.reset();
1591            }
1592            let pipeline = Pipeline::new((), service.clone());
1593            let mut cx = Context::from_waker(std::task::Waker::noop());
1594            {
1595                let mut ready = pin!(pipeline.ready());
1596                for _ in 0..3 {
1597                    assert!(ready.as_mut().poll(&mut cx).is_pending());
1598                    assert_eq!(created.get(), 1);
1599                }
1600                inner.changed.notify();
1601                assert!(ready.as_mut().poll(&mut cx).is_pending());
1602                assert_eq!(created.get(), 1);
1603            }
1604            let retry_at = inner.retry_at.get();
1605            failing.set(false);
1606            {
1607                let mut ready = pin!(pipeline.ready());
1608                assert!(ready.as_mut().poll(&mut cx).is_pending());
1609                assert_eq!(created.get(), 1);
1610            }
1611            assert_eq!(inner.retry_at.get(), retry_at);
1612
1613            let cloned = Pipeline::new((), service.as_ref().clone());
1614            {
1615                let mut ready = pin!(cloned.ready());
1616                assert!(matches!(ready.as_mut().poll(&mut cx), Poll::Ready(Ok(()))));
1617            }
1618            assert_eq!(created.get(), 2);
1619
1620            inner
1621                .retry_at
1622                .set(Some(Instant::now() + Duration::from_millis(1)));
1623            pipeline.ready().await.unwrap();
1624            pipeline.call(()).await.unwrap();
1625            assert_eq!(created.get(), 3);
1626            assert_eq!(
1627                inner.backoff.borrow().current_interval,
1628                Duration::from_secs(30)
1629            );
1630        }
1631    }
1632
1633    /// STATEMENT: Creation resets backoff before readiness succeeds, but preserves the retry budget.
1634    ///
1635    /// HOW:
1636    /// - Fail initial creation to grow backoff and consume one of two retries.
1637    /// - Expire the elapsed-time window, then create a replacement whose readiness is gated.
1638    /// - Verify creation reset the interval and elapsed clock without restoring the retry budget.
1639    /// - Fail child readiness, consume the final retry, and recover with a third child.
1640    #[ntex::test]
1641    async fn creation_resets_backoff_before_readiness() {
1642        struct GatedReady {
1643            id: usize,
1644            gate: Rc<oneshot::Receiver<()>>,
1645        }
1646
1647        impl Service<(), ()> for GatedReady {
1648            type Res = usize;
1649            type Error = io::Error;
1650
1651            /// Suspends and fails the first created child's readiness.
1652            async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), io::Error> {
1653                if self.id == 1 {
1654                    self.gate.recv().await.unwrap();
1655                    Err(io::Error::other("readiness failed"))
1656                } else {
1657                    Ok(())
1658                }
1659            }
1660
1661            /// Identifies the child reached after successful recovery.
1662            async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<usize, io::Error> {
1663                Ok(self.id)
1664            }
1665        }
1666
1667        let attempts = Rc::new(Cell::new(0));
1668        let (release, gate) = oneshot::channel();
1669        let gate = Rc::new(gate);
1670        let factory = fn_factory({
1671            let attempts = attempts.clone();
1672            move |(): &()| {
1673                let id = attempts.get();
1674                attempts.set(id + 1);
1675                let gate = gate.clone();
1676                async move {
1677                    if id == 0 {
1678                        Err(io::Error::other("creation failed"))
1679                    } else {
1680                        Ok(GatedReady { id, gate })
1681                    }
1682                }
1683            }
1684        });
1685        let service = Rc::new(ReconnectService::new("creation-reset", factory).retry(2));
1686        let inner = service.inner.get_ref();
1687        {
1688            let mut backoff = inner.backoff.borrow_mut();
1689            backoff.initial_interval = Duration::from_secs(30);
1690            backoff.randomization_factor = 0.0;
1691            backoff.reset();
1692        }
1693        let pipeline = Pipeline::new((), service.clone());
1694        let mut cx = Context::from_waker(std::task::Waker::noop());
1695        {
1696            let mut ready = pin!(pipeline.ready());
1697            assert!(ready.as_mut().poll(&mut cx).is_pending());
1698        }
1699        assert_eq!(attempts.get(), 1);
1700        assert_eq!(inner.retry.get(), 1);
1701        assert!(inner.backoff.borrow().current_interval > Duration::from_secs(30));
1702        let expired_start = {
1703            let mut backoff = inner.backoff.borrow_mut();
1704            backoff.start_time -= Duration::from_mins(16);
1705            backoff.start_time
1706        };
1707        inner.retry_at.set(Some(time::now()));
1708        {
1709            let mut ready = pin!(pipeline.ready());
1710            assert!(ready.as_mut().poll(&mut cx).is_pending());
1711            assert_eq!(attempts.get(), 2);
1712            assert_eq!(
1713                inner.backoff.borrow().current_interval,
1714                Duration::from_secs(30)
1715            );
1716            assert!(inner.backoff.borrow().start_time > expired_start);
1717            assert_eq!(inner.retry.get(), 1);
1718
1719            release.send(()).unwrap();
1720            assert!(ready.as_mut().poll(&mut cx).is_pending());
1721            assert_eq!(attempts.get(), 2);
1722            assert_eq!(inner.retry.get(), 0);
1723        }
1724        inner.retry_at.set(Some(time::now()));
1725        assert_eq!(pipeline.call(()).await.unwrap(), 2);
1726        assert_eq!(attempts.get(), 3);
1727        assert_eq!(inner.retry.get(), 2);
1728    }
1729
1730    /// STATEMENT: Exhausted backoff stops retries and returns the current creation or readiness error.
1731    ///
1732    /// HOW:
1733    /// - Fail creation or child readiness with a zero elapsed-time limit and retries remaining.
1734    /// - Verify readiness returns the original error after exactly one factory attempt.
1735    #[ntex::test]
1736    async fn exhausted_backoff_stops_retries() {
1737        struct FailReady;
1738
1739        impl Service<(), ()> for FailReady {
1740            type Res = ();
1741            type Error = io::Error;
1742
1743            /// Always fails readiness to exercise the exhausted-backoff path.
1744            async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), io::Error> {
1745                Err(io::Error::other("readiness failed"))
1746            }
1747
1748            /// Completes a request without introducing another failure source.
1749            async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<(), io::Error> {
1750                Ok(())
1751            }
1752        }
1753
1754        for fail_creation in [true, false] {
1755            let attempts = Rc::new(Cell::new(0));
1756            let factory = fn_factory({
1757                let attempts = attempts.clone();
1758                move |(): &()| {
1759                    attempts.set(attempts.get() + 1);
1760                    async move {
1761                        if fail_creation {
1762                            Err(io::Error::other("creation failed"))
1763                        } else {
1764                            Ok(FailReady)
1765                        }
1766                    }
1767                }
1768            });
1769            let service = ReconnectService::new("exhausted-backoff", factory);
1770            service
1771                .inner
1772                .get_ref()
1773                .backoff
1774                .borrow_mut()
1775                .max_elapsed_time = Some(Duration::ZERO);
1776            let pipeline = Pipeline::new((), service);
1777            let err = pipeline.ready().await.unwrap_err();
1778            assert_eq!(
1779                err.to_string(),
1780                if fail_creation {
1781                    "creation failed"
1782                } else {
1783                    "readiness failed"
1784                }
1785            );
1786            assert_eq!(attempts.get(), 1, "creation error: {fail_creation}");
1787        }
1788    }
1789
1790    /// STATEMENT: Unused and healthy time do not exhaust the next recovery window.
1791    ///
1792    /// HOW:
1793    /// - Age the backoff clock by sixteen minutes before first use or after successful readiness.
1794    /// - Trigger initial creation, call-error recovery, or readiness-error recovery with one retry.
1795    /// - Fail creation and verify the configured retry is attempted in each case.
1796    #[ntex::test]
1797    async fn idle_time_preserves_retry_window() {
1798        struct RecoveryProbe {
1799            fail_ready: Rc<Cell<bool>>,
1800            changed: ReadyNotifier,
1801        }
1802
1803        impl Service<(), ()> for RecoveryProbe {
1804            type Res = ();
1805            type Error = io::Error;
1806
1807            /// Subscribes to the test's readiness failure notification.
1808            fn bind(&self, ctx: BindCtx<'_>) {
1809                ctx.subscribe(&self.changed);
1810            }
1811
1812            /// Fails readiness after the test invalidates a healthy connection.
1813            async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), io::Error> {
1814                if self.fail_ready.get() {
1815                    Err(io::Error::other("readiness failed"))
1816                } else {
1817                    Ok(())
1818                }
1819            }
1820
1821            /// Triggers replacement of a previously healthy connection.
1822            async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<(), io::Error> {
1823                Err(io::Error::other("call failed"))
1824            }
1825        }
1826
1827        for (connected, fail_readiness) in [(false, false), (true, false), (true, true)] {
1828            let attempts = Rc::new(Cell::new(0));
1829            let fail_creation = Rc::new(Cell::new(false));
1830            let fail_ready = Rc::new(Cell::new(false));
1831            let changed = ReadyNotifier::new();
1832            let factory = fn_factory({
1833                let attempts = attempts.clone();
1834                let fail_creation = fail_creation.clone();
1835                let fail_ready = fail_ready.clone();
1836                let changed = changed.clone();
1837                move |(): &()| {
1838                    attempts.set(attempts.get() + 1);
1839                    let fail = fail_creation.get();
1840                    let fail_ready = fail_ready.clone();
1841                    let changed = changed.clone();
1842                    async move {
1843                        if fail {
1844                            Err(io::Error::other("creation failed"))
1845                        } else {
1846                            Ok(RecoveryProbe {
1847                                fail_ready,
1848                                changed,
1849                            })
1850                        }
1851                    }
1852                }
1853            });
1854            let service = Rc::new(if connected {
1855                ReconnectService::new("idle-window", factory).retry(1)
1856            } else {
1857                Reconnect::new("idle-window", factory)
1858                    .retry(1)
1859                    .create(&())
1860                    .await
1861                    .unwrap()
1862            });
1863            let pipeline = Pipeline::new((), service.clone());
1864            if connected {
1865                pipeline.ready().await.unwrap();
1866            }
1867            {
1868                let mut backoff = service.inner.get_ref().backoff.borrow_mut();
1869                backoff.initial_interval = Duration::ZERO;
1870                backoff.current_interval = Duration::ZERO;
1871                backoff.start_time -= Duration::from_mins(16);
1872            }
1873            if fail_readiness {
1874                fail_ready.set(true);
1875                changed.notify();
1876            } else if connected {
1877                assert!(pipeline.call(()).await.is_err());
1878            }
1879            fail_creation.set(true);
1880            let before = attempts.get();
1881            assert_eq!(
1882                pipeline.ready().await.unwrap_err().to_string(),
1883                "creation failed"
1884            );
1885            assert_eq!(attempts.get() - before, if fail_readiness { 1 } else { 2 });
1886        }
1887    }
1888
1889    /// STATEMENT: Restarting recovery does not renew its elapsed-time window.
1890    ///
1891    /// HOW:
1892    /// - Suspend initial creation or its retry delay, then age the active window past its limit.
1893    /// - Invalidate and cancel readiness, preserving any outstanding retry deadline.
1894    /// - Fail the next attempt and a later check, verifying neither gets another retry.
1895    #[ntex::test]
1896    async fn retry_window_survives_readiness_restarts() {
1897        for pending_creation in [false, true] {
1898            let attempts = Rc::new(Cell::new(0));
1899            let factory = fn_factory({
1900                let attempts = attempts.clone();
1901                move |(): &()| {
1902                    let attempt = attempts.get();
1903                    attempts.set(attempt + 1);
1904                    async move {
1905                        if pending_creation && attempt == 0 {
1906                            std::future::pending::<()>().await;
1907                        }
1908                        Err::<ReadyBinding<Probe>, _>(io::Error::other("creation failed"))
1909                    }
1910                }
1911            });
1912            let service = Rc::new(ReconnectService::new("active-window", factory));
1913            let inner = service.inner.get_ref();
1914            {
1915                let mut backoff = inner.backoff.borrow_mut();
1916                backoff.initial_interval = Duration::from_secs(30);
1917                backoff.randomization_factor = 0.0;
1918                backoff.reset();
1919            }
1920            let pipeline = Pipeline::new((), service.clone());
1921            let mut cx = Context::from_waker(std::task::Waker::noop());
1922            {
1923                let mut ready = pin!(pipeline.ready());
1924                assert!(ready.as_mut().poll(&mut cx).is_pending());
1925                assert_eq!(attempts.get(), 1);
1926                inner.backoff.borrow_mut().start_time -= Duration::from_mins(16);
1927                inner.changed.notify();
1928            }
1929            if !pending_creation {
1930                let retry_at = inner.retry_at.get();
1931                {
1932                    let mut ready = pin!(pipeline.ready());
1933                    assert!(ready.as_mut().poll(&mut cx).is_pending());
1934                }
1935                assert_eq!(attempts.get(), 1);
1936                assert_eq!(inner.retry_at.get(), retry_at);
1937                inner.retry_at.set(Some(time::now()));
1938            }
1939            assert_eq!(
1940                pipeline.ready().await.unwrap_err().to_string(),
1941                "creation failed"
1942            );
1943            assert_eq!(attempts.get(), 2);
1944            assert!(pipeline.ready().await.is_err());
1945            assert_eq!(attempts.get(), 3);
1946        }
1947    }
1948
1949    /// STATEMENT: Configured retry budgets survive successful connection and recovery.
1950    ///
1951    /// HOW:
1952    /// - Set zero or five retries through `Reconnect` or `ReconnectService`.
1953    /// - Connect successfully, fail a call, and count replacement attempts while creation fails.
1954    /// - Recover and repeat, verifying each cycle permits exactly the configured extra attempts.
1955    #[ntex::test]
1956    async fn configured_retry_limit_survives_success() {
1957        for use_factory in [false, true] {
1958            for retry in [0, 5] {
1959                let attempts = Rc::new(Cell::new(0));
1960                let fail_creation = Rc::new(Cell::new(false));
1961                let factory = fn_factory({
1962                    let attempts = attempts.clone();
1963                    let fail_creation = fail_creation.clone();
1964                    move |(): &()| {
1965                        attempts.set(attempts.get() + 1);
1966                        let fail = fail_creation.get();
1967                        async move {
1968                            if fail {
1969                                Err(io::Error::other("creation failed"))
1970                            } else {
1971                                Ok(fn_service(|(): ()| async {
1972                                    Err::<(), _>(io::Error::other("call failed"))
1973                                }))
1974                            }
1975                        }
1976                    }
1977                });
1978                let service = if use_factory {
1979                    Reconnect::new("retry-limit", factory)
1980                        .retry(retry)
1981                        .create(&())
1982                        .await
1983                        .unwrap()
1984                } else {
1985                    ReconnectService::new("retry-limit", factory).retry(retry)
1986                };
1987                {
1988                    let mut backoff = service.inner.get_ref().backoff.borrow_mut();
1989                    backoff.initial_interval = Duration::ZERO;
1990                    backoff.max_elapsed_time = None;
1991                }
1992                let pipeline = Pipeline::new((), service);
1993                for _ in 0..2 {
1994                    fail_creation.set(false);
1995                    pipeline.ready().await.unwrap();
1996                    assert!(pipeline.call(()).await.is_err());
1997
1998                    fail_creation.set(true);
1999                    let before = attempts.get();
2000                    assert!(pipeline.ready().await.is_err());
2001                    assert_eq!(
2002                        attempts.get() - before,
2003                        retry + 1,
2004                        "factory setter: {use_factory}, retry limit: {retry}"
2005                    );
2006                }
2007            }
2008        }
2009    }
2010
2011    /// STATEMENT: Shutdown awaits the current child without creating or replacing a connection.
2012    ///
2013    /// HOW:
2014    /// - Exercise disconnected, connected, and call-failed reconnect services.
2015    /// - Wrap a child with a channel-gated shutdown in `ReadyBinding`.
2016    /// - Verify connected shutdown stays pending until the child finishes, even after a call error.
2017    /// - Verify disconnected shutdown skips the child and no shutdown path invokes the factory.
2018    #[ntex::test]
2019    async fn shutdown_awaits_current_child_without_reconnecting() {
2020        struct ShutdownProbe {
2021            started: Cell<usize>,
2022            finished: Cell<bool>,
2023            complete: oneshot::Receiver<()>,
2024        }
2025
2026        impl Service<(), ()> for ShutdownProbe {
2027            type Res = ();
2028            type Error = io::Error;
2029
2030            /// Marks the reconnect wrapper errored before shutdown is exercised.
2031            async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<(), io::Error> {
2032                Err(io::Error::other("call failed"))
2033            }
2034
2035            /// Records shutdown entry and waits for the test to permit completion.
2036            async fn shutdown(&self, _: Ctx<'_, Self>) {
2037                self.started.set(self.started.get() + 1);
2038                self.complete.recv().await.unwrap();
2039                self.finished.set(true);
2040            }
2041        }
2042
2043        for (connected, failed) in [(false, false), (true, false), (true, true)] {
2044            let created = Rc::new(Cell::new(0));
2045            let (complete, receiver) = oneshot::channel();
2046            let child = Rc::new(ShutdownProbe {
2047                started: Cell::new(0),
2048                finished: Cell::new(false),
2049                complete: receiver,
2050            });
2051            let factory = fn_factory({
2052                let created = created.clone();
2053                let child = child.clone();
2054                move |(): &()| {
2055                    created.set(created.get() + 1);
2056                    let child = child.clone();
2057                    async move { Ok::<_, io::Error>(ReadyBinding::new(child)) }
2058                }
2059            });
2060            let pipeline = Pipeline::new((), ReconnectService::new("shutdown", factory));
2061            if connected {
2062                pipeline.ready().await.unwrap();
2063            }
2064            if failed {
2065                assert!(pipeline.call(()).await.is_err());
2066            }
2067
2068            let mut shutdown = pin!(pipeline.shutdown());
2069            let mut cx = Context::from_waker(std::task::Waker::noop());
2070            if connected {
2071                assert!(shutdown.as_mut().poll(&mut cx).is_pending());
2072                assert_eq!(child.started.get(), 1);
2073                assert!(!child.finished.get());
2074                complete.send(()).unwrap();
2075                shutdown.await;
2076                assert!(child.finished.get());
2077            } else {
2078                assert!(shutdown.as_mut().poll(&mut cx).is_ready());
2079                assert_eq!(child.started.get(), 0);
2080                assert!(!child.finished.get());
2081            }
2082            assert_eq!(created.get(), usize::from(connected));
2083        }
2084    }
2085}