nexus-async-rt 0.3.3

Single-threaded async executor with pre-allocated task storage
Documentation
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Exponential backoff with optional jitter and deadline.
//!
//! A small struct that tracks retry state. The user controls the loop —
//! no closures, no future wrapping, no magic.
//!
//! ```ignore
//! use nexus_async_rt::Backoff;
//! use std::time::{Duration, Instant};
//!
//! let mut backoff = Backoff::builder()
//!     .initial(Duration::from_millis(10))
//!     .max_delay(Duration::from_secs(5))
//!     .max_retries(10)
//!     .deadline(Instant::now() + Duration::from_secs(30))
//!     .jitter(0.25)
//!     .build();
//!
//! loop {
//!     match try_connect().await {
//!         Ok(conn) => break conn,
//!         Err(e) => backoff.wait(e).await?,
//!     }
//! }
//! ```

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

/// Global counter for per-instance jitter seed.
static BACKOFF_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Retries exhausted — either max retries reached or deadline passed.
///
/// Wraps the last error from the failed operation.
#[derive(Debug)]
pub struct Exhausted<E>(pub E);

impl<E: std::fmt::Display> std::fmt::Display for Exhausted<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "backoff exhausted: {}", self.0)
    }
}

impl<E: std::fmt::Debug + std::fmt::Display> std::error::Error for Exhausted<E> {}

/// Exponential backoff with optional jitter and deadline.
///
/// Tracks current delay, retry count, and optional wall-clock deadline.
/// Call `.wait(err).await` to check exhaustion, sleep if retries remain,
/// and advance state. Returns `Err(Exhausted(err))` when done.
pub struct Backoff {
    initial: Duration,
    current: Duration,
    max_delay: Duration,
    max_retries: Option<u32>,
    deadline: Option<Instant>,
    retries: u32,
    jitter: f64,
    /// Per-instance seed so identically-configured instances produce
    /// different jitter sequences (mitigates thundering herd).
    seed: u64,
}

impl Backoff {
    /// Create a builder.
    #[must_use]
    pub fn builder() -> BackoffBuilder {
        BackoffBuilder::new()
    }

    /// Check exhaustion, sleep for the current delay, then advance.
    ///
    /// Returns `Ok(())` if retries remain (caller should loop).
    /// Returns `Err(Exhausted(err))` if max retries or deadline
    /// reached — the caller should escalate or fail over.
    ///
    /// If a deadline is set, the sleep is capped to not exceed it.
    ///
    /// # Panics
    ///
    /// Panics if called outside [`Runtime::block_on`](crate::Runtime::block_on).
    pub async fn wait<E>(&mut self, err: E) -> Result<(), Exhausted<E>> {
        if self.is_exhausted() {
            return Err(Exhausted(err));
        }

        let delay = self.effective_delay();

        // Re-check: deadline may have been reached while computing delay.
        if delay.is_zero() && self.deadline.is_some_and(|d| Instant::now() >= d) {
            return Err(Exhausted(err));
        }

        crate::context::sleep(delay).await;
        self.advance();
        Ok(())
    }

    /// Advance the backoff state without sleeping.
    ///
    /// Useful when the caller manages timing externally.
    pub fn advance(&mut self) {
        self.retries += 1;
        self.current = self
            .current
            .checked_mul(2)
            .map_or(self.max_delay, |next| next.min(self.max_delay));
    }

    /// Whether retries are exhausted (max retries or deadline).
    ///
    /// Returns `false` if neither limit is set.
    pub fn is_exhausted(&self) -> bool {
        if self.max_retries.is_some_and(|max| self.retries >= max) {
            return true;
        }
        if self.deadline.is_some_and(|d| Instant::now() >= d) {
            return true;
        }
        false
    }

    /// Current retry count.
    pub fn retries(&self) -> u32 {
        self.retries
    }

    /// The next delay (before jitter).
    pub fn current_delay(&self) -> Duration {
        self.current
    }

    /// Time remaining until deadline, if one is set.
    pub fn remaining(&self) -> Option<Duration> {
        self.deadline
            .map(|d| d.saturating_duration_since(Instant::now()))
    }

    /// Reset delay and retry count to initial state.
    ///
    /// The deadline is **not** reset — it is wall-clock absolute.
    pub fn reset(&mut self) {
        self.current = self.initial;
        self.retries = 0;
    }

    /// Compute the effective delay: jittered, then capped to deadline.
    fn effective_delay(&self) -> Duration {
        let delay = self.jittered_delay();
        self.deadline.map_or(delay, |d| {
            delay.min(d.saturating_duration_since(Instant::now()))
        })
    }

