FSTStream.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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 "FSTDatastore.h"
  17. #import <GRPCClient/GRPCCall+OAuth2.h>
  18. #import <GRPCClient/GRPCCall.h>
  19. #import "FIRFirestore+Internal.h"
  20. #import "FIRFirestoreErrors.h"
  21. #import "FSTAssert.h"
  22. #import "FSTBufferedWriter.h"
  23. #import "FSTClasses.h"
  24. #import "FSTCredentialsProvider.h"
  25. #import "FSTDatabaseID.h"
  26. #import "FSTDatabaseInfo.h"
  27. #import "FSTDispatchQueue.h"
  28. #import "FSTExponentialBackoff.h"
  29. #import "FSTLogger.h"
  30. #import "FSTMutation.h"
  31. #import "FSTQueryData.h"
  32. #import "FSTSerializerBeta.h"
  33. #import "FSTStream.h"
  34. #import "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. * Closes the stream and cleans up as necessary:
  258. *
  259. * * closes the underlying GRPC stream;
  260. * * calls the onClose handler with the given 'error';
  261. * * sets internal stream state to 'finalState';
  262. * * adjusts the backoff timer based on the error
  263. *
  264. * A new stream can be opened by calling `start` unless `finalState` is set to
  265. * `FSTStreamStateStopped`.
  266. *
  267. * @param finalState the intended state of the stream after closing.
  268. * @param error the NSError the connection was closed with.
  269. */
  270. - (void)closeWithFinalState:(FSTStreamState)finalState error:(nullable NSError *)error {
  271. FSTAssert(finalState == FSTStreamStateError || error == nil,
  272. @"Can't provide an error when not in an error state.");
  273. [self.workerDispatchQueue verifyIsCurrentQueue];
  274. [self cancelIdleCheck];
  275. if (finalState != FSTStreamStateError) {
  276. // If this is an intentional close ensure we don't delay our next connection attempt.
  277. [self.backoff reset];
  278. } else if (error != nil && error.code == FIRFirestoreErrorCodeResourceExhausted) {
  279. FSTLog(@"%@ %p Using maximum backoff delay to prevent overloading the backend.", [self class],
  280. (__bridge void *)self);
  281. [self.backoff resetToMax];
  282. }
  283. // This state must be assigned before calling `notifyStreamInterrupted` to allow the callback to
  284. // inhibit backoff or otherwise manipulate the state in its non-started state.
  285. self.state = finalState;
  286. if (self.requestsWriter) {
  287. // Clean up the underlying RPC. If this close: is in response to an error, don't attempt to
  288. // call half-close to avoid secondary failures.
  289. if (finalState != FSTStreamStateError) {
  290. FSTLog(@"%@ %p Closing stream client-side", [self class], (__bridge void *)self);
  291. @synchronized(self.requestsWriter) {
  292. [self.requestsWriter finishWithError:nil];
  293. }
  294. }
  295. _requestsWriter = nil;
  296. }
  297. [self.callbackFilter suppressCallbacks];
  298. _callbackFilter = nil;
  299. // Clean up remaining state.
  300. _messageReceived = NO;
  301. _rpc = nil;
  302. // If the caller explicitly requested a stream stop, don't notify them of a closing stream (it
  303. // could trigger undesirable recovery logic, etc.).
  304. if (finalState != FSTStreamStateStopped) {
  305. [self notifyStreamInterruptedWithError:error];
  306. }
  307. // Clear the delegates to avoid any possible bleed through of events from GRPC.
  308. FSTAssert(_delegate,
  309. @"closeWithFinalState should only be called for a started stream that has an active "
  310. @"delegate.");
  311. _delegate = nil;
  312. }
  313. - (void)stop {
  314. FSTLog(@"%@ %p stop", NSStringFromClass([self class]), (__bridge void *)self);
  315. if ([self isStarted]) {
  316. [self closeWithFinalState:FSTStreamStateStopped error:nil];
  317. }
  318. }
  319. - (void)inhibitBackoff {
  320. FSTAssert(![self isStarted], @"Can only inhibit backoff after an error (was %ld)",
  321. (long)self.state);
  322. [self.workerDispatchQueue verifyIsCurrentQueue];
  323. // Clear the error condition.
  324. self.state = FSTStreamStateInitial;
  325. [self.backoff reset];
  326. }
  327. /** Called by the idle timer when the stream should close due to inactivity. */
  328. - (void)handleIdleCloseTimer {
  329. [self.workerDispatchQueue verifyIsCurrentQueue];
  330. if (self.state == FSTStreamStateOpen && [self isIdle]) {
  331. // When timing out an idle stream there's no reason to force the stream into backoff when
  332. // it restarts so set the stream state to Initial instead of Error.
  333. [self closeWithFinalState:FSTStreamStateInitial error:nil];
  334. }
  335. }
  336. - (void)markIdle {
  337. [self.workerDispatchQueue verifyIsCurrentQueue];
  338. if (self.state == FSTStreamStateOpen) {
  339. self.idle = YES;
  340. [self.workerDispatchQueue dispatchAfterDelay:kIdleTimeout
  341. block:^() {
  342. [self handleIdleCloseTimer];
  343. }];
  344. }
  345. }
  346. - (void)cancelIdleCheck {
  347. [self.workerDispatchQueue verifyIsCurrentQueue];
  348. self.idle = NO;
  349. }
  350. /**
  351. * Parses a protocol buffer response from the server. If the message fails to parse, generates
  352. * an error and closes the stream.
  353. *
  354. * @param protoClass A protocol buffer message class object, that responds to parseFromData:error:.
  355. * @param data The bytes in the response as returned from GRPC.
  356. * @return An instance of the protocol buffer message, parsed from the data if parsing was
  357. * successful, or nil otherwise.
  358. */
  359. - (nullable id)parseProto:(Class)protoClass data:(NSData *)data error:(NSError **)error {
  360. NSError *parseError;
  361. id parsed = [protoClass parseFromData:data error:&parseError];
  362. if (parsed) {
  363. *error = nil;
  364. return parsed;
  365. } else {
  366. NSDictionary *info = @{
  367. NSLocalizedDescriptionKey : @"Unable to parse response from the server",
  368. NSUnderlyingErrorKey : parseError,
  369. @"Expected class" : protoClass,
  370. @"Received value" : data,
  371. };
  372. *error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  373. code:FIRFirestoreErrorCodeInternal
  374. userInfo:info];
  375. return nil;
  376. }
  377. }
  378. /**
  379. * Writes a request proto into the stream.
  380. */
  381. - (void)writeRequest:(GPBMessage *)request {
  382. NSData *data = [request data];
  383. [self cancelIdleCheck];
  384. FSTBufferedWriter *requestsWriter = self.requestsWriter;
  385. @synchronized(requestsWriter) {
  386. [requestsWriter writeValue:data];
  387. }
  388. }
  389. #pragma mark Template methods for subclasses
  390. /**
  391. * Called by the stream after the stream has opened.
  392. *
  393. * Subclasses should relay to their stream-specific delegate. Calling [super notifyStreamOpen] is
  394. * not required.
  395. */
  396. - (void)notifyStreamOpen {
  397. }
  398. /**
  399. * Called by the stream after the stream has been unexpectedly interrupted, either due to an error
  400. * or due to idleness.
  401. *
  402. * Subclasses should relay to their stream-specific delegate. Calling [super
  403. * notifyStreamInterrupted] is not required.
  404. */
  405. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  406. }
  407. /**
  408. * Called by the stream for each incoming protocol message coming from the server.
  409. *
  410. * Subclasses should implement this to deserialize the value and relay to their stream-specific
  411. * delegate, if appropriate. Calling [super handleStreamMessage] is not required.
  412. */
  413. - (void)handleStreamMessage:(id)value {
  414. }
  415. /**
  416. * Called by the stream when the underlying RPC has been closed for whatever reason.
  417. */
  418. - (void)handleStreamClose:(nullable NSError *)error {
  419. FSTLog(@"%@ %p close: %@", NSStringFromClass([self class]), (__bridge void *)self, error);
  420. FSTAssert([self isStarted], @"Can't handle server close in non-started state.");
  421. // In theory the stream could close cleanly, however, in our current model we never expect this
  422. // to happen because if we stop a stream ourselves, this callback will never be called. To
  423. // prevent cases where we retry without a backoff accidentally, we set the stream to error
  424. // in all cases.
  425. [self closeWithFinalState:FSTStreamStateError error:error];
  426. }
  427. #pragma mark GRXWriteable implementation
  428. // The GRXWriteable implementation defines the receive side of the RPC stream.
  429. /**
  430. * Called by GRPC when it publishes a value. It is called from GRPC's own queue so we immediately
  431. * redispatch back onto our own worker queue.
  432. */
  433. - (void)writeValue:(id)value __used {
  434. // TODO(mcg): remove the double-dispatch once GRPCCall at head is released.
  435. // Once released we can set the responseDispatchQueue property on the GRPCCall and then this
  436. // method can call handleStreamMessage directly.
  437. FSTWeakify(self);
  438. [self.workerDispatchQueue dispatchAsync:^{
  439. FSTStrongify(self);
  440. if (!self || self.state == FSTStreamStateStopped) {
  441. return;
  442. }
  443. if (!self.messageReceived) {
  444. self.messageReceived = YES;
  445. if ([FIRFirestore isLoggingEnabled]) {
  446. FSTLog(@"%@ %p headers (whitelisted): %@", NSStringFromClass([self class]),
  447. (__bridge void *)self,
  448. [FSTDatastore extractWhiteListedHeaders:self.rpc.responseHeaders]);
  449. }
  450. }
  451. NSError *error;
  452. id proto = [self parseProto:self.responseMessageClass data:value error:&error];
  453. if (proto) {
  454. [self handleStreamMessage:proto];
  455. } else {
  456. [_rpc finishWithError:error];
  457. }
  458. }];
  459. }
  460. /**
  461. * Called by GRPC when it closed the stream with an error representing the final state of the
  462. * stream.
  463. *
  464. * Do not call directly, since it dispatches via the worker queue. Call handleStreamClose to
  465. * directly inform stream-specific logic, or call stop to tear down the stream.
  466. */
  467. - (void)writesFinishedWithError:(nullable NSError *)error __used {
  468. error = [FSTDatastore firestoreErrorForError:error];
  469. FSTWeakify(self);
  470. [self.workerDispatchQueue dispatchAsync:^{
  471. FSTStrongify(self);
  472. if (!self || self.state == FSTStreamStateStopped) {
  473. return;
  474. }
  475. [self handleStreamClose:error];
  476. }];
  477. }
  478. @end
  479. #pragma mark - FSTWatchStream
  480. @interface FSTWatchStream ()
  481. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  482. @end
  483. @implementation FSTWatchStream
  484. - (instancetype)initWithDatabase:(FSTDatabaseInfo *)database
  485. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  486. credentials:(id<FSTCredentialsProvider>)credentials
  487. serializer:(FSTSerializerBeta *)serializer {
  488. self = [super initWithDatabase:database
  489. workerDispatchQueue:workerDispatchQueue
  490. credentials:credentials
  491. responseMessageClass:[GCFSListenResponse class]];
  492. if (self) {
  493. _serializer = serializer;
  494. }
  495. return self;
  496. }
  497. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter {
  498. return [[GRPCCall alloc] initWithHost:self.databaseInfo.host
  499. path:@"/google.firestore.v1beta1.Firestore/Listen"
  500. requestsWriter:requestsWriter];
  501. }
  502. - (void)notifyStreamOpen {
  503. [self.delegate watchStreamDidOpen];
  504. }
  505. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  506. [self.delegate watchStreamWasInterruptedWithError:error];
  507. }
  508. - (void)watchQuery:(FSTQueryData *)query {
  509. FSTAssert([self isOpen], @"Not yet open");
  510. [self.workerDispatchQueue verifyIsCurrentQueue];
  511. GCFSListenRequest *request = [GCFSListenRequest message];
  512. request.database = [_serializer encodedDatabaseID];
  513. request.addTarget = [_serializer encodedTarget:query];
  514. request.labels = [_serializer encodedListenRequestLabelsForQueryData:query];
  515. FSTLog(@"FSTWatchStream %p watch: %@", (__bridge void *)self, request);
  516. [self writeRequest:request];
  517. }
  518. - (void)unwatchTargetID:(FSTTargetID)targetID {
  519. FSTAssert([self isOpen], @"Not yet open");
  520. [self.workerDispatchQueue verifyIsCurrentQueue];
  521. GCFSListenRequest *request = [GCFSListenRequest message];
  522. request.database = [_serializer encodedDatabaseID];
  523. request.removeTarget = targetID;
  524. FSTLog(@"FSTWatchStream %p unwatch: %@", (__bridge void *)self, request);
  525. [self writeRequest:request];
  526. }
  527. /**
  528. * Receives an inbound message from GRPC, deserializes, and then passes that on to the delegate's
  529. * watchStreamDidChange:snapshotVersion: callback.
  530. */
  531. - (void)handleStreamMessage:(GCFSListenResponse *)proto {
  532. FSTLog(@"FSTWatchStream %p response: %@", (__bridge void *)self, proto);
  533. [self.workerDispatchQueue verifyIsCurrentQueue];
  534. // A successful response means the stream is healthy.
  535. [self.backoff reset];
  536. FSTWatchChange *change = [_serializer decodedWatchChange:proto];
  537. FSTSnapshotVersion *snap = [_serializer versionFromListenResponse:proto];
  538. [self.delegate watchStreamDidChange:change snapshotVersion:snap];
  539. }
  540. @end
  541. #pragma mark - FSTWriteStream
  542. @interface FSTWriteStream ()
  543. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  544. @end
  545. @implementation FSTWriteStream
  546. - (instancetype)initWithDatabase:(FSTDatabaseInfo *)database
  547. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  548. credentials:(id<FSTCredentialsProvider>)credentials
  549. serializer:(FSTSerializerBeta *)serializer {
  550. self = [super initWithDatabase:database
  551. workerDispatchQueue:workerDispatchQueue
  552. credentials:credentials
  553. responseMessageClass:[GCFSWriteResponse class]];
  554. if (self) {
  555. _serializer = serializer;
  556. }
  557. return self;
  558. }
  559. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter {
  560. return [[GRPCCall alloc] initWithHost:self.databaseInfo.host
  561. path:@"/google.firestore.v1beta1.Firestore/Write"
  562. requestsWriter:requestsWriter];
  563. }
  564. - (void)startWithDelegate:(id)delegate {
  565. self.handshakeComplete = NO;
  566. [super startWithDelegate:delegate];
  567. }
  568. - (void)notifyStreamOpen {
  569. [self.delegate writeStreamDidOpen];
  570. }
  571. - (void)notifyStreamInterruptedWithError:(nullable NSError *)error {
  572. [self.delegate writeStreamWasInterruptedWithError:error];
  573. }
  574. - (void)writeHandshake {
  575. // The initial request cannot contain mutations, but must contain a projectID.
  576. FSTAssert([self isOpen], @"Not yet open");
  577. FSTAssert(!self.handshakeComplete, @"Handshake sent out of turn");
  578. [self.workerDispatchQueue verifyIsCurrentQueue];
  579. GCFSWriteRequest *request = [GCFSWriteRequest message];
  580. request.database = [_serializer encodedDatabaseID];
  581. // TODO(dimond): Support stream resumption. We intentionally do not set the stream token on the
  582. // handshake, ignoring any stream token we might have.
  583. FSTLog(@"FSTWriteStream %p initial request: %@", (__bridge void *)self, request);
  584. [self writeRequest:request];
  585. }
  586. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations {
  587. FSTAssert([self isOpen], @"Not yet open");
  588. FSTAssert(self.handshakeComplete, @"Mutations sent out of turn");
  589. [self.workerDispatchQueue verifyIsCurrentQueue];
  590. NSMutableArray<GCFSWrite *> *protos = [NSMutableArray arrayWithCapacity:mutations.count];
  591. for (FSTMutation *mutation in mutations) {
  592. [protos addObject:[_serializer encodedMutation:mutation]];
  593. };
  594. GCFSWriteRequest *request = [GCFSWriteRequest message];
  595. request.writesArray = protos;
  596. request.streamToken = self.lastStreamToken;
  597. FSTLog(@"FSTWriteStream %p mutation request: %@", (__bridge void *)self, request);
  598. [self writeRequest:request];
  599. }
  600. /**
  601. * Implements GRXWriteable to receive an inbound message from GRPC, deserialize, and then pass
  602. * that on to the mutationResultsHandler.
  603. */
  604. - (void)handleStreamMessage:(GCFSWriteResponse *)response {
  605. FSTLog(@"FSTWriteStream %p response: %@", (__bridge void *)self, response);
  606. [self.workerDispatchQueue verifyIsCurrentQueue];
  607. // Always capture the last stream token.
  608. self.lastStreamToken = response.streamToken;
  609. if (!self.isHandshakeComplete) {
  610. // The first response is the handshake response
  611. self.handshakeComplete = YES;
  612. [self.delegate writeStreamDidCompleteHandshake];
  613. } else {
  614. // A successful first write response means the stream is healthy.
  615. // Note that we could consider a successful handshake healthy, however, the write itself
  616. // might be causing an error we want to back off from.
  617. [self.backoff reset];
  618. FSTSnapshotVersion *commitVersion = [_serializer decodedVersion:response.commitTime];
  619. NSMutableArray<GCFSWriteResult *> *protos = response.writeResultsArray;
  620. NSMutableArray<FSTMutationResult *> *results = [NSMutableArray arrayWithCapacity:protos.count];
  621. for (GCFSWriteResult *proto in protos) {
  622. [results addObject:[_serializer decodedMutationResult:proto]];
  623. };
  624. [self.delegate writeStreamDidReceiveResponseWithVersion:commitVersion mutationResults:results];
  625. }
  626. }
  627. @end