seatbelt 0.4.2

Resilience and recovery mechanisms for fallible operations.
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::marker::PhantomData;
use std::sync::Arc;
use std::time::Duration;

use layered::Layer;

use crate::timeout::*;
use crate::typestates::{NotSet, Set};
use crate::utils::{EnableIf, TelemetryHelper};
use crate::{ResilienceContext, TelemetryString};

/// Builder for configuring timeout resilience middleware.
///
/// This type is created by calling [`Timeout::layer`](crate::timeout::Timeout::layer) and uses the
/// type-state pattern to enforce that required properties are configured before the timeout middleware can be built:
///
/// - [`timeout_output`][TimeoutLayer::timeout_output]: Required to specify how to represent output values when a timeout occurs
/// - [`timeout`][TimeoutLayer::timeout]: Required to set the timeout duration for operations
///
/// For comprehensive examples, see the [timeout module][crate::timeout] documentation.
///
/// # Type State
///
/// - `S1`: Tracks whether [`timeout`][TimeoutLayer::timeout] has been set
/// - `S2`: Tracks whether [`timeout_output`][TimeoutLayer::timeout_output] has been set
#[derive(Debug)]
pub struct TimeoutLayer<In, Out, S1 = Set, S2 = Set> {
    context: ResilienceContext<In, Out>,
    timeout: Option<Duration>,
    timeout_output: Option<TimeoutOutput<Out>>,
    on_timeout: Option<OnTimeout<Out>>,
    enable_if: EnableIf<In>,
    telemetry: TelemetryHelper,
    timeout_override: Option<TimeoutOverride<In>>,
    _state: PhantomData<fn(In, S1, S2) -> Out>,
}

impl<In, Out> TimeoutLayer<In, Out, NotSet, NotSet> {
    #[must_use]
    pub(crate) fn new(name: TelemetryString, context: &ResilienceContext<In, Out>) -> Self {
        Self {
            timeout: None,
            timeout_output: None,
            on_timeout: None,
            enable_if: EnableIf::default(),
            telemetry: context.create_telemetry(name),
            context: context.clone(),
            timeout_override: None,
            _state: PhantomData,
        }
    }
}

impl<In, Out, E, S1, S2> TimeoutLayer<In, Result<Out, E>, S1, S2> {
    /// Configures the error value to return when a timeout occurs for Result types.
    ///
    /// This is a convenience method for Result types that creates an error value
    /// when a timeout occurs instead of requiring you to specify the full Result.
    /// The `timeout_error` function receives [`TimeoutOutputArgs`] containing timeout
    /// context and returns the error value to use when a timeout occurs.
    pub fn timeout_error(
        self,
        timeout_error: impl Fn(TimeoutOutputArgs) -> E + Send + Sync + 'static,
    ) -> TimeoutLayer<In, Result<Out, E>, S1, Set> {
        self.into_state::<Set, S2>()
            .timeout_output(move |args| Err(timeout_error(args)))
            .into_state()
    }
}

impl<In, Out, S1, S2> TimeoutLayer<In, Out, S1, S2> {
    /// Sets the timeout duration.
    ///
    /// The `timeout` parameter specifies the maximum duration to wait before
    /// timing out an operation. This call replaces any previous timeout value.
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> TimeoutLayer<In, Out, Set, S2> {
        self.timeout = Some(timeout);
        self.into_state::<Set, S2>()
    }

    /// Applies all settings from a [`TimeoutConfig`] to this layer.
    ///
    /// This is a convenience method for applying configuration loaded from external sources
    /// (e.g., configuration files) without calling individual builder methods.
    #[must_use]
    pub fn config(self, config: &TimeoutConfig) -> TimeoutLayer<In, Out, Set, S2> {
        self.timeout(config.timeout).enable(config.enabled)
    }

    /// Sets the timeout result factory function.
    ///
    /// This function is called when a timeout occurs to create the output value
    /// that will be returned instead of the original operation's result. The `output`
    /// function receives [`TimeoutOutputArgs`] containing timeout context and returns
    /// the output value to use when a timeout occurs. This call replaces any previous
    /// timeout output handler.
    #[must_use]
    pub fn timeout_output(mut self, output: impl Fn(TimeoutOutputArgs) -> Out + Send + Sync + 'static) -> TimeoutLayer<In, Out, S1, Set> {
        self.timeout_output = Some(TimeoutOutput::new(output));
        self.into_state::<S1, Set>()
    }

    /// Configures a callback invoked when a timeout occurs.
    ///
    /// This callback is useful for logging, metrics, or other observability
    /// purposes. The `on_timeout` callback receives a reference to the timeout
    /// output and [`OnTimeoutArgs`] with detailed timeout information.
    ///
    /// The callback does not affect timeout behavior - it's purely for observation.
    /// This call replaces any previous callback.
    ///
    /// **Default**: None (no observability by default)
    #[must_use]
    pub fn on_timeout(mut self, on_timeout: impl Fn(&Out, OnTimeoutArgs) + Send + Sync + 'static) -> Self {
        self.on_timeout = Some(OnTimeout::new(on_timeout));
        self
    }

