FSTRemoteStore.m 27 KB

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