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
//! Execution drivers.
//!
//! These functions glue a [`BackoffPolicy`] to *your* notion of "do the work"
//! and "wait". They are deliberately tiny and own no I/O of their own:
//!
//! * [`retry_sync`] takes a blocking `sleep` closure.
//! * [`retry_async`] takes futures for both the operation and the sleep, and is
//! runtime-agnostic — it never mentions Tokio, async-std, or `embassy`.
//!
//! # The `ControlFlow` contract
//!
//! Your operation returns a [`ControlFlow<B, C>`]:
//!
//! * [`ControlFlow::Break`]`(value)` — **terminal**. The retry loop stops and
//! hands `value` back as `Ok(value)`. Encode *both* success and fatal errors
//! here, e.g. by returning `ControlFlow::Break(Result<T, E>)`.
//! * [`ControlFlow::Continue`]`(state)` — **transient**. The operation should be
//! retried after a backoff delay. The `state` you carry is preserved and, if
//! the policy gives up, returned inside [`RetryError::Exhausted`] so you can
//! report the last transient failure.
use ControlFlow;
use crateBackoffPolicy;
/// The reason a retry loop stopped without a terminal [`ControlFlow::Break`].
///
/// The generic parameter `C` is the [`ControlFlow::Continue`] payload type, so
/// the caller always gets back the *last* transient state observed before the
/// policy gave up.
/// Drive an operation to completion synchronously, backing off between tries.
///
/// The loop:
/// 1. runs `operation`;
/// 2. on [`ControlFlow::Break`]`(b)` returns `Ok(b)`;
/// 3. on [`ControlFlow::Continue`]`(c)` asks `policy` for the next delay;
/// 4. if there is one, calls `sleep(delay)` and loops; otherwise returns
/// `Err(`[`RetryError::Exhausted`]`(c))`.
///
/// `sleep` is *yours* — it can call `std::thread::sleep`, busy-spin a virtual
/// clock in a test, or do nothing at all.
///
/// # Example: dummy clock + no-op sleep
///
/// ```
/// use core::ops::ControlFlow;
/// use core::time::Duration;
/// use sisyphus::{retry_sync, ExponentialBackoff, PolicyExt, RetryError};
///
/// let policy = ExponentialBackoff::default().max_attempts(5);
///
/// let mut attempts = 0u32;
/// let mut virtual_clock = Duration::ZERO; // our "host" time, advanced by sleep
///
/// let result: Result<u32, RetryError<&'static str>> = retry_sync(
/// policy,
/// || {
/// attempts += 1;
/// if attempts < 3 {
/// ControlFlow::Continue("service warming up")
/// } else {
/// ControlFlow::Break(attempts) // terminal success
/// }
/// },
/// |delay| virtual_clock += delay, // "sleep" by advancing virtual time
/// );
///
/// assert_eq!(result, Ok(3));
/// assert_eq!(attempts, 3);
/// assert!(virtual_clock > Duration::ZERO);
/// ```
///
/// # Example: giving up
///
/// ```
/// use core::ops::ControlFlow;
/// use core::time::Duration;
/// use sisyphus::{retry_sync, Constant, PolicyExt, RetryError};
///
/// let policy = Constant::new(Duration::from_millis(1)).max_attempts(2);
/// let result: Result<(), RetryError<i32>> = retry_sync(
/// policy,
/// || ControlFlow::Continue(-1), // never succeeds
/// |_d| {},
/// );
/// assert_eq!(result, Err(RetryError::Exhausted(-1)));
/// ```
/// Drive an operation to completion asynchronously, backing off between tries.
///
/// Identical in spirit to [`retry_sync`], but `operation` and `sleep` each
/// produce a [`Future`]. This function is a plain `async fn` over `core`'s
/// [`Future`] and is **not** tied to any executor: plug in Tokio's
/// `tokio::time::sleep`, `embassy_time::Timer`, a WASM timer, or a virtual one.
///
/// [`Future`]: core::future::Future
///
/// # Example: runtime-free, deterministic async
///
/// This example uses a trivial hand-rolled executor and an instantly-ready
/// sleep future, proving the function needs no real runtime.
///
/// ```
/// use core::future::Future;
/// use core::ops::ControlFlow;
/// use core::pin::Pin;
/// use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
/// use core::time::Duration;
/// use sisyphus::{retry_async, ExponentialBackoff, PolicyExt, RetryError};
///
/// // A future that is ready immediately (a stand-in for a real timer).
/// async fn ready() {}
///
/// async fn run() -> Result<u32, RetryError<&'static str>> {
/// let policy = ExponentialBackoff::default().max_attempts(5);
/// let mut attempts = 0u32;
/// retry_async(
/// policy,
/// || {
/// attempts += 1;
/// async move {
/// if attempts < 3 {
/// ControlFlow::Continue("warming up")
/// } else {
/// ControlFlow::Break(attempts)
/// }
/// }
/// },
/// |_delay| ready(), // your runtime's sleep goes here
/// )
/// .await
/// }
///
/// // Minimal block_on so the doctest needs no async runtime dependency.
/// fn block_on<F: Future>(mut fut: F) -> F::Output {
/// fn noop(_: *const ()) {}
/// fn clone(_: *const ()) -> RawWaker { RawWaker::new(core::ptr::null(), &VTABLE) }
/// static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
/// let waker = unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &VTABLE)) };
/// let mut cx = Context::from_waker(&waker);
/// // Safety: `fut` is not moved after being pinned.
/// let mut fut = unsafe { Pin::new_unchecked(&mut fut) };
/// loop {
/// if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
/// return v;
/// }
/// }
/// }
///
/// assert_eq!(block_on(run()), Ok(3));
/// ```
pub async