    /// Overrides the default timeout on a per-request basis.
    ///
    /// Use this to compute a timeout dynamically from the input. The `timeout_override`
    /// function receives a reference to the input and [`TimeoutOverrideArgs`], which
    /// exposes the default via [`TimeoutOverrideArgs::default_timeout`]. Return
    /// `Some(Duration)` to apply an override, or `None` to fall back to the default
    /// timeout configured via [`timeout`][TimeoutLayer::timeout].
    ///
    /// This call replaces any previous timeout override.
    ///
    /// **Default**: None (uses default timeout for all requests)
    #[must_use]
    pub fn timeout_override(
        mut self,
        timeout_override: impl Fn(&In, TimeoutOverrideArgs) -> Option<Duration> + Send + Sync + 'static,
    ) -> Self {
        self.timeout_override = Some(TimeoutOverride::new(timeout_override));
        self
    }

    /// Optionally enables the timeout middleware based on a condition.
    ///
    /// When disabled, requests pass through without timeout protection.
    /// This call replaces any previous condition. The `is_enabled` function
    /// receives a reference to the input and returns `true` if timeout
    /// protection should be enabled for this request.
    ///
    /// **Default**: Always enabled
    #[must_use]
    pub fn enable_if(mut self, is_enabled: impl Fn(&In) -> bool + Send + Sync + 'static) -> Self {
        self.enable_if = EnableIf::custom(is_enabled);
        self
    }

    /// Enables or disables the timeout middleware.
    ///
    /// When disabled, requests pass through without timeout protection.
    /// This call replaces any previous condition.
    #[must_use]
    fn enable(mut self, enabled: bool) -> Self {
        self.enable_if = EnableIf::new(enabled);
        self
    }

    /// Enables the timeout middleware unconditionally.
    ///
    /// All requests will have timeout protection applied.
    /// This call replaces any previous condition.
    ///
    /// **Note**: This is the default behavior - timeout is enabled by default.
    #[must_use]
    pub fn enable_always(self) -> Self {
        self.enable(true)
    }

    /// Disables the timeout middleware completely.
    ///
    /// All requests will pass through without timeout protection.
    /// This call replaces any previous condition.
    ///
    /// **Note**: This overrides the default enabled behavior.
    #[must_use]
    pub fn disable(self) -> Self {
        self.enable(false)
    }
}

impl<In, Out, S> Layer<S> for TimeoutLayer<In, Out, Set, Set> {
    type Service = Timeout<In, Out, S>;

    fn layer(&self, inner: S) -> Self::Service {
        let shared = TimeoutShared {
            clock: self.context.get_clock().clone(),
            timeout: self.timeout.expect("enforced by the type state pattern"),
            enable_if: self.enable_if.clone(),
            on_timeout: self.on_timeout.clone(),
            timeout_output: self.timeout_output.clone().expect("enforced by the type state pattern"),
            timeout_override: self.timeout_override.clone(),
            #[cfg(any(feature = "logs", feature = "metrics", test))]
            telemetry: self.telemetry.clone(),
        };

        Timeout {
            shared: Arc::new(shared),
            inner,
        }
    }
}

impl<In, Out, S1, S2> TimeoutLayer<In, Out, S1, S2> {
    fn into_state<T1, T2>(self) -> TimeoutLayer<In, Out, T1, T2> {
        TimeoutLayer {
            timeout: self.timeout,
            enable_if: self.enable_if,
            timeout_output: self.timeout_output,
            on_timeout: self.on_timeout,
            telemetry: self.telemetry,
            context: self.context,
            timeout_override: self.timeout_override,
            _state: PhantomData,
        }
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use std::fmt::Debug;
    use std::sync::atomic::{AtomicBool, Ordering};

    use layered::Execute;
    use tick::Clock;

    use super::*;

    #[cfg_attr(miri, ignore)]
    #[test]
    fn new_needs_timeout_output() {
        let layer = create_ready_layer();
        insta::assert_debug_snapshot!(layer);
    }

    #[test]
    fn timeout_output_ensure_set_correctly() {
        let context = create_test_context();
        let layer = TimeoutLayer::new("test".into(), &context);

        let layer: TimeoutLayer<_, _, NotSet, Set> = layer.timeout_output(|args| format!("timeout: {}", args.timeout().as_millis()));
        let result = layer.timeout_output.unwrap().call(TimeoutOutputArgs {
            timeout: Duration::from_millis(3),
        });

        assert_eq!(result, "timeout: 3");
    }

    #[test]
    fn timeout_error_ensure_set_correctly() {
        let context = create_test_context_result();
        let layer = TimeoutLayer::new("test".into(), &context);

        let layer: TimeoutLayer<_, _, NotSet, Set> = layer.timeout_error(|args| format!("timeout: {}", args.timeout().as_millis()));
        let result = layer
            .timeout_output
            .unwrap()
            .call(TimeoutOutputArgs {
                timeout: Duration::from_millis(3),
            })
            .unwrap_err();

        assert_eq!(result, "timeout: 3");
    }

    #[test]
    fn timeout_ensure_set_correctly() {
        let layer: TimeoutLayer<_, _, Set, Set> = TimeoutLayer::new("test".into(), &create_test_context())
            .timeout_output(|_args| "timeout: ".to_string())
            .timeout(Duration::from_millis(3));

        assert_eq!(layer.timeout.unwrap(), Duration::from_millis(3));
    }

    #[test]
    fn on_timeout_ok() {
        let called = Arc::new(AtomicBool::new(false));
        let called_clone = Arc::clone(&called);

        let layer: TimeoutLayer<_, _, Set, Set> = create_ready_layer().on_timeout(move |_output, _args| {
            called_clone.store(true, Ordering::SeqCst);
        });

        layer.on_timeout.unwrap().call(
            &"output".to_string(),
            OnTimeoutArgs {
                timeout: Duration::from_millis(3),
            },
        );

        assert!(called.load(Ordering::SeqCst));
    }

    #[test]
    fn timeout_override_ok() {
        let layer: TimeoutLayer<_, _, Set, Set> = create_ready_layer().timeout_override(|_input, _args| Some(Duration::from_secs(3)));

        let result = layer.timeout_override.unwrap().call(
            &"a".to_string(),
            TimeoutOverrideArgs {
                default_timeout: Duration::from_millis(3),
            },
        );

        assert_eq!(result, Some(Duration::from_secs(3)));
    }

    #[test]
    fn enable_if_ok() {
        let layer: TimeoutLayer<_, _, Set, Set> = create_ready_layer().enable_if(|input| matches!(input.as_ref(), "enable"));

        assert!(layer.enable_if.call(&"enable".to_string()));
        assert!(!layer.enable_if.call(&"disable".to_string()));
    }

    #[test]
    fn disable_ok() {
        let layer: TimeoutLayer<_, _, Set, Set> = create_ready_layer().disable();

        assert!(!layer.enable_if.call(&"whatever".to_string()));
    }

    #[test]
    fn enable_ok() {
        let layer: TimeoutLayer<_, _, Set, Set> = create_ready_layer().disable().enable_always();

        assert!(layer.enable_if.call(&"whatever".to_string()));
    }

    #[test]
    fn timeout_when_ready_ok() {
        let layer: TimeoutLayer<_, _, Set, Set> = create_ready_layer().timeout(Duration::from_secs(123));

        assert_eq!(layer.timeout.unwrap(), Duration::from_secs(123));
    }

    #[test]
    fn timeout_output_when_ready_ok() {
        let layer: TimeoutLayer<_, _, Set, Set> = create_ready_layer().timeout_output(|_args| "some new value".to_string());
        assert!(layer.timeout_output.is_some());
        let result = layer.timeout_output.unwrap().call(TimeoutOutputArgs {
            timeout: Duration::from_secs(123),
        });

        assert_eq!(result, "some new value");
    }

    #[test]
    fn timeout_error_when_ready_ok() {
        let layer: TimeoutLayer<_, _, Set, Set> = create_ready_layer_with_result().timeout_error(|_args| "some error value".to_string());
        assert!(layer.timeout_output.is_some());
        let result = layer
            .timeout_output
            .unwrap()
            .call(TimeoutOutputArgs {
                timeout: Duration::from_secs(123),
            })
            .unwrap_err();

        assert_eq!(result, "some error value");
    }

    #[test]
    fn layer_ok() {
        let _layered = create_ready_layer().layer(Execute::new(|input: String| async move { input }));
    }

    #[cfg_attr(miri, ignore)]
    #[test]
    fn config_applies_all_settings() {
        let config = TimeoutConfig {
            enabled: false,
            timeout: Duration::from_secs(45),
        };

        let context = create_test_context();
        let layer = TimeoutLayer::new("test".into(), &context)
            .timeout_output(|_args| "timeout".to_string())
            .config(&config);

        insta::assert_debug_snapshot!(layer);
    }

    #[test]
    fn static_assertions() {
        static_assertions::assert_impl_all!(TimeoutLayer<String, String, Set, Set>: Layer<String>);
        static_assertions::assert_not_impl_all!(TimeoutLayer<String, String, Set, NotSet>: Layer<String>);
        static_assertions::assert_not_impl_all!(TimeoutLayer<String, String, NotSet, Set>: Layer<String>);
        static_assertions::assert_impl_all!(TimeoutLayer<String, String, Set, Set>: Debug);
    }

    fn create_test_context() -> ResilienceContext<String, String> {
        ResilienceContext::new(Clock::new_frozen()).name("test_pipeline")
    }

    fn create_test_context_result() -> ResilienceContext<String, Result<String, String>> {
        ResilienceContext::new(Clock::new_frozen()).name("test_pipeline")
    }

    fn create_ready_layer() -> TimeoutLayer<String, String, Set, Set> {
        TimeoutLayer::new("test".into(), &create_test_context())
            .timeout_output(|_args| "timeout: ".to_string())
            .timeout(Duration::from_millis(3))
    }

    fn create_ready_layer_with_result() -> TimeoutLayer<String, Result<String, String>, Set, Set> {
        TimeoutLayer::new("test".into(), &create_test_context_result())
            .timeout_error(|_args| "timeout: ".to_string())
            .timeout(Duration::from_millis(3))
    }
}