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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
//! Retry and polling for Rust — with composable strategies, policy reuse, and
//! first-class support for polling workflows where `Ok(_)` doesn't always mean
//! "done."
//!
//! Most retry libraries handle the simple case well: call a function, retry on
//! error, back off. `relentless` handles that too, but it also handles the cases
//! those libraries make awkward:
//!
//! - **Polling**, where `Ok("pending")` means "keep going" and you need
//! [`.until(predicate)`](SyncRetryBuilder::until) rather than just retrying errors.
//! - **Policy reuse**, where a single [`RetryPolicy`] captures your retry rules and
//! gets shared across multiple call sites — no duplicated builder chains.
//! - **Strategy composition**, where
//! `wait::fixed(50ms) + wait::exponential(100ms)` and
//! `stop::attempts(5) | stop::elapsed(2s)` express complex behavior in one line.
//! - **Hooks and stats**, where you observe the retry lifecycle (logging, metrics)
//! without restructuring your retry logic.
//!
//! All of this works in sync and async code, across `std`, `no_std`, and `wasm`
//! targets.
//!
//! # Quick start
//!
//! The [`RetryExt`] extension trait is the fastest way to add retries. Defaults:
//! 3 attempts, exponential backoff from 100 ms, retry on any `Err`.
//!
//! ```
//! use relentless::RetryExt;
//!
//! let result = (|| Ok::<_, &str>(42)).retry().sleep(|_| {}).call();
//! assert_eq!(result.unwrap(), 42);
//! ```
//!
//! The [`retry`] and [`retry_async`] free functions are equivalent, with the
//! added ability to capture retry loop state via the [`RetryState`] argument:
//!
//! ```
//! use relentless::retry;
//!
//! let result = retry(|state| {
//! if state.attempt >= 2 { Ok(state.attempt) } else { Err("not yet") }
//! })
//! .sleep(|_| {})
//! .call();
//!
//! assert_eq!(result.unwrap(), 2);
//! ```
//!
//! # Customizing retry behavior
//!
//! Builder methods control **when** to retry, **how long** to wait, and **when**
//! to stop:
//!
//! ```
//! use core::time::Duration;
//! use relentless::{Wait, retry, predicate, stop, wait};
//!
//! let result = retry(|_| Err::<(), &str>("boom"))
//! .when(predicate::error(|e: &&str| *e == "boom"))
//! .wait(
//! wait::exponential(Duration::from_millis(100))
//! .full_jitter()
//! .cap(Duration::from_secs(5)),
//! )
//! .stop(stop::attempts(3))
//! .sleep(|_| {})
//! .call();
//!
//! assert!(result.is_err());
//! ```
//!
//! To bound the **total** wall-clock time across all attempts and sleeps, add
//! [`.timeout(dur)`](SyncRetryBuilder::timeout). It OR-folds an elapsed deadline
//! into the stop strategy and clamps each inter-attempt sleep to the remaining
//! budget; it does not interrupt an attempt already running. See [Cancellation]
//! for the runtime-agnostic deadline pattern.
//!
//! [Cancellation]: #cancellation
//!
//! # Policy reuse
//!
//! [`RetryPolicy`] captures retry rules once. Compose wait strategies with `+`
//! and stop strategies with `|` or `&`.
//!
//! ```
//! use core::time::Duration;
//! use relentless::{RetryPolicy, stop, wait};
//!
//! let policy = RetryPolicy::new()
//! .wait(
//! wait::fixed(Duration::from_millis(50))
//! + wait::exponential(Duration::from_millis(100)),
//! )
//! .stop(stop::attempts(5) | stop::elapsed(Duration::from_secs(30)));
//!
//! // Same policy, different operations.
//! let a = policy.retry(|_| Ok::<_, &str>("a")).sleep(|_| {}).call();
//! let b = policy.retry(|_| Ok::<_, &str>("b")).sleep(|_| {}).call();
//!
//! assert_eq!(a.unwrap(), "a");
//! assert_eq!(b.unwrap(), "b");
//! ```
//!
//! # Polling for a condition
//!
//! Use [`.until(predicate)`](SyncRetryBuilder::until) to keep retrying until a
//! success condition is met. Unlike [`.when()`](SyncRetryBuilder::when), which
//! retries on matching outcomes, `.until()` retries on everything *except* the
//! matching outcome.
//!
//! ```
//! use relentless::{RetryPolicy, predicate};
//!
//! #[derive(Debug, PartialEq)]
//! enum Status { Pending, Done }
//!
//! let mut count = 0;
//! let result = RetryPolicy::new()
//! .until(predicate::ok(|s: &Status| *s == Status::Done))
//! .retry(|_| {
//! count += 1;
//! Ok::<_, &str>(if count >= 2 { Status::Done } else { Status::Pending })
//! })
//! .sleep(|_| {})
//! .call();
//!
//! assert_eq!(result.unwrap(), Status::Done);
//! ```
//!
//! # Hooks and stats
//!
//! ```
//! use relentless::retry;
//!
//! let (result, stats) = retry(|_| Ok::<_, &str>("done"))
//! .before_attempt(|state| {
//! if state.attempt > 1 {
//! println!("retrying (attempt {})", state.attempt);
//! }
//! })
//! .after_attempt(|state| {
//! if let Err(e) = state.outcome {
//! eprintln!("attempt {} failed: {e}", state.attempt);
//! }
//! })
//! .sleep(|_| {})
//! .with_stats()
//! .call();
//!
//! println!("attempts: {}, total wait: {:?}", stats.attempts, stats.total_wait);
//! ```
//!
//! # Error handling
//!
//! The retry loop returns `Ok(T)` on success. On failure it returns
//! [`RetryError`], which distinguishes between exhaustion (stop strategy fired)
//! and rejection (predicate deemed the error non-retryable):
//!
//! ```
//! use relentless::{retry, RetryError};
//!
//! match retry(|_| Err::<(), &str>("boom")).sleep(|_| {}).call() {
//! Ok(val) => println!("success: {val:?}"),
//! Err(RetryError::Exhausted { last }) => {
//! println!("gave up: {last:?}");
//! }
//! Err(RetryError::Rejected { last }) => {
//! println!("non-retryable: {last}");
//! }
//! // `RetryError` is `#[non_exhaustive]`; match future variants here.
//! Err(_) => {}
//! }
//! ```
//!
//! # Cancellation
//!
//! By design, the retry engine has no built-in cancellation primitive — it
//! composes with the cancellation your environment already provides, observed at
//! attempt boundaries (a running operation or sleep is never interrupted
//! mid-flight).
//!
//! - **Async:** the future returned by [`.call()`](AsyncRetryExec::call) is
//! cancel-safe — drop it (e.g. via `tokio::time::timeout` or `select!`) to
//! stop at the next `.await`. Note `on_exit` does **not** fire on drop; use
//! `Drop` on your own types for guaranteed cleanup. See the `async-cancel`
//! example.
//! - **Sync:** bound the wall-clock with [`.timeout()`](SyncRetryBuilder::timeout),
//! or check a flag inside the operation and return a sentinel error. With the
//! default `any_error()` predicate that sentinel is *retried*, so make it
//! non-retryable via [`.when()`](SyncRetryBuilder::when) (it then terminates as
//! [`RetryError::Rejected`]). See the `sync-cancel` example.
//!
//! # Custom wait strategies
//!
//! Implement [`Wait`] to build your own wait strategies. All combinators
//! ([`.cap()`](Wait::cap), [`.full_jitter()`](Wait::full_jitter),
//! [`.chain()`](Wait::chain), `+`) work on any `Wait` implementor.
//!
//! ```
//! use core::time::Duration;
//! use relentless::{RetryState, Wait, wait};
//!
//! struct CustomWait(Duration);
//!
//! impl Wait for CustomWait {
//! fn next_wait(&self, _state: &RetryState) -> Duration {
//! self.0
//! }
//! }
//!
//! let strategy = CustomWait(Duration::from_millis(20))
//! .cap(Duration::from_millis(15))
//! .chain(wait::fixed(Duration::from_millis(50)), 2);
//!
//! let state = RetryState::new(3, None);
//! assert_eq!(strategy.next_wait(&state), Duration::from_millis(50));
//! ```
//!
//! # Feature flags
//!
//! | Flag | Purpose |
//! |------|---------|
//! | `std` (default) | `std::thread::sleep` fallback, `Instant` elapsed clock, `std::error::Error` on `RetryError` |
//! | `alloc` | Boxed policies, closure elapsed clocks, multiple hooks per point |
//! | `tokio-sleep` | `sleep::tokio()` async sleep adapter |
//! | `embassy-sleep` | `sleep::embassy()` async sleep adapter |
//! | `gloo-timers-sleep` | `sleep::gloo()` async sleep adapter (wasm32) |
//! | `futures-timer-sleep` | `sleep::futures_timer()` async sleep adapter |
//!
//! Async retry does not require `alloc`. Sync `std` builds automatically fall
//! back to `std::thread::sleep`, so `.sleep(...)` is optional.
// Compile-test README code examples as doctests.
// Gated on `tokio-sleep` because the async example uses `sleep::tokio()`.
extern crate alloc;
extern crate std;
/// Async sleep abstractions used by the retry engine between attempts.
pub use ;
pub use RetryPolicy;
pub use ;
pub use ;
pub use ;
pub use ;
// Sleeper sentinels for the "no sleep configured" type-state. Exported so the
// return types of `retry`/`retry_async` (which mention them) are nameable.
pub use ;
pub use Predicate;
pub use Sleeper;
pub use ;
pub use ;
pub use Stop;
pub use Wait;
/// Commonly used traits, glob-imported to enable the builder DSL.
///
/// The combinator methods (`.cap()`, `.full_jitter()`, `.chain()` on [`Wait`];
/// `.or()`/`.and()` on [`Stop`] and [`Predicate`]) and the closure extensions
/// (`.retry()` on [`RetryExt`], `.retry_async()` on [`AsyncRetryExt`]) are trait
/// methods, so the trait must be in scope to call them. Glob-import this module
/// to bring them all in at once:
///
/// ```
/// use relentless::prelude::*;
/// use relentless::wait;
/// use core::time::Duration;
///
/// // `.full_jitter()` and `.cap()` resolve without naming `Wait`.
/// let _ = wait::exponential(Duration::from_millis(100))
/// .full_jitter()
/// .cap(Duration::from_secs(5));
/// ```
///
/// Strategy constructors (`wait::exponential`, `stop::attempts`, …) are *not*
/// re-exported here; import them explicitly by name.
/// Returns a [`SyncRetryBuilder`] with default policy: `attempts(3)`,
/// `exponential(100ms)`, `any_error()`.
///
/// # Examples
///
/// ```
/// use relentless::{retry, stop};
///
/// let result = retry(|_| Ok::<u32, &str>(42))
/// .stop(stop::attempts(1))
/// .sleep(|_| {})
/// .call();
/// assert_eq!(result.unwrap(), 42);
/// ```
/// Returns an [`AsyncRetryBuilder`] with default policy: `attempts(3)`,
/// `exponential(100ms)`, `any_error()`.
///
/// # Examples
///
/// ```
/// use core::time::Duration;
/// use relentless::retry_async;
///
/// # async fn doc() {
/// // Async terminates with `.call().await` (mirroring the sync `.call()`).
/// let result = retry_async(|_| async { Ok::<u32, &str>(42) })
/// .sleep(|_dur: Duration| async {})
/// .call()
/// .await;
/// assert_eq!(result.unwrap(), 42);
/// # }
/// ```