tower-resilience-fallback 0.9.1

Fallback middleware for Tower services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! Fallback middleware for Tower services.
//!
//! Provides alternative responses when the inner service fails, enabling
//! graceful degradation and backup service routing.
//!
//! # Overview
//!
//! The fallback pattern allows you to provide alternative responses when your
//! primary service fails. This is useful for:
//!
//! - Returning cached or stale data when the primary source is unavailable
//! - Providing degraded functionality instead of complete failure
//! - Routing to backup services
//! - Transforming errors into user-friendly responses
//!
//! # Fallback Strategies
//!
//! ## Static Value
//!
//! Return a fixed value when the service fails:
//!
//! ```rust
//! use tower_resilience_fallback::FallbackLayer;
//! use tower::ServiceBuilder;
//!
//! # #[derive(Debug, Clone)]
//! # struct MyError;
//! let layer = FallbackLayer::<String, String, MyError>::value("default response".to_string());
//! ```
//!
//! ## Fallback Function
//!
//! Compute a response based on the error:
//!
//! ```rust
//! use tower_resilience_fallback::FallbackLayer;
//!
//! # #[derive(Debug, Clone)]
//! # struct MyError { message: String }
//! let layer = FallbackLayer::<String, String, MyError>::from_error(|error: &MyError| {
//!     format!("Service unavailable: {}", error.message)
//! });
//! ```
//!
//! ## Fallback with Request Context
//!
//! Access both the original request and error:
//!
//! ```rust
//! use tower_resilience_fallback::FallbackLayer;
//! use std::sync::Arc;
//! use std::collections::HashMap;
//!
//! # #[derive(Debug, Clone)]
//! # struct MyError;
//! let cache: Arc<HashMap<String, String>> = Arc::new(HashMap::new());
//! let cache_clone = Arc::clone(&cache);
//!
//! let layer = FallbackLayer::<String, String, MyError>::from_request_error(move |req: &String, _err: &MyError| {
//!     cache_clone.get(req).cloned().unwrap_or_else(|| "not found".to_string())
//! });
//! ```
//!
//! ## Backup Service
//!
//! Route to an alternative service (async):
//!
//! ```rust
//! use tower_resilience_fallback::FallbackLayer;
//!
//! # #[derive(Debug, Clone)]
//! # struct MyError;
//! let layer = FallbackLayer::<String, String, MyError>::service(|req: String| async move {
//!     Ok::<_, MyError>(format!("backup: {}", req))
//! });
//! ```
//!
//! ## Error Transformation
//!
//! Convert errors to a different type (still returns error, not success):
//!
//! ```rust
//! use tower_resilience_fallback::FallbackLayer;
//!
//! # #[derive(Debug, Clone)]
//! # struct InternalError { code: u32 }
//! // Note: This changes the error type, so layer types must align
//! let layer = FallbackLayer::<String, String, InternalError>::exception(|err: InternalError| {
//!     InternalError { code: 500 } // Transform but still error
//! });
//! ```
//!
//! # Selective Error Handling
//!
//! Only trigger fallback for specific errors:
//!
//! ```rust
//! use tower_resilience_fallback::FallbackLayer;
//!
//! # #[derive(Debug, Clone)]
//! # struct MyError { retryable: bool }
//! let layer: FallbackLayer<String, String, MyError> = FallbackLayer::builder()
//!     .value("fallback".to_string())
//!     .handle(|e: &MyError| e.retryable) // Only fallback on retryable errors
//!     .build();
//! ```
//!
//! # Composition with Other Layers
//!
//! Fallback works well with other resilience patterns:
//!
//! ```rust
//! use tower_resilience_fallback::FallbackLayer;
//! use tower::ServiceBuilder;
//!
//! # #[derive(Debug, Clone)]
//! # struct MyError;
//! # async fn example() {
//! // Fallback catches anything that escapes retry + circuit breaker
//! let service = ServiceBuilder::new()
//!     .layer(FallbackLayer::<String, String, MyError>::value("unavailable".to_string()))
//!     // .layer(CircuitBreakerLayer::new(cb_config))
//!     // .layer(RetryLayer::new(retry_config))
//!     .service(tower::service_fn(|req: String| async move {
//!         Ok::<_, MyError>(req)
//!     }));
//! # }
//! ```
//!
//! # Events
//!
//! The fallback service emits events for observability:
//!
//! - `Success`: Inner service succeeded, no fallback needed
//! - `FailedAttempt`: Inner service failed, fallback will be attempted
//! - `Applied`: Fallback was successfully applied
//! - `Failed`: Fallback itself failed (service fallback only)
//! - `Skipped`: Error didn't match predicate, propagated as-is

