google_cloud_gax/
polling_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//! Defines the trait for polling backoff policies and a common implementations.
16//!
17//! The client libraries can automatically poll long-running operations (LROs)
18//! until completion. When doing so they may backoff between polling to avoid
19//! overloading the service.
20//!
21//! These policies should not be confused with retry backoff policies. Their
22//! purpose is different, and their implementation is too. Notably, polling
23//! backoff policies should not use jitter, while retry policies should.
24//!
25//! The most common implementation is truncated [exponential backoff]
26//! **without** jitter. The backoff period grows exponentially until some limit
27//! is reached. This works well when the expected execution time is not known
28//! in advance.
29//!
30//! To configure the default polling backoff policy for a client, use
31//! [ClientBuilder::with_polling_backoff_policy]. To configure the polling
32//! backoff policy used for a specific request, use
33//! [RequestOptionsBuilder::with_polling_backoff_policy].
34//!
35//! [ClientBuilder::with_polling_backoff_policy]: crate::client_builder::ClientBuilder::with_polling_backoff_policy
36//! [RequestOptionsBuilder::with_polling_backoff_policy]: crate::options::RequestOptionsBuilder::with_polling_backoff_policy
37//!
38//! # Example
39//! ```
40//! # use google_cloud_gax::exponential_backoff::Error;
41//! # use google_cloud_gax::exponential_backoff::ExponentialBackoffBuilder;
42//! use std::time::Duration;
43//!
44//! let policy = ExponentialBackoffBuilder::new()
45//!     .with_initial_delay(Duration::from_millis(100))
46//!     .with_maximum_delay(Duration::from_secs(5))
47//!     .with_scaling(4.0)
48//!     .build()?;
49//! // `policy` implements the `PollingBackoffPolicy` trait.
50//! # Ok::<(), Error>(())
51//! ```
52//!
53//! [Exponential backoff]: https://en.wikipedia.org/wiki/Exponential_backoff
54
55use crate::polling_state::PollingState;
56use std::sync::Arc;
57
58/// Defines the trait implemented by all backoff strategies.
59pub trait PollingBackoffPolicy: Send + Sync + std::fmt::Debug {
60    /// Returns the backoff delay on a failure.
61    ///
62    /// # Parameters
63    /// * `state` - the current state of the polling loop.
64    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
65    fn wait_period(&self, state: &PollingState) -> std::time::Duration;
66}
67
68/// A helper type to use [PollingBackoffPolicy] in client and request options.
69#[derive(Clone)]
70pub struct PollingBackoffPolicyArg(pub(crate) Arc<dyn PollingBackoffPolicy>);
71
72impl<T: PollingBackoffPolicy + 'static> std::convert::From<T> for PollingBackoffPolicyArg {
73    fn from(value: T) -> Self {
74        Self(Arc::new(value))
75    }
76}
77
78impl std::convert::From<Arc<dyn PollingBackoffPolicy>> for PollingBackoffPolicyArg {
79    fn from(value: Arc<dyn PollingBackoffPolicy>) -> Self {
80        Self(value)
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::exponential_backoff::ExponentialBackoffBuilder;
88
89    // Verify `BackoffPolicyArg` can be converted from the desired types.
90    #[test]
91    fn backoff_policy_arg() {
92        let policy = ExponentialBackoffBuilder::default().clamp();
93        let _ = PollingBackoffPolicyArg::from(policy);
94
95        let policy: Arc<dyn PollingBackoffPolicy> =
96            Arc::new(ExponentialBackoffBuilder::default().clamp());
97        let _ = PollingBackoffPolicyArg::from(policy);
98    }
99}