miden_node_utils/retry.rs
1//! Shared retry/backoff helpers built on top of the [`backon`] crate.
2//!
3//! These constructors give the node a single definition of the "standard" backoff schedules so
4//! that retry behaviour stays consistent across components instead of being re-derived at each call
5//! site. Use them together with the [`Retryable`] suffix extension, e.g.
6//!
7//! ```ignore
8//! use miden_node_utils::retry::{self, Retryable};
9//! use miden_node_tracing::warn;
10//!
11//! miden_node_tracing::declare_targets! { default: "miden::process", }
12//!
13//! let value = (|| async { do_thing().await })
14//! .retry(retry::exponential(min, max))
15//! .when(|err| is_transient(err))
16//! .notify(|err, dur| {
17//! warn!(
18//! err,
19//! "retrying",
20//! retry.delay_ms = dur
21//! );
22//! })
23//! .await?;
24//! ```
25
26use std::error::Error as _;
27use std::time::Duration;
28
29pub use backon::{BackoffBuilder, Retryable, RetryableWithContext};
30use backon::{ConstantBuilder, ExponentialBuilder};
31
32// BACKOFF BUILDERS
33// ================================================================================================
34
35/// Builds an exponential backoff schedule that retries indefinitely.
36///
37/// Delays start at `min`, double on each attempt (factor `2.0`), are capped at `max`, and have
38/// jitter applied to spread out concurrent retriers.
39pub fn exponential(min: Duration, max: Duration) -> ExponentialBuilder {
40 ExponentialBuilder::default()
41 .with_min_delay(min)
42 .with_max_delay(max)
43 .with_factor(2.0)
44 .with_jitter()
45 .without_max_times()
46}
47
48/// Same as [`exponential`], but stops after `max_times` retries (i.e. `max_times + 1` total
49/// attempts).
50pub fn exponential_bounded(min: Duration, max: Duration, max_times: usize) -> ExponentialBuilder {
51 exponential(min, max).with_max_times(max_times)
52}
53
54/// Builds a constant-delay backoff schedule.
55///
56/// `max_times` bounds the number of retries; pass `None` to retry indefinitely.
57pub fn constant(delay: Duration, max_times: Option<usize>) -> ConstantBuilder {
58 let builder = ConstantBuilder::default().with_delay(delay);
59 match max_times {
60 Some(max_times) => builder.with_max_times(max_times),
61 None => builder.without_max_times(),
62 }
63}
64
65// GRPC RETRIES
66// ================================================================================================
67
68/// Retries a gRPC call with the node's standard policy for transient connection failures.
69///
70/// It is implemented for closures that start the call rather than for the call's future, since each
71/// attempt needs a fresh request future.
72pub trait RetryableGrpc<T> {
73 /// Retries the call up to ten times with exponential backoff from 100 ms to 2 s while it fails
74 /// with an error accepted by [`is_retryable_grpc_error`].
75 fn retry_transient(self) -> impl Future<Output = Result<T, tonic::Status>>;
76}
77
78impl<F, Fut, T> RetryableGrpc<T> for F
79where
80 F: FnMut() -> Fut,
81 Fut: Future<Output = Result<T, tonic::Status>>,
82{
83 fn retry_transient(self) -> impl Future<Output = Result<T, tonic::Status>> {
84 self.retry(exponential_bounded(Duration::from_millis(100), Duration::from_secs(2), 10))
85 .when(is_retryable_grpc_error)
86 }
87}
88
89/// Identifies service unavailability and local transport failures for retryable gRPC calls.
90///
91/// Tonic can report connection closures as cancelled, internal, or unknown errors. Requiring a
92/// transport error in their source chain avoids retrying application errors with those codes.
93///
94/// Client request timeouts also surface as cancelled transport errors. They are excluded so that
95/// an unresponsive server fails after one timeout instead of one per attempt.
96pub fn is_retryable_grpc_error(status: &tonic::Status) -> bool {
97 match status.code() {
98 tonic::Code::Unavailable => true,
99 tonic::Code::Cancelled | tonic::Code::Internal | tonic::Code::Unknown => {
100 let mut transport = false;
101 let mut source = status.source();
102 while let Some(error) = source {
103 if error.is::<tonic::TimeoutExpired>() {
104 return false;
105 }
106 transport |= error.is::<tonic::transport::Error>();
107 source = error.source();
108 }
109 transport
110 },
111 _ => false,
112 }
113}
114
115#[cfg(test)]
116mod tests {
117 use super::is_retryable_grpc_error;
118
119 #[test]
120 fn application_errors_are_not_connection_failures() {
121 for code in [
122 tonic::Code::Cancelled,
123 tonic::Code::Internal,
124 tonic::Code::Unknown,
125 tonic::Code::InvalidArgument,
126 tonic::Code::PermissionDenied,
127 tonic::Code::DeadlineExceeded,
128 ] {
129 assert!(
130 !is_retryable_grpc_error(&tonic::Status::new(code, "connection closed")),
131 "{code:?}"
132 );
133 }
134 assert!(is_retryable_grpc_error(&tonic::Status::unavailable("reconnecting")));
135 }
136}