FSTRemoteStore.mm 23 KB

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