FSTExponentialBackoff.mm 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "Firestore/Source/Remote/FSTExponentialBackoff.h"
  17. #include <random>
  18. #import "Firestore/Source/Util/FSTClasses.h"
  19. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  20. #include "Firestore/core/src/firebase/firestore/util/log.h"
  21. #include "Firestore/core/src/firebase/firestore/util/secure_random.h"
  22. using firebase::firestore::util::SecureRandom;
  23. @interface FSTExponentialBackoff ()
  24. @property(nonatomic, strong) FSTDispatchQueue *dispatchQueue;
  25. @property(nonatomic, assign, readonly) FSTTimerID timerID;
  26. @property(nonatomic) double backoffFactor;
  27. @property(nonatomic) NSTimeInterval initialDelay;
  28. @property(nonatomic) NSTimeInterval maxDelay;
  29. @property(nonatomic) NSTimeInterval currentBase;
  30. @property(nonatomic) NSTimeInterval lastAttemptTime;
  31. @property(nonatomic, strong, nullable) FSTDelayedCallback *timerCallback;
  32. @end
  33. @implementation FSTExponentialBackoff {
  34. SecureRandom _secureRandom;
  35. }
  36. - (instancetype)initWithDispatchQueue:(FSTDispatchQueue *)dispatchQueue
  37. timerID:(FSTTimerID)timerID
  38. initialDelay:(NSTimeInterval)initialDelay
  39. backoffFactor:(double)backoffFactor
  40. maxDelay:(NSTimeInterval)maxDelay {
  41. if (self = [super init]) {
  42. _dispatchQueue = dispatchQueue;
  43. _timerID = timerID;
  44. _initialDelay = initialDelay;
  45. _backoffFactor = backoffFactor;
  46. _maxDelay = maxDelay;
  47. _lastAttemptTime = [[NSDate date] timeIntervalSince1970];
  48. [self reset];
  49. }
  50. return self;
  51. }
  52. - (void)reset {
  53. _currentBase = 0;
  54. }
  55. - (void)resetToMax {
  56. _currentBase = _maxDelay;
  57. }
  58. - (void)backoffAndRunBlock:(void (^)(void))block {
  59. [self cancel];
  60. // First schedule the block using the current base (which may be 0 and should be honored as such).
  61. NSTimeInterval desiredDelayWithJitter = _currentBase + [self jitterDelay];
  62. // Guard against lastAttemptTime being in the future due to a clock change.
  63. NSTimeInterval delaySoFar = MAX(0, [[NSDate date] timeIntervalSince1970] - self.lastAttemptTime);
  64. // Guard against the backoff delay already being past.
  65. NSTimeInterval remainingDelay = MAX(0, desiredDelayWithJitter - delaySoFar);
  66. if (_currentBase > 0) {
  67. LOG_DEBUG(
  68. "Backing off for %s seconds ("
  69. "base delay: %s seconds, "
  70. "delay with jitter: %s seconds, "
  71. "last attempt: %s seconds ago)",
  72. remainingDelay, _currentBase, desiredDelayWithJitter, delaySoFar);
  73. }
  74. FSTWeakify(self);
  75. self.timerCallback = [self.dispatchQueue
  76. dispatchAfterDelay:remainingDelay
  77. timerID:self.timerID
  78. block:^{
  79. FSTStrongify(self);
  80. if (self) {
  81. self.lastAttemptTime = [[NSDate date] timeIntervalSince1970];
  82. block();
  83. }
  84. }];
  85. // Apply backoff factor to determine next delay and ensure it is within bounds.
  86. _currentBase *= _backoffFactor;
  87. if (_currentBase < _initialDelay) {
  88. _currentBase = _initialDelay;
  89. }
  90. if (_currentBase > _maxDelay) {
  91. _currentBase = _maxDelay;
  92. }
  93. }
  94. - (void)cancel {
  95. if (self.timerCallback) {
  96. [self.timerCallback cancel];
  97. self.timerCallback = nil;
  98. }
  99. }
  100. /** Returns a random value in the range [-currentBase/2, currentBase/2] */
  101. - (NSTimeInterval)jitterDelay {
  102. std::uniform_real_distribution<double> dist;
  103. double random_double = dist(_secureRandom);
  104. return (random_double - 0.5) * _currentBase;
  105. }
  106. @end