FSTStream.mm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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 <GRPCClient/GRPCCall+OAuth2.h>
  17. #import <GRPCClient/GRPCCall.h>
  18. #import "FIRFirestoreErrors.h"
  19. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  20. #import "Firestore/Source/Local/FSTQueryData.h"
  21. #import "Firestore/Source/Model/FSTMutation.h"
  22. #import "Firestore/Source/Remote/FSTBufferedWriter.h"
  23. #import "Firestore/Source/Remote/FSTDatastore.h"
  24. #import "Firestore/Source/Remote/FSTExponentialBackoff.h"
  25. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  26. #import "Firestore/Source/Remote/FSTStream.h"
  27. #import "Firestore/Source/Util/FSTClasses.h"
  28. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  29. #import "Firestore/Protos/objc/google/firestore/v1beta1/Firestore.pbrpc.h"
  30. #include "Firestore/core/src/firebase/firestore/auth/token.h"
  31. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  32. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  33. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  34. #include "Firestore/core/src/firebase/firestore/util/error_apple.h"
  35. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  36. #include "Firestore/core/src/firebase/firestore/util/log.h"
  37. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  38. namespace util = firebase::firestore::util;
  39. using firebase::firestore::auth::CredentialsProvider;
  40. using firebase::firestore::auth::Token;
  41. using firebase::firestore::core::DatabaseInfo;
  42. using firebase::firestore::model::DatabaseId;
  43. using firebase::firestore::model::SnapshotVersion;
  44. /**
  45. * Initial backoff time in seconds after an error.
  46. * Set to 1s according to https://cloud.google.com/apis/design/errors.
  47. */
  48. static const NSTimeInterval kBackoffInitialDelay = 1;
  49. static const NSTimeInterval kBackoffMaxDelay = 60.0;
  50. static const double kBackoffFactor = 1.5;
  51. #pragma mark - FSTStream
  52. /** The state of a stream. */
  53. typedef NS_ENUM(NSInteger, FSTStreamState) {
  54. /**
  55. * The streaming RPC is not running and there's no error condition. Calling `start` will
  56. * start the stream immediately without backoff. While in this state -isStarted will return NO.
  57. */
  58. FSTStreamStateInitial = 0,
  59. /**
  60. * The stream is starting, and is waiting for an auth token to attach to the initial request.
  61. * While in this state, isStarted will return YES but isOpen will return NO.
  62. */
  63. FSTStreamStateAuth,
  64. /**
  65. * The streaming RPC is up and running. Requests and responses can flow freely. Both
  66. * isStarted and isOpen will return YES.
  67. */
  68. FSTStreamStateOpen,
  69. /**
  70. * The stream encountered an error. The next start attempt will back off. While in this state
  71. * -isStarted will return NO.
  72. */
  73. FSTStreamStateError,
  74. /**
  75. * An in-between state after an error where the stream is waiting before re-starting. After
  76. * waiting is complete, the stream will try to open. While in this state -isStarted will
  77. * return YES but isOpen will return NO.
  78. */
  79. FSTStreamStateBackoff,
  80. /**
  81. * The stream has been explicitly stopped; no further events will be emitted.
  82. */
  83. FSTStreamStateStopped,
  84. };
  85. // We need to declare these classes first so that Datastore can alloc them.
  86. @interface FSTWatchStream ()
  87. /**
  88. * Initializes the watch stream with its dependencies.
  89. */
  90. - (instancetype)initWithDatabase:(const DatabaseInfo *)database
  91. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  92. credentials:(CredentialsProvider *)credentials
  93. serializer:(FSTSerializerBeta *)serializer NS_DESIGNATED_INITIALIZER;
  94. - (instancetype)initWithDatabase:(const DatabaseInfo *)database
  95. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  96. credentials:(CredentialsProvider *)credentials
  97. responseMessageClass:(Class)responseMessageClass NS_UNAVAILABLE;
  98. @end
  99. @interface FSTStream ()
  100. @property(nonatomic, assign, readonly) FSTTimerID idleTimerID;
  101. @property(nonatomic, strong, nullable) FSTDelayedCallback *idleTimerCallback;
  102. @property(nonatomic, weak, readwrite, nullable) id delegate;
  103. @end
  104. @interface FSTStream () <GRXWriteable>
  105. // Does not own this DatabaseInfo.
  106. @property(nonatomic, assign, readonly) const DatabaseInfo *databaseInfo;
  107. @property(nonatomic, strong, readonly) FSTDispatchQueue *workerDispatchQueue;
  108. @property(nonatomic, assign, readonly) CredentialsProvider *credentials;
  109. @property(nonatomic, unsafe_unretained, readonly) Class responseMessageClass;
  110. @property(nonatomic, strong, readonly) FSTExponentialBackoff *backoff;
  111. /** A flag tracking whether the stream received a message from the backend. */
  112. @property(nonatomic, assign) BOOL messageReceived;
  113. /**
  114. * Stream state as exposed to consumers of FSTStream. This differs from GRXWriter's notion of the
  115. * state of the stream.
  116. */
  117. @property(nonatomic, assign) FSTStreamState state;
  118. /** The RPC handle. Used for cancellation. */
  119. @property(nonatomic, strong, nullable) GRPCCall *rpc;
  120. /**
  121. * The send-side of the RPC stream in which to submit requests, but only once the underlying RPC has
  122. * started.
  123. */
  124. @property(nonatomic, strong, nullable) FSTBufferedWriter *requestsWriter;
  125. @end
  126. #pragma mark - FSTCallbackFilter
  127. /**
  128. * Implements callbacks from gRPC via the GRXWriteable protocol. This is separate from the main
  129. * FSTStream to allow the stream to be stopped externally (either by the user or via idle timer)
  130. * and be able to completely prevent any subsequent events from gRPC from calling back into the
  131. * FSTSTream.
  132. */
  133. @interface FSTCallbackFilter : NSObject <GRXWriteable>
  134. - (instancetype)initWithStream:(FSTStream *)stream NS_DESIGNATED_INITIALIZER;
  135. - (instancetype)init NS_UNAVAILABLE;
  136. @property(atomic, readwrite) BOOL callbacksEnabled;
  137. @property(nonatomic, strong, readonly) FSTStream *stream;
  138. @end
  139. @implementation FSTCallbackFilter
  140. - (instancetype)initWithStream:(FSTStream *)stream {
  141. if (self = [super init]) {
  142. _callbacksEnabled = YES;
  143. _stream = stream;
  144. }
  145. return self;
  146. }
  147. - (void)suppressCallbacks {
  148. _callbacksEnabled = NO;
  149. }
  150. - (void)writeValue:(id)value {
  151. if (_callbacksEnabled) {
  152. [self.stream writeValue:value];
  153. }
  154. }
  155. - (void)writesFinishedWithError:(NSError *)errorOrNil {
  156. if (_callbacksEnabled) {
  157. [self.stream writesFinishedWithError:errorOrNil];
  158. }
  159. }
  160. @end
  161. #pragma mark - FSTStream
  162. @interface FSTStream ()
  163. @property(nonatomic, strong, readwrite) FSTCallbackFilter *callbackFilter;
  164. @end
  165. @implementation FSTStream
  166. /** The time a stream stays open after it is marked idle. */
  167. static const NSTimeInterval kIdleTimeout = 60.0;
  168. - (instancetype)initWithDatabase:(const DatabaseInfo *)database
  169. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  170. connectionTimerID:(FSTTimerID)connectionTimerID
  171. idleTimerID:(FSTTimerID)idleTimerID
  172. credentials:(CredentialsProvider *)credentials
  173. responseMessageClass:(Class)responseMessageClass {
  174. if (self = [super init]) {
  175. _databaseInfo = database;
  176. _workerDispatchQueue = workerDispatchQueue;
  177. _idleTimerID = idleTimerID;
  178. _credentials = credentials;
  179. _responseMessageClass = responseMessageClass;
  180. _backoff = [[FSTExponentialBackoff alloc] initWithDispatchQueue:workerDispatchQueue
  181. timerID:connectionTimerID
  182. initialDelay:kBackoffInitialDelay
  183. backoffFactor:kBackoffFactor
  184. maxDelay:kBackoffMaxDelay];
  185. _state = FSTStreamStateInitial;
  186. }
  187. return self;
  188. }
  189. - (BOOL)isStarted {
  190. [self.workerDispatchQueue verifyIsCurrentQueue];
  191. FSTStreamState state = self.state;
  192. return state == FSTStreamStateBackoff || state == FSTStreamStateAuth ||
  193. state == FSTStreamStateOpen;
  194. }
  195. - (BOOL)isOpen {
  196. [self.workerDispatchQueue verifyIsCurrentQueue];
  197. return self.state == FSTStreamStateOpen;
  198. }
  199. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter {
  200. @throw FSTAbstractMethodException(); // NOLINT
  201. }
  202. - (void)startWithDelegate:(id)delegate {
  203. [self.workerDispatchQueue verifyIsCurrentQueue];
  204. if (self.state == FSTStreamStateError) {
  205. [self performBackoffWithDelegate:delegate];
  206. return;
  207. }
  208. LOG_DEBUG("%s %s start", NSStringFromClass([self class]), (__bridge void *)self);
  209. HARD_ASSERT(self.state == FSTStreamStateInitial, "Already started");
  210. self.state = FSTStreamStateAuth;
  211. HARD_ASSERT(_delegate == nil, "Delegate must be nil");
  212. _delegate = delegate;
  213. _credentials->GetToken(
  214. /*force_refresh=*/false, [self](util::StatusOr<Token> result) {
  215. [self.workerDispatchQueue dispatchAsyncAllowingSameQueue:^{
  216. [self resumeStartWithToken:result];
  217. }];
  218. });
  219. }
  220. /** Add an access token to our RPC, after obtaining one from the credentials provider. */
  221. - (void)resumeStartWithToken:(const util::StatusOr<Token> &)result {
  222. [self.workerDispatchQueue verifyIsCurrentQueue];
  223. if (self.state == FSTStreamStateStopped) {
  224. // Streams can be stopped while waiting for authorization.
  225. return;
  226. }
  227. HARD_ASSERT(self.state == FSTStreamStateAuth, "State should still be auth (was %s)", self.state);
  228. // TODO(mikelehen): We should force a refresh if the previous RPC failed due to an expired token,
  229. // but I'm not sure how to detect that right now. http://b/32762461
  230. if (!result.ok()) {
  231. // RPC has not been started yet, so just invoke higher-level close handler.
  232. [self handleStreamClose:util::MakeNSError(result.status())];
  233. return;
  234. }
  235. self.requestsWriter = [[FSTBufferedWriter alloc] init];
  236. _rpc = [self createRPCWithRequestsWriter:self.requestsWriter];
  237. [_rpc setResponseDispatchQueue:self.workerDispatchQueue.queue];
  238. const Token &token = result.ValueOrDie();
  239. [FSTDatastore
  240. prepareHeadersForRPC:_rpc
  241. databaseID:&self.databaseInfo->database_id()
  242. token:(token.user().is_authenticated() ? token.token() : absl::string_view())];
  243. HARD_ASSERT(_callbackFilter == nil, "GRX Filter must be nil");
  244. _callbackFilter = [[FSTCallbackFilter alloc] initWithStream:self];
  245. [_rpc startWithWriteable:_callbackFilter];
  246. self.state = FSTStreamStateOpen;
  247. [self notifyStreamOpen];
  248. }
  249. /** Backs off after an error. */
  250. - (void)performBackoffWithDelegate:(id)delegate {
  251. LOG_DEBUG("%s %s backoff", NSStringFromClass([self class]), (__bridge void *)self);
  252. [self.workerDispatchQueue verifyIsCurrentQueue];
  253. HARD_ASSERT(self.state == FSTStreamStateError, "Should only perform backoff in an error case");
  254. self.state = FSTStreamStateBackoff;
  255. FSTWeakify(self);
  256. [self.backoff backoffAndRunBlock:^{
  257. FSTStrongify(self);
  258. [self resumeStartFromBackoffWithDelegate:delegate];
  259. }];
  260. }
  261. /** Resumes stream start after backing off. */
  262. - (void)resumeStartFromBackoffWithDelegate:(id)delegate {
  263. if (self.state == FSTStreamStateStopped) {
  264. // We should have canceled the backoff timer when the stream was closed, but just in case we
  265. // make this a no-op.
  266. return;
  267. }
  268. // In order to have performed a backoff the stream must have been in an error state just prior
  269. // to entering the backoff state. If we weren't stopped we must be in the backoff state.
  270. HARD_ASSERT(self.state == FSTStreamStateBackoff, "State should still be backoff (was %s)",
  271. self.state);
  272. // Momentarily set state to FSTStreamStateInitial as `start` expects it.
  273. self.state = FSTStreamStateInitial;
  274. [self startWithDelegate:delegate];
  275. HARD_ASSERT([self isStarted], "Stream should have started.");
  276. }
  277. /**
  278. * Can be overridden to perform additional cleanup before the stream is closed. Calling
  279. * [super tearDown] is not required.
  280. */
  281. - (void)tearDown {
  282. }
  283. /**
  284. * Closes the stream and cleans up as necessary:
  285. *
  286. * * closes the underlying GRPC stream;
  287. * * calls the onClose handler with the given 'error';
  288. * * sets internal stream state to 'finalState';
  289. * * adjusts the backoff timer based on the error
  290. *
  291. * A new stream can be opened by calling `start` unless `finalState` is set to
  292. * `FSTStreamStateStopped`.
  293. *
  294. * @param finalState the intended state of the stream after closing.
  295. * @param error the NSError the connection was closed with.
  296. */
  297. - (void)closeWithFinalState:(FSTStreamState)finalState error:(nullable NSError *)error {
  298. HARD_ASSERT(finalState == FSTStreamStateError || error == nil,
  299. "Can't provide an error when not in an error state.");
  300. [self.workerDispatchQueue verifyIsCurrentQueue];
  301. // The stream will be closed so we don't need our idle close timer anymore.
  302. [self cancelIdleCheck];
  303. // Ensure we don't leave a pending backoff operation queued (in case close()
  304. // was called while we were waiting to reconnect).
  305. [self.backoff cancel];
  306. if (finalState != FSTStreamStateError) {
  307. // If this is an intentional close ensure we don't delay our next connection attempt.
  308. [self.backoff reset];
  309. } else if (error != nil && error.code == FIRFirestoreErrorCodeResourceExhausted) {
  310. LOG_DEBUG("%s %s Using maximum backoff delay to prevent overloading the backend.", [self class],
  311. (__bridge void *)self);
  312. [self.backoff resetToMax];
  313. }
  314. if (finalState != FSTStreamStateError) {
  315. LOG_DEBUG("%s %s Performing stream teardown", [self class], (__bridge void *)self);
  316. [self tearDown];
  317. }
  318. if (self.requestsWriter) {
  319. // Clean up the underlying RPC. If this close: is in response to an error, don't attempt to
  320. // call half-close to avoid secondary failures.
  321. if (finalState != FSTStreamStateError) {
  322. LOG_DEBUG("%s %s Closing stream client-side", [self class], (__bridge void *)self);
  323. @synchronized(self.requestsWriter) {
  324. [self.requestsWriter finishWithError:nil];
  325. }
  326. }
  327. _requestsWriter = nil;
  328. }
  329. // This state must be assigned before calling `notifyStreamInterrupted` to allow the callback to
  330. // inhibit backoff or otherwise manipulate the state in its non-started state.
  331. self.state = finalState;
  332. [self.callbackFilter suppressCallbacks];
  333. _callbackFilter = nil;
  334. // Clean up remaining state.
  335. _messageReceived = NO;
  336. _rpc = nil;
  337. // If the caller explicitly requested a stream stop, don't notify them of a closing stream (it
  338. // could trigger undesirable recovery logic, etc.).
  339. if (finalState != FSTStreamStateStopped) {
  340. [self notifyStreamInterruptedWithError:error];
  341. }
  342. // PORTING NOTE: notifyStreamInterruptedWithError may have restarted the stream with a new
  343. // delegate so we do /not/ want to clear the delegate here. And since we've already suppressed
  344. // callbacks via our callbackFilter, there is no worry about bleed through of events from GRPC.
  345. }
  346. - (void)stop {
  347. LOG_DEBUG("%s %s stop", NSStringFromClass([self class]), (__bridge void *)self);
  348. if ([self isStarted]) {
  349. [self closeWithFinalState:FSTStreamStateStopped error:nil];
  350. }
  351. }
  352. - (void)inhibitBackoff {
  353. HARD_ASSERT(![self isStarted], "Can only inhibit backoff after an error (was %s)", self.state);
  354. [self.workerDispatchQueue verifyIsCurrentQueue];
  355. // Clear the error condition.
  356. self.state = FSTStreamStateInitial;
  357. [self.backoff reset];
  358. }
  359. /** Called by the idle timer when the stream should close due to inactivity. */
  360. - (void)handleIdleCloseTimer {
  361. [self.workerDispatchQueue verifyIsCurrentQueue];
  362. if ([self isOpen]) {
  363. // When timing out an idle stream there's no reason to force the stream into backoff when
  364. // it restarts so set the stream state to Initial instead of Error.
  365. [self closeWithFinalState:FSTStreamStateInitial error:nil];
  366. }
  367. }
  368. - (void)markIdle {
  369. [self.workerDispatchQueue verifyIsCurrentQueue];
  370. // Starts the idle timer if we are in state 'Open' and are not yet already running a timer (in
  371. // which case the previous idle timeout still applies).
  372. if ([self isOpen] && !self.idleTimerCallback) {
  373. self.idleTimerCallback = [self.workerDispatchQueue dispatchAfterDelay:kIdleTimeout
  374. timerID:self.idleTimerID
  375. block:^() {
  376. [self handleIdleCloseTimer];
  377. }];
  378. }
  379. }
  380. - (void)cancelIdleCheck {
  381. [self.workerDispatchQueue verifyIsCurrentQueue];
  382. if (self.idleTimerCallback) {
  383. [self.idleTimerCallback cancel];
  384. self.idleTimerCallback = nil;
  385. }
  386. }
  387. /**
  388. * Parses a protocol buffer response from the server. If the message fails to parse, generates
  389. * an error and closes the stream.
  390. *
  391. * @param protoClass A protocol buffer message class object, that responds to parseFromData:error:.
  392. * @param data The bytes in the response as returned from GRPC.
  393. * @return An instance of the protocol buffer message, parsed from the data if parsing was
  394. * successful, or nil otherwise.
  395. */
  396. - (nullable id)parseProto:(Class)protoClass data:(NSData *)data error:(NSError **)error {
  397. NSError *parseError;
  398. id parsed = [protoClass parseFromData:data error:&parseError];
  399. if (parsed) {
  400. *error = nil;
  401. return parsed;
  402. } else {
  403. NSDictionary *info = @{
  404. NSLocalizedDescriptionKey : @"Unable to parse response from the server",
  405. NSUnderlyingErrorKey : parseError,
  406. @"Expected class" : protoClass,
  407. @"Received value" : data,
  408. };
  409. *error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  410. code:FIRFirestoreErrorCodeInternal
  411. userInfo:info];
  412. return nil;
  413. }
  414. }
  415. /**
  416. * Writes a request proto into the stream.
  417. */
  418. - (void)writeRequest:(GPBMessage *)request {
  419. NSData *data = [request data];
  420. [self cancelIdleCheck];
  421. FSTBufferedWriter *requestsWriter = self.requestsWriter;
  422. @synchronized(requestsWriter) {
  423. [requestsWriter writeValue:data];
  424. }
  425. }
  426. #pragma mark Template methods for subclasses
  427. /**
  428. * Called by the stream after the stream has opened.
  429. *
  430. * Subclasses should relay to their stream-specific delegate. Calling [super notifyStreamOpen] is
  431. * not required.
  432. */
  433. - (void)notifyStreamOpen {
  434. }
  435. /**
  436. * Called by the stream after the stream has been unexpectedly interrupted, either due to an error
  437. * or due to idleness.
  438. *
  439. * Subclasses should relay to their stream-specific delegate. Calling [super
  440. * notifyStreamInterrupted] is not required.
  441. */
  442. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  443. }
  444. /**
  445. * Called by the stream for each incoming protocol message coming from the server.
  446. *
  447. * Subclasses should implement this to deserialize the value and relay to their stream-specific
  448. * delegate, if appropriate. Calling [super handleStreamMessage] is not required.
  449. */
  450. - (void)handleStreamMessage:(id)value {
  451. }
  452. /**
  453. * Called by the stream when the underlying RPC has been closed for whatever reason.
  454. */
  455. - (void)handleStreamClose:(nullable NSError *)error {
  456. LOG_DEBUG("%s %s close: %s", NSStringFromClass([self class]), (__bridge void *)self, error);
  457. HARD_ASSERT([self isStarted], "handleStreamClose: called for non-started stream.");
  458. // In theory the stream could close cleanly, however, in our current model we never expect this
  459. // to happen because if we stop a stream ourselves, this callback will never be called. To
  460. // prevent cases where we retry without a backoff accidentally, we set the stream to error
  461. // in all cases.
  462. [self closeWithFinalState:FSTStreamStateError error:error];
  463. }
  464. #pragma mark GRXWriteable implementation
  465. // The GRXWriteable implementation defines the receive side of the RPC stream.
  466. /**
  467. * Called by GRPC when it publishes a value.
  468. *
  469. * GRPC must be configured to use our worker queue by calling
  470. * `[call setResponseDispatchQueue:self.workerDispatchQueue.queue]` on the GRPCCall before starting
  471. * the RPC.
  472. */
  473. - (void)writeValue:(id)value {
  474. [self.workerDispatchQueue enterCheckedOperation:^{
  475. HARD_ASSERT([self isStarted], "writeValue: called for stopped stream.");
  476. if (!self.messageReceived) {
  477. self.messageReceived = YES;
  478. if ([FIRFirestore isLoggingEnabled]) {
  479. LOG_DEBUG("%s %s headers (whitelisted): %s", NSStringFromClass([self class]),
  480. (__bridge void *)self,
  481. [FSTDatastore extractWhiteListedHeaders:self.rpc.responseHeaders]);
  482. }
  483. }
  484. NSError *error;
  485. id proto = [self parseProto:self.responseMessageClass data:value error:&error];
  486. if (proto) {
  487. [self handleStreamMessage:proto];
  488. } else {
  489. [self.rpc finishWithError:error];
  490. }
  491. }];
  492. }
  493. /**
  494. * Called by GRPC when it closed the stream with an error representing the final state of the
  495. * stream.
  496. *
  497. * GRPC must be configured to use our worker queue by calling
  498. * `[call setResponseDispatchQueue:self.workerDispatchQueue.queue]` on the GRPCCall before starting
  499. * the RPC.
  500. *
  501. * Do not call directly. Call handleStreamClose to directly inform stream-specific logic, or call
  502. * stop to tear down the stream.
  503. */
  504. - (void)writesFinishedWithError:(nullable NSError *)error __used {
  505. error = [FSTDatastore firestoreErrorForError:error];
  506. [self.workerDispatchQueue enterCheckedOperation:^{
  507. HARD_ASSERT([self isStarted], "writesFinishedWithError: called for stopped stream.");
  508. [self handleStreamClose:error];
  509. }];
  510. }
  511. @end
  512. #pragma mark - FSTWatchStream
  513. @interface FSTWatchStream ()
  514. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  515. @end
  516. @implementation FSTWatchStream
  517. - (instancetype)initWithDatabase:(const DatabaseInfo *)database
  518. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  519. credentials:(CredentialsProvider *)credentials
  520. serializer:(FSTSerializerBeta *)serializer {
  521. self = [super initWithDatabase:database
  522. workerDispatchQueue:workerDispatchQueue
  523. connectionTimerID:FSTTimerIDListenStreamConnectionBackoff
  524. idleTimerID:FSTTimerIDListenStreamIdle
  525. credentials:credentials
  526. responseMessageClass:[GCFSListenResponse class]];
  527. if (self) {
  528. _serializer = serializer;
  529. }
  530. return self;
  531. }
  532. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter {
  533. return [[GRPCCall alloc] initWithHost:util::WrapNSString(self.databaseInfo->host())
  534. path:@"/google.firestore.v1beta1.Firestore/Listen"
  535. requestsWriter:requestsWriter];
  536. }
  537. - (void)notifyStreamOpen {
  538. [self.delegate watchStreamDidOpen];
  539. }
  540. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  541. id<FSTWatchStreamDelegate> delegate = self.delegate;
  542. self.delegate = nil;
  543. [delegate watchStreamWasInterruptedWithError:error];
  544. }
  545. - (void)watchQuery:(FSTQueryData *)query {
  546. HARD_ASSERT([self isOpen], "Not yet open");
  547. [self.workerDispatchQueue verifyIsCurrentQueue];
  548. GCFSListenRequest *request = [GCFSListenRequest message];
  549. request.database = [_serializer encodedDatabaseID];
  550. request.addTarget = [_serializer encodedTarget:query];
  551. request.labels = [_serializer encodedListenRequestLabelsForQueryData:query];
  552. LOG_DEBUG("FSTWatchStream %s watch: %s", (__bridge void *)self, request);
  553. [self writeRequest:request];
  554. }
  555. - (void)unwatchTargetID:(FSTTargetID)targetID {
  556. HARD_ASSERT([self isOpen], "Not yet open");
  557. [self.workerDispatchQueue verifyIsCurrentQueue];
  558. GCFSListenRequest *request = [GCFSListenRequest message];
  559. request.database = [_serializer encodedDatabaseID];
  560. request.removeTarget = targetID;
  561. LOG_DEBUG("FSTWatchStream %s unwatch: %s", (__bridge void *)self, request);
  562. [self writeRequest:request];
  563. }
  564. /**
  565. * Receives an inbound message from GRPC, deserializes, and then passes that on to the delegate's
  566. * watchStreamDidChange:snapshotVersion: callback.
  567. */
  568. - (void)handleStreamMessage:(GCFSListenResponse *)proto {
  569. LOG_DEBUG("FSTWatchStream %s response: %s", (__bridge void *)self, proto);
  570. [self.workerDispatchQueue verifyIsCurrentQueue];
  571. // A successful response means the stream is healthy.
  572. [self.backoff reset];
  573. FSTWatchChange *change = [_serializer decodedWatchChange:proto];
  574. SnapshotVersion snap = [_serializer versionFromListenResponse:proto];
  575. [self.delegate watchStreamDidChange:change snapshotVersion:snap];
  576. }
  577. @end
  578. #pragma mark - FSTWriteStream
  579. @interface FSTWriteStream ()
  580. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  581. @end
  582. @implementation FSTWriteStream
  583. - (instancetype)initWithDatabase:(const DatabaseInfo *)database
  584. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  585. credentials:(CredentialsProvider *)credentials
  586. serializer:(FSTSerializerBeta *)serializer {
  587. self = [super initWithDatabase:database
  588. workerDispatchQueue:workerDispatchQueue
  589. connectionTimerID:FSTTimerIDWriteStreamConnectionBackoff
  590. idleTimerID:FSTTimerIDWriteStreamIdle
  591. credentials:credentials
  592. responseMessageClass:[GCFSWriteResponse class]];
  593. if (self) {
  594. _serializer = serializer;
  595. }
  596. return self;
  597. }
  598. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter {
  599. return [[GRPCCall alloc] initWithHost:util::WrapNSString(self.databaseInfo->host())
  600. path:@"/google.firestore.v1beta1.Firestore/Write"
  601. requestsWriter:requestsWriter];
  602. }
  603. - (void)startWithDelegate:(id)delegate {
  604. self.handshakeComplete = NO;
  605. [super startWithDelegate:delegate];
  606. }
  607. - (void)notifyStreamOpen {
  608. [self.delegate writeStreamDidOpen];
  609. }
  610. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  611. id<FSTWriteStreamDelegate> delegate = self.delegate;
  612. self.delegate = nil;
  613. [delegate writeStreamWasInterruptedWithError:error];
  614. }
  615. - (void)tearDown {
  616. if ([self isHandshakeComplete]) {
  617. // Send an empty write request to the backend to indicate imminent stream closure. This allows
  618. // the backend to clean up resources.
  619. [self writeMutations:@[]];
  620. }
  621. }
  622. - (void)writeHandshake {
  623. // The initial request cannot contain mutations, but must contain a projectID.
  624. HARD_ASSERT([self isOpen], "Not yet open");
  625. HARD_ASSERT(!self.handshakeComplete, "Handshake sent out of turn");
  626. [self.workerDispatchQueue verifyIsCurrentQueue];
  627. GCFSWriteRequest *request = [GCFSWriteRequest message];
  628. request.database = [_serializer encodedDatabaseID];
  629. // TODO(dimond): Support stream resumption. We intentionally do not set the stream token on the
  630. // handshake, ignoring any stream token we might have.
  631. LOG_DEBUG("FSTWriteStream %s initial request: %s", (__bridge void *)self, request);
  632. [self writeRequest:request];
  633. }
  634. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations {
  635. HARD_ASSERT([self isOpen], "Not yet open");
  636. HARD_ASSERT(self.handshakeComplete, "Mutations sent out of turn");
  637. [self.workerDispatchQueue verifyIsCurrentQueue];
  638. NSMutableArray<GCFSWrite *> *protos = [NSMutableArray arrayWithCapacity:mutations.count];
  639. for (FSTMutation *mutation in mutations) {
  640. [protos addObject:[_serializer encodedMutation:mutation]];
  641. };
  642. GCFSWriteRequest *request = [GCFSWriteRequest message];
  643. request.writesArray = protos;
  644. request.streamToken = self.lastStreamToken;
  645. LOG_DEBUG("FSTWriteStream %s mutation request: %s", (__bridge void *)self, request);
  646. [self writeRequest:request];
  647. }
  648. /**
  649. * Implements GRXWriteable to receive an inbound message from GRPC, deserialize, and then pass
  650. * that on to the mutationResultsHandler.
  651. */
  652. - (void)handleStreamMessage:(GCFSWriteResponse *)response {
  653. LOG_DEBUG("FSTWriteStream %s response: %s", (__bridge void *)self, response);
  654. [self.workerDispatchQueue verifyIsCurrentQueue];
  655. // Always capture the last stream token.
  656. self.lastStreamToken = response.streamToken;
  657. if (!self.isHandshakeComplete) {
  658. // The first response is the handshake response
  659. self.handshakeComplete = YES;
  660. [self.delegate writeStreamDidCompleteHandshake];
  661. } else {
  662. // A successful first write response means the stream is healthy.
  663. // Note that we could consider a successful handshake healthy, however, the write itself
  664. // might be causing an error we want to back off from.
  665. [self.backoff reset];
  666. SnapshotVersion commitVersion = [_serializer decodedVersion:response.commitTime];
  667. NSMutableArray<GCFSWriteResult *> *protos = response.writeResultsArray;
  668. NSMutableArray<FSTMutationResult *> *results = [NSMutableArray arrayWithCapacity:protos.count];
  669. for (GCFSWriteResult *proto in protos) {
  670. [results addObject:[_serializer decodedMutationResult:proto]];
  671. };
  672. [self.delegate writeStreamDidReceiveResponseWithVersion:commitVersion mutationResults:results];
  673. }
  674. }
  675. @end