1use crate::{Error, Result};
16use google_cloud_gax::backoff_policy::BackoffPolicy;
17use google_cloud_gax::error::rpc::Code;
18use google_cloud_gax::exponential_backoff::{ExponentialBackoff, ExponentialBackoffBuilder};
19use google_cloud_gax::retry_result::RetryResult;
20use google_cloud_gax::retry_state::RetryState;
21use std::fmt::Debug;
22use std::sync::Arc;
23use std::time::Duration;
24use tokio::time::{Instant, sleep};
25
26pub trait TransactionRetryPolicy: Debug + Send + Sync {
57 fn on_abort(&self, error: Error, attempts: u32, elapsed: Duration) -> RetryResult;
64}
65
66impl<T: ?Sized + TransactionRetryPolicy> TransactionRetryPolicy for Box<T> {
67 fn on_abort(&self, error: Error, attempts: u32, elapsed: Duration) -> RetryResult {
68 (**self).on_abort(error, attempts, elapsed)
69 }
70}
71
72impl<T: ?Sized + TransactionRetryPolicy> TransactionRetryPolicy for Arc<T> {
73 fn on_abort(&self, error: Error, attempts: u32, elapsed: Duration) -> RetryResult {
74 (**self).on_abort(error, attempts, elapsed)
75 }
76}
77
78#[derive(Clone, Debug)]
81pub struct BasicTransactionRetryPolicy {
82 max_attempts: u32,
84 total_timeout: Duration,
86}
87
88impl BasicTransactionRetryPolicy {
89 pub fn new() -> Self {
91 Self::default()
92 }
93
94 pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
96 self.max_attempts = max_attempts;
97 self
98 }
99
100 pub fn with_total_timeout(mut self, total_timeout: Duration) -> Self {
102 self.total_timeout = total_timeout;
103 self
104 }
105
106 pub fn max_attempts(&self) -> u32 {
108 self.max_attempts
109 }
110
111 pub fn total_timeout(&self) -> Duration {
113 self.total_timeout
114 }
115}
116
117impl Default for BasicTransactionRetryPolicy {
118 fn default() -> Self {
119 Self {
120 max_attempts: 0,
121 total_timeout: Duration::from_secs(0),
122 }
123 }
124}
125
126impl TransactionRetryPolicy for BasicTransactionRetryPolicy {
127 fn on_abort(&self, error: Error, attempts: u32, elapsed: Duration) -> RetryResult {
128 if self.max_attempts > 0 && attempts >= self.max_attempts {
129 return RetryResult::Exhausted(error);
130 }
131 if self.total_timeout > Duration::from_secs(0) && elapsed > self.total_timeout {
132 return RetryResult::Exhausted(error);
133 }
134 RetryResult::Continue(error)
135 }
136}
137
138pub(crate) async fn retry_aborted<T, F, Fut>(
145 policy: &dyn TransactionRetryPolicy,
146 mut f: F,
147 is_emulator: bool,
148) -> crate::Result<T>
149where
150 F: FnMut() -> Fut,
151 Fut: std::future::Future<Output = crate::Result<T>>,
152{
153 let start_time = tokio::time::Instant::now();
154 let mut attempts: u32 = 0;
155
156 let backoff = default_retry_backoff();
158
159 loop {
160 attempts += 1;
161 match f().await {
162 Ok(v) => return Ok(v),
163 Err(error) => {
164 backoff_if_aborted(
165 error,
166 AbortBackoffParams {
167 retry_delay: None,
168 attempts,
169 elapsed: start_time.elapsed(),
170 policy,
171 backoff: &backoff,
172 is_emulator,
173 deadline: None,
174 },
175 )
176 .await?;
177 }
178 }
179 }
180}
181
182pub(crate) fn is_aborted(error: &Error) -> bool {
183 error
184 .status()
185 .is_some_and(|status| status.code == Code::Aborted)
186}
187
188pub(crate) use crate::retry_delay::extract_retry_delay_from_error as extract_retry_delay;
189
190pub(crate) fn default_retry_backoff() -> ExponentialBackoff {
191 ExponentialBackoffBuilder::new()
192 .with_initial_delay(Duration::from_millis(10))
193 .with_maximum_delay(Duration::from_secs(1))
194 .with_scaling(1.3)
195 .build()
196 .expect("default retry backoff parameters are valid")
197}
198
199pub(crate) fn is_internal_emulator_error(error: &Error) -> bool {
200 error.status().is_some_and(|status| {
201 status.code == Code::Internal
202 && status.message.contains("Schema generation")
203 && status
204 .message
205 .contains("was not registered with the Action Manager")
206 })
207}
208
209pub(crate) fn is_aborted_or_emulator_error(error: &Error, is_emulator: bool) -> bool {
211 is_aborted(error) || (is_emulator && is_internal_emulator_error(error))
212}
213
214pub(crate) struct AbortBackoffParams<'a> {
216 pub(crate) retry_delay: Option<Duration>,
217 pub(crate) attempts: u32,
218 pub(crate) elapsed: Duration,
219 pub(crate) policy: &'a dyn TransactionRetryPolicy,
220 pub(crate) backoff: &'a ExponentialBackoff,
221 pub(crate) is_emulator: bool,
222 pub(crate) deadline: Option<Instant>,
223}
224
225pub(crate) async fn backoff_if_aborted(error: Error, params: AbortBackoffParams<'_>) -> Result<()> {
228 if !is_aborted_or_emulator_error(&error, params.is_emulator) {
229 return Err(error);
230 }
231
232 let aborted_error = match params
233 .policy
234 .on_abort(error, params.attempts, params.elapsed)
235 {
236 RetryResult::Continue(err) => err,
237 RetryResult::Exhausted(err) | RetryResult::Permanent(err) => return Err(err),
238 };
239
240 let sleep_duration = params
241 .retry_delay
242 .or_else(|| extract_retry_delay(&aborted_error))
243 .unwrap_or_else(|| {
244 params
245 .backoff
246 .on_failure(&RetryState::new(true).set_attempt_count(params.attempts))
247 });
248
249 if let Some(deadline) = params.deadline {
250 let now = Instant::now();
251 if now >= deadline || deadline.saturating_duration_since(now) < sleep_duration {
252 return Err(aborted_error);
253 }
254 }
255
256 sleep(sleep_duration).await;
257 Ok(())
258}
259
260#[cfg(test)]
261pub(crate) mod tests {
262 use super::*;
263 use crate::Error;
264 use gaxi::grpc::tonic::{Code as TonicCode, Status as TonicStatus};
265 use google_cloud_gax::error::rpc::{Code, Status};
266 use google_cloud_rpc::model::RetryInfo;
267 use std::sync::Arc;
268 use std::sync::atomic::{AtomicU32, Ordering};
269 use wkt::Any;
270
271 fn create_aborted_error(retry_delay: Option<Duration>) -> Error {
272 let mut status = Status::default()
273 .set_code(Code::Aborted)
274 .set_message("aborted");
275
276 if let Some(delay) = retry_delay {
277 let retry_info = RetryInfo::default().set_retry_delay(wkt::Duration::clamp(
278 delay.as_secs() as i64,
279 delay.subsec_nanos() as i32,
280 ));
281 status = status.set_details(vec![
282 Any::from_msg(&retry_info).expect("serializing RetryInfo to Any must succeed"),
283 ]);
284 }
285
286 Error::service(status)
287 }
288
289 pub(crate) fn create_aborted_status(retry_delay: Duration) -> TonicStatus {
290 use crate::retry_delay::{ProtoRetryInfo, RETRY_INFO_TYPE_URL};
291 use prost::Message;
292
293 let retry_info = ProtoRetryInfo {
294 retry_delay: Some(prost_types::Duration {
295 seconds: retry_delay.as_secs() as i64,
296 nanos: retry_delay.subsec_nanos() as i32,
297 }),
298 };
299
300 let mut retry_buf = vec![];
301 retry_info
302 .encode(&mut retry_buf)
303 .expect("encoding retry_info should succeed");
304
305 let status = spanner_grpc_mock::google::rpc::Status {
306 code: TonicCode::Aborted as i32,
307 message: "test transaction aborted".to_string(),
308 details: vec![prost_types::Any {
309 type_url: RETRY_INFO_TYPE_URL.to_string(),
310 value: retry_buf,
311 }],
312 };
313
314 let mut buf = vec![];
315 status
316 .encode(&mut buf)
317 .expect("encoding mock status should succeed");
318
319 TonicStatus::with_details(
320 TonicCode::Aborted,
321 "test transaction aborted",
322 bytes::Bytes::from(buf),
323 )
324 }
325
326 #[test]
327 fn auto_traits() {
328 use std::fmt::Debug;
329 static_assertions::assert_impl_all!(
330 BasicTransactionRetryPolicy: Send,
331 Sync,
332 Unpin,
333 Clone,
334 Debug,
335 Default,
336 TransactionRetryPolicy,
337 );
338 static_assertions::assert_impl_all!(
339 Box<dyn TransactionRetryPolicy>: TransactionRetryPolicy,
340 Debug,
341 Send,
342 Sync,
343 );
344 static_assertions::assert_impl_all!(
345 Arc<dyn TransactionRetryPolicy>: TransactionRetryPolicy,
346 Debug,
347 Send,
348 Sync,
349 );
350 }
351
352 #[test]
353 fn box_and_arc_dispatch_on_abort() {
354 let boxed: Box<dyn TransactionRetryPolicy> =
355 Box::new(BasicTransactionRetryPolicy::new().with_max_attempts(2));
356 let error = create_aborted_error(None);
357 let result = boxed.on_abort(error, 1, Duration::from_millis(10));
358 assert!(
359 matches!(result, RetryResult::Continue(_)),
360 "Box<dyn TransactionRetryPolicy> should forward on_abort to inner policy"
361 );
362
363 let arc: Arc<dyn TransactionRetryPolicy> =
364 Arc::new(BasicTransactionRetryPolicy::new().with_max_attempts(2));
365 let error = create_aborted_error(None);
366 let result = arc.on_abort(error, 1, Duration::from_millis(10));
367 assert!(
368 matches!(result, RetryResult::Continue(_)),
369 "Arc<dyn TransactionRetryPolicy> should forward on_abort to inner policy"
370 );
371 }
372
373 #[test]
374 fn basic_retry_policy_getters() {
375 let policy = BasicTransactionRetryPolicy::new()
376 .with_max_attempts(3)
377 .with_total_timeout(Duration::from_secs(10));
378 assert_eq!(policy.max_attempts(), 3);
379 assert_eq!(policy.total_timeout(), Duration::from_secs(10));
380 }
381
382 #[tokio::test]
383 async fn retry_aborted_success_first_try() {
384 let policy = BasicTransactionRetryPolicy::default();
385 let res = retry_aborted(
386 &policy,
387 || async { Ok::<i32, Error>(42) },
388 false,
389 )
390 .await;
391 assert_eq!(res.expect("Transaction should succeed cleanly"), 42);
392 }
393
394 #[tokio::test]
395 async fn retry_aborted_not_aborted_error() {
396 let policy = BasicTransactionRetryPolicy::default();
397 let res = retry_aborted(
398 &policy,
399 || async {
400 let status = Status::default()
401 .set_code(Code::Unavailable)
402 .set_message("server unavailable");
403 Err::<i32, Error>(Error::service(status))
404 },
405 false,
406 )
407 .await;
408
409 let err = res.unwrap_err();
410 assert_eq!(
411 err.status().expect("Error should contain a status").code,
412 Code::Unavailable
413 );
414 }
415
416 #[tokio::test(start_paused = true)]
417 async fn retry_aborted_max_attempts_exceeded() {
418 let policy = BasicTransactionRetryPolicy::new()
419 .with_max_attempts(2)
420 .with_total_timeout(Duration::from_secs(0));
421 let attempts = Arc::new(AtomicU32::new(0));
422
423 let res = retry_aborted(
424 &policy,
425 || {
426 let attempts = attempts.clone();
427 async move {
428 attempts.fetch_add(1, Ordering::SeqCst);
429 Err::<i32, Error>(create_aborted_error(None))
430 }
431 },
432 false,
433 )
434 .await;
435
436 assert!(res.is_err());
437 assert_eq!(attempts.load(Ordering::SeqCst), 2); }
439
440 #[tokio::test(start_paused = true)]
441 async fn retry_aborted_with_retry_info() {
442 let policy = BasicTransactionRetryPolicy::default();
443 let attempts = Arc::new(AtomicU32::new(0));
444
445 let start = tokio::time::Instant::now();
446 let res = retry_aborted(
447 &policy,
448 || {
449 let attempts = attempts.clone();
450 async move {
451 let current = attempts.fetch_add(1, Ordering::SeqCst);
452 if current == 0 {
453 Err::<i32, Error>(create_aborted_error(Some(Duration::from_nanos(1))))
454 } else {
455 Ok::<i32, Error>(100)
456 }
457 }
458 },
459 false,
460 )
461 .await;
462 let elapsed = start.elapsed();
463
464 assert_eq!(res.expect("Transaction should succeed after 1 retry"), 100);
465 assert_eq!(attempts.load(Ordering::SeqCst), 2);
466 assert!(
467 elapsed >= Duration::from_nanos(1),
468 "Expected elapsed time to be at least 1ns, but was {:?}",
469 elapsed
470 );
471 }
472
473 #[tokio::test(start_paused = true)]
474 async fn retry_aborted_with_default_backoff() {
475 let policy = BasicTransactionRetryPolicy::default();
476 let attempts = Arc::new(AtomicU32::new(0));
477
478 let res = retry_aborted(
479 &policy,
480 || {
481 let attempts = attempts.clone();
482 async move {
483 let current = attempts.fetch_add(1, Ordering::SeqCst);
484 if current == 0 {
485 Err::<i32, Error>(create_aborted_error(None))
486 } else {
487 Ok::<i32, Error>(100)
488 }
489 }
490 },
491 false,
492 )
493 .await;
494
495 assert_eq!(
496 res.expect("Transaction should succeed using default backoff"),
497 100
498 );
499 assert_eq!(attempts.load(Ordering::SeqCst), 2);
500 }
501
502 #[tokio::test(start_paused = true)]
503 async fn retry_aborted_total_timeout_exceeded() {
504 let policy = BasicTransactionRetryPolicy::new()
505 .with_max_attempts(0)
506 .with_total_timeout(Duration::from_secs(1));
507 let attempts = Arc::new(AtomicU32::new(0));
508
509 let res = retry_aborted(
510 &policy,
511 || {
512 let attempts = attempts.clone();
513 async move {
514 attempts.fetch_add(1, Ordering::SeqCst);
515 Err::<i32, Error>(create_aborted_error(Some(Duration::from_millis(600))))
518 }
519 },
520 false,
521 )
522 .await;
523
524 assert!(res.is_err());
525 assert_eq!(attempts.load(Ordering::SeqCst), 3); }
527
528 #[test]
529 fn is_aborted_non_status_error() {
530 let err = Error::deser("test internal error");
531 assert!(!is_aborted(&err));
532 }
533
534 #[test]
535 fn extract_retry_delay_no_status() {
536 let err = Error::deser("test internal error");
537 assert_eq!(extract_retry_delay(&err), None);
538 }
539
540 #[test]
541 fn extract_retry_delay_no_retry_info() {
542 let mut status = Status::default().set_code(Code::Aborted);
543 status = status.set_details(vec![Any::default()]);
545 let err = Error::service(status);
546 assert_eq!(extract_retry_delay(&err), None);
547 }
548
549 #[test]
550 fn extract_retry_delay_empty_retry_info() {
551 let mut status = Status::default().set_code(Code::Aborted);
552 let retry_info = RetryInfo::default(); status = status.set_details(vec![
554 Any::from_msg(&retry_info).expect("serializing RetryInfo to Any must succeed"),
555 ]);
556 let error = Error::service(status);
557 assert_eq!(extract_retry_delay(&error), None);
558 }
559
560 #[test]
561 fn extract_retry_delay_invalid_delay() {
562 let mut status = Status::default().set_code(Code::Aborted);
563 let retry_info = RetryInfo::default().set_retry_delay(wkt::Duration::clamp(
564 -10, 0,
566 ));
567 status = status.set_details(vec![
568 Any::from_msg(&retry_info).expect("serializing RetryInfo to Any must succeed"),
569 ]);
570 let error = Error::service(status);
571 assert_eq!(extract_retry_delay(&error), None);
572 }
573
574 #[tokio::test(start_paused = true)]
575 async fn retry_aborted_with_custom_policy() {
576 #[derive(Debug)]
577 struct CustomPolicy;
578 impl TransactionRetryPolicy for CustomPolicy {
579 fn on_abort(&self, error: Error, attempts: u32, _elapsed: Duration) -> RetryResult {
580 if attempts < 3 {
581 RetryResult::Continue(error)
582 } else {
583 RetryResult::Exhausted(error)
584 }
585 }
586 }
587
588 let policy = CustomPolicy;
589 let attempts = Arc::new(AtomicU32::new(0));
590
591 let res = retry_aborted(
592 &policy,
593 || {
594 let attempts = attempts.clone();
595 async move {
596 attempts.fetch_add(1, Ordering::SeqCst);
597 Err::<i32, Error>(create_aborted_error(None))
598 }
599 },
600 false,
601 )
602 .await;
603
604 assert!(res.is_err());
605 assert_eq!(attempts.load(Ordering::SeqCst), 3); }
607
608 #[tokio::test(start_paused = true)]
609 async fn retry_aborted_emulator_internal_schema_error() {
610 let policy = BasicTransactionRetryPolicy::default();
611 let attempts = Arc::new(AtomicU32::new(0));
612
613 let make_schema_error = || {
614 let status = Status::default().set_code(Code::Internal).set_message(
615 "INTERNAL: Schema generation 0 was not registered with the Action Manager",
616 );
617 Error::service(status)
618 };
619
620 let res = retry_aborted(
622 &policy,
623 || {
624 let attempts = attempts.clone();
625 let err = make_schema_error();
626 async move {
627 attempts.fetch_add(1, Ordering::SeqCst);
628 Err::<i32, Error>(err)
629 }
630 },
631 false,
632 )
633 .await;
634 assert!(res.is_err());
635 assert_eq!(attempts.load(Ordering::SeqCst), 1);
636
637 attempts.store(0, Ordering::SeqCst);
639 let res = retry_aborted(
640 &policy,
641 || {
642 let attempts = attempts.clone();
643 let err = make_schema_error();
644 async move {
645 let current = attempts.fetch_add(1, Ordering::SeqCst);
646 if current == 0 {
647 Err::<i32, Error>(err)
648 } else {
649 Ok::<i32, Error>(200)
650 }
651 }
652 },
653 true,
654 )
655 .await;
656 assert_eq!(res.expect("should succeed after retry"), 200);
657 assert_eq!(attempts.load(Ordering::SeqCst), 2);
658 }
659
660 #[tokio::test(start_paused = true)]
661 async fn backoff_if_aborted_skips_sleep_when_deadline_passed() {
662 let policy = BasicTransactionRetryPolicy::default();
663 let backoff = default_retry_backoff();
664 let deadline = Instant::now() - Duration::from_millis(100);
665 let error = create_aborted_error(Some(Duration::from_millis(500)));
666
667 let start = Instant::now();
668 let result = backoff_if_aborted(
669 error,
670 AbortBackoffParams {
671 retry_delay: None,
672 attempts: 1,
673 elapsed: Duration::from_millis(10),
674 policy: &policy,
675 backoff: &backoff,
676 is_emulator: false,
677 deadline: Some(deadline),
678 },
679 )
680 .await;
681
682 assert!(
683 result.is_err(),
684 "backoff_if_aborted should return Err when deadline has passed"
685 );
686 let elapsed = start.elapsed();
687 assert_eq!(
688 elapsed,
689 Duration::ZERO,
690 "no sleep should occur when deadline has passed"
691 );
692 }
693
694 #[tokio::test(start_paused = true)]
695 async fn backoff_if_aborted_skips_sleep_when_delay_exceeds_remaining_deadline() {
696 let policy = BasicTransactionRetryPolicy::default();
697 let backoff = default_retry_backoff();
698 let deadline = Instant::now() + Duration::from_millis(100);
699 let error = create_aborted_error(Some(Duration::from_millis(500)));
700
701 let start = Instant::now();
702 let result = backoff_if_aborted(
703 error,
704 AbortBackoffParams {
705 retry_delay: None,
706 attempts: 1,
707 elapsed: Duration::from_millis(10),
708 policy: &policy,
709 backoff: &backoff,
710 is_emulator: false,
711 deadline: Some(deadline),
712 },
713 )
714 .await;
715
716 assert!(
717 result.is_err(),
718 "backoff_if_aborted should return Err when backoff delay exceeds remaining deadline"
719 );
720 let elapsed = start.elapsed();
721 assert_eq!(
722 elapsed,
723 Duration::ZERO,
724 "no sleep should occur when backoff delay exceeds remaining deadline"
725 );
726 }
727
728 #[tokio::test(start_paused = true)]
729 async fn backoff_if_aborted_sleeps_when_delay_within_deadline() {
730 let policy = BasicTransactionRetryPolicy::default();
731 let backoff = default_retry_backoff();
732 let deadline = Instant::now() + Duration::from_millis(500);
733 let error = create_aborted_error(Some(Duration::from_millis(100)));
734
735 let start = Instant::now();
736 let result = backoff_if_aborted(
737 error,
738 AbortBackoffParams {
739 retry_delay: None,
740 attempts: 1,
741 elapsed: Duration::from_millis(10),
742 policy: &policy,
743 backoff: &backoff,
744 is_emulator: false,
745 deadline: Some(deadline),
746 },
747 )
748 .await;
749
750 assert!(
751 result.is_ok(),
752 "backoff_if_aborted should succeed when backoff delay is within deadline"
753 );
754 let elapsed = start.elapsed();
755 assert_eq!(
756 elapsed,
757 Duration::from_millis(100),
758 "expected sleep duration to match retry delay"
759 );
760 }
761
762 #[test]
763 fn is_aborted_or_emulator_error_truth_table() {
764 let aborted_status = Status::default().set_code(Code::Aborted);
765 let aborted_error = Error::service(aborted_status);
766 assert!(
767 is_aborted_or_emulator_error(&aborted_error, false),
768 "Aborted must match when is_emulator is false"
769 );
770 assert!(
771 is_aborted_or_emulator_error(&aborted_error, true),
772 "Aborted must match when is_emulator is true"
773 );
774
775 let emulator_schema_status = Status::default()
776 .set_code(Code::Internal)
777 .set_message("Schema generation error: was not registered with the Action Manager");
778 let emulator_schema_error = Error::service(emulator_schema_status);
779 assert!(
780 is_aborted_or_emulator_error(&emulator_schema_error, true),
781 "Internal emulator schema error must match when is_emulator is true"
782 );
783 assert!(
784 !is_aborted_or_emulator_error(&emulator_schema_error, false),
785 "Internal emulator schema error must NOT match when is_emulator is false"
786 );
787
788 let other_internal_status = Status::default()
789 .set_code(Code::Internal)
790 .set_message("Other unexpected internal failure");
791 let other_internal_error = Error::service(other_internal_status);
792 assert!(
793 !is_aborted_or_emulator_error(&other_internal_error, true),
794 "Generic Internal error must NOT match even on emulator"
795 );
796 assert!(
797 !is_aborted_or_emulator_error(&other_internal_error, false),
798 "Generic Internal error must NOT match on production"
799 );
800
801 let unavailable_status = Status::default().set_code(Code::Unavailable);
802 let unavailable_error = Error::service(unavailable_status);
803 assert!(
804 !is_aborted_or_emulator_error(&unavailable_error, true),
805 "Unavailable error must NOT match as aborted"
806 );
807 assert!(
808 !is_aborted_or_emulator_error(&unavailable_error, false),
809 "Unavailable error must NOT match as aborted"
810 );
811 }
812
813 #[tokio::test(start_paused = true)]
814 async fn backoff_if_aborted_prefers_params_retry_delay() {
815 let policy = BasicTransactionRetryPolicy::default();
816 let backoff = default_retry_backoff();
817 let error = create_aborted_error(Some(Duration::from_millis(50)));
819
820 let start = Instant::now();
821 let result = backoff_if_aborted(
822 error,
823 AbortBackoffParams {
824 retry_delay: Some(Duration::from_millis(250)),
825 attempts: 1,
826 elapsed: Duration::from_millis(10),
827 policy: &policy,
828 backoff: &backoff,
829 is_emulator: false,
830 deadline: None,
831 },
832 )
833 .await;
834
835 result.expect("backoff_if_aborted should succeed");
836 let elapsed = start.elapsed();
837 assert_eq!(
838 elapsed,
839 Duration::from_millis(250),
840 "expected sleep duration to match params retry_delay override"
841 );
842 }
843}