mod config;
mod error;
mod events;
mod layer;

pub use config::{FallbackConfig, FallbackConfigBuilder};
pub use error::FallbackError;
pub use events::FallbackEvent;
pub use layer::FallbackLayer;

use futures::future::BoxFuture;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Instant;
use tower::Service;

#[cfg(feature = "metrics")]
use metrics::{counter, describe_counter};

#[cfg(feature = "metrics")]
use std::sync::Once;

#[cfg(feature = "metrics")]
static METRICS_INIT: Once = Once::new();

/// Function that produces a fallback value (no Clone required).
pub type ValueFn<Res> = Arc<dyn Fn() -> Res + Send + Sync>;

/// Function that computes a fallback response from an error.
pub type FromErrorFn<Res, E> = Arc<dyn Fn(&E) -> Res + Send + Sync>;

/// Function that computes a fallback response from request and error.
pub type FromRequestErrorFn<Req, Res, E> = Arc<dyn Fn(&Req, &E) -> Res + Send + Sync>;

/// Function that calls a backup service asynchronously.
pub type ServiceFn<Req, Res, E> =
    Arc<dyn Fn(Req) -> BoxFuture<'static, Result<Res, E>> + Send + Sync>;

/// Function that transforms an error into a different error.
pub type ExceptionFn<E> = Arc<dyn Fn(E) -> E + Send + Sync>;

/// The strategy used to produce a fallback response.
pub enum FallbackStrategy<Req, Res, E> {
    /// Return a static value (cloned for each fallback).
    Value(Res),

    /// Generate a value using a function (no Clone required).
    ValueFn(ValueFn<Res>),

    /// Compute a response from the error.
    FromError(FromErrorFn<Res, E>),

    /// Compute a response from both the request and error.
    FromRequestError(FromRequestErrorFn<Req, Res, E>),

    /// Call a backup service asynchronously.
    /// The function takes the request and returns a future.
    Service(ServiceFn<Req, Res, E>),

    /// Transform the error into a different error (still fails, but with transformed error).
    Exception(ExceptionFn<E>),
}

impl<Req, Res, E> Clone for FallbackStrategy<Req, Res, E>
where
    Res: Clone,
{
    fn clone(&self) -> Self {
        match self {
            Self::Value(v) => Self::Value(v.clone()),
            Self::ValueFn(f) => Self::ValueFn(Arc::clone(f)),
            Self::FromError(f) => Self::FromError(Arc::clone(f)),
            Self::FromRequestError(f) => Self::FromRequestError(Arc::clone(f)),
            Self::Service(s) => Self::Service(Arc::clone(s)),
            Self::Exception(f) => Self::Exception(Arc::clone(f)),
        }
    }
}

/// Predicate to determine if an error should trigger the fallback.
pub type HandlePredicate<E> = Arc<dyn Fn(&E) -> bool + Send + Sync>;

/// Predicate to determine if a successful response should trigger the fallback.
///
/// When this predicate returns `true`, the response is treated as if the service
/// had failed, and the fallback strategy is applied.
pub type HandleResponsePredicate<Res> = Arc<dyn Fn(&Res) -> bool + Send + Sync>;

/// A Tower service that provides fallback responses when the inner service fails.
///
/// See the [module-level documentation](crate) for usage examples.
pub struct Fallback<S, Req, Res, E> {
    inner: S,
    config: Arc<FallbackConfig<Req, Res, E>>,
}

impl<S, Req, Res, E> Fallback<S, Req, Res, E> {
    /// Creates a new `Fallback` service wrapping the given service.
    pub fn new(inner: S, config: Arc<FallbackConfig<Req, Res, E>>) -> Self {
        #[cfg(feature = "metrics")]
        METRICS_INIT.call_once(|| {
            describe_counter!(
                "fallback_calls_total",
                "Total number of fallback operations"
            );
        });

        Self { inner, config }
    }
}

