FSTRemoteStore.mm 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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/FSTRemoteStore.h"
  17. #include <inttypes.h>
  18. #import "Firestore/Source/Core/FSTQuery.h"
  19. #import "Firestore/Source/Core/FSTSnapshotVersion.h"
  20. #import "Firestore/Source/Core/FSTTransaction.h"
  21. #import "Firestore/Source/Local/FSTLocalStore.h"
  22. #import "Firestore/Source/Local/FSTQueryData.h"
  23. #import "Firestore/Source/Model/FSTDocument.h"
  24. #import "Firestore/Source/Model/FSTDocumentKey.h"
  25. #import "Firestore/Source/Model/FSTMutation.h"
  26. #import "Firestore/Source/Model/FSTMutationBatch.h"
  27. #import "Firestore/Source/Remote/FSTDatastore.h"
  28. #import "Firestore/Source/Remote/FSTExistenceFilter.h"
  29. #import "Firestore/Source/Remote/FSTRemoteEvent.h"
  30. #import "Firestore/Source/Remote/FSTStream.h"
  31. #import "Firestore/Source/Remote/FSTWatchChange.h"
  32. #import "Firestore/Source/Util/FSTAssert.h"
  33. #import "Firestore/Source/Util/FSTLogger.h"
  34. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  35. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  36. namespace util = firebase::firestore::util;
  37. using firebase::firestore::auth::User;
  38. NS_ASSUME_NONNULL_BEGIN
  39. /**
  40. * The maximum number of pending writes to allow.
  41. * TODO(bjornick): Negotiate this value with the backend.
  42. */
  43. static const int kMaxPendingWrites = 10;
  44. /**
  45. * The FSTRemoteStore notifies an onlineStateDelegate with FSTOnlineStateFailed if we fail to
  46. * connect to the backend. This subsequently triggers get() requests to fail or use cached data,
  47. * etc. Unfortunately, our connections have historically been subject to various transient failures.
  48. * So we wait for multiple failures before notifying the onlineStateDelegate.
  49. */
  50. static const int kOnlineAttemptsBeforeFailure = 2;
  51. #pragma mark - FSTRemoteStore
  52. @interface FSTRemoteStore () <FSTWatchStreamDelegate, FSTWriteStreamDelegate>
  53. - (instancetype)initWithLocalStore:(FSTLocalStore *)localStore
  54. datastore:(FSTDatastore *)datastore NS_DESIGNATED_INITIALIZER;
  55. /**
  56. * The local store, used to fill the write pipeline with outbound mutations and resolve existence
  57. * filter mismatches. Immutable after initialization.
  58. */
  59. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  60. /** The client-side proxy for interacting with the backend. Immutable after initialization. */
  61. @property(nonatomic, strong, readonly) FSTDatastore *datastore;
  62. #pragma mark Watch Stream
  63. // The watchStream is null when the network is disabled. The non-null check is performed by
  64. // isNetworkEnabled.
  65. @property(nonatomic, strong, nullable) FSTWatchStream *watchStream;
  66. /**
  67. * A mapping of watched targets that the client cares about tracking and the
  68. * user has explicitly called a 'listen' for this target.
  69. *
  70. * These targets may or may not have been sent to or acknowledged by the
  71. * server. On re-establishing the listen stream, these targets should be sent
  72. * to the server. The targets removed with unlistens are removed eagerly
  73. * without waiting for confirmation from the listen stream. */
  74. @property(nonatomic, strong, readonly)
  75. NSMutableDictionary<FSTBoxedTargetID *, FSTQueryData *> *listenTargets;
  76. /**
  77. * A mapping of targetId to pending acks needed.
  78. *
  79. * If a targetId is present in this map, then we're waiting for watch to
  80. * acknowledge a removal or addition of the target. If a target is not in this
  81. * mapping, and it's in the listenTargets map, then we consider the target to
  82. * be active.
  83. *
  84. * We increment the count here everytime we issue a request over the stream to
  85. * watch or unwatch. We then decrement the count everytime we get a target
  86. * added or target removed message from the server. Once the count is equal to
  87. * 0 we know that the client and server are in the same state (once this state
  88. * is reached the targetId is removed from the map to free the memory).
  89. */
  90. @property(nonatomic, strong, readonly)
  91. NSMutableDictionary<FSTBoxedTargetID *, NSNumber *> *pendingTargetResponses;
  92. @property(nonatomic, strong) NSMutableArray<FSTWatchChange *> *accumulatedChanges;
  93. @property(nonatomic, assign) FSTBatchID lastBatchSeen;
  94. /**
  95. * The online state of the watch stream. The state is set to healthy if and only if there are
  96. * messages received by the backend.
  97. */
  98. @property(nonatomic, assign) FSTOnlineState watchStreamOnlineState;
  99. /** A count of consecutive failures to open the stream. */
  100. @property(nonatomic, assign) int watchStreamFailures;
  101. /** Whether the client should fire offline warning. */
  102. @property(nonatomic, assign) BOOL shouldWarnOffline;
  103. #pragma mark Write Stream
  104. // The writeStream is null when the network is disabled. The non-null check is performed by
  105. // isNetworkEnabled.
  106. @property(nonatomic, strong, nullable) FSTWriteStream *writeStream;
  107. /**
  108. * The approximate time the StreamingWrite stream was opened. Used to estimate if stream was
  109. * closed due to an auth expiration (a recoverable error) or some other more permanent error.
  110. */
  111. @property(nonatomic, strong, nullable) NSDate *writeStreamOpenTime;
  112. /**
  113. * A FIFO queue of in-flight writes. This is in-flight from the point of view of the caller of
  114. * writeMutations, not from the point of view from the Datastore itself. In particular, these
  115. * requests may not have been sent to the Datastore server if the write stream is not yet running.
  116. */
  117. @property(nonatomic, strong, readonly) NSMutableArray<FSTMutationBatch *> *pendingWrites;
  118. @end
  119. @implementation FSTRemoteStore
  120. + (instancetype)remoteStoreWithLocalStore:(FSTLocalStore *)localStore
  121. datastore:(FSTDatastore *)datastore {
  122. return [[FSTRemoteStore alloc] initWithLocalStore:localStore datastore:datastore];
  123. }
  124. - (instancetype)initWithLocalStore:(FSTLocalStore *)localStore datastore:(FSTDatastore *)datastore {
  125. if (self = [super init]) {
  126. _localStore = localStore;
  127. _datastore = datastore;
  128. _listenTargets = [NSMutableDictionary dictionary];
  129. _pendingTargetResponses = [NSMutableDictionary dictionary];
  130. _accumulatedChanges = [NSMutableArray array];
  131. _lastBatchSeen = kFSTBatchIDUnknown;
  132. _watchStreamOnlineState = FSTOnlineStateUnknown;
  133. _shouldWarnOffline = YES;
  134. _pendingWrites = [NSMutableArray array];
  135. }
  136. return self;
  137. }
  138. - (void)start {
  139. // For now, all setup is handled by enableNetwork(). We might expand on this in the future.
  140. [self enableNetwork];
  141. }
  142. /**
  143. * Updates our OnlineState to the new state, updating local state and notifying the
  144. * onlineStateHandler as appropriate.
  145. */
  146. - (void)updateOnlineState:(FSTOnlineState)newState {
  147. // Update and broadcast the new state.
  148. if (newState != self.watchStreamOnlineState) {
  149. if (newState == FSTOnlineStateHealthy) {
  150. // We've connected to watch at least once. Don't warn the developer about being offline going
  151. // forward.
  152. self.shouldWarnOffline = NO;
  153. } else if (newState == FSTOnlineStateUnknown) {
  154. // The state is set to unknown when a healthy stream is closed (e.g. due to a token timeout)
  155. // or when we have no active listens and therefore there's no need to start the stream.
  156. // Assuming there is (possibly in the future) an active listen, then we will eventually move
  157. // to state Online or Failed, but we always want to make at least kOnlineAttemptsBeforeFailure
  158. // attempts before failing, so we reset the count here.
  159. self.watchStreamFailures = 0;
  160. }
  161. self.watchStreamOnlineState = newState;
  162. [self.onlineStateDelegate applyChangedOnlineState:newState];
  163. }
  164. }
  165. /**
  166. * Updates our FSTOnlineState as appropriate after the watch stream reports a failure. The first
  167. * failure moves us to the 'Unknown' state. We then may allow multiple failures (based on
  168. * kOnlineAttemptsBeforeFailure) before we actually transition to FSTOnlineStateFailed.
  169. */
  170. - (void)updateOnlineStateAfterFailure {
  171. if (self.watchStreamOnlineState == FSTOnlineStateHealthy) {
  172. [self updateOnlineState:FSTOnlineStateUnknown];
  173. } else {
  174. self.watchStreamFailures++;
  175. if (self.watchStreamFailures >= kOnlineAttemptsBeforeFailure) {
  176. if (self.shouldWarnOffline) {
  177. FSTWarn(@"Could not reach Firestore backend.");
  178. self.shouldWarnOffline = NO;
  179. }
  180. [self updateOnlineState:FSTOnlineStateFailed];
  181. }
  182. }
  183. }
  184. #pragma mark Online/Offline state
  185. - (BOOL)isNetworkEnabled {
  186. FSTAssert((self.watchStream == nil) == (self.writeStream == nil),
  187. @"WatchStream and WriteStream should both be null or non-null");
  188. return self.watchStream != nil;
  189. }
  190. - (void)enableNetwork {
  191. if ([self isNetworkEnabled]) {
  192. return;
  193. }
  194. // Create new streams (but note they're not started yet).
  195. self.watchStream = [self.datastore createWatchStream];
  196. self.writeStream = [self.datastore createWriteStream];
  197. // Load any saved stream token from persistent storage
  198. self.writeStream.lastStreamToken = [self.localStore lastStreamToken];
  199. if ([self shouldStartWatchStream]) {
  200. [self startWatchStream];
  201. }
  202. [self fillWritePipeline]; // This may start the writeStream.
  203. // We move back to the unknown state because we might not want to re-open the stream
  204. [self updateOnlineState:FSTOnlineStateUnknown];
  205. }
  206. - (void)disableNetwork {
  207. [self disableNetworkInternal];
  208. // Set the FSTOnlineState to failed so get()'s return from cache, etc.
  209. [self updateOnlineState:FSTOnlineStateFailed];
  210. }
  211. /** Disables the network, setting the FSTOnlineState to the specified targetOnlineState. */
  212. - (void)disableNetworkInternal {
  213. if ([self isNetworkEnabled]) {
  214. // NOTE: We're guaranteed not to get any further events from these streams (not even a close
  215. // event).
  216. [self.watchStream stop];
  217. [self.writeStream stop];
  218. [self cleanUpWatchStreamState];
  219. [self cleanUpWriteStreamState];
  220. self.writeStream = nil;
  221. self.watchStream = nil;
  222. }
  223. }
  224. #pragma mark Shutdown
  225. - (void)shutdown {
  226. FSTLog(@"FSTRemoteStore %p shutting down", (__bridge void *)self);
  227. [self disableNetworkInternal];
  228. // Set the FSTOnlineState to Unknown (rather than Failed) to avoid potentially triggering
  229. // spurious listener events with cached data, etc.
  230. [self updateOnlineState:FSTOnlineStateUnknown];
  231. }
  232. - (void)userDidChange:(const User &)user {
  233. FSTLog(@"FSTRemoteStore %p changing users: %@", (__bridge void *)self,
  234. util::WrapNSStringNoCopy(user.uid()));
  235. if ([self isNetworkEnabled]) {
  236. // Tear down and re-create our network streams. This will ensure we get a fresh auth token
  237. // for the new user and re-fill the write pipeline with new mutations from the LocalStore
  238. // (since mutations are per-user).
  239. [self disableNetworkInternal];
  240. [self updateOnlineState:FSTOnlineStateUnknown];
  241. [self enableNetwork];
  242. }
  243. }
  244. #pragma mark Watch Stream
  245. - (void)startWatchStream {
  246. FSTAssert([self shouldStartWatchStream],
  247. @"startWatchStream: called when shouldStartWatchStream: is false.");
  248. [self.watchStream startWithDelegate:self];
  249. }
  250. - (void)listenToTargetWithQueryData:(FSTQueryData *)queryData {
  251. NSNumber *targetKey = @(queryData.targetID);
  252. FSTAssert(!self.listenTargets[targetKey], @"listenToQuery called with duplicate target id: %@",
  253. targetKey);
  254. self.listenTargets[targetKey] = queryData;
  255. if ([self shouldStartWatchStream]) {
  256. [self startWatchStream];
  257. } else if ([self isNetworkEnabled] && [self.watchStream isOpen]) {
  258. [self sendWatchRequestWithQueryData:queryData];
  259. }
  260. }
  261. - (void)sendWatchRequestWithQueryData:(FSTQueryData *)queryData {
  262. [self recordPendingRequestForTargetID:@(queryData.targetID)];
  263. [self.watchStream watchQuery:queryData];
  264. }
  265. - (void)stopListeningToTargetID:(FSTTargetID)targetID {
  266. FSTBoxedTargetID *targetKey = @(targetID);
  267. FSTQueryData *queryData = self.listenTargets[targetKey];
  268. FSTAssert(queryData, @"unlistenToTarget: target not currently watched: %@", targetKey);
  269. [self.listenTargets removeObjectForKey:targetKey];
  270. if ([self isNetworkEnabled] && [self.watchStream isOpen]) {
  271. [self sendUnwatchRequestForTargetID:targetKey];
  272. if ([self.listenTargets count] == 0) {
  273. [self.watchStream markIdle];
  274. }
  275. }
  276. }
  277. - (void)sendUnwatchRequestForTargetID:(FSTBoxedTargetID *)targetID {
  278. [self recordPendingRequestForTargetID:targetID];
  279. [self.watchStream unwatchTargetID:[targetID intValue]];
  280. }
  281. - (void)recordPendingRequestForTargetID:(FSTBoxedTargetID *)targetID {
  282. NSNumber *count = [self.pendingTargetResponses objectForKey:targetID];
  283. count = @([count intValue] + 1);
  284. [self.pendingTargetResponses setObject:count forKey:targetID];
  285. }
  286. /**
  287. * Returns YES if the network is enabled, the watch stream has not yet been started and there are
  288. * active watch targets.
  289. */
  290. - (BOOL)shouldStartWatchStream {
  291. return [self isNetworkEnabled] && ![self.watchStream isStarted] && self.listenTargets.count > 0;
  292. }
  293. - (void)cleanUpWatchStreamState {
  294. // If the connection is closed then we'll never get a snapshot version for the accumulated
  295. // changes and so we'll never be able to complete the batch. When we start up again the server
  296. // is going to resend these changes anyway, so just toss the accumulated state.
  297. [self.accumulatedChanges removeAllObjects];
  298. [self.pendingTargetResponses removeAllObjects];
  299. }
  300. - (void)watchStreamDidOpen {
  301. // Restore any existing watches.
  302. for (FSTQueryData *queryData in [self.listenTargets objectEnumerator]) {
  303. [self sendWatchRequestWithQueryData:queryData];
  304. }
  305. }
  306. - (void)watchStreamDidChange:(FSTWatchChange *)change
  307. snapshotVersion:(FSTSnapshotVersion *)snapshotVersion {
  308. // Mark the connection as healthy because we got a message from the server.
  309. [self updateOnlineState:FSTOnlineStateHealthy];
  310. FSTWatchTargetChange *watchTargetChange =
  311. [change isKindOfClass:[FSTWatchTargetChange class]] ? (FSTWatchTargetChange *)change : nil;
  312. if (watchTargetChange && watchTargetChange.state == FSTWatchTargetChangeStateRemoved &&
  313. watchTargetChange.cause) {
  314. // There was an error on a target, don't wait for a consistent snapshot to raise events
  315. [self processTargetErrorForWatchChange:(FSTWatchTargetChange *)change];
  316. } else {
  317. // Accumulate watch changes but don't process them if there's no snapshotVersion or it's
  318. // older than a previous snapshot we've processed (can happen after we resume a target
  319. // using a resume token).
  320. [self.accumulatedChanges addObject:change];
  321. FSTAssert(snapshotVersion, @"snapshotVersion must not be nil.");
  322. if ([snapshotVersion isEqual:[FSTSnapshotVersion noVersion]] ||
  323. [snapshotVersion compare:[self.localStore lastRemoteSnapshotVersion]] ==
  324. NSOrderedAscending) {
  325. return;
  326. }
  327. // Create a batch, giving it the accumulatedChanges array.
  328. NSArray<FSTWatchChange *> *changes = self.accumulatedChanges;
  329. self.accumulatedChanges = [NSMutableArray array];
  330. [self processBatchedWatchChanges:changes snapshotVersion:snapshotVersion];
  331. }
  332. }
  333. - (void)watchStreamWasInterruptedWithError:(nullable NSError *)error {
  334. FSTAssert([self isNetworkEnabled],
  335. @"watchStreamDidClose should only be called when the network is enabled");
  336. [self cleanUpWatchStreamState];
  337. // If the watch stream closed due to an error, retry the connection if there are any active
  338. // watch targets.
  339. if ([self shouldStartWatchStream]) {
  340. [self updateOnlineStateAfterFailure];
  341. [self startWatchStream];
  342. } else {
  343. // We don't need to restart the watch stream because there are no active targets. The online
  344. // state is set to unknown because there is no active attempt at establishing a connection.
  345. [self updateOnlineState:FSTOnlineStateUnknown];
  346. }
  347. }
  348. /**
  349. * Takes a batch of changes from the Datastore, repackages them as a RemoteEvent, and passes that
  350. * on to the SyncEngine.
  351. */
  352. - (void)processBatchedWatchChanges:(NSArray<FSTWatchChange *> *)changes
  353. snapshotVersion:(FSTSnapshotVersion *)snapshotVersion {
  354. FSTWatchChangeAggregator *aggregator =
  355. [[FSTWatchChangeAggregator alloc] initWithSnapshotVersion:snapshotVersion
  356. listenTargets:self.listenTargets
  357. pendingTargetResponses:self.pendingTargetResponses];
  358. [aggregator addWatchChanges:changes];
  359. FSTRemoteEvent *remoteEvent = [aggregator remoteEvent];
  360. [self.pendingTargetResponses removeAllObjects];
  361. [self.pendingTargetResponses setDictionary:aggregator.pendingTargetResponses];
  362. // Handle existence filters and existence filter mismatches
  363. [aggregator.existenceFilters enumerateKeysAndObjectsUsingBlock:^(FSTBoxedTargetID *target,
  364. FSTExistenceFilter *filter,
  365. BOOL *stop) {
  366. FSTTargetID targetID = target.intValue;
  367. FSTQueryData *queryData = self.listenTargets[target];
  368. FSTQuery *query = queryData.query;
  369. if (!queryData) {
  370. // A watched target might have been removed already.
  371. return;
  372. } else if ([query isDocumentQuery]) {
  373. if (filter.count == 0) {
  374. // The existence filter told us the document does not exist.
  375. // We need to deduce that this document does not exist and apply a deleted document to our
  376. // updates. Without applying a deleted document there might be another query that will
  377. // raise this document as part of a snapshot until it is resolved, essentially exposing
  378. // inconsistency between queries
  379. FSTDocumentKey *key = [FSTDocumentKey keyWithPath:query.path];
  380. FSTDeletedDocument *deletedDoc =
  381. [FSTDeletedDocument documentWithKey:key version:snapshotVersion];
  382. [remoteEvent addDocumentUpdate:deletedDoc];
  383. } else {
  384. FSTAssert(filter.count == 1, @"Single document existence filter with count: %" PRId32,
  385. filter.count);
  386. }
  387. } else {
  388. // Not a document query.
  389. FSTDocumentKeySet *trackedRemote = [self.localStore remoteDocumentKeysForTarget:targetID];
  390. FSTTargetMapping *mapping = remoteEvent.targetChanges[target].mapping;
  391. if (mapping) {
  392. if ([mapping isKindOfClass:[FSTUpdateMapping class]]) {
  393. FSTUpdateMapping *update = (FSTUpdateMapping *)mapping;
  394. trackedRemote = [update applyTo:trackedRemote];
  395. } else {
  396. FSTAssert([mapping isKindOfClass:[FSTResetMapping class]],
  397. @"Expected either reset or update mapping but got something else %@", mapping);
  398. trackedRemote = ((FSTResetMapping *)mapping).documents;
  399. }
  400. }
  401. if (trackedRemote.count != (NSUInteger)filter.count) {
  402. FSTLog(@"Existence filter mismatch, resetting mapping");
  403. // Make sure the mismatch is exposed in the remote event
  404. [remoteEvent handleExistenceFilterMismatchForTargetID:target];
  405. // Clear the resume token for the query, since we're in a known mismatch state.
  406. queryData = [[FSTQueryData alloc] initWithQuery:query
  407. targetID:targetID
  408. listenSequenceNumber:queryData.sequenceNumber
  409. purpose:queryData.purpose];
  410. self.listenTargets[target] = queryData;
  411. // Cause a hard reset by unwatching and rewatching immediately, but deliberately don't
  412. // send a resume token so that we get a full update.
  413. [self sendUnwatchRequestForTargetID:@(targetID)];
  414. // Mark the query we send as being on behalf of an existence filter mismatch, but don't
  415. // actually retain that in listenTargets. This ensures that we flag the first re-listen
  416. // this way without impacting future listens of this target (that might happen e.g. on
  417. // reconnect).
  418. FSTQueryData *requestQueryData =
  419. [[FSTQueryData alloc] initWithQuery:query
  420. targetID:targetID
  421. listenSequenceNumber:queryData.sequenceNumber
  422. purpose:FSTQueryPurposeExistenceFilterMismatch];
  423. [self sendWatchRequestWithQueryData:requestQueryData];
  424. }
  425. }
  426. }];
  427. // Update in-memory resume tokens. FSTLocalStore will update the persistent view of these when
  428. // applying the completed FSTRemoteEvent.
  429. [remoteEvent.targetChanges enumerateKeysAndObjectsUsingBlock:^(
  430. FSTBoxedTargetID *target, FSTTargetChange *change, BOOL *stop) {
  431. NSData *resumeToken = change.resumeToken;
  432. if (resumeToken.length > 0) {
  433. FSTQueryData *queryData = self->_listenTargets[target];
  434. // A watched target might have been removed already.
  435. if (queryData) {
  436. self->_listenTargets[target] =
  437. [queryData queryDataByReplacingSnapshotVersion:change.snapshotVersion
  438. resumeToken:resumeToken];
  439. }
  440. }
  441. }];
  442. // Finally handle remote event
  443. [self.syncEngine applyRemoteEvent:remoteEvent];
  444. }
  445. /** Process a target error and passes the error along to SyncEngine. */
  446. - (void)processTargetErrorForWatchChange:(FSTWatchTargetChange *)change {
  447. FSTAssert(change.cause, @"Handling target error without a cause");
  448. // Ignore targets that have been removed already.
  449. for (FSTBoxedTargetID *targetID in change.targetIDs) {
  450. if (self.listenTargets[targetID]) {
  451. [self.listenTargets removeObjectForKey:targetID];
  452. [self.syncEngine rejectListenWithTargetID:targetID error:change.cause];
  453. }
  454. }
  455. }
  456. #pragma mark Write Stream
  457. /**
  458. * Returns YES if the network is enabled, the write stream has not yet been started and there are
  459. * pending writes.
  460. */
  461. - (BOOL)shouldStartWriteStream {
  462. return [self isNetworkEnabled] && ![self.writeStream isStarted] && self.pendingWrites.count > 0;
  463. }
  464. - (void)startWriteStream {
  465. FSTAssert([self shouldStartWriteStream],
  466. @"startWriteStream: called when shouldStartWriteStream: is false.");
  467. [self.writeStream startWithDelegate:self];
  468. }
  469. - (void)cleanUpWriteStreamState {
  470. self.lastBatchSeen = kFSTBatchIDUnknown;
  471. FSTLog(@"Stopping write stream with %lu pending writes",
  472. (unsigned long)[self.pendingWrites count]);
  473. [self.pendingWrites removeAllObjects];
  474. }
  475. - (void)fillWritePipeline {
  476. if ([self isNetworkEnabled]) {
  477. while ([self canWriteMutations]) {
  478. FSTMutationBatch *batch = [self.localStore nextMutationBatchAfterBatchID:self.lastBatchSeen];
  479. if (!batch) {
  480. break;
  481. }
  482. [self commitBatch:batch];
  483. }
  484. if ([self.pendingWrites count] == 0) {
  485. [self.writeStream markIdle];
  486. }
  487. }
  488. }
  489. /**
  490. * Returns YES if the backend can accept additional write requests.
  491. *
  492. * When sending mutations to the write stream (e.g. in -fillWritePipeline), call this method first
  493. * to check if more mutations can be sent.
  494. *
  495. * Currently the only thing that can prevent the backend from accepting write requests is if
  496. * there are too many requests already outstanding. As writes complete the backend will be able
  497. * to accept more.
  498. */
  499. - (BOOL)canWriteMutations {
  500. return [self isNetworkEnabled] && self.pendingWrites.count < kMaxPendingWrites;
  501. }
  502. /** Given mutations to commit, actually commits them to the backend. */
  503. - (void)commitBatch:(FSTMutationBatch *)batch {
  504. FSTAssert([self canWriteMutations], @"commitBatch called when mutations can't be written");
  505. self.lastBatchSeen = batch.batchID;
  506. [self.pendingWrites addObject:batch];
  507. if ([self shouldStartWriteStream]) {
  508. [self startWriteStream];
  509. } else if ([self isNetworkEnabled] && self.writeStream.handshakeComplete) {
  510. [self.writeStream writeMutations:batch.mutations];
  511. }
  512. }
  513. - (void)writeStreamDidOpen {
  514. self.writeStreamOpenTime = [NSDate date];
  515. [self.writeStream writeHandshake];
  516. }
  517. /**
  518. * Handles a successful handshake response from the server, which is our cue to send any pending
  519. * writes.
  520. */
  521. - (void)writeStreamDidCompleteHandshake {
  522. // Record the stream token.
  523. [self.localStore setLastStreamToken:self.writeStream.lastStreamToken];
  524. // Drain any pending writes.
  525. //
  526. // Note that at this point pendingWrites contains mutations that have already been accepted by
  527. // fillWritePipeline/commitBatch. If the pipeline is full, canWriteMutations will be NO, despite
  528. // the fact that we actually need to send mutations over.
  529. //
  530. // This also means that this method indirectly respects the limits imposed by canWriteMutations
  531. // since writes can't be added to the pendingWrites array when canWriteMutations is NO. If the
  532. // limits imposed by canWriteMutations actually protect us from DOSing ourselves then those limits
  533. // won't be exceeded here and we'll continue to make progress.
  534. for (FSTMutationBatch *write in self.pendingWrites) {
  535. [self.writeStream writeMutations:write.mutations];
  536. }
  537. }
  538. /** Handles a successful StreamingWriteResponse from the server that contains a mutation result. */
  539. - (void)writeStreamDidReceiveResponseWithVersion:(FSTSnapshotVersion *)commitVersion
  540. mutationResults:(NSArray<FSTMutationResult *> *)results {
  541. // This is a response to a write containing mutations and should be correlated to the first
  542. // pending write.
  543. NSMutableArray *pendingWrites = self.pendingWrites;
  544. FSTMutationBatch *batch = pendingWrites[0];
  545. [pendingWrites removeObjectAtIndex:0];
  546. FSTMutationBatchResult *batchResult =
  547. [FSTMutationBatchResult resultWithBatch:batch
  548. commitVersion:commitVersion
  549. mutationResults:results
  550. streamToken:self.writeStream.lastStreamToken];
  551. [self.syncEngine applySuccessfulWriteWithResult:batchResult];
  552. // It's possible that with the completion of this mutation another slot has freed up.
  553. [self fillWritePipeline];
  554. }
  555. /**
  556. * Handles the closing of the StreamingWrite RPC, either because of an error or because the RPC
  557. * has been terminated by the client or the server.
  558. */
  559. - (void)writeStreamWasInterruptedWithError:(nullable NSError *)error {
  560. FSTAssert([self isNetworkEnabled],
  561. @"writeStreamDidClose: should only be called when the network is enabled");
  562. // If the write stream closed due to an error, invoke the error callbacks if there are pending
  563. // writes.
  564. if (error != nil && self.pendingWrites.count > 0) {
  565. if (self.writeStream.handshakeComplete) {
  566. // This error affects the actual writes.
  567. [self handleWriteError:error];
  568. } else {
  569. // If there was an error before the handshake finished, it's possible that the server is
  570. // unable to process the stream token we're sending. (Perhaps it's too old?)
  571. [self handleHandshakeError:error];
  572. }
  573. }
  574. // The write stream might have been started by refilling the write pipeline for failed writes
  575. if ([self shouldStartWriteStream]) {
  576. [self startWriteStream];
  577. }
  578. }
  579. - (void)handleHandshakeError:(NSError *)error {
  580. // Reset the token if it's a permanent error or the error code is ABORTED, signaling the write
  581. // stream is no longer valid.
  582. if ([FSTDatastore isPermanentWriteError:error] || [FSTDatastore isAbortedError:error]) {
  583. NSString *token = [self.writeStream.lastStreamToken base64EncodedStringWithOptions:0];
  584. FSTLog(@"FSTRemoteStore %p error before completed handshake; resetting stream token %@: %@",
  585. (__bridge void *)self, token, error);
  586. self.writeStream.lastStreamToken = nil;
  587. [self.localStore setLastStreamToken:nil];
  588. }
  589. }
  590. - (void)handleWriteError:(NSError *)error {
  591. // Only handle permanent error. If it's transient, just let the retry logic kick in.
  592. if (![FSTDatastore isPermanentWriteError:error]) {
  593. return;
  594. }
  595. // If this was a permanent error, the request itself was the problem so it's not going to
  596. // succeed if we resend it.
  597. FSTMutationBatch *batch = self.pendingWrites[0];
  598. [self.pendingWrites removeObjectAtIndex:0];
  599. // In this case it's also unlikely that the server itself is melting down--this was just a
  600. // bad request so inhibit backoff on the next restart.
  601. [self.writeStream inhibitBackoff];
  602. [self.syncEngine rejectFailedWriteWithBatchID:batch.batchID error:error];
  603. // It's possible that with the completion of this mutation another slot has freed up.
  604. [self fillWritePipeline];
  605. }
  606. - (FSTTransaction *)transaction {
  607. return [FSTTransaction transactionWithDatastore:self.datastore];
  608. }
  609. @end
  610. NS_ASSUME_NONNULL_END