FSTStream.mm 29 KB

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