Skip to main content

google_cloud_spanner/
retry_policy.rs

1// Copyright 2026 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//! RPC retry policies used by the Spanner client.
16
17use google_cloud_gax::error::Error;
18use google_cloud_gax::error::rpc::Code;
19use google_cloud_gax::retry_policy::{Aip194Strict, RetryPolicy};
20use google_cloud_gax::retry_state::RetryState;
21use google_cloud_gax::throttle_result::ThrottleResult;
22use std::time::Duration;
23
24pub use crate::transaction_retry_policy::{BasicTransactionRetryPolicy, TransactionRetryPolicy};
25pub use google_cloud_gax::retry_result::RetryResult;
26
27/// The retry policy the Spanner client applies to RPCs that do not configure
28/// their own. It decorates/extends [google_cloud_gax::retry_policy::Aip194Strict].
29///
30/// Like `Aip194Strict`, this policy retries `UNAVAILABLE` errors and transient
31/// failures that occur before the request reaches the service, but only for
32/// idempotent requests. In addition — because Spanner allows transport and
33/// connection errors to be retried on idempotent operations — it also retries
34/// transport/network and I/O errors that `Aip194Strict` would classify as
35/// permanent (such as a connection dropped after the request was sent), as well
36/// as transient `INTERNAL` errors caused by HTTP/2 stream resets (such as
37/// `stream terminated by RST_STREAM`), again only if the request is idempotent.
38///
39/// The policy places no limit on the number of attempts or the elapsed time.
40/// Applications that want to bound the client's default retry behavior can
41/// decorate this policy with
42/// [RetryPolicyExt][google_cloud_gax::retry_policy::RetryPolicyExt] instead of
43/// re-implementing its error classification:
44///
45/// # Example
46/// ```
47/// # use std::time::Duration;
48/// # use google_cloud_spanner::retry_policy::SpannerRetryPolicy;
49/// # use google_cloud_spanner::statement::Statement;
50/// # use google_cloud_gax::retry_policy::RetryPolicyExt;
51/// let statement = Statement::builder("SELECT * FROM Users")
52///     .with_retry_policy(
53///         SpannerRetryPolicy::new()
54///             .with_attempt_limit(5)
55///             .with_time_limit(Duration::from_secs(30)),
56///     )
57///     .build();
58/// ```
59#[derive(Clone, Debug)]
60pub struct SpannerRetryPolicy {
61    inner: Aip194Strict,
62}
63
64impl SpannerRetryPolicy {
65    /// Creates a new Spanner retry policy.
66    pub fn new() -> Self {
67        Self {
68            inner: Aip194Strict,
69        }
70    }
71}
72
73impl Default for SpannerRetryPolicy {
74    fn default() -> Self {
75        Self::new()
76    }
77}
78
79impl RetryPolicy for SpannerRetryPolicy {
80    fn on_error(&self, state: &RetryState, error: Error) -> RetryResult {
81        // 1. Strict AIP-194 checks (Unavailable, is_transient_and_before_rpc)
82        let result = self.inner.on_error(state, error);
83        match result {
84            // If the strict AIP-194 checks classified the error as permanent (such as a transport
85            // error that occurred post-headers or a transient stream reset), we override it to Continue
86            // if the request is idempotent.
87            RetryResult::Permanent(error)
88                if state.idempotent
89                    && (error.is_transport()
90                        || error.is_io()
91                        || is_retryable_internal_error(&error)) =>
92            {
93                RetryResult::Continue(error)
94            }
95            result => result,
96        }
97    }
98
99    fn on_throttle(&self, state: &RetryState, error: Error) -> ThrottleResult {
100        self.inner.on_throttle(state, error)
101    }
102
103    fn remaining_time(&self, state: &RetryState) -> Option<Duration> {
104        self.inner.remaining_time(state)
105    }
106}
107
108/// Known transient `INTERNAL` error messages indicating HTTP/2 stream resets or connection terminations
109/// that are safe to retry on idempotent requests.
110const RETRYABLE_INTERNAL_ERROR_MESSAGES: &[&str] = &[
111    "HTTP/2 error code: INTERNAL_ERROR",
112    "Connection closed with unknown cause",
113    "Received unexpected EOS on DATA frame from server",
114    "stream terminated by RST_STREAM",
115    "Authentication backend internal server error. Please retry",
116];
117
118/// Returns `true` if the error is a `Code::Internal` error caused by a known transient stream reset or connection drop.
119fn is_retryable_internal_error(error: &Error) -> bool {
120    error.status().is_some_and(|status| {
121        status.code == Code::Internal
122            && RETRYABLE_INTERNAL_ERROR_MESSAGES
123                .iter()
124                .any(|&message| status.message.contains(message))
125    })
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use google_cloud_gax::error::Error as GaxError;
132    use google_cloud_gax::error::rpc::{Code, Status};
133    use http::HeaderMap;
134
135    #[test]
136    fn traits() {
137        use std::fmt::Debug;
138        static_assertions::assert_impl_all!(
139            SpannerRetryPolicy: Send,
140            Sync,
141            Clone,
142            Debug,
143            Default,
144            RetryPolicy,
145        );
146    }
147
148    #[test]
149    fn test_spanner_retry_policy_idempotent() {
150        let policy = SpannerRetryPolicy::new();
151        let state = RetryState::new(true); // idempotent = true
152
153        // 1. Service UNAVAILABLE error should be retried (via inner AIP-194)
154        let status = Status::default()
155            .set_code(Code::Unavailable)
156            .set_message("Service Unavailable");
157        let err = GaxError::service(status);
158        assert!(
159            policy.on_error(&state, err).is_continue(),
160            "Expected UNAVAILABLE to be retried when idempotent"
161        );
162
163        // 2. Service PERMISSION_DENIED error should not be retried
164        let status = Status::default()
165            .set_code(Code::PermissionDenied)
166            .set_message("Denied");
167        let err = GaxError::service(status);
168        assert!(
169            policy.on_error(&state, err).is_permanent(),
170            "Expected PERMISSION_DENIED to not be retried"
171        );
172
173        // 3. IO/Transport error should be retried when idempotent
174        let err = GaxError::transport(
175            HeaderMap::new(),
176            std::io::Error::new(std::io::ErrorKind::ConnectionReset, "connection closed"),
177        );
178        assert!(
179            policy.on_error(&state, err).is_continue(),
180            "Expected transport connection reset to be retried when idempotent"
181        );
182    }
183
184    #[test]
185    fn test_spanner_retry_policy_non_idempotent() {
186        let policy = SpannerRetryPolicy::new();
187        let state = RetryState::new(false); // idempotent = false
188
189        // 1. Service UNAVAILABLE error should NOT be retried (AIP-194 requires idempotency)
190        let status = Status::default()
191            .set_code(Code::Unavailable)
192            .set_message("Service Unavailable");
193        let err = GaxError::service(status);
194        assert!(
195            policy.on_error(&state, err).is_permanent(),
196            "Expected UNAVAILABLE to be permanent when non-idempotent"
197        );
198
199        // 2. IO/Transport error should NOT be retried when non-idempotent
200        let err = GaxError::transport(
201            HeaderMap::new(),
202            std::io::Error::new(std::io::ErrorKind::ConnectionReset, "connection closed"),
203        );
204        assert!(
205            policy.on_error(&state, err).is_permanent(),
206            "Expected transport connection reset to not be retried when non-idempotent"
207        );
208    }
209
210    #[test]
211    fn retryable_internal_error_messages() {
212        let policy = SpannerRetryPolicy::new();
213        let state = RetryState::new(true);
214
215        let messages = [
216            "HTTP/2 error code: INTERNAL_ERROR",
217            "INTERNAL: HTTP/2 error code: INTERNAL_ERROR\nReceived Rst Stream",
218            "Connection closed with unknown cause",
219            "Received unexpected EOS on DATA frame from server",
220            "stream terminated by RST_STREAM",
221            "gRPC call failed: stream terminated by RST_STREAM during streaming",
222            "Authentication backend internal server error. Please retry.",
223        ];
224
225        for message in messages {
226            let status = Status::default()
227                .set_code(Code::Internal)
228                .set_message(message);
229            assert!(
230                policy
231                    .on_error(&state, GaxError::service(status))
232                    .is_continue(),
233                "expected INTERNAL error with message '{message}' to be retried when idempotent"
234            );
235        }
236    }
237
238    #[test]
239    fn non_retryable_scenarios() {
240        let policy = SpannerRetryPolicy::new();
241        let cases = [
242            (
243                RetryState::new(false),
244                GaxError::service(
245                    Status::default()
246                        .set_code(Code::Internal)
247                        .set_message("stream terminated by RST_STREAM"),
248                ),
249                "non-idempotent operation with RST_STREAM",
250            ),
251            (
252                RetryState::new(true),
253                GaxError::service(
254                    Status::default()
255                        .set_code(Code::Internal)
256                        .set_message("Corrupted database page encountered on disk"),
257                ),
258                "unrelated INTERNAL error message",
259            ),
260            (
261                RetryState::new(true),
262                GaxError::service(
263                    Status::default()
264                        .set_code(Code::InvalidArgument)
265                        .set_message("stream terminated by RST_STREAM"),
266                ),
267                "non-INTERNAL code with matching message",
268            ),
269            (
270                RetryState::new(true),
271                GaxError::deser("failed to deserialize payload"),
272                "error without gRPC status",
273            ),
274        ];
275
276        for (state, error, reason) in cases {
277            assert!(
278                policy.on_error(&state, error).is_permanent(),
279                "expected {reason} to be permanent"
280            );
281        }
282    }
283}