Skip to main content

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