FSTStream.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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. [self.workerDispatchQueue verifyIsCurrentQueue];
  280. [self cancelIdleCheck];
  281. if (finalState != FSTStreamStateError) {
  282. // If this is an intentional close ensure we don't delay our next connection attempt.
  283. [self.backoff reset];
  284. } else if (error != nil && error.code == FIRFirestoreErrorCodeResourceExhausted) {
  285. FSTLog(@"%@ %p Using maximum backoff delay to prevent overloading the backend.", [self class],
  286. (__bridge void *)self);
  287. [self.backoff resetToMax];
  288. }
  289. [self tearDown];
  290. if (self.requestsWriter) {
  291. // Clean up the underlying RPC. If this close: is in response to an error, don't attempt to
  292. // call half-close to avoid secondary failures.
  293. if (finalState != FSTStreamStateError) {
  294. FSTLog(@"%@ %p Closing stream client-side", [self class], (__bridge void *)self);
  295. @synchronized(self.requestsWriter) {
  296. [self.requestsWriter finishWithError:nil];
  297. }
  298. }
  299. _requestsWriter = nil;
  300. }
  301. // This state must be assigned before calling `notifyStreamInterrupted` to allow the callback to
  302. // inhibit backoff or otherwise manipulate the state in its non-started state.
  303. self.state = finalState;
  304. [self.callbackFilter suppressCallbacks];
  305. _callbackFilter = nil;
  306. // Clean up remaining state.
  307. _messageReceived = NO;
  308. _rpc = nil;
  309. // If the caller explicitly requested a stream stop, don't notify them of a closing stream (it
  310. // could trigger undesirable recovery logic, etc.).
  311. if (finalState != FSTStreamStateStopped) {
  312. [self notifyStreamInterruptedWithError:error];
  313. }
  314. // Clear the delegates to avoid any possible bleed through of events from GRPC.
  315. FSTAssert(_delegate,
  316. @"closeWithFinalState should only be called for a started stream that has an active "
  317. @"delegate.");
  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. FSTAssert([self isStarted], @"Can't handle server close in non-started state.");
  428. // In theory the stream could close cleanly, however, in our current model we never expect this
  429. // to happen because if we stop a stream ourselves, this callback will never be called. To
  430. // prevent cases where we retry without a backoff accidentally, we set the stream to error
  431. // in all cases.
  432. [self closeWithFinalState:FSTStreamStateError error:error];
  433. }
  434. #pragma mark GRXWriteable implementation
  435. // The GRXWriteable implementation defines the receive side of the RPC stream.
  436. /**
  437. * Called by GRPC when it publishes a value. It is called from GRPC's own queue so we immediately
  438. * redispatch back onto our own worker queue.
  439. */
  440. - (void)writeValue:(id)value __used {
  441. // TODO(mcg): remove the double-dispatch once GRPCCall at head is released.
  442. // Once released we can set the responseDispatchQueue property on the GRPCCall and then this
  443. // method can call handleStreamMessage directly.
  444. FSTWeakify(self);
  445. [self.workerDispatchQueue dispatchAsync:^{
  446. FSTStrongify(self);
  447. if (!self || self.state == FSTStreamStateStopped) {
  448. return;
  449. }
  450. if (!self.messageReceived) {
  451. self.messageReceived = YES;
  452. if ([FIRFirestore isLoggingEnabled]) {
  453. FSTLog(@"%@ %p headers (whitelisted): %@", NSStringFromClass([self class]),
  454. (__bridge void *)self,
  455. [FSTDatastore extractWhiteListedHeaders:self.rpc.responseHeaders]);
  456. }
  457. }
  458. NSError *error;
  459. id proto = [self parseProto:self.responseMessageClass data:value error:&error];
  460. if (proto) {
  461. [self handleStreamMessage:proto];
  462. } else {
  463. [_rpc finishWithError:error];
  464. }
  465. }];
  466. }
  467. /**
  468. * Called by GRPC when it closed the stream with an error representing the final state of the
  469. * stream.
  470. *
  471. * Do not call directly, since it dispatches via the worker queue. Call handleStreamClose to
  472. * directly inform stream-specific logic, or call stop to tear down the stream.
  473. */
  474. - (void)writesFinishedWithError:(nullable NSError *)error __used {
  475. error = [FSTDatastore firestoreErrorForError:error];
  476. FSTWeakify(self);
  477. [self.workerDispatchQueue dispatchAsync:^{
  478. FSTStrongify(self);
  479. if (!self || self.state == FSTStreamStateStopped) {
  480. return;
  481. }
  482. [self handleStreamClose:error];
  483. }];
  484. }
  485. @end
  486. #pragma mark - FSTWatchStream
  487. @interface FSTWatchStream ()
  488. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  489. @end
  490. @implementation FSTWatchStream
  491. - (instancetype)initWithDatabase:(FSTDatabaseInfo *)database
  492. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  493. credentials:(id<FSTCredentialsProvider>)credentials
  494. serializer:(FSTSerializerBeta *)serializer {
  495. self = [super initWithDatabase:database
  496. workerDispatchQueue:workerDispatchQueue
  497. credentials:credentials
  498. responseMessageClass:[GCFSListenResponse class]];
  499. if (self) {
  500. _serializer = serializer;
  501. }
  502. return self;
  503. }
  504. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter {
  505. return [[GRPCCall alloc] initWithHost:self.databaseInfo.host
  506. path:@"/google.firestore.v1beta1.Firestore/Listen"
  507. requestsWriter:requestsWriter];
  508. }
  509. - (void)notifyStreamOpen {
  510. [self.delegate watchStreamDidOpen];
  511. }
  512. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  513. [self.delegate watchStreamWasInterruptedWithError:error];
  514. }
  515. - (void)watchQuery:(FSTQueryData *)query {
  516. FSTAssert([self isOpen], @"Not yet open");
  517. [self.workerDispatchQueue verifyIsCurrentQueue];
  518. GCFSListenRequest *request = [GCFSListenRequest message];
  519. request.database = [_serializer encodedDatabaseID];
  520. request.addTarget = [_serializer encodedTarget:query];
  521. request.labels = [_serializer encodedListenRequestLabelsForQueryData:query];
  522. FSTLog(@"FSTWatchStream %p watch: %@", (__bridge void *)self, request);
  523. [self writeRequest:request];
  524. }
  525. - (void)unwatchTargetID:(FSTTargetID)targetID {
  526. FSTAssert([self isOpen], @"Not yet open");
  527. [self.workerDispatchQueue verifyIsCurrentQueue];
  528. GCFSListenRequest *request = [GCFSListenRequest message];
  529. request.database = [_serializer encodedDatabaseID];
  530. request.removeTarget = targetID;
  531. FSTLog(@"FSTWatchStream %p unwatch: %@", (__bridge void *)self, request);
  532. [self writeRequest:request];
  533. }
  534. /**
  535. * Receives an inbound message from GRPC, deserializes, and then passes that on to the delegate's
  536. * watchStreamDidChange:snapshotVersion: callback.
  537. */
  538. - (void)handleStreamMessage:(GCFSListenResponse *)proto {
  539. FSTLog(@"FSTWatchStream %p response: %@", (__bridge void *)self, proto);
  540. [self.workerDispatchQueue verifyIsCurrentQueue];
  541. // A successful response means the stream is healthy.
  542. [self.backoff reset];
  543. FSTWatchChange *change = [_serializer decodedWatchChange:proto];
  544. FSTSnapshotVersion *snap = [_serializer versionFromListenResponse:proto];
  545. [self.delegate watchStreamDidChange:change snapshotVersion:snap];
  546. }
  547. @end
  548. #pragma mark - FSTWriteStream
  549. @interface FSTWriteStream ()
  550. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  551. @end
  552. @implementation FSTWriteStream
  553. - (instancetype)initWithDatabase:(FSTDatabaseInfo *)database
  554. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  555. credentials:(id<FSTCredentialsProvider>)credentials
  556. serializer:(FSTSerializerBeta *)serializer {
  557. self = [super initWithDatabase:database
  558. workerDispatchQueue:workerDispatchQueue
  559. credentials:credentials
  560. responseMessageClass:[GCFSWriteResponse class]];
  561. if (self) {
  562. _serializer = serializer;
  563. }
  564. return self;
  565. }
  566. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter {
  567. return [[GRPCCall alloc] initWithHost:self.databaseInfo.host
  568. path:@"/google.firestore.v1beta1.Firestore/Write"
  569. requestsWriter:requestsWriter];
  570. }
  571. - (void)startWithDelegate:(id)delegate {
  572. self.handshakeComplete = NO;
  573. [super startWithDelegate:delegate];
  574. }
  575. - (void)notifyStreamOpen {
  576. [self.delegate writeStreamDidOpen];
  577. }
  578. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  579. [self.delegate writeStreamWasInterruptedWithError:error];
  580. }
  581. - (void)tearDown {
  582. if ([self isHandshakeComplete]) {
  583. // Send an empty write request to the backend to indicate imminent stream closure. This allows
  584. // the backend to clean up resources.
  585. [self writeMutations:@[]];
  586. }
  587. }
  588. - (void)writeHandshake {
  589. // The initial request cannot contain mutations, but must contain a projectID.
  590. FSTAssert([self isOpen], @"Not yet open");
  591. FSTAssert(!self.handshakeComplete, @"Handshake sent out of turn");
  592. [self.workerDispatchQueue verifyIsCurrentQueue];
  593. GCFSWriteRequest *request = [GCFSWriteRequest message];
  594. request.database = [_serializer encodedDatabaseID];
  595. // TODO(dimond): Support stream resumption. We intentionally do not set the stream token on the
  596. // handshake, ignoring any stream token we might have.
  597. FSTLog(@"FSTWriteStream %p initial request: %@", (__bridge void *)self, request);
  598. [self writeRequest:request];
  599. }
  600. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations {
  601. FSTAssert([self isOpen], @"Not yet open");
  602. FSTAssert(self.handshakeComplete, @"Mutations sent out of turn");
  603. [self.workerDispatchQueue verifyIsCurrentQueue];
  604. NSMutableArray<GCFSWrite *> *protos = [NSMutableArray arrayWithCapacity:mutations.count];
  605. for (FSTMutation *mutation in mutations) {
  606. [protos addObject:[_serializer encodedMutation:mutation]];
  607. };
  608. GCFSWriteRequest *request = [GCFSWriteRequest message];
  609. request.writesArray = protos;
  610. request.streamToken = self.lastStreamToken;
  611. FSTLog(@"FSTWriteStream %p mutation request: %@", (__bridge void *)self, request);
  612. [self writeRequest:request];
  613. }
  614. /**
  615. * Implements GRXWriteable to receive an inbound message from GRPC, deserialize, and then pass
  616. * that on to the mutationResultsHandler.
  617. */
  618. - (void)handleStreamMessage:(GCFSWriteResponse *)response {
  619. FSTLog(@"FSTWriteStream %p response: %@", (__bridge void *)self, response);
  620. [self.workerDispatchQueue verifyIsCurrentQueue];
  621. // Always capture the last stream token.
  622. self.lastStreamToken = response.streamToken;
  623. if (!self.isHandshakeComplete) {
  624. // The first response is the handshake response
  625. self.handshakeComplete = YES;
  626. [self.delegate writeStreamDidCompleteHandshake];
  627. } else {
  628. // A successful first write response means the stream is healthy.
  629. // Note that we could consider a successful handshake healthy, however, the write itself
  630. // might be causing an error we want to back off from.
  631. [self.backoff reset];
  632. FSTSnapshotVersion *commitVersion = [_serializer decodedVersion:response.commitTime];
  633. NSMutableArray<GCFSWriteResult *> *protos = response.writeResultsArray;
  634. NSMutableArray<FSTMutationResult *> *results = [NSMutableArray arrayWithCapacity:protos.count];
  635. for (GCFSWriteResult *proto in protos) {
  636. [results addObject:[_serializer decodedMutationResult:proto]];
  637. };
  638. [self.delegate writeStreamDidReceiveResponseWithVersion:commitVersion mutationResults:results];
  639. }
  640. }
  641. @end