From 31a6d9cd065706dc2f04dc4e9336d93addd70b21 Mon Sep 17 00:00:00 2001 From: Zixuan James Li Date: Tue, 10 Dec 2024 16:32:15 -0500 Subject: [PATCH] backoff: Support overriding backoff duration This will be used for testing. Signed-off-by: Zixuan James Li --- lib/api/backoff.dart | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/api/backoff.dart b/lib/api/backoff.dart index f81630529c..cfbba60f96 100644 --- a/lib/api/backoff.dart +++ b/lib/api/backoff.dart @@ -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. /// @@ -66,8 +85,8 @@ class BackoffMachine { Future 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.delayed(duration); _waitsCompleted++; }