FSTRemoteStore.mm 23 KB

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