FSTRemoteStore.mm 23 KB

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