FSTRemoteStore.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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::DocumentKey;
  40. using firebase::firestore::model::SnapshotVersion;
  41. using firebase::firestore::model::DocumentKeySet;
  42. NS_ASSUME_NONNULL_BEGIN
  43. /**
  44. * The maximum number of pending writes to allow.
  45. * TODO(bjornick): Negotiate this value with the backend.
  46. */
  47. static const int kMaxPendingWrites = 10;
  48. #pragma mark - FSTRemoteStore
  49. @interface FSTRemoteStore () <FSTWatchStreamDelegate, FSTWriteStreamDelegate>
  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, assign) FSTBatchID lastBatchSeen;
  86. @property(nonatomic, strong, readonly) FSTOnlineStateTracker *onlineStateTracker;
  87. @property(nonatomic, strong, nullable) FSTWatchChangeAggregator *watchChangeAggregator;
  88. #pragma mark Write Stream
  89. // The writeStream is null when the network is disabled. The non-null check is performed by
  90. // isNetworkEnabled.
  91. @property(nonatomic, strong, nullable) FSTWriteStream *writeStream;
  92. /**
  93. * A FIFO queue of in-flight writes. This is in-flight from the point of view of the caller of
  94. * writeMutations, not from the point of view from the Datastore itself. In particular, these
  95. * requests may not have been sent to the Datastore server if the write stream is not yet running.
  96. */
  97. @property(nonatomic, strong, readonly) NSMutableArray<FSTMutationBatch *> *pendingWrites;
  98. @end
  99. @implementation FSTRemoteStore
  100. - (instancetype)initWithLocalStore:(FSTLocalStore *)localStore
  101. datastore:(FSTDatastore *)datastore
  102. workerDispatchQueue:(FSTDispatchQueue *)queue {
  103. if (self = [super init]) {
  104. _localStore = localStore;
  105. _datastore = datastore;
  106. _listenTargets = [NSMutableDictionary dictionary];
  107. _lastBatchSeen = kFSTBatchIDUnknown;
  108. _pendingWrites = [NSMutableArray array];
  109. _onlineStateTracker = [[FSTOnlineStateTracker alloc] initWithWorkerDispatchQueue:queue];
  110. }
  111. return self;
  112. }
  113. - (void)start {
  114. // For now, all setup is handled by enableNetwork(). We might expand on this in the future.
  115. [self enableNetwork];
  116. }
  117. @dynamic onlineStateDelegate;
  118. - (nullable id<FSTOnlineStateDelegate>)onlineStateDelegate {
  119. return self.onlineStateTracker.onlineStateDelegate;
  120. }
  121. - (void)setOnlineStateDelegate:(nullable id<FSTOnlineStateDelegate>)delegate {
  122. self.onlineStateTracker.onlineStateDelegate = delegate;
  123. }
  124. #pragma mark Online/Offline state
  125. - (BOOL)isNetworkEnabled {
  126. HARD_ASSERT((self.watchStream == nil) == (self.writeStream == nil),
  127. "WatchStream and WriteStream should both be null or non-null");
  128. return self.watchStream != nil;
  129. }
  130. - (void)enableNetwork {
  131. if ([self isNetworkEnabled]) {
  132. return;
  133. }
  134. // Create new streams (but note they're not started yet).
  135. self.watchStream = [self.datastore createWatchStream];
  136. self.writeStream = [self.datastore createWriteStream];
  137. // Load any saved stream token from persistent storage
  138. self.writeStream.lastStreamToken = [self.localStore lastStreamToken];
  139. if ([self shouldStartWatchStream]) {
  140. [self startWatchStream];
  141. } else {
  142. [self.onlineStateTracker updateState:FSTOnlineStateUnknown];
  143. }
  144. [self fillWritePipeline]; // This may start the writeStream.
  145. }
  146. - (void)disableNetwork {
  147. [self disableNetworkInternal];
  148. // Set the FSTOnlineState to Offline so get()s return from cache, etc.
  149. [self.onlineStateTracker updateState:FSTOnlineStateOffline];
  150. }
  151. /** Disables the network, setting the FSTOnlineState to the specified targetOnlineState. */
  152. - (void)disableNetworkInternal {
  153. if ([self isNetworkEnabled]) {
  154. // NOTE: We're guaranteed not to get any further events from these streams (not even a close
  155. // event).
  156. [self.watchStream stop];
  157. [self.writeStream stop];
  158. [self cleanUpWatchStreamState];
  159. [self cleanUpWriteStreamState];
  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 FSTOnlineState to Unknown (rather than Offline) to avoid potentially triggering
  169. // spurious listener events with cached data, etc.
  170. [self.onlineStateTracker updateState:FSTOnlineStateUnknown];
  171. }
  172. - (void)userDidChange:(const User &)user {
  173. LOG_DEBUG("FSTRemoteStore %s changing users: %s", (__bridge void *)self, user.uid());
  174. if ([self isNetworkEnabled]) {
  175. // Tear down and re-create our network streams. This will ensure we get a fresh auth token
  176. // for the new user and re-fill the write pipeline with new mutations from the LocalStore
  177. // (since mutations are per-user).
  178. [self disableNetworkInternal];
  179. [self.onlineStateTracker updateState:FSTOnlineStateUnknown];
  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:(FSTTargetID)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:FSTOnlineStateOnline];
  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. [self.onlineStateTracker handleWatchStreamFailure];
  270. // If the watch stream closed due to an error, retry the connection if there are any active
  271. // watch targets.
  272. if ([self shouldStartWatchStream]) {
  273. [self startWatchStream];
  274. } else {
  275. // We don't need to restart the watch stream because there are no active targets. The online
  276. // state is set to unknown because there is no active attempt at establishing a connection.
  277. [self.onlineStateTracker updateState:FSTOnlineStateUnknown];
  278. }
  279. }
  280. /**
  281. * Takes a batch of changes from the Datastore, repackages them as a RemoteEvent, and passes that
  282. * on to the SyncEngine.
  283. */
  284. - (void)raiseWatchSnapshotWithSnapshotVersion:(const SnapshotVersion &)snapshotVersion {
  285. HARD_ASSERT(snapshotVersion != SnapshotVersion::None(),
  286. "Can't raise event for unknown SnapshotVersion");
  287. FSTRemoteEvent *remoteEvent =
  288. [self.watchChangeAggregator remoteEventAtSnapshotVersion:snapshotVersion];
  289. // Update in-memory resume tokens. FSTLocalStore will update the persistent view of these when
  290. // applying the completed FSTRemoteEvent.
  291. for (const auto &entry : remoteEvent.targetChanges) {
  292. NSData *resumeToken = entry.second.resumeToken;
  293. if (resumeToken.length > 0) {
  294. FSTBoxedTargetID *targetID = @(entry.first);
  295. FSTQueryData *queryData = _listenTargets[targetID];
  296. // A watched target might have been removed already.
  297. if (queryData) {
  298. _listenTargets[targetID] =
  299. [queryData queryDataByReplacingSnapshotVersion:snapshotVersion
  300. resumeToken:resumeToken
  301. sequenceNumber:queryData.sequenceNumber];
  302. }
  303. }
  304. }
  305. // Re-establish listens for the targets that have been invalidated by existence filter mismatches.
  306. for (FSTTargetID targetID : remoteEvent.targetMismatches) {
  307. FSTQueryData *queryData = self.listenTargets[@(targetID)];
  308. if (!queryData) {
  309. // A watched target might have been removed already.
  310. continue;
  311. }
  312. // Clear the resume token for the query, since we're in a known mismatch state.
  313. queryData = [[FSTQueryData alloc] initWithQuery:queryData.query
  314. targetID:targetID
  315. listenSequenceNumber:queryData.sequenceNumber
  316. purpose:queryData.purpose];
  317. self.listenTargets[@(targetID)] = queryData;
  318. // Cause a hard reset by unwatching and rewatching immediately, but deliberately don't send a
  319. // resume token so that we get a full update.
  320. [self sendUnwatchRequestForTargetID:@(targetID)];
  321. // Mark the query we send as being on behalf of an existence filter mismatch, but don't actually
  322. // retain that in listenTargets. This ensures that we flag the first re-listen this way without
  323. // impacting future listens of this target (that might happen e.g. on reconnect).
  324. FSTQueryData *requestQueryData =
  325. [[FSTQueryData alloc] initWithQuery:queryData.query
  326. targetID:targetID
  327. listenSequenceNumber:queryData.sequenceNumber
  328. purpose:FSTQueryPurposeExistenceFilterMismatch];
  329. [self sendWatchRequestWithQueryData:requestQueryData];
  330. }
  331. // Finally handle remote event
  332. [self.syncEngine applyRemoteEvent:remoteEvent];
  333. }
  334. /** Process a target error and passes the error along to SyncEngine. */
  335. - (void)processTargetErrorForWatchChange:(FSTWatchTargetChange *)change {
  336. HARD_ASSERT(change.cause, "Handling target error without a cause");
  337. // Ignore targets that have been removed already.
  338. for (FSTBoxedTargetID *targetID in change.targetIDs) {
  339. if (self.listenTargets[targetID]) {
  340. [self.listenTargets removeObjectForKey:targetID];
  341. [self.syncEngine rejectListenWithTargetID:[targetID intValue] error:change.cause];
  342. }
  343. }
  344. }
  345. - (firebase::firestore::model::DocumentKeySet)remoteKeysForTarget:(FSTBoxedTargetID *)targetID {
  346. return [self.syncEngine remoteKeysForTarget:targetID];
  347. }
  348. - (nullable FSTQueryData *)queryDataForTarget:(FSTBoxedTargetID *)targetID {
  349. return self.listenTargets[targetID];
  350. }
  351. #pragma mark Write Stream
  352. /**
  353. * Returns YES if the network is enabled, the write stream has not yet been started and there are
  354. * pending writes.
  355. */
  356. - (BOOL)shouldStartWriteStream {
  357. return [self isNetworkEnabled] && ![self.writeStream isStarted] && self.pendingWrites.count > 0;
  358. }
  359. - (void)startWriteStream {
  360. HARD_ASSERT([self shouldStartWriteStream],
  361. "startWriteStream: called when shouldStartWriteStream: is false.");
  362. [self.writeStream startWithDelegate:self];
  363. }
  364. - (void)cleanUpWriteStreamState {
  365. self.lastBatchSeen = kFSTBatchIDUnknown;
  366. LOG_DEBUG("Stopping write stream with %s pending writes", [self.pendingWrites count]);
  367. [self.pendingWrites removeAllObjects];
  368. }
  369. - (void)fillWritePipeline {
  370. if ([self isNetworkEnabled]) {
  371. while ([self canWriteMutations]) {
  372. FSTMutationBatch *batch = [self.localStore nextMutationBatchAfterBatchID:self.lastBatchSeen];
  373. if (!batch) {
  374. break;
  375. }
  376. [self commitBatch:batch];
  377. }
  378. if ([self.pendingWrites count] == 0) {
  379. [self.writeStream markIdle];
  380. }
  381. }
  382. }
  383. /**
  384. * Returns YES if the backend can accept additional write requests.
  385. *
  386. * When sending mutations to the write stream (e.g. in -fillWritePipeline), call this method first
  387. * to check if more mutations can be sent.
  388. *
  389. * Currently the only thing that can prevent the backend from accepting write requests is if
  390. * there are too many requests already outstanding. As writes complete the backend will be able
  391. * to accept more.
  392. */
  393. - (BOOL)canWriteMutations {
  394. return [self isNetworkEnabled] && self.pendingWrites.count < kMaxPendingWrites;
  395. }
  396. /** Given mutations to commit, actually commits them to the backend. */
  397. - (void)commitBatch:(FSTMutationBatch *)batch {
  398. HARD_ASSERT([self canWriteMutations], "commitBatch called when mutations can't be written");
  399. self.lastBatchSeen = batch.batchID;
  400. [self.pendingWrites addObject:batch];
  401. if ([self shouldStartWriteStream]) {
  402. [self startWriteStream];
  403. } else if ([self isNetworkEnabled] && self.writeStream.handshakeComplete) {
  404. [self.writeStream writeMutations:batch.mutations];
  405. }
  406. }
  407. - (void)writeStreamDidOpen {
  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:(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. // 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)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.pendingWrites.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.pendingWrites[0];
  491. [self.pendingWrites 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