FSTRemoteStore.m 26 KB

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