FSTStream.m 27 KB

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