FSTOnlineStateTracker.mm 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. /*
  2. * Copyright 2018 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/FSTOnlineStateTracker.h"
  17. #include <chrono> // NOLINT(build/c++11)
  18. #import "Firestore/Source/Remote/FSTRemoteStore.h"
  19. #include "Firestore/core/src/firebase/firestore/util/executor.h"
  20. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  21. #include "Firestore/core/src/firebase/firestore/util/log.h"
  22. namespace chr = std::chrono;
  23. using firebase::firestore::model::OnlineState;
  24. using firebase::firestore::util::AsyncQueue;
  25. using firebase::firestore::util::DelayedOperation;
  26. using firebase::firestore::util::TimerId;
  27. NS_ASSUME_NONNULL_BEGIN
  28. namespace {
  29. // To deal with transient failures, we allow multiple stream attempts before giving up and
  30. // transitioning from OnlineState Unknown to Offline.
  31. // TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394. @jdimond thinks that
  32. // bug is sufficiently fixed so that we can set this back to 1. If that works okay, we could
  33. // potentially remove this logic entirely.
  34. const int kMaxWatchStreamFailures = 1;
  35. // To deal with stream attempts that don't succeed or fail in a timely manner, we have a
  36. // timeout for OnlineState to reach Online or Offline. If the timeout is reached, we transition
  37. // to Offline rather than waiting indefinitely.
  38. const AsyncQueue::Milliseconds kOnlineStateTimeout = chr::seconds(10);
  39. } // namespace
  40. @interface FSTOnlineStateTracker ()
  41. /** The current OnlineState. */
  42. @property(nonatomic, assign) OnlineState state;
  43. /**
  44. * A count of consecutive failures to open the stream. If it reaches the maximum defined by
  45. * kMaxWatchStreamFailures, we'll revert to OnlineState::Offline.
  46. */
  47. @property(nonatomic, assign) int watchStreamFailures;
  48. /**
  49. * Whether the client should log a warning message if it fails to connect to the backend
  50. * (initially YES, cleared after a successful stream, or if we've logged the message already).
  51. */
  52. @property(nonatomic, assign) BOOL shouldWarnClientIsOffline;
  53. @end
  54. @implementation FSTOnlineStateTracker {
  55. /**
  56. * A timer that elapses after kOnlineStateTimeout, at which point we transition from OnlineState
  57. * Unknown to Offline without waiting for the stream to actually fail (kMaxWatchStreamFailures
  58. * times).
  59. */
  60. DelayedOperation _onlineStateTimer;
  61. /** The worker queue to use for running timers (and to call onlineStateDelegate). */
  62. AsyncQueue *_workerQueue;
  63. }
  64. - (instancetype)initWithWorkerQueue:(AsyncQueue *)workerQueue {
  65. if (self = [super init]) {
  66. _workerQueue = workerQueue;
  67. _state = OnlineState::Unknown;
  68. _shouldWarnClientIsOffline = YES;
  69. }
  70. return self;
  71. }
  72. - (void)handleWatchStreamStart {
  73. if (self.watchStreamFailures == 0) {
  74. [self setAndBroadcastState:OnlineState::Unknown];
  75. HARD_ASSERT(!_onlineStateTimer, "_onlineStateTimer shouldn't be started yet");
  76. _onlineStateTimer =
  77. _workerQueue->EnqueueAfterDelay(kOnlineStateTimeout, TimerId::OnlineStateTimeout, [self] {
  78. _onlineStateTimer = {};
  79. HARD_ASSERT(self.state == OnlineState::Unknown,
  80. "Timer should be canceled if we transitioned to a different state.");
  81. [self logClientOfflineWarningIfNecessaryWithReason:
  82. [NSString stringWithFormat:@"Backend didn't respond within %lld seconds.",
  83. chr::duration_cast<chr::seconds>(kOnlineStateTimeout)
  84. .count()]];
  85. [self setAndBroadcastState:OnlineState::Offline];
  86. // NOTE: handleWatchStreamFailure will continue to increment
  87. // watchStreamFailures even though we are already marked Offline but this is
  88. // non-harmful.
  89. });
  90. }
  91. }
  92. - (void)handleWatchStreamFailure:(NSError *)error {
  93. if (self.state == OnlineState::Online) {
  94. [self setAndBroadcastState:OnlineState::Unknown];
  95. // To get to OnlineState::Online, updateState: must have been called which would have reset
  96. // our heuristics.
  97. HARD_ASSERT(self.watchStreamFailures == 0, "watchStreamFailures must be 0");
  98. HARD_ASSERT(!_onlineStateTimer, "_onlineStateTimer must not be set yet");
  99. } else {
  100. self.watchStreamFailures++;
  101. if (self.watchStreamFailures >= kMaxWatchStreamFailures) {
  102. [self clearOnlineStateTimer];
  103. [self logClientOfflineWarningIfNecessaryWithReason:
  104. [NSString stringWithFormat:@"Connection failed %d times. Most recent error: %@",
  105. kMaxWatchStreamFailures, error]];
  106. [self setAndBroadcastState:OnlineState::Offline];
  107. }
  108. }
  109. }
  110. - (void)updateState:(OnlineState)newState {
  111. [self clearOnlineStateTimer];
  112. self.watchStreamFailures = 0;
  113. if (newState == OnlineState::Online) {
  114. // We've connected to watch at least once. Don't warn the developer about being offline going
  115. // forward.
  116. self.shouldWarnClientIsOffline = NO;
  117. }
  118. [self setAndBroadcastState:newState];
  119. }
  120. - (void)setAndBroadcastState:(OnlineState)newState {
  121. if (newState != self.state) {
  122. self.state = newState;
  123. [self.onlineStateDelegate applyChangedOnlineState:newState];
  124. }
  125. }
  126. - (void)logClientOfflineWarningIfNecessaryWithReason:(NSString *)reason {
  127. NSString *message = [NSString
  128. stringWithFormat:
  129. @"Could not reach Cloud Firestore backend. %@\n This typically indicates that your "
  130. @"device does not have a healthy Internet connection at the moment. The client will "
  131. @"operate in offline mode until it is able to successfully connect to the backend.",
  132. reason];
  133. if (self.shouldWarnClientIsOffline) {
  134. LOG_WARN("%s", message);
  135. self.shouldWarnClientIsOffline = NO;
  136. } else {
  137. LOG_DEBUG("%s", message);
  138. }
  139. }
  140. - (void)clearOnlineStateTimer {
  141. _onlineStateTimer.Cancel();
  142. }
  143. @end
  144. NS_ASSUME_NONNULL_END