FSTOnlineStateTracker.mm 6.0 KB

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