FSTRemoteStore.mm 28 KB

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