impl<S, Req, Res, E> Clone for Fallback<S, Req, Res, E>
where
    S: Clone,
    Res: Clone,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            config: Arc::clone(&self.config),
        }
    }
}

impl<S, Req, Res, E> Service<Req> for Fallback<S, Req, Res, E>
where
    S: Service<Req, Response = Res, Error = E> + Clone + Send + 'static,
    S::Future: Send + 'static,
    Req: Clone + Send + Sync + 'static,
    Res: Clone + Send + Sync + 'static,
    E: Clone + Send + Sync + 'static,
{
    type Response = Res;
    type Error = FallbackError<E>;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx).map_err(FallbackError::Inner)
    }

    fn call(&mut self, req: Req) -> Self::Future {
        let mut service = self.inner.clone();
        let config = Arc::clone(&self.config);
        let req_clone = req.clone();

        Box::pin(async move {
            #[cfg(feature = "tracing")]
            tracing::debug!(fallback = %config.name, "Calling inner service");

            let result = service.call(req).await;

            match result {
                Ok(response) => {
                    // Check if the response should trigger fallback
                    let should_handle_response = config
                        .handle_response_predicate
                        .as_ref()
                        .map(|p| p(&response))
                        .unwrap_or(false);

                    if should_handle_response {
                        #[cfg(feature = "tracing")]
                        tracing::debug!(
                            fallback = %config.name,
                            "Response matches predicate, applying fallback"
                        );

                        // Emit failed attempt event
                        let event = FallbackEvent::FailedAttempt {
                            pattern_name: config.name.clone(),
                            timestamp: Instant::now(),
                        };
                        config.event_listeners.emit(&event);

                        // Apply fallback strategy (only strategies that don't need an error)
                        match &config.strategy {
                            FallbackStrategy::Value(v) => {
                                #[cfg(feature = "metrics")]
                                counter!(
                                    "fallback_calls_total",
                                    "fallback" => config.name.clone(),
                                    "result" => "applied",
                                    "strategy" => "value"
                                )
                                .increment(1);

                                let event = FallbackEvent::Applied {
                                    pattern_name: config.name.clone(),
                                    timestamp: Instant::now(),
                                    strategy: "value",
                                };
                                config.event_listeners.emit(&event);

                                return Ok(v.clone());
                            }

                            FallbackStrategy::ValueFn(f) => {
                                let fallback_response = f();

                                #[cfg(feature = "metrics")]
                                counter!(
                                    "fallback_calls_total",
                                    "fallback" => config.name.clone(),
                                    "result" => "applied",
                                    "strategy" => "value_fn"
                                )
                                .increment(1);

                                let event = FallbackEvent::Applied {
                                    pattern_name: config.name.clone(),
                                    timestamp: Instant::now(),
                                    strategy: "value_fn",
                                };
                                config.event_listeners.emit(&event);

                                return Ok(fallback_response);
                            }

                            FallbackStrategy::Service(backup) => {
                                #[cfg(feature = "tracing")]
                                tracing::debug!(fallback = %config.name, "Calling backup service (response predicate)");

                                match backup(req_clone).await {
                                    Ok(backup_response) => {
                                        #[cfg(feature = "metrics")]
                                        counter!(
                                            "fallback_calls_total",
                                            "fallback" => config.name.clone(),
                                            "result" => "applied",
                                            "strategy" => "service"
                                        )
                                        .increment(1);

                                        let event = FallbackEvent::Applied {
                                            pattern_name: config.name.clone(),
                                            timestamp: Instant::now(),
                                            strategy: "service",
                                        };
                                        config.event_listeners.emit(&event);

                                        return Ok(backup_response);
                                    }
                                    Err(backup_error) => {
                                        #[cfg(feature = "tracing")]
                                        tracing::warn!(
                                            fallback = %config.name,
                                            "Backup service failed (response predicate)"
                                        );

                                        #[cfg(feature = "metrics")]
                                        counter!(
                                            "fallback_calls_total",
                                            "fallback" => config.name.clone(),
                                            "result" => "failed",
                                            "strategy" => "service"
                                        )
                                        .increment(1);

                                        let event = FallbackEvent::Failed {
                                            pattern_name: config.name.clone(),
                                            timestamp: Instant::now(),
                                        };
                                        config.event_listeners.emit(&event);

                                        return Err(FallbackError::FallbackFailed(backup_error));
                                    }
                                }
                            }

                            // FromError, FromRequestError, Exception need an error which we
                            // don't have — return the original response unchanged.
                            _ => {
                                return Ok(response);
                            }
                        }
                    }

                    #[cfg(feature = "tracing")]
                    tracing::debug!(fallback = %config.name, "Inner service succeeded");

                    #[cfg(feature = "metrics")]
                    counter!(
                        "fallback_calls_total",
                        "fallback" => config.name.clone(),
                        "result" => "success"
                    )
                    .increment(1);

                    let event = FallbackEvent::Success {
                        pattern_name: config.name.clone(),
                        timestamp: Instant::now(),
                    };
                    config.event_listeners.emit(&event);

                    Ok(response)
                }
                Err(error) => {
                    // Check if we should handle this error
                    let should_handle = config
                        .handle_predicate
                        .as_ref()
                        .map(|p| p(&error))
                        .unwrap_or(true);

                    if !should_handle {
                        #[cfg(feature = "tracing")]
                        tracing::debug!(
                            fallback = %config.name,
                            "Error does not match predicate, skipping fallback"
                        );

                        #[cfg(feature = "metrics")]
                        counter!(
                            "fallback_calls_total",
                            "fallback" => config.name.clone(),
                            "result" => "skipped"
                        )
                        .increment(1);

                        let event = FallbackEvent::Skipped {
                            pattern_name: config.name.clone(),
                            timestamp: Instant::now(),
                        };
                        config.event_listeners.emit(&event);

                        return Err(FallbackError::Inner(error));
                    }

                    #[cfg(feature = "tracing")]
                    tracing::debug!(fallback = %config.name, "Inner service failed, applying fallback");

                    // Emit failed attempt event
                    let event = FallbackEvent::FailedAttempt {
                        pattern_name: config.name.clone(),
                        timestamp: Instant::now(),
                    };
                    config.event_listeners.emit(&event);

                    // Apply fallback strategy
                    match &config.strategy {
                        FallbackStrategy::Value(v) => {
                            #[cfg(feature = "metrics")]
                            counter!(
                                "fallback_calls_total",
                                "fallback" => config.name.clone(),
                                "result" => "applied",
                                "strategy" => "value"
                            )
                            .increment(1);

                            let event = FallbackEvent::Applied {
                                pattern_name: config.name.clone(),
                                timestamp: Instant::now(),
                                strategy: "value",
                            };
                            config.event_listeners.emit(&event);

                            Ok(v.clone())
                        }

                        FallbackStrategy::ValueFn(f) => {
                            let response = f();

                            #[cfg(feature = "metrics")]
                            counter!(
                                "fallback_calls_total",
                                "fallback" => config.name.clone(),
                                "result" => "applied",
                                "strategy" => "value_fn"
                            )
                            .increment(1);

                            let event = FallbackEvent::Applied {
                                pattern_name: config.name.clone(),
                                timestamp: Instant::now(),
                                strategy: "value_fn",
                            };
                            config.event_listeners.emit(&event);

                            Ok(response)
                        }

                        FallbackStrategy::FromError(f) => {
                            let response = f(&error);

                            #[cfg(feature = "metrics")]
                            counter!(
                                "fallback_calls_total",
                                "fallback" => config.name.clone(),
                                "result" => "applied",
                                "strategy" => "from_error"
                            )
                            .increment(1);

                            let event = FallbackEvent::Applied {
                                pattern_name: config.name.clone(),
                                timestamp: Instant::now(),
                                strategy: "from_error",
                            };
                            config.event_listeners.emit(&event);

                            Ok(response)
                        }

                        FallbackStrategy::FromRequestError(f) => {
                            let response = f(&req_clone, &error);

                            #[cfg(feature = "metrics")]
                            counter!(
                                "fallback_calls_total",
                                "fallback" => config.name.clone(),
                                "result" => "applied",
                                "strategy" => "from_request_error"
                            )
                            .increment(1);

                            let event = FallbackEvent::Applied {
                                pattern_name: config.name.clone(),
                                timestamp: Instant::now(),
                                strategy: "from_request_error",
                            };
                            config.event_listeners.emit(&event);

                            Ok(response)
                        }

                        FallbackStrategy::Service(backup) => {
                            #[cfg(feature = "tracing")]
                            tracing::debug!(fallback = %config.name, "Calling backup service");

                            match backup(req_clone).await {
                                Ok(response) => {
                                    #[cfg(feature = "metrics")]
                                    counter!(
                                        "fallback_calls_total",
                                        "fallback" => config.name.clone(),
                                        "result" => "applied",
                                        "strategy" => "service"
                                    )
                                    .increment(1);

                                    let event = FallbackEvent::Applied {
                                        pattern_name: config.name.clone(),
                                        timestamp: Instant::now(),
                                        strategy: "service",
                                    };
                                    config.event_listeners.emit(&event);

                                    Ok(response)
                                }
                                Err(backup_error) => {
                                    #[cfg(feature = "tracing")]
                                    tracing::warn!(
                                        fallback = %config.name,
                                        "Backup service also failed"
                                    );

                                    #[cfg(feature = "metrics")]
                                    counter!(
                                        "fallback_calls_total",
                                        "fallback" => config.name.clone(),
                                        "result" => "failed",
                                        "strategy" => "service"
                                    )
                                    .increment(1);

                                    let event = FallbackEvent::Failed {
                                        pattern_name: config.name.clone(),
                                        timestamp: Instant::now(),
                                    };
                                    config.event_listeners.emit(&event);

                                    Err(FallbackError::FallbackFailed(backup_error))
                                }
                            }
                        }

                        FallbackStrategy::Exception(transform) => {
                            let transformed = transform(error);

                            #[cfg(feature = "metrics")]
                            counter!(
                                "fallback_calls_total",
                                "fallback" => config.name.clone(),
                                "result" => "transformed",
                                "strategy" => "exception"
                            )
                            .increment(1);

                            let event = FallbackEvent::Applied {
                                pattern_name: config.name.clone(),
                                timestamp: Instant::now(),
                                strategy: "exception",
                            };
                            config.event_listeners.emit(&event);

                            Err(FallbackError::Inner(transformed))
                        }
                    }
                }
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tower::{service_fn, Layer, ServiceExt};
    use tower_resilience_core::ResilienceEvent;

    #[derive(Debug, Clone)]
    struct TestError {
        message: String,
        retryable: bool,
    }

    impl TestError {
        fn new(message: &str) -> Self {
            Self {
                message: message.to_string(),
                retryable: true,
            }
        }

        fn non_retryable(message: &str) -> Self {
            Self {
                message: message.to_string(),
                retryable: false,
            }
        }
    }

    #[tokio::test]
    async fn success_no_fallback() {
        let service =
            service_fn(
                |req: String| async move { Ok::<_, TestError>(format!("response: {}", req)) },
            );

        let layer = FallbackLayer::<String, String, TestError>::value("fallback".to_string());
        let mut service = layer.layer(service);

        let response = service
            .ready()
            .await
            .unwrap()
            .call("test".to_string())
            .await
            .unwrap();

        assert_eq!(response, "response: test");
    }

    #[tokio::test]
    async fn failure_triggers_value_fallback() {
        let service =
            service_fn(|_req: String| async move { Err::<String, _>(TestError::new("failed")) });

        let layer = FallbackLayer::<String, String, TestError>::value("fallback".to_string());
        let mut service = layer.layer(service);

        let response = service
            .ready()
            .await
            .unwrap()
            .call("test".to_string())
            .await
            .unwrap();

        assert_eq!(response, "fallback");
    }

    #[tokio::test]
    async fn failure_triggers_from_error_fallback() {
        let service = service_fn(|_req: String| async move {
            Err::<String, _>(TestError::new("something went wrong"))
        });

        let layer = FallbackLayer::<String, String, TestError>::from_error(|e: &TestError| {
            format!("Error: {}", e.message)
        });
        let mut service = layer.layer(service);

        let response = service
            .ready()
            .await
            .unwrap()
            .call("test".to_string())
            .await
            .unwrap();

        assert_eq!(response, "Error: something went wrong");
    }

    #[tokio::test]
    async fn failure_triggers_from_request_error_fallback() {
        let service =
            service_fn(|_req: String| async move { Err::<String, _>(TestError::new("failed")) });

        let layer = FallbackLayer::<String, String, TestError>::from_request_error(
            |req: &String, _e: &TestError| format!("fallback for: {}", req),
        );
        let mut service = layer.layer(service);

        let response = service
            .ready()
            .await
            .unwrap()
            .call("my-request".to_string())
            .await
            .unwrap();

        assert_eq!(response, "fallback for: my-request");
    }

    #[tokio::test]
    async fn predicate_skips_non_matching_errors() {
        let service = service_fn(|_req: String| async move {
            Err::<String, _>(TestError::non_retryable("permanent failure"))
        });

        let layer = FallbackLayer::builder()
            .value("fallback".to_string())
            .handle(|e: &TestError| e.retryable) // Only handle retryable errors
            .build();
        let mut service = layer.layer(service);

        let result = service
            .ready()
            .await
            .unwrap()
            .call("test".to_string())
            .await;

        // Should propagate the original error, not apply fallback
        assert!(matches!(result, Err(FallbackError::Inner(_))));
    }

    #[tokio::test]
    async fn backup_service_fallback() {
        let call_count = Arc::new(AtomicUsize::new(0));
        let cc = Arc::clone(&call_count);

        let primary = service_fn(move |_req: String| {
            let cc = Arc::clone(&cc);
            async move {
                cc.fetch_add(1, Ordering::SeqCst);
                Err::<String, _>(TestError::new("primary failed"))
            }
        });

        let backup_calls = Arc::new(AtomicUsize::new(0));
        let bc = Arc::clone(&backup_calls);

        let layer = FallbackLayer::<String, String, TestError>::service(move |req: String| {
            let bc = Arc::clone(&bc);
            async move {
                bc.fetch_add(1, Ordering::SeqCst);
                Ok::<_, TestError>(format!("backup: {}", req))
            }
        });
        let mut service = layer.layer(primary);

        let response = service
            .ready()
            .await
            .unwrap()
            .call("test".to_string())
            .await
            .unwrap();

        assert_eq!(response, "backup: test");
        assert_eq!(call_count.load(Ordering::SeqCst), 1);
        assert_eq!(backup_calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn backup_service_also_fails() {
        let primary =
            service_fn(
                |_req: String| async move { Err::<String, _>(TestError::new("primary failed")) },
            );

        let layer =
            FallbackLayer::<String, String, TestError>::service(|_req: String| async move {
                Err::<String, _>(TestError::new("backup also failed"))
            });
        let mut service = layer.layer(primary);

        let result = service
            .ready()
            .await
            .unwrap()
            .call("test".to_string())
            .await;

        assert!(matches!(result, Err(FallbackError::FallbackFailed(_))));
    }

    #[tokio::test]
    async fn exception_transforms_error() {
        let service =
            service_fn(
                |_req: String| async move { Err::<String, _>(TestError::new("original error")) },
            );

        let layer = FallbackLayer::<String, String, TestError>::exception(|_e: TestError| {
            TestError::new("transformed error")
        });
        let mut service = layer.layer(service);

        let result = service
            .ready()
            .await
            .unwrap()
            .call("test".to_string())
            .await;

        match result {
            Err(FallbackError::Inner(e)) => {
                assert_eq!(e.message, "transformed error");
            }
            _ => panic!("expected transformed error"),
        }
    }

    #[tokio::test]
    async fn event_listeners_called() {
        use std::sync::Mutex;

        let events: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let events_clone = Arc::clone(&events);

        let service =
            service_fn(|_req: String| async move { Err::<String, _>(TestError::new("failed")) });

        let layer = FallbackLayer::builder()
            .name("test-fallback")
            .value("fallback".to_string())
            .on_event(move |event: &FallbackEvent| {
                events_clone
                    .lock()
                    .unwrap()
                    .push(event.event_type().to_string());
            })
            .build();
        let mut service = layer.layer(service);

        let _ = service
            .ready()
            .await
            .unwrap()
            .call("test".to_string())
            .await;

        let recorded = events.lock().unwrap();
        assert!(recorded.contains(&"failed_attempt".to_string()));
        assert!(recorded.contains(&"applied".to_string()));
    }
}