Skip to content

Commit

Permalink
backoff: Support overriding backoff duration
Browse files Browse the repository at this point in the history
This will be used for testing.

Signed-off-by: Zixuan James Li <[email protected]>
  • Loading branch information
PIG208 authored and gnprice committed Dec 11, 2024
1 parent 410eb16 commit 31a6d9c
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions lib/api/backoff.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,25 @@ class BackoffMachine {
/// not the (random) previous wait duration itself.
static const double base = 2;

/// In debug mode, overrides the duration of the backoff wait.
///
/// Outside of debug mode, this is always `null` and the setter has no effect.
static Duration? get debugDuration {
Duration? result;
assert(() {
result = _debugDuration;
return true;
}());
return result;
}
static Duration? _debugDuration;
static set debugDuration(Duration? newValue) {
assert(() {
_debugDuration = newValue;
return true;
}());
}

/// A future that resolves after an appropriate backoff time,
/// with jitter applied to capped exponential growth.
///
Expand Down Expand Up @@ -66,8 +85,8 @@ class BackoffMachine {
Future<void> wait() async {
final bound = _minDuration(maxBound,
firstBound * pow(base, _waitsCompleted));
final duration = _maxDuration(const Duration(microseconds: 1),
bound * Random().nextDouble());
final duration = debugDuration ?? _maxDuration(const Duration(microseconds: 1),
bound * Random().nextDouble());
await Future<void>.delayed(duration);
_waitsCompleted++;
}
Expand Down

0 comments on commit 31a6d9c

Please sign in to comment.