Skip to content

Commit fd0aa31

Browse files
PIG208gnprice
authored andcommitted
backoff: Support overriding backoff duration
This will be used for testing. Signed-off-by: Zixuan James Li <[email protected]>
1 parent 91fd05e commit fd0aa31

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

lib/api/backoff.dart

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,25 @@ class BackoffMachine {
3636
/// not the (random) previous wait duration itself.
3737
static const double base = 2;
3838

39+
/// In debug mode, overrides the duration of the backoff wait.
40+
///
41+
/// Outside of debug mode, this is always `null` and the setter has no effect.
42+
static Duration? get debugDuration {
43+
Duration? result;
44+
assert(() {
45+
result = _debugDuration;
46+
return true;
47+
}());
48+
return result;
49+
}
50+
static Duration? _debugDuration;
51+
static set debugDuration(Duration? newValue) {
52+
assert(() {
53+
_debugDuration = newValue;
54+
return true;
55+
}());
56+
}
57+
3958
/// A future that resolves after an appropriate backoff time,
4059
/// with jitter applied to capped exponential growth.
4160
///
@@ -66,8 +85,8 @@ class BackoffMachine {
6685
Future<void> wait() async {
6786
final bound = _minDuration(maxBound,
6887
firstBound * pow(base, _waitsCompleted));
69-
final duration = _maxDuration(const Duration(microseconds: 1),
70-
bound * Random().nextDouble());
88+
final duration = debugDuration ?? _maxDuration(const Duration(microseconds: 1),
89+
bound * Random().nextDouble());
7190
await Future<void>.delayed(duration);
7291
_waitsCompleted++;
7392
}

0 commit comments

Comments
 (0)