Skip to main content

google_cloud_storage/
backoff_policy.rs

1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Types and functions related to the default backoff policy.
16
17use google_cloud_gax::{
18    backoff_policy::BackoffPolicy, exponential_backoff::ExponentialBackoffBuilder,
19};
20use std::time::Duration;
21
22/// The default backoff policy for the Storage clients.
23///
24/// The service recommends exponential backoff with jitter, starting with a one
25/// second backoff and doubling on each attempt.
26pub fn default() -> impl BackoffPolicy {
27    ExponentialBackoffBuilder::new()
28        .with_initial_delay(Duration::from_secs(1))
29        .with_maximum_delay(Duration::from_secs(60))
30        .with_scaling(2.0)
31        .build()
32        .expect("statically configured policy should succeed")
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    use google_cloud_gax::retry_state::RetryState;
39
40    #[test]
41    fn default() {
42        let policy = super::default();
43
44        let delay = policy.on_failure(&RetryState::new(true).set_attempt_count(1_u32));
45        assert!(
46            delay <= Duration::from_secs(1),
47            "{delay:?}, policy={policy:?}"
48        );
49
50        let delay = policy.on_failure(&RetryState::new(true).set_attempt_count(2_u32));
51        assert!(
52            delay <= Duration::from_secs(2),
53            "{delay:?}, policy={policy:?}"
54        );
55    }
56}