FSTStream.mm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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/FSTAssert.h"
  28. #import "Firestore/Source/Util/FSTClasses.h"
  29. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  30. #import "Firestore/Source/Util/FSTLogger.h"
  31. #import "Firestore/Protos/objc/google/firestore/v1beta1/Firestore.pbrpc.h"
  32. #include "Firestore/core/src/firebase/firestore/auth/token.h"
  33. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  34. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  35. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  36. #include "Firestore/core/src/firebase/firestore/util/error_apple.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. FSTLog(@"%@ %p start", NSStringFromClass([self class]), (__bridge void *)self);
  209. FSTAssert(self.state == FSTStreamStateInitial, @"Already started");
  210. self.state = FSTStreamStateAuth;
  211. FSTAssert(_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. FSTAssert(self.state == FSTStreamStateAuth, @"State should still be auth (was %ld)",
  228. (long)self.state);
  229. // TODO(mikelehen): We should force a refresh if the previous RPC failed due to an expired token,
  230. // but I'm not sure how to detect that right now. http://b/32762461
  231. if (!result.ok()) {
  232. // RPC has not been started yet, so just invoke higher-level close handler.
  233. [self handleStreamClose:util::MakeNSError(result.status())];
  234. return;
  235. }
  236. self.requestsWriter = [[FSTBufferedWriter alloc] init];
  237. _rpc = [self createRPCWithRequestsWriter:self.requestsWriter];
  238. [_rpc setResponseDispatchQueue:self.workerDispatchQueue.queue];
  239. const Token &token = result.ValueOrDie();
  240. [FSTDatastore
  241. prepareHeadersForRPC:_rpc
  242. databaseID:&self.databaseInfo->database_id()
  243. token:(token.user().is_authenticated() ? token.token() : absl::string_view())];
  244. FSTAssert(_callbackFilter == nil, @"GRX Filter must be nil");
  245. _callbackFilter = [[FSTCallbackFilter alloc] initWithStream:self];
  246. [_rpc startWithWriteable:_callbackFilter];
  247. self.state = FSTStreamStateOpen;
  248. [self notifyStreamOpen];
  249. }
  250. /** Backs off after an error. */
  251. - (void)performBackoffWithDelegate:(id)delegate {
  252. FSTLog(@"%@ %p backoff", NSStringFromClass([self class]), (__bridge void *)self);
  253. [self.workerDispatchQueue verifyIsCurrentQueue];
  254. FSTAssert(self.state == FSTStreamStateError, @"Should only perform backoff in an error case");
  255. self.state = FSTStreamStateBackoff;
  256. FSTWeakify(self);
  257. [self.backoff backoffAndRunBlock:^{
  258. FSTStrongify(self);
  259. [self resumeStartFromBackoffWithDelegate:delegate];
  260. }];
  261. }
  262. /** Resumes stream start after backing off. */
  263. - (void)resumeStartFromBackoffWithDelegate:(id)delegate {
  264. if (self.state == FSTStreamStateStopped) {
  265. // We should have canceled the backoff timer when the stream was closed, but just in case we
  266. // make this a no-op.
  267. return;
  268. }
  269. // In order to have performed a backoff the stream must have been in an error state just prior
  270. // to entering the backoff state. If we weren't stopped we must be in the backoff state.
  271. FSTAssert(self.state == FSTStreamStateBackoff, @"State should still be backoff (was %ld)",
  272. (long)self.state);
  273. // Momentarily set state to FSTStreamStateInitial as `start` expects it.
  274. self.state = FSTStreamStateInitial;
  275. [self startWithDelegate:delegate];
  276. FSTAssert([self isStarted], @"Stream should have started.");
  277. }
  278. /**
  279. * Can be overridden to perform additional cleanup before the stream is closed. Calling
  280. * [super tearDown] is not required.
  281. */
  282. - (void)tearDown {
  283. }
  284. /**
  285. * Closes the stream and cleans up as necessary:
  286. *
  287. * * closes the underlying GRPC stream;
  288. * * calls the onClose handler with the given 'error';
  289. * * sets internal stream state to 'finalState';
  290. * * adjusts the backoff timer based on the error
  291. *
  292. * A new stream can be opened by calling `start` unless `finalState` is set to
  293. * `FSTStreamStateStopped`.
  294. *
  295. * @param finalState the intended state of the stream after closing.
  296. * @param error the NSError the connection was closed with.
  297. */
  298. - (void)closeWithFinalState:(FSTStreamState)finalState error:(nullable NSError *)error {
  299. FSTAssert(finalState == FSTStreamStateError || error == nil,
  300. @"Can't provide an error when not in an error state.");
  301. [self.workerDispatchQueue verifyIsCurrentQueue];
  302. // The stream will be closed so we don't need our idle close timer anymore.
  303. [self cancelIdleCheck];
  304. // Ensure we don't leave a pending backoff operation queued (in case close()
  305. // was called while we were waiting to reconnect).
  306. [self.backoff cancel];
  307. if (finalState != FSTStreamStateError) {
  308. // If this is an intentional close ensure we don't delay our next connection attempt.
  309. [self.backoff reset];
  310. } else if (error != nil && error.code == FIRFirestoreErrorCodeResourceExhausted) {
  311. FSTLog(@"%@ %p Using maximum backoff delay to prevent overloading the backend.", [self class],
  312. (__bridge void *)self);
  313. [self.backoff resetToMax];
  314. }
  315. if (finalState != FSTStreamStateError) {
  316. FSTLog(@"%@ %p Performing stream teardown", [self class], (__bridge void *)self);
  317. [self tearDown];
  318. }
  319. if (self.requestsWriter) {
  320. // Clean up the underlying RPC. If this close: is in response to an error, don't attempt to
  321. // call half-close to avoid secondary failures.
  322. if (finalState != FSTStreamStateError) {
  323. FSTLog(@"%@ %p Closing stream client-side", [self class], (__bridge void *)self);
  324. @synchronized(self.requestsWriter) {
  325. [self.requestsWriter finishWithError:nil];
  326. }
  327. }
  328. _requestsWriter = nil;
  329. }
  330. // This state must be assigned before calling `notifyStreamInterrupted` to allow the callback to
  331. // inhibit backoff or otherwise manipulate the state in its non-started state.
  332. self.state = finalState;
  333. [self.callbackFilter suppressCallbacks];
  334. _callbackFilter = nil;
  335. // Clean up remaining state.
  336. _messageReceived = NO;
  337. _rpc = nil;
  338. // If the caller explicitly requested a stream stop, don't notify them of a closing stream (it
  339. // could trigger undesirable recovery logic, etc.).
  340. if (finalState != FSTStreamStateStopped) {
  341. [self notifyStreamInterruptedWithError:error];
  342. }
  343. // PORTING NOTE: notifyStreamInterruptedWithError may have restarted the stream with a new
  344. // delegate so we do /not/ want to clear the delegate here. And since we've already suppressed
  345. // callbacks via our callbackFilter, there is no worry about bleed through of events from GRPC.
  346. }
  347. - (void)stop {
  348. FSTLog(@"%@ %p stop", NSStringFromClass([self class]), (__bridge void *)self);
  349. if ([self isStarted]) {
  350. [self closeWithFinalState:FSTStreamStateStopped error:nil];
  351. }
  352. }
  353. - (void)inhibitBackoff {
  354. FSTAssert(![self isStarted], @"Can only inhibit backoff after an error (was %ld)",
  355. (long)self.state);
  356. [self.workerDispatchQueue verifyIsCurrentQueue];
  357. // Clear the error condition.
  358. self.state = FSTStreamStateInitial;
  359. [self.backoff reset];
  360. }
  361. /** Called by the idle timer when the stream should close due to inactivity. */
  362. - (void)handleIdleCloseTimer {
  363. [self.workerDispatchQueue verifyIsCurrentQueue];
  364. if ([self isOpen]) {
  365. // When timing out an idle stream there's no reason to force the stream into backoff when
  366. // it restarts so set the stream state to Initial instead of Error.
  367. [self closeWithFinalState:FSTStreamStateInitial error:nil];
  368. }
  369. }
  370. - (void)markIdle {
  371. [self.workerDispatchQueue verifyIsCurrentQueue];
  372. // Starts the idle timer if we are in state 'Open' and are not yet already running a timer (in
  373. // which case the previous idle timeout still applies).
  374. if ([self isOpen] && !self.idleTimerCallback) {
  375. self.idleTimerCallback = [self.workerDispatchQueue dispatchAfterDelay:kIdleTimeout
  376. timerID:self.idleTimerID
  377. block:^() {
  378. [self handleIdleCloseTimer];
  379. }];
  380. }
  381. }
  382. - (void)cancelIdleCheck {
  383. [self.workerDispatchQueue verifyIsCurrentQueue];
  384. if (self.idleTimerCallback) {
  385. [self.idleTimerCallback cancel];
  386. self.idleTimerCallback = nil;
  387. }
  388. }
  389. /**
  390. * Parses a protocol buffer response from the server. If the message fails to parse, generates
  391. * an error and closes the stream.
  392. *
  393. * @param protoClass A protocol buffer message class object, that responds to parseFromData:error:.
  394. * @param data The bytes in the response as returned from GRPC.
  395. * @return An instance of the protocol buffer message, parsed from the data if parsing was
  396. * successful, or nil otherwise.
  397. */
  398. - (nullable id)parseProto:(Class)protoClass data:(NSData *)data error:(NSError **)error {
  399. NSError *parseError;
  400. id parsed = [protoClass parseFromData:data error:&parseError];
  401. if (parsed) {
  402. *error = nil;
  403. return parsed;
  404. } else {
  405. NSDictionary *info = @{
  406. NSLocalizedDescriptionKey : @"Unable to parse response from the server",
  407. NSUnderlyingErrorKey : parseError,
  408. @"Expected class" : protoClass,
  409. @"Received value" : data,
  410. };
  411. *error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  412. code:FIRFirestoreErrorCodeInternal
  413. userInfo:info];
  414. return nil;
  415. }
  416. }
  417. /**
  418. * Writes a request proto into the stream.
  419. */
  420. - (void)writeRequest:(GPBMessage *)request {
  421. NSData *data = [request data];
  422. [self cancelIdleCheck];
  423. FSTBufferedWriter *requestsWriter = self.requestsWriter;
  424. @synchronized(requestsWriter) {
  425. [requestsWriter writeValue:data];
  426. }
  427. }
  428. #pragma mark Template methods for subclasses
  429. /**
  430. * Called by the stream after the stream has opened.
  431. *
  432. * Subclasses should relay to their stream-specific delegate. Calling [super notifyStreamOpen] is
  433. * not required.
  434. */
  435. - (void)notifyStreamOpen {
  436. }
  437. /**
  438. * Called by the stream after the stream has been unexpectedly interrupted, either due to an error
  439. * or due to idleness.
  440. *
  441. * Subclasses should relay to their stream-specific delegate. Calling [super
  442. * notifyStreamInterrupted] is not required.
  443. */
  444. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  445. }
  446. /**
  447. * Called by the stream for each incoming protocol message coming from the server.
  448. *
  449. * Subclasses should implement this to deserialize the value and relay to their stream-specific
  450. * delegate, if appropriate. Calling [super handleStreamMessage] is not required.
  451. */
  452. - (void)handleStreamMessage:(id)value {
  453. }
  454. /**
  455. * Called by the stream when the underlying RPC has been closed for whatever reason.
  456. */
  457. - (void)handleStreamClose:(nullable NSError *)error {
  458. FSTLog(@"%@ %p close: %@", NSStringFromClass([self class]), (__bridge void *)self, error);
  459. FSTAssert([self isStarted], @"handleStreamClose: called for non-started stream.");
  460. // In theory the stream could close cleanly, however, in our current model we never expect this
  461. // to happen because if we stop a stream ourselves, this callback will never be called. To
  462. // prevent cases where we retry without a backoff accidentally, we set the stream to error
  463. // in all cases.
  464. [self closeWithFinalState:FSTStreamStateError error:error];
  465. }
  466. #pragma mark GRXWriteable implementation
  467. // The GRXWriteable implementation defines the receive side of the RPC stream.
  468. /**
  469. * Called by GRPC when it publishes a value.
  470. *
  471. * GRPC must be configured to use our worker queue by calling
  472. * `[call setResponseDispatchQueue:self.workerDispatchQueue.queue]` on the GRPCCall before starting
  473. * the RPC.
  474. */
  475. - (void)writeValue:(id)value {
  476. [self.workerDispatchQueue enterCheckedOperation:^{
  477. FSTAssert([self isStarted], @"writeValue: called for stopped stream.");
  478. if (!self.messageReceived) {
  479. self.messageReceived = YES;
  480. if ([FIRFirestore isLoggingEnabled]) {
  481. FSTLog(@"%@ %p headers (whitelisted): %@", NSStringFromClass([self class]),
  482. (__bridge void *)self,
  483. [FSTDatastore extractWhiteListedHeaders:self.rpc.responseHeaders]);
  484. }
  485. }
  486. NSError *error;
  487. id proto = [self parseProto:self.responseMessageClass data:value error:&error];
  488. if (proto) {
  489. [self handleStreamMessage:proto];
  490. } else {
  491. [self.rpc finishWithError:error];
  492. }
  493. }];
  494. }
  495. /**
  496. * Called by GRPC when it closed the stream with an error representing the final state of the
  497. * stream.
  498. *
  499. * GRPC must be configured to use our worker queue by calling
  500. * `[call setResponseDispatchQueue:self.workerDispatchQueue.queue]` on the GRPCCall before starting
  501. * the RPC.
  502. *
  503. * Do not call directly. Call handleStreamClose to directly inform stream-specific logic, or call
  504. * stop to tear down the stream.
  505. */
  506. - (void)writesFinishedWithError:(nullable NSError *)error __used {
  507. error = [FSTDatastore firestoreErrorForError:error];
  508. [self.workerDispatchQueue enterCheckedOperation:^{
  509. FSTAssert([self isStarted], @"writesFinishedWithError: called for stopped stream.");
  510. [self handleStreamClose:error];
  511. }];
  512. }
  513. @end
  514. #pragma mark - FSTWatchStream
  515. @interface FSTWatchStream ()
  516. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  517. @end
  518. @implementation FSTWatchStream
  519. - (instancetype)initWithDatabase:(const DatabaseInfo *)database
  520. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  521. credentials:(CredentialsProvider *)credentials
  522. serializer:(FSTSerializerBeta *)serializer {
  523. self = [super initWithDatabase:database
  524. workerDispatchQueue:workerDispatchQueue
  525. connectionTimerID:FSTTimerIDListenStreamConnectionBackoff
  526. idleTimerID:FSTTimerIDListenStreamIdle
  527. credentials:credentials
  528. responseMessageClass:[GCFSListenResponse class]];
  529. if (self) {
  530. _serializer = serializer;
  531. }
  532. return self;
  533. }
  534. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter {
  535. return [[GRPCCall alloc] initWithHost:util::WrapNSString(self.databaseInfo->host())
  536. path:@"/google.firestore.v1beta1.Firestore/Listen"
  537. requestsWriter:requestsWriter];
  538. }
  539. - (void)notifyStreamOpen {
  540. [self.delegate watchStreamDidOpen];
  541. }
  542. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  543. id<FSTWatchStreamDelegate> delegate = self.delegate;
  544. self.delegate = nil;
  545. [delegate watchStreamWasInterruptedWithError:error];
  546. }
  547. - (void)watchQuery:(FSTQueryData *)query {
  548. FSTAssert([self isOpen], @"Not yet open");
  549. [self.workerDispatchQueue verifyIsCurrentQueue];
  550. GCFSListenRequest *request = [GCFSListenRequest message];
  551. request.database = [_serializer encodedDatabaseID];
  552. request.addTarget = [_serializer encodedTarget:query];
  553. request.labels = [_serializer encodedListenRequestLabelsForQueryData:query];
  554. FSTLog(@"FSTWatchStream %p watch: %@", (__bridge void *)self, request);
  555. [self writeRequest:request];
  556. }
  557. - (void)unwatchTargetID:(FSTTargetID)targetID {
  558. FSTAssert([self isOpen], @"Not yet open");
  559. [self.workerDispatchQueue verifyIsCurrentQueue];
  560. GCFSListenRequest *request = [GCFSListenRequest message];
  561. request.database = [_serializer encodedDatabaseID];
  562. request.removeTarget = targetID;
  563. FSTLog(@"FSTWatchStream %p unwatch: %@", (__bridge void *)self, request);
  564. [self writeRequest:request];
  565. }
  566. /**
  567. * Receives an inbound message from GRPC, deserializes, and then passes that on to the delegate's
  568. * watchStreamDidChange:snapshotVersion: callback.
  569. */
  570. - (void)handleStreamMessage:(GCFSListenResponse *)proto {
  571. FSTLog(@"FSTWatchStream %p response: %@", (__bridge void *)self, proto);
  572. [self.workerDispatchQueue verifyIsCurrentQueue];
  573. // A successful response means the stream is healthy.
  574. [self.backoff reset];
  575. FSTWatchChange *change = [_serializer decodedWatchChange:proto];
  576. SnapshotVersion snap = [_serializer versionFromListenResponse:proto];
  577. [self.delegate watchStreamDidChange:change snapshotVersion:snap];
  578. }
  579. @end
  580. #pragma mark - FSTWriteStream
  581. @interface FSTWriteStream ()
  582. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  583. @end
  584. @implementation FSTWriteStream
  585. - (instancetype)initWithDatabase:(const DatabaseInfo *)database
  586. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  587. credentials:(CredentialsProvider *)credentials
  588. serializer:(FSTSerializerBeta *)serializer {
  589. self = [super initWithDatabase:database
  590. workerDispatchQueue:workerDispatchQueue
  591. connectionTimerID:FSTTimerIDWriteStreamConnectionBackoff
  592. idleTimerID:FSTTimerIDWriteStreamIdle
  593. credentials:credentials
  594. responseMessageClass:[GCFSWriteResponse class]];
  595. if (self) {
  596. _serializer = serializer;
  597. }
  598. return self;
  599. }
  600. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter {
  601. return [[GRPCCall alloc] initWithHost:util::WrapNSString(self.databaseInfo->host())
  602. path:@"/google.firestore.v1beta1.Firestore/Write"
  603. requestsWriter:requestsWriter];
  604. }
  605. - (void)startWithDelegate:(id)delegate {
  606. self.handshakeComplete = NO;
  607. [super startWithDelegate:delegate];
  608. }
  609. - (void)notifyStreamOpen {
  610. [self.delegate writeStreamDidOpen];
  611. }
  612. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  613. id<FSTWriteStreamDelegate> delegate = self.delegate;
  614. self.delegate = nil;
  615. [delegate writeStreamWasInterruptedWithError:error];
  616. }
  617. - (void)tearDown {
  618. if ([self isHandshakeComplete]) {
  619. // Send an empty write request to the backend to indicate imminent stream closure. This allows
  620. // the backend to clean up resources.
  621. [self writeMutations:@[]];
  622. }
  623. }
  624. - (void)writeHandshake {
  625. // The initial request cannot contain mutations, but must contain a projectID.
  626. FSTAssert([self isOpen], @"Not yet open");
  627. FSTAssert(!self.handshakeComplete, @"Handshake sent out of turn");
  628. [self.workerDispatchQueue verifyIsCurrentQueue];
  629. GCFSWriteRequest *request = [GCFSWriteRequest message];
  630. request.database = [_serializer encodedDatabaseID];
  631. // TODO(dimond): Support stream resumption. We intentionally do not set the stream token on the
  632. // handshake, ignoring any stream token we might have.
  633. FSTLog(@"FSTWriteStream %p initial request: %@", (__bridge void *)self, request);
  634. [self writeRequest:request];
  635. }
  636. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations {
  637. FSTAssert([self isOpen], @"Not yet open");
  638. FSTAssert(self.handshakeComplete, @"Mutations sent out of turn");
  639. [self.workerDispatchQueue verifyIsCurrentQueue];
  640. NSMutableArray<GCFSWrite *> *protos = [NSMutableArray arrayWithCapacity:mutations.count];
  641. for (FSTMutation *mutation in mutations) {
  642. [protos addObject:[_serializer encodedMutation:mutation]];
  643. };
  644. GCFSWriteRequest *request = [GCFSWriteRequest message];
  645. request.writesArray = protos;
  646. request.streamToken = self.lastStreamToken;
  647. FSTLog(@"FSTWriteStream %p mutation request: %@", (__bridge void *)self, request);
  648. [self writeRequest:request];
  649. }
  650. /**
  651. * Implements GRXWriteable to receive an inbound message from GRPC, deserialize, and then pass
  652. * that on to the mutationResultsHandler.
  653. */
  654. - (void)handleStreamMessage:(GCFSWriteResponse *)response {
  655. FSTLog(@"FSTWriteStream %p response: %@", (__bridge void *)self, response);
  656. [self.workerDispatchQueue verifyIsCurrentQueue];
  657. // Always capture the last stream token.
  658. self.lastStreamToken = response.streamToken;
  659. if (!self.isHandshakeComplete) {
  660. // The first response is the handshake response
  661. self.handshakeComplete = YES;
  662. [self.delegate writeStreamDidCompleteHandshake];
  663. } else {
  664. // A successful first write response means the stream is healthy.
  665. // Note that we could consider a successful handshake healthy, however, the write itself
  666. // might be causing an error we want to back off from.
  667. [self.backoff reset];
  668. SnapshotVersion commitVersion = [_serializer decodedVersion:response.commitTime];
  669. NSMutableArray<GCFSWriteResult *> *protos = response.writeResultsArray;
  670. NSMutableArray<FSTMutationResult *> *results = [NSMutableArray arrayWithCapacity:protos.count];
  671. for (GCFSWriteResult *proto in protos) {
  672. [results addObject:[_serializer decodedMutationResult:proto]];
  673. };
  674. [self.delegate writeStreamDidReceiveResponseWithVersion:commitVersion mutationResults:results];
  675. }
  676. }
  677. @end