    /// Compute the jittered delay for the current step.
    fn jittered_delay(&self) -> Duration {
        if self.jitter == 0.0 {
            return self.current;
        }

        // Jitter: multiply by (1.0 ± jitter).
        // Per-instance seed mixed with retry count so identically-configured
        // instances produce different sequences (mitigates thundering herd).
        let hash = {
            let a = self.retries as u64;
            let b = self.current.as_nanos() as u64;
            a.wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(b)
                .wrapping_add(self.seed)
        };
        // Map to [-1.0, 1.0]
        let normalized = (hash as f64 / u64::MAX as f64).mul_add(2.0, -1.0);
        let factor = self.jitter.mul_add(normalized, 1.0);
        let jittered_nanos = self.current.as_nanos() as f64 * factor;
        Duration::from_nanos(jittered_nanos.max(0.0) as u64)
    }
}

impl std::fmt::Debug for Backoff {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Backoff")
            .field("current", &self.current)
            .field("retries", &self.retries)
            .field("max_delay", &self.max_delay)
            .field("max_retries", &self.max_retries)
            .field("deadline", &self.deadline)
            .field("jitter", &self.jitter)
            .finish()
    }
}

// =============================================================================
// Builder
// =============================================================================

/// Builder for [`Backoff`].
pub struct BackoffBuilder {
    initial: Duration,
    max_delay: Duration,
    max_retries: Option<u32>,
    deadline: Option<Instant>,
    jitter: f64,
}

impl BackoffBuilder {
    #[must_use]
    fn new() -> Self {
        Self {
            initial: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            max_retries: None,
            deadline: None,
            jitter: 0.0,
        }
    }

    /// Initial delay. Default: 100ms.
    #[must_use]
    pub fn initial(mut self, d: Duration) -> Self {
        self.initial = d;
        self
    }

    /// Maximum delay cap. Default: 30s.
    #[must_use]
    pub fn max_delay(mut self, d: Duration) -> Self {
        self.max_delay = d;
        self
    }

    /// Maximum number of retries. Default: unlimited.
    #[must_use]
    pub fn max_retries(mut self, n: u32) -> Self {
        self.max_retries = Some(n);
        self
    }

    /// Wall-clock deadline. After this instant, [`Backoff::wait`] returns
    /// `Err(Exhausted)`. Sleep durations are capped to not exceed it.
    ///
    /// Default: no deadline.
    #[must_use]
    pub fn deadline(mut self, deadline: Instant) -> Self {
        self.deadline = Some(deadline);
        self
    }

    /// Jitter factor (0.0 to 1.0). Default: 0.0 (no jitter).
    ///
    /// Each delay is randomly scaled by `1.0 ± jitter`. For example,
    /// `jitter(0.25)` means a 100ms delay becomes 75ms–125ms.
    #[must_use]
    pub fn jitter(mut self, factor: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&factor),
            "jitter must be between 0.0 and 1.0, got {factor}"
        );
        self.jitter = factor;
        self
    }

    /// Build the backoff.
    ///
    /// # Panics
    ///
    /// Panics if `initial` exceeds `max_delay`.
    #[must_use]
    pub fn build(self) -> Backoff {
        assert!(
            self.initial <= self.max_delay,
            "initial delay ({:?}) must not exceed max_delay ({:?})",
            self.initial,
            self.max_delay,
        );
        Backoff {
            initial: self.initial,
            current: self.initial,
            max_delay: self.max_delay,
            max_retries: self.max_retries,
            deadline: self.deadline,
            retries: 0,
            jitter: self.jitter,
            seed: BACKOFF_COUNTER.fetch_add(1, Ordering::Relaxed),
        }
    }
}

impl Default for BackoffBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn doubles_each_step() {
        let mut b = Backoff::builder()
            .initial(Duration::from_millis(10))
            .max_delay(Duration::from_secs(10))
            .build();

        assert_eq!(b.current_delay(), Duration::from_millis(10));
        b.advance();
        assert_eq!(b.current_delay(), Duration::from_millis(20));
        b.advance();
        assert_eq!(b.current_delay(), Duration::from_millis(40));
        b.advance();
        assert_eq!(b.current_delay(), Duration::from_millis(80));
    }

    #[test]
    fn caps_at_max() {
        let mut b = Backoff::builder()
            .initial(Duration::from_secs(1))
            .max_delay(Duration::from_secs(5))
            .build();

        b.advance(); // 2s
        b.advance(); // 4s
        b.advance(); // 5s (capped)
        assert_eq!(b.current_delay(), Duration::from_secs(5));
        b.advance(); // still 5s
        assert_eq!(b.current_delay(), Duration::from_secs(5));
    }

    #[test]
    fn exhausted_after_max_retries() {
        let mut b = Backoff::builder()
            .initial(Duration::from_millis(1))
            .max_retries(3)
            .build();

        assert!(!b.is_exhausted());
        b.advance();
        assert!(!b.is_exhausted());
        b.advance();
        assert!(!b.is_exhausted());
        b.advance();
        assert!(b.is_exhausted());
    }

    #[test]
    fn unlimited_retries() {
        let mut b = Backoff::builder()
            .initial(Duration::from_millis(1))
            .max_delay(Duration::from_millis(1))
            .build();

        for _ in 0..10_000 {
            b.advance();
        }
        assert!(!b.is_exhausted());
        assert_eq!(b.retries(), 10_000);
    }

    #[test]
    fn reset_restores_initial() {
        let mut b = Backoff::builder()
            .initial(Duration::from_millis(10))
            .max_retries(5)
            .build();

        b.advance();
        b.advance();
        b.advance();
        assert_eq!(b.retries(), 3);
        assert_eq!(b.current_delay(), Duration::from_millis(80));

        b.reset();
        assert_eq!(b.retries(), 0);
        assert_eq!(b.current_delay(), Duration::from_millis(10));
    }

    #[test]
    fn jitter_stays_in_range() {
        let mut b = Backoff::builder()
            .initial(Duration::from_millis(100))
            .max_delay(Duration::from_secs(10))
            .jitter(0.5)
            .build();

        // Run several iterations — jittered delay should be within ±50%.
        // Allow 1ns tolerance for float→integer truncation.
        for _ in 0..20 {
            let delay = b.jittered_delay();
            let base = b.current_delay().as_nanos();
            let actual = delay.as_nanos();
            let lo = (base as f64 * 0.5) as u128;
            let hi = (base as f64 * 1.5) as u128 + 1;
            assert!(
                actual >= lo && actual <= hi,
                "delay {actual}ns out of range [{lo}, {hi}] for base {base}ns"
            );
            b.advance();
        }
    }

    #[test]
    #[should_panic(expected = "jitter must be between")]
    fn jitter_out_of_range_panics() {
        let _ = Backoff::builder().jitter(1.5).build();
    }

    #[test]
    #[should_panic(expected = "initial delay")]
    fn initial_exceeds_max_delay_panics() {
        Backoff::builder()
            .initial(Duration::from_secs(60))
            .max_delay(Duration::from_secs(5))
            .build();
    }

    #[test]
    fn default_values() {
        let b = Backoff::builder().build();
        assert_eq!(b.current_delay(), Duration::from_millis(100));
        assert_eq!(b.max_delay, Duration::from_secs(30));
        assert!(!b.is_exhausted());
        assert!(b.remaining().is_none());
    }

    #[test]
    fn deadline_exhausts() {
        // Deadline in the past — immediately exhausted.
        let b = Backoff::builder()
            .initial(Duration::from_millis(10))
            .deadline(Instant::now() - Duration::from_secs(1))
            .build();

        assert!(b.is_exhausted());
    }

    #[test]
    fn deadline_remaining() {
        let deadline = Instant::now() + Duration::from_secs(60);
        let b = Backoff::builder()
            .initial(Duration::from_millis(10))
            .deadline(deadline)
            .build();

        let remaining = b.remaining().expect("should have remaining");
        assert!(remaining > Duration::ZERO);
        assert!(remaining <= Duration::from_secs(60));
    }

    #[test]
    fn effective_delay_capped_by_deadline() {
        // Deadline 50ms from now, but current delay is 10s.
        let b = Backoff::builder()
            .initial(Duration::from_millis(50))
            .max_delay(Duration::from_secs(10))
            .deadline(Instant::now() + Duration::from_millis(50))
            .build();

        let delay = b.effective_delay();
        // Should be capped to ~50ms, not 10s.
        assert!(delay <= Duration::from_millis(55));
    }

    #[test]
    fn reset_does_not_clear_deadline() {
        let deadline = Instant::now() + Duration::from_secs(30);
        let mut b = Backoff::builder()
            .initial(Duration::from_millis(10))
            .deadline(deadline)
            .build();

        b.advance();
        b.advance();
        b.reset();

        // Deadline still set.
        assert!(b.remaining().is_some());
        assert_eq!(b.retries(), 0);
        assert_eq!(b.current_delay(), Duration::from_millis(10));
    }

    #[test]
    fn advance_does_not_overflow_large_delay() {
        let mut b = Backoff::builder()
            .initial(Duration::from_secs(u64::MAX / 4))
            .max_delay(Duration::from_secs(u64::MAX / 4))
            .build();

        // Should not panic — checked_mul saturates to max_delay.
        b.advance();
        assert_eq!(b.current_delay(), Duration::from_secs(u64::MAX / 4));
    }

    #[test]
    fn different_instances_different_jitter() {
        let a = Backoff::builder()
            .initial(Duration::from_millis(100))
            .jitter(0.5)
            .build();
        let b = Backoff::builder()
            .initial(Duration::from_millis(100))
            .jitter(0.5)
            .build();

        // Different seeds → different jitter values.
        assert_ne!(a.seed, b.seed);
    }
}