FSTRemoteStore.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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 <cinttypes>
  18. #import "Firestore/Source/Core/FSTQuery.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/FSTMutation.h"
  24. #import "Firestore/Source/Model/FSTMutationBatch.h"
  25. #import "Firestore/Source/Remote/FSTDatastore.h"
  26. #import "Firestore/Source/Remote/FSTExistenceFilter.h"
  27. #import "Firestore/Source/Remote/FSTOnlineStateTracker.h"
  28. #import "Firestore/Source/Remote/FSTRemoteEvent.h"
  29. #import "Firestore/Source/Remote/FSTStream.h"
  30. #import "Firestore/Source/Remote/FSTWatchChange.h"
  31. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  32. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  33. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  34. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  35. #include "Firestore/core/src/firebase/firestore/util/log.h"
  36. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  37. namespace util = firebase::firestore::util;
  38. using firebase::firestore::auth::User;
  39. using firebase::firestore::model::BatchId;
  40. using firebase::firestore::model::DocumentKey;
  41. using firebase::firestore::model::DocumentKeySet;
  42. using firebase::firestore::model::OnlineState;
  43. using firebase::firestore::model::SnapshotVersion;
  44. using firebase::firestore::model::TargetId;
  45. NS_ASSUME_NONNULL_BEGIN
  46. /**
  47. * The maximum number of pending writes to allow.
  48. * TODO(bjornick): Negotiate this value with the backend.
  49. */
  50. static const int kMaxPendingWrites = 10;
  51. #pragma mark - FSTRemoteStore
  52. @interface FSTRemoteStore () <FSTWatchStreamDelegate, FSTWriteStreamDelegate>
  53. /**
  54. * The local store, used to fill the write pipeline with outbound mutations and resolve existence
  55. * filter mismatches. Immutable after initialization.
  56. */
  57. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  58. /** The client-side proxy for interacting with the backend. Immutable after initialization. */
  59. @property(nonatomic, strong, readonly) FSTDatastore *datastore;
  60. #pragma mark Watch Stream
  61. // The watchStream is null when the network is disabled. The non-null check is performed by
  62. // isNetworkEnabled.
  63. @property(nonatomic, strong, nullable) FSTWatchStream *watchStream;
  64. /**
  65. * A mapping of watched targets that the client cares about tracking and the
  66. * user has explicitly called a 'listen' for this target.
  67. *
  68. * These targets may or may not have been sent to or acknowledged by the
  69. * server. On re-establishing the listen stream, these targets should be sent
  70. * to the server. The targets removed with unlistens are removed eagerly
  71. * without waiting for confirmation from the listen stream. */
  72. @property(nonatomic, strong, readonly)
  73. NSMutableDictionary<FSTBoxedTargetID *, FSTQueryData *> *listenTargets;
  74. @property(nonatomic, strong, readonly) FSTOnlineStateTracker *onlineStateTracker;
  75. @property(nonatomic, strong, nullable) FSTWatchChangeAggregator *watchChangeAggregator;
  76. #pragma mark Write Stream
  77. // The writeStream is null when the network is disabled. The non-null check is performed by
  78. // isNetworkEnabled.
  79. @property(nonatomic, strong, nullable) FSTWriteStream *writeStream;
  80. /**
  81. * A list of up to kMaxPendingWrites writes that we have fetched from the LocalStore via
  82. * fillWritePipeline and have or will send to the write stream.
  83. *
  84. * Whenever writePipeline is not empty, the RemoteStore will attempt to start or restart the write
  85. * stream. When the stream is established, the writes in the pipeline will be sent in order.
  86. *
  87. * Writes remain in writePipeline until they are acknowledged by the backend and thus will
  88. * automatically be re-sent if the stream is interrupted / restarted before they're acknowledged.
  89. *
  90. * Write responses from the backend are linked to their originating request purely based on
  91. * order, and so we can just remove writes from the front of the writePipeline as we receive
  92. * responses.
  93. */
  94. @property(nonatomic, strong, readonly) NSMutableArray<FSTMutationBatch *> *writePipeline;
  95. @end
  96. @implementation FSTRemoteStore
  97. - (instancetype)initWithLocalStore:(FSTLocalStore *)localStore
  98. datastore:(FSTDatastore *)datastore
  99. workerDispatchQueue:(FSTDispatchQueue *)queue {
  100. if (self = [super init]) {
  101. _localStore = localStore;
  102. _datastore = datastore;
  103. _listenTargets = [NSMutableDictionary dictionary];
  104. _writePipeline = [NSMutableArray array];
  105. _onlineStateTracker = [[FSTOnlineStateTracker alloc] initWithWorkerDispatchQueue:queue];
  106. }
  107. return self;
  108. }
  109. - (void)start {
  110. // For now, all setup is handled by enableNetwork(). We might expand on this in the future.
  111. [self enableNetwork];
  112. }
  113. @dynamic onlineStateDelegate;
  114. - (nullable id<FSTOnlineStateDelegate>)onlineStateDelegate {
  115. return self.onlineStateTracker.onlineStateDelegate;
  116. }
  117. - (void)setOnlineStateDelegate:(nullable id<FSTOnlineStateDelegate>)delegate {
  118. self.onlineStateTracker.onlineStateDelegate = delegate;
  119. }
  120. #pragma mark Online/Offline state
  121. - (BOOL)isNetworkEnabled {
  122. HARD_ASSERT((self.watchStream == nil) == (self.writeStream == nil),
  123. "WatchStream and WriteStream should both be null or non-null");
  124. return self.watchStream != nil;
  125. }
  126. - (void)enableNetwork {
  127. if ([self isNetworkEnabled]) {
  128. return;
  129. }
  130. // Create new streams (but note they're not started yet).
  131. self.watchStream = [self.datastore createWatchStream];
  132. self.writeStream = [self.datastore createWriteStream];
  133. // Load any saved stream token from persistent storage
  134. self.writeStream.lastStreamToken = [self.localStore lastStreamToken];
  135. if ([self shouldStartWatchStream]) {
  136. [self startWatchStream];
  137. } else {
  138. [self.onlineStateTracker updateState:OnlineState::Unknown];
  139. }
  140. [self fillWritePipeline]; // This may start the writeStream.
  141. }
  142. - (void)disableNetwork {
  143. [self disableNetworkInternal];
  144. // Set the OnlineState to Offline so get()s return from cache, etc.
  145. [self.onlineStateTracker updateState:OnlineState::Offline];
  146. }
  147. /** Disables the network, setting the OnlineState to the specified targetOnlineState. */
  148. - (void)disableNetworkInternal {
  149. if ([self isNetworkEnabled]) {
  150. // NOTE: We're guaranteed not to get any further events from these streams (not even a close
  151. // event).
  152. [self.watchStream stop];
  153. [self.writeStream stop];
  154. [self cleanUpWatchStreamState];
  155. if (self.writePipeline.count > 0) {
  156. LOG_DEBUG("Stopping write stream with %lu pending writes",
  157. (unsigned long)self.writePipeline.count);
  158. [self.writePipeline removeAllObjects];
  159. }
  160. self.writeStream = nil;
  161. self.watchStream = nil;
  162. }
  163. }
  164. #pragma mark Shutdown
  165. - (void)shutdown {
  166. LOG_DEBUG("FSTRemoteStore %s shutting down", (__bridge void *)self);
  167. [self disableNetworkInternal];
  168. // Set the OnlineState to Unknown (rather than Offline) to avoid potentially triggering
  169. // spurious listener events with cached data, etc.
  170. [self.onlineStateTracker updateState:OnlineState::Unknown];
  171. }
  172. - (void)credentialDidChange {
  173. if ([self isNetworkEnabled]) {
  174. // Tear down and re-create our network streams. This will ensure we get a fresh auth token
  175. // for the new user and re-fill the write pipeline with new mutations from the LocalStore
  176. // (since mutations are per-user).
  177. LOG_DEBUG("FSTRemoteStore %s restarting streams for new credential", (__bridge void *)self);
  178. [self disableNetworkInternal];
  179. [self.onlineStateTracker updateState:OnlineState::Unknown];
  180. [self enableNetwork];
  181. }
  182. }
  183. #pragma mark Watch Stream
  184. - (void)startWatchStream {
  185. HARD_ASSERT([self shouldStartWatchStream],
  186. "startWatchStream: called when shouldStartWatchStream: is false.");
  187. _watchChangeAggregator = [[FSTWatchChangeAggregator alloc] initWithTargetMetadataProvider:self];
  188. [self.watchStream startWithDelegate:self];
  189. [self.onlineStateTracker handleWatchStreamStart];
  190. }
  191. - (void)listenToTargetWithQueryData:(FSTQueryData *)queryData {
  192. NSNumber *targetKey = @(queryData.targetID);
  193. HARD_ASSERT(!self.listenTargets[targetKey], "listenToQuery called with duplicate target id: %s",
  194. targetKey);
  195. self.listenTargets[targetKey] = queryData;
  196. if ([self shouldStartWatchStream]) {
  197. [self startWatchStream];
  198. } else if ([self isNetworkEnabled] && [self.watchStream isOpen]) {
  199. [self sendWatchRequestWithQueryData:queryData];
  200. }
  201. }
  202. - (void)sendWatchRequestWithQueryData:(FSTQueryData *)queryData {
  203. [self.watchChangeAggregator recordTargetRequest:@(queryData.targetID)];
  204. [self.watchStream watchQuery:queryData];
  205. }
  206. - (void)stopListeningToTargetID:(TargetId)targetID {
  207. FSTBoxedTargetID *targetKey = @(targetID);
  208. FSTQueryData *queryData = self.listenTargets[targetKey];
  209. HARD_ASSERT(queryData, "unlistenToTarget: target not currently watched: %s", targetKey);
  210. [self.listenTargets removeObjectForKey:targetKey];
  211. if ([self isNetworkEnabled] && [self.watchStream isOpen]) {
  212. [self sendUnwatchRequestForTargetID:targetKey];
  213. if ([self.listenTargets count] == 0) {
  214. [self.watchStream markIdle];
  215. }
  216. }
  217. }
  218. - (void)sendUnwatchRequestForTargetID:(FSTBoxedTargetID *)targetID {
  219. [self.watchChangeAggregator recordTargetRequest:targetID];
  220. [self.watchStream unwatchTargetID:[targetID intValue]];
  221. }
  222. /**
  223. * Returns YES if the network is enabled, the watch stream has not yet been started and there are
  224. * active watch targets.
  225. */
  226. - (BOOL)shouldStartWatchStream {
  227. return [self isNetworkEnabled] && ![self.watchStream isStarted] && self.listenTargets.count > 0;
  228. }
  229. - (void)cleanUpWatchStreamState {
  230. _watchChangeAggregator = nil;
  231. }
  232. - (void)watchStreamDidOpen {
  233. // Restore any existing watches.
  234. for (FSTQueryData *queryData in [self.listenTargets objectEnumerator]) {
  235. [self sendWatchRequestWithQueryData:queryData];
  236. }
  237. }
  238. - (void)watchStreamDidChange:(FSTWatchChange *)change
  239. snapshotVersion:(const SnapshotVersion &)snapshotVersion {
  240. // Mark the connection as Online because we got a message from the server.
  241. [self.onlineStateTracker updateState:OnlineState::Online];
  242. if ([change isKindOfClass:[FSTWatchTargetChange class]]) {
  243. FSTWatchTargetChange *watchTargetChange = (FSTWatchTargetChange *)change;
  244. if (watchTargetChange.state == FSTWatchTargetChangeStateRemoved && watchTargetChange.cause) {
  245. // There was an error on a target, don't wait for a consistent snapshot to raise events
  246. return [self processTargetErrorForWatchChange:watchTargetChange];
  247. } else {
  248. [self.watchChangeAggregator handleTargetChange:watchTargetChange];
  249. }
  250. } else if ([change isKindOfClass:[FSTDocumentWatchChange class]]) {
  251. [self.watchChangeAggregator handleDocumentChange:(FSTDocumentWatchChange *)change];
  252. } else {
  253. HARD_ASSERT([change isKindOfClass:[FSTExistenceFilterWatchChange class]],
  254. "Expected watchChange to be an instance of FSTExistenceFilterWatchChange");
  255. [self.watchChangeAggregator handleExistenceFilter:(FSTExistenceFilterWatchChange *)change];
  256. }
  257. if (snapshotVersion != SnapshotVersion::None() &&
  258. snapshotVersion >= [self.localStore lastRemoteSnapshotVersion]) {
  259. // We have received a target change with a global snapshot if the snapshot version is not equal
  260. // to SnapshotVersion.None().
  261. [self raiseWatchSnapshotWithSnapshotVersion:snapshotVersion];
  262. }
  263. }
  264. - (void)watchStreamWasInterruptedWithError:(nullable NSError *)error {
  265. HARD_ASSERT([self isNetworkEnabled],
  266. "watchStreamWasInterruptedWithError: should only be called when the network is "
  267. "enabled");
  268. [self cleanUpWatchStreamState];
  269. // If the watch stream closed due to an error, retry the connection if there are any active
  270. // watch targets.
  271. if ([self shouldStartWatchStream]) {
  272. if (error) {
  273. // There should generally be an error if the watch stream was closed when it's still needed,
  274. // but it's not quite worth asserting.
  275. [self.onlineStateTracker handleWatchStreamFailure:error];
  276. }
  277. [self startWatchStream];
  278. } else {
  279. // We don't need to restart the watch stream because there are no active targets. The online
  280. // state is set to unknown because there is no active attempt at establishing a connection.
  281. [self.onlineStateTracker updateState:OnlineState::Unknown];
  282. }
  283. }
  284. /**
  285. * Takes a batch of changes from the Datastore, repackages them as a RemoteEvent, and passes that
  286. * on to the SyncEngine.
  287. */
  288. - (void)raiseWatchSnapshotWithSnapshotVersion:(const SnapshotVersion &)snapshotVersion {
  289. HARD_ASSERT(snapshotVersion != SnapshotVersion::None(),
  290. "Can't raise event for unknown SnapshotVersion");
  291. FSTRemoteEvent *remoteEvent =
  292. [self.watchChangeAggregator remoteEventAtSnapshotVersion:snapshotVersion];
  293. // Update in-memory resume tokens. FSTLocalStore will update the persistent view of these when
  294. // applying the completed FSTRemoteEvent.
  295. for (const auto &entry : remoteEvent.targetChanges) {
  296. NSData *resumeToken = entry.second.resumeToken;
  297. if (resumeToken.length > 0) {
  298. FSTBoxedTargetID *targetID = @(entry.first);
  299. FSTQueryData *queryData = _listenTargets[targetID];
  300. // A watched target might have been removed already.
  301. if (queryData) {
  302. _listenTargets[targetID] =
  303. [queryData queryDataByReplacingSnapshotVersion:snapshotVersion
  304. resumeToken:resumeToken
  305. sequenceNumber:queryData.sequenceNumber];
  306. }
  307. }
  308. }
  309. // Re-establish listens for the targets that have been invalidated by existence filter mismatches.
  310. for (TargetId targetID : remoteEvent.targetMismatches) {
  311. FSTQueryData *queryData = self.listenTargets[@(targetID)];
  312. if (!queryData) {
  313. // A watched target might have been removed already.
  314. continue;
  315. }
  316. // Clear the resume token for the query, since we're in a known mismatch state.
  317. queryData = [[FSTQueryData alloc] initWithQuery:queryData.query
  318. targetID:targetID
  319. listenSequenceNumber:queryData.sequenceNumber
  320. purpose:queryData.purpose];
  321. self.listenTargets[@(targetID)] = queryData;
  322. // Cause a hard reset by unwatching and rewatching immediately, but deliberately don't send a
  323. // resume token so that we get a full update.
  324. [self sendUnwatchRequestForTargetID:@(targetID)];
  325. // Mark the query we send as being on behalf of an existence filter mismatch, but don't actually
  326. // retain that in listenTargets. This ensures that we flag the first re-listen this way without
  327. // impacting future listens of this target (that might happen e.g. on reconnect).
  328. FSTQueryData *requestQueryData =
  329. [[FSTQueryData alloc] initWithQuery:queryData.query
  330. targetID:targetID
  331. listenSequenceNumber:queryData.sequenceNumber
  332. purpose:FSTQueryPurposeExistenceFilterMismatch];
  333. [self sendWatchRequestWithQueryData:requestQueryData];
  334. }
  335. // Finally handle remote event
  336. [self.syncEngine applyRemoteEvent:remoteEvent];
  337. }
  338. /** Process a target error and passes the error along to SyncEngine. */
  339. - (void)processTargetErrorForWatchChange:(FSTWatchTargetChange *)change {
  340. HARD_ASSERT(change.cause, "Handling target error without a cause");
  341. // Ignore targets that have been removed already.
  342. for (FSTBoxedTargetID *targetID in change.targetIDs) {
  343. if (self.listenTargets[targetID]) {
  344. int unboxedTargetId = targetID.intValue;
  345. [self.listenTargets removeObjectForKey:targetID];
  346. [self.watchChangeAggregator removeTarget:unboxedTargetId];
  347. [self.syncEngine rejectListenWithTargetID:unboxedTargetId error:change.cause];
  348. }
  349. }
  350. }
  351. - (firebase::firestore::model::DocumentKeySet)remoteKeysForTarget:(FSTBoxedTargetID *)targetID {
  352. return [self.syncEngine remoteKeysForTarget:targetID];
  353. }
  354. - (nullable FSTQueryData *)queryDataForTarget:(FSTBoxedTargetID *)targetID {
  355. return self.listenTargets[targetID];
  356. }
  357. #pragma mark Write Stream
  358. /**
  359. * Returns YES if the network is enabled, the write stream has not yet been started and there are
  360. * pending writes.
  361. */
  362. - (BOOL)shouldStartWriteStream {
  363. return [self isNetworkEnabled] && ![self.writeStream isStarted] && self.writePipeline.count > 0;
  364. }
  365. - (void)startWriteStream {
  366. HARD_ASSERT([self shouldStartWriteStream],
  367. "startWriteStream: called when shouldStartWriteStream: is false.");
  368. [self.writeStream startWithDelegate:self];
  369. }
  370. /**
  371. * Attempts to fill our write pipeline with writes from the LocalStore.
  372. *
  373. * Called internally to bootstrap or refill the write pipeline and by SyncEngine whenever there
  374. * are new mutations to process.
  375. *
  376. * Starts the write stream if necessary.
  377. */
  378. - (void)fillWritePipeline {
  379. BatchId lastBatchIDRetrieved =
  380. self.writePipeline.count == 0 ? kFSTBatchIDUnknown : self.writePipeline.lastObject.batchID;
  381. while ([self canAddToWritePipeline]) {
  382. FSTMutationBatch *batch = [self.localStore nextMutationBatchAfterBatchID:lastBatchIDRetrieved];
  383. if (!batch) {
  384. if (self.writePipeline.count == 0) {
  385. [self.writeStream markIdle];
  386. }
  387. break;
  388. }
  389. [self addBatchToWritePipeline:batch];
  390. lastBatchIDRetrieved = batch.batchID;
  391. }
  392. if ([self shouldStartWriteStream]) {
  393. [self startWriteStream];
  394. }
  395. }
  396. /**
  397. * Returns YES if we can add to the write pipeline (i.e. it is not full and the network is enabled).
  398. */
  399. - (BOOL)canAddToWritePipeline {
  400. return [self isNetworkEnabled] && self.writePipeline.count < kMaxPendingWrites;
  401. }
  402. /**
  403. * Queues additional writes to be sent to the write stream, sending them immediately if the write
  404. * stream is established, else starting the write stream if it is not yet started.
  405. */
  406. - (void)addBatchToWritePipeline:(FSTMutationBatch *)batch {
  407. HARD_ASSERT([self canAddToWritePipeline],
  408. "addBatchToWritePipeline called when mutations can't be written");
  409. [self.writePipeline addObject:batch];
  410. if ([self shouldStartWriteStream]) {
  411. [self startWriteStream];
  412. } else if ([self isNetworkEnabled] && self.writeStream.handshakeComplete) {
  413. [self.writeStream writeMutations:batch.mutations];
  414. }
  415. }
  416. - (void)writeStreamDidOpen {
  417. [self.writeStream writeHandshake];
  418. }
  419. /**
  420. * Handles a successful handshake response from the server, which is our cue to send any pending
  421. * writes.
  422. */
  423. - (void)writeStreamDidCompleteHandshake {
  424. // Record the stream token.
  425. [self.localStore setLastStreamToken:self.writeStream.lastStreamToken];
  426. // Send the write pipeline now that the stream is established.
  427. for (FSTMutationBatch *write in self.writePipeline) {
  428. [self.writeStream writeMutations:write.mutations];
  429. }
  430. }
  431. /** Handles a successful StreamingWriteResponse from the server that contains a mutation result. */
  432. - (void)writeStreamDidReceiveResponseWithVersion:(const SnapshotVersion &)commitVersion
  433. mutationResults:(NSArray<FSTMutationResult *> *)results {
  434. // This is a response to a write containing mutations and should be correlated to the first
  435. // write in our write pipeline.
  436. NSMutableArray *writePipeline = self.writePipeline;
  437. FSTMutationBatch *batch = writePipeline[0];
  438. [writePipeline 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)writeStreamWasInterruptedWithError:(nullable NSError *)error {
  453. HARD_ASSERT([self isNetworkEnabled],
  454. "writeStreamDidClose: should only be called when the network is enabled");
  455. // If the write stream closed due to an error, invoke the error callbacks if there are pending
  456. // writes.
  457. if (error != nil && self.writePipeline.count > 0) {
  458. if (self.writeStream.handshakeComplete) {
  459. // This error affects the actual writes.
  460. [self handleWriteError:error];
  461. } else {
  462. // If there was an error before the handshake finished, it's possible that the server is
  463. // unable to process the stream token we're sending. (Perhaps it's too old?)
  464. [self handleHandshakeError:error];
  465. }
  466. }
  467. // The write stream might have been started by refilling the write pipeline for failed writes
  468. if ([self shouldStartWriteStream]) {
  469. [self startWriteStream];
  470. }
  471. }
  472. - (void)handleHandshakeError:(NSError *)error {
  473. // Reset the token if it's a permanent error or the error code is ABORTED, signaling the write
  474. // stream is no longer valid.
  475. if ([FSTDatastore isPermanentWriteError:error] || [FSTDatastore isAbortedError:error]) {
  476. NSString *token = [self.writeStream.lastStreamToken base64EncodedStringWithOptions:0];
  477. LOG_DEBUG("FSTRemoteStore %s error before completed handshake; resetting stream token %s: %s",
  478. (__bridge void *)self, token, error);
  479. self.writeStream.lastStreamToken = nil;
  480. [self.localStore setLastStreamToken:nil];
  481. }
  482. }
  483. - (void)handleWriteError:(NSError *)error {
  484. // Only handle permanent error. If it's transient, just let the retry logic kick in.
  485. if (![FSTDatastore isPermanentWriteError:error]) {
  486. return;
  487. }
  488. // If this was a permanent error, the request itself was the problem so it's not going to
  489. // succeed if we resend it.
  490. FSTMutationBatch *batch = self.writePipeline[0];
  491. [self.writePipeline removeObjectAtIndex:0];
  492. // In this case it's also unlikely that the server itself is melting down--this was just a
  493. // bad request so inhibit backoff on the next restart.
  494. [self.writeStream inhibitBackoff];
  495. [self.syncEngine rejectFailedWriteWithBatchID:batch.batchID error:error];
  496. // It's possible that with the completion of this mutation another slot has freed up.
  497. [self fillWritePipeline];
  498. }
  499. - (FSTTransaction *)transaction {
  500. return [FSTTransaction transactionWithDatastore:self.datastore];
  501. }
  502. @end
  503. NS_ASSUME_NONNULL_END