FSTRemoteStore.mm 26 KB

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