FSTRemoteStore.m 23 KB

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