1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//! Top-level `retry:` block — user-facing YAML configuration for the shared
//! retry-with-backoff machinery.
//!
//! Project-level retry policy:
//!
//! ```yaml
//! retry:
//! attempts: 10
//! delay: 10s
//! max_delay: 5m
//! ```
//!
//! Defaults are `Attempts:10, Delay:10s, MaxDelay:5m`
//! so that consumers see identical retry behaviour with the
//! same YAML.
//!
//! [`RetryConfig::to_policy`] bridges the user-facing type to
//! [`crate::retry::RetryPolicy`] which is what `retry_sync` / `retry_async`
//! consume. The conversion fixes the multiplier at 2.0 (hard-coded in
//! `RetryPolicy::delay_for`); a fixed 2× backoff is used via
//! `retry.BackOffDelay`.
//!
//! ## See also
//!
//! - [`crate::retry`] — the policy + retry primitives.
//! - [`crate::retry::is_retriable`] — companion predicate (network / 5xx /
//! 429 / explicitly-marked retriable).
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::HumanDuration;
use crate::retry::RetryPolicy;
/// User-facing retry configuration block (`retry:` at config root).
///
/// All fields are optional in YAML; missing fields fall back to the
/// defaults (10 attempts, 10s base delay, 5m cap).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct RetryConfig {
/// Total attempts (including the first). Default `10`. Values < 1 are
/// clamped up to 1 by the policy layer.
pub attempts: u32,
/// Initial delay before the second attempt. Default `10s`. Subsequent
/// delays grow exponentially (`delay × 2^(n-2)`) up to [`Self::max_delay`].
pub delay: HumanDuration,
/// Upper bound on any individual sleep between attempts. Default `5m`.
/// Without this cap, an exponential backoff with `delay=10s` would
/// stretch attempt 9 to ~42 minutes.
pub max_delay: HumanDuration,
/// Cap on TOTAL retry wall-time across all attempts of a single operation.
/// Retrying stops before a backoff sleep would push elapsed time past this
/// budget, so a long transient storm fails cleanly (with the last error,
/// resumable on an idempotent re-run) instead of running the full attempt
/// ladder. Unset (field default `None`) resolves to a 15-minute budget
/// ([`crate::retry::DEFAULT_MAX_ELAPSED`]); set it to raise or lower that
/// ceiling. A publisher honors this budget by threading
/// [`crate::Context::retry_deadline`] into its retry ladder; those whose
/// surrounding CI job has a hard timeout should keep it below that timeout.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_elapsed: Option<HumanDuration>,
}
impl RetryConfig {
/// Default attempt count (10).
pub const DEFAULT_ATTEMPTS: u32 = 10;
/// Default initial delay (10s).
pub const DEFAULT_DELAY: std::time::Duration = std::time::Duration::from_secs(10);
/// Default delay cap (5m).
pub const DEFAULT_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(5 * 60);
/// Bridge to the internal [`RetryPolicy`] consumed by
/// [`crate::retry::retry_sync`] / [`crate::retry::retry_async`].
///
/// If `max_delay < delay`, every backoff is immediately capped to
/// `max_delay`. This is parity-correct passthrough
/// but almost certainly a config mistake, so a `tracing::warn!` fires
/// once at conversion time to surface the issue in logs.
pub fn to_policy(&self) -> RetryPolicy {
if self.max_delay.duration() < self.delay.duration() {
tracing::warn!(
"retry.max_delay ({:?}) is less than retry.delay ({:?}); \
backoff will be capped at max_delay",
self.max_delay.duration(),
self.delay.duration(),
);
}
RetryPolicy {
max_attempts: self.attempts.max(1),
base_delay: self.delay.duration(),
max_delay: self.max_delay.duration(),
}
}
/// The configured total-retry-wall-time budget, if any.
pub fn max_elapsed_duration(&self) -> Option<std::time::Duration> {
self.max_elapsed.map(|h| h.duration())
}
}
impl Default for RetryConfig {
fn default() -> Self {
Self {
attempts: Self::DEFAULT_ATTEMPTS,
delay: HumanDuration(Self::DEFAULT_DELAY),
max_delay: HumanDuration(Self::DEFAULT_MAX_DELAY),
max_elapsed: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_match_goreleaser() {
let c = RetryConfig::default();
assert_eq!(c.attempts, 10);
assert_eq!(c.delay.duration(), std::time::Duration::from_secs(10));
assert_eq!(c.max_delay.duration(), std::time::Duration::from_secs(300));
}
#[test]
fn empty_yaml_yields_defaults() {
let c: RetryConfig = serde_yaml_ng::from_str("{}").unwrap();
assert_eq!(c.attempts, 10);
assert_eq!(c.delay.duration(), std::time::Duration::from_secs(10));
assert_eq!(c.max_delay.duration(), std::time::Duration::from_secs(300));
}
#[test]
fn parses_explicit_yaml() {
let yaml = r#"
attempts: 5
delay: 1s
max_delay: 30s
"#;
let c: RetryConfig = serde_yaml_ng::from_str(yaml).unwrap();
assert_eq!(c.attempts, 5);
assert_eq!(c.delay.duration(), std::time::Duration::from_secs(1));
assert_eq!(c.max_delay.duration(), std::time::Duration::from_secs(30));
}
#[test]
fn parses_compound_humantime() {
let yaml = r#"
attempts: 3
delay: 500ms
max_delay: 1h30m
"#;
let c: RetryConfig = serde_yaml_ng::from_str(yaml).unwrap();
assert_eq!(c.delay.duration(), std::time::Duration::from_millis(500));
assert_eq!(
c.max_delay.duration(),
std::time::Duration::from_secs(90 * 60),
);
}
#[test]
fn rejects_unknown_fields() {
let yaml = "bogus: 1";
let result: Result<RetryConfig, _> = serde_yaml_ng::from_str(yaml);
assert!(result.is_err(), "expected deny_unknown_fields to reject");
}
#[test]
fn to_policy_round_trip_defaults() {
let policy = RetryConfig::default().to_policy();
assert_eq!(policy.max_attempts, 10);
assert_eq!(policy.base_delay, std::time::Duration::from_secs(10));
assert_eq!(policy.max_delay, std::time::Duration::from_secs(300));
}
#[test]
fn to_policy_clamps_zero_attempts_to_one() {
let c = RetryConfig {
attempts: 0,
delay: HumanDuration(std::time::Duration::from_secs(1)),
max_delay: HumanDuration(std::time::Duration::from_secs(2)),
max_elapsed: None,
};
assert_eq!(c.to_policy().max_attempts, 1);
}
#[test]
fn to_policy_max_delay_below_delay_does_not_panic() {
// Invalid config (max_delay < delay) is parity-correct passthrough:
// every backoff is immediately capped at max_delay. The conversion
// emits a tracing::warn! but must not panic.
let c = RetryConfig {
attempts: 3,
delay: HumanDuration(std::time::Duration::from_secs(10)),
max_delay: HumanDuration(std::time::Duration::from_secs(1)),
max_elapsed: None,
};
let p = c.to_policy();
assert_eq!(p.max_attempts, 3);
assert_eq!(p.base_delay, std::time::Duration::from_secs(10));
assert_eq!(p.max_delay, std::time::Duration::from_secs(1));
}
#[test]
fn to_policy_preserves_custom_values() {
let c = RetryConfig {
attempts: 4,
delay: HumanDuration(std::time::Duration::from_millis(250)),
max_delay: HumanDuration(std::time::Duration::from_secs(7)),
max_elapsed: None,
};
let p = c.to_policy();
assert_eq!(p.max_attempts, 4);
assert_eq!(p.base_delay, std::time::Duration::from_millis(250));
assert_eq!(p.max_delay, std::time::Duration::from_secs(7));
}
#[test]
fn max_elapsed_defaults_to_none() {
let c = RetryConfig::default();
assert_eq!(c.max_elapsed, None);
assert_eq!(c.max_elapsed_duration(), None);
}
#[test]
fn max_elapsed_parses_and_other_fields_default() {
let c: RetryConfig = serde_yaml_ng::from_str("max_elapsed: 15m").unwrap();
assert_eq!(
c.max_elapsed_duration(),
Some(std::time::Duration::from_secs(15 * 60))
);
// Unspecified fields fall back to defaults.
assert_eq!(c.attempts, 10);
assert_eq!(c.delay.duration(), std::time::Duration::from_secs(10));
assert_eq!(c.max_delay.duration(), std::time::Duration::from_secs(300));
}
#[test]
fn max_elapsed_unset_leaves_accessor_none() {
let c: RetryConfig = serde_yaml_ng::from_str("attempts: 5").unwrap();
assert_eq!(c.max_elapsed_duration(), None);
}
}