FSTRemoteStore.mm 23 KB

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