FSTOnlineStateTracker.mm 6.2 KB

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