FSTStream.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 <Foundation/Foundation.h>
  17. #import "Firestore/Source/Core/FSTTypes.h"
  18. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  19. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  20. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  21. @class FSTDocumentKey;
  22. @class FSTDispatchQueue;
  23. @class FSTMutation;
  24. @class FSTMutationResult;
  25. @class FSTQueryData;
  26. @class FSTSerializerBeta;
  27. @class FSTSnapshotVersion;
  28. @class FSTWatchChange;
  29. @class FSTWatchStream;
  30. @class FSTWriteStream;
  31. @class GRPCCall;
  32. @class GRXWriter;
  33. @protocol FSTWatchStreamDelegate;
  34. @protocol FSTWriteStreamDelegate;
  35. NS_ASSUME_NONNULL_BEGIN
  36. /**
  37. * An FSTStream is an abstract base class that represents a restartable streaming RPC to the
  38. * Firestore backend. It's built on top of GRPC's own support for streaming RPCs, and adds several
  39. * critical features for our clients:
  40. *
  41. * - Restarting a stream is allowed (after failure)
  42. * - Exponential backoff on failure (independent of the underlying channel)
  43. * - Authentication via CredentialsProvider
  44. * - Dispatching all callbacks into the shared worker queue
  45. *
  46. * Subclasses of FSTStream implement serialization of models to and from bytes (via protocol
  47. * buffers) for a specific streaming RPC and emit events specific to the stream.
  48. *
  49. * ## Starting and Stopping
  50. *
  51. * Streaming RPCs are stateful and need to be started before messages can be sent and received.
  52. * The FSTStream will call its delegate's specific streamDidOpen method once the stream is ready
  53. * to accept requests.
  54. *
  55. * Should a `start` fail, FSTStream will call its delegate's specific streamDidClose method with an
  56. * NSError indicating what went wrong. The delegate is free to call start again.
  57. *
  58. * An FSTStream can also be explicitly stopped which indicates that the caller has discarded the
  59. * stream and no further events should be emitted. Once explicitly stopped, a stream cannot be
  60. * restarted.
  61. *
  62. * ## Subclassing Notes
  63. *
  64. * An implementation of FSTStream needs to implement the following methods:
  65. * - `createRPCWithRequestsWriter`, should create the specific RPC (a GRPCCall object).
  66. * - `handleStreamMessage`, receives protocol buffer responses from GRPC and must deserialize and
  67. * delegate to some stream specific response method.
  68. * - `notifyStreamOpen`, should call through to the stream-specific streamDidOpen method.
  69. * - `notifyStreamInterrupted`, calls through to the stream-specific streamWasInterrupted method.
  70. *
  71. * Additionally, beyond these required methods, subclasses will want to implement methods that
  72. * take request models, serialize them, and write them to using writeRequest:. Implementation
  73. * specific cleanup logic can be added to tearDown:.
  74. *
  75. * ## RPC Message Type
  76. *
  77. * FSTStream intentionally uses the GRPCCall interface to GRPC directly, bypassing both GRPCProtoRPC
  78. * and GRXBufferedPipe for sending data. This has been done to avoid race conditions that come out
  79. * of a loosely specified locking contract on GRXWriter. There's essentially no way to safely use
  80. * any of the wrapper objects for GRXWriter (that perform buffering or conversion to/from protos).
  81. *
  82. * See https://github.com/grpc/grpc/issues/10957 for the kinds of things we're trying to avoid.
  83. */
  84. @interface FSTStream <__covariant FSTStreamDelegate> : NSObject
  85. - (instancetype)initWithDatabase:(const firebase::firestore::core::DatabaseInfo *)database
  86. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  87. connectionTimerID:(FSTTimerID)connectionTimerID
  88. idleTimerID:(FSTTimerID)idleTimerID
  89. credentials:(firebase::firestore::auth::CredentialsProvider *)credentials // no passing ownership
  90. responseMessageClass:(Class)responseMessageClass NS_DESIGNATED_INITIALIZER;
  91. - (instancetype)init NS_UNAVAILABLE;
  92. /**
  93. * An abstract method used by `start` to create a streaming RPC specific to this type of stream.
  94. * The RPC should be created such that requests are taken from `self`.
  95. *
  96. * Note that the returned GRPCCall must not be a GRPCProtoRPC, since the rest of the streaming
  97. * mechanism assumes it is dealing in bytes-level requests and responses.
  98. */
  99. - (GRPCCall *)createRPCWithRequestsWriter:(GRXWriter *)requestsWriter;
  100. /**
  101. * Returns YES if `start` has been called and no error has occurred. YES indicates the stream is
  102. * open or in the process of opening (which encompasses respecting backoff, getting auth tokens,
  103. * and starting the actual RPC). Use `isOpen` to determine if the stream is open and ready for
  104. * outbound requests.
  105. */
  106. - (BOOL)isStarted;
  107. /** Returns YES if the underlying RPC is open and the stream is ready for outbound requests. */
  108. - (BOOL)isOpen;
  109. /**
  110. * Starts the RPC. Only allowed if isStarted returns NO. The stream is not immediately ready for
  111. * use: the delegate's watchStreamDidOpen method will be invoked when the RPC is ready for outbound
  112. * requests, at which point `isOpen` will return YES.
  113. *
  114. * When start returns, -isStarted will return YES.
  115. */
  116. - (void)startWithDelegate:(id)delegate;
  117. /**
  118. * Stops the RPC. This call is idempotent and allowed regardless of the current isStarted state.
  119. *
  120. * Unlike a transient stream close, stopping a stream is permanent. This is guaranteed NOT to emit
  121. * any further events on the stream-specific delegate, including the streamDidClose method.
  122. *
  123. * NOTE: This no-events contract may seem counter-intuitive but allows the caller to
  124. * straightforwardly sequence stream tear-down without having to worry about when the delegate's
  125. * streamDidClose methods will get called. For example if the stream must be exchanged for another
  126. * during a user change this allows `stop` to be called eagerly without worrying about the
  127. * streamDidClose method accidentally restarting the stream before the new one is ready.
  128. *
  129. * When stop returns, -isStarted and -isOpen will both return NO.
  130. */
  131. - (void)stop;
  132. /**
  133. * Marks this stream as idle. If no further actions are performed on the stream for one minute, the
  134. * stream will automatically close itself and notify the stream's close handler. The stream will
  135. * then be in a non-started state, requiring the caller to start the stream again before further
  136. * use.
  137. *
  138. * Only streams that are in state 'Open' can be marked idle, as all other states imply pending
  139. * network operations.
  140. */
  141. - (void)markIdle;
  142. /**
  143. * After an error the stream will usually back off on the next attempt to start it. If the error
  144. * warrants an immediate restart of the stream, the sender can use this to indicate that the
  145. * receiver should not back off.
  146. *
  147. * Each error will call the stream-specific streamDidClose method. That method can decide to
  148. * inhibit backoff if required.
  149. */
  150. - (void)inhibitBackoff;
  151. @end
  152. #pragma mark - FSTWatchStream
  153. /** A protocol defining the events that can be emitted by the FSTWatchStream. */
  154. @protocol FSTWatchStreamDelegate <NSObject>
  155. /** Called by the FSTWatchStream when it is ready to accept outbound request messages. */
  156. - (void)watchStreamDidOpen;
  157. /**
  158. * Called by the FSTWatchStream with changes and the snapshot versions included in in the
  159. * WatchChange responses sent back by the server.
  160. */
  161. - (void)watchStreamDidChange:(FSTWatchChange *)change
  162. snapshotVersion:(FSTSnapshotVersion *)snapshotVersion;
  163. /**
  164. * Called by the FSTWatchStream when the underlying streaming RPC is interrupted for whatever
  165. * reason, usually because of an error, but possibly due to an idle timeout. The error passed to
  166. * this method may be nil, in which case the stream was closed without attributable fault.
  167. *
  168. * NOTE: This will not be called after `stop` is called on the stream. See "Starting and Stopping"
  169. * on FSTStream for details.
  170. */
  171. - (void)watchStreamWasInterruptedWithError:(nullable NSError *)error;
  172. @end
  173. /**
  174. * An FSTStream that implements the StreamingWatch RPC.
  175. *
  176. * Once the FSTWatchStream has called the streamDidOpen method, any number of watchQuery and
  177. * unwatchTargetId calls can be sent to control what changes will be sent from the server for
  178. * WatchChanges.
  179. */
  180. @interface FSTWatchStream : FSTStream
  181. /**
  182. * Initializes the watch stream with its dependencies.
  183. */
  184. - (instancetype)initWithDatabase:(const firebase::firestore::core::DatabaseInfo *)database
  185. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  186. credentials:(firebase::firestore::auth::CredentialsProvider *)
  187. credentials // no passsing ownership
  188. serializer:(FSTSerializerBeta *)serializer NS_DESIGNATED_INITIALIZER;
  189. - (instancetype)initWithDatabase:(const firebase::firestore::core::DatabaseInfo *)database
  190. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  191. connectionTimerID:(FSTTimerID)connectionTimerID
  192. idleTimerID:(FSTTimerID)idleTimerID
  193. credentials:(firebase::firestore::auth::CredentialsProvider *)
  194. credentials // no passing ownership
  195. responseMessageClass:(Class)responseMessageClass NS_UNAVAILABLE;
  196. - (instancetype)init NS_UNAVAILABLE;
  197. /**
  198. * Registers interest in the results of the given query. If the query includes a resumeToken it
  199. * will be included in the request. Results that affect the query will be streamed back as
  200. * WatchChange messages that reference the targetID included in |query|.
  201. */
  202. - (void)watchQuery:(FSTQueryData *)query;
  203. /** Unregisters interest in the results of the query associated with the given target ID. */
  204. - (void)unwatchTargetID:(FSTTargetID)targetID;
  205. @end
  206. #pragma mark - FSTWriteStream
  207. @protocol FSTWriteStreamDelegate <NSObject>
  208. /** Called by the FSTWriteStream when it is ready to accept outbound request messages. */
  209. - (void)writeStreamDidOpen;
  210. /**
  211. * Called by the FSTWriteStream upon a successful handshake response from the server, which is the
  212. * receiver's cue to send any pending writes.
  213. */
  214. - (void)writeStreamDidCompleteHandshake;
  215. /**
  216. * Called by the FSTWriteStream upon receiving a StreamingWriteResponse from the server that
  217. * contains mutation results.
  218. */
  219. - (void)writeStreamDidReceiveResponseWithVersion:(FSTSnapshotVersion *)commitVersion
  220. mutationResults:(NSArray<FSTMutationResult *> *)results;
  221. /**
  222. * Called when the FSTWriteStream's underlying RPC is interrupted for whatever reason, usually
  223. * because of an error, but possibly due to an idle timeout. The error passed to this method may be
  224. * nil, in which case the stream was closed without attributable fault.
  225. *
  226. * NOTE: This will not be called after `stop` is called on the stream. See "Starting and Stopping"
  227. * on FSTStream for details.
  228. */
  229. - (void)writeStreamWasInterruptedWithError:(nullable NSError *)error;
  230. @end
  231. /**
  232. * An FSTStream that implements the StreamingWrite RPC.
  233. *
  234. * The StreamingWrite RPC requires the caller to maintain special `streamToken` state in between
  235. * calls, to help the server understand which responses the client has processed by the time the
  236. * next request is made. Every response may contain a `streamToken`; this value must be passed to
  237. * the next request.
  238. *
  239. * After calling `start` on this stream, the next request must be a handshake, containing whatever
  240. * streamToken is on hand. Once a response to this request is received, all pending mutations may
  241. * be submitted. When submitting multiple batches of mutations at the same time, it's okay to use
  242. * the same streamToken for the calls to `writeMutations:`.
  243. */
  244. @interface FSTWriteStream : FSTStream
  245. /**
  246. * Initializes the write stream with its dependencies.
  247. */
  248. - (instancetype)initWithDatabase:(const firebase::firestore::core::DatabaseInfo *)database
  249. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  250. credentials:(firebase::firestore::auth::CredentialsProvider *)
  251. credentials // no passing ownership
  252. serializer:(FSTSerializerBeta *)serializer;
  253. - (instancetype)initWithDatabase:(const firebase::firestore::core::DatabaseInfo *)database
  254. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  255. connectionTimerID:(FSTTimerID)connectionTimerID
  256. idleTimerID:(FSTTimerID)idleTimerID
  257. credentials:(firebase::firestore::auth::CredentialsProvider *)
  258. credentials // no passing ownership
  259. responseMessageClass:(Class)responseMessageClass NS_UNAVAILABLE;
  260. - (instancetype)init NS_UNAVAILABLE;
  261. /**
  262. * Sends an initial streamToken to the server, performing the handshake required to make the
  263. * StreamingWrite RPC work. Subsequent `writeMutations:` calls should wait until a response has
  264. * been delivered to the delegate's writeStreamDidCompleteHandshake method.
  265. */
  266. - (void)writeHandshake;
  267. /** Sends a group of mutations to the Firestore backend to apply. */
  268. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations;
  269. /**
  270. * Tracks whether or not a handshake has been successfully exchanged and the stream is ready to
  271. * accept mutations.
  272. */
  273. @property(nonatomic, assign, readwrite, getter=isHandshakeComplete) BOOL handshakeComplete;
  274. /**
  275. * The last received stream token from the server, used to acknowledge which responses the client
  276. * has processed. Stream tokens are opaque checkpoint markers whose only real value is their
  277. * inclusion in the next request.
  278. *
  279. * FSTWriteStream manages propagating this value from responses to the next request.
  280. */
  281. @property(nonatomic, strong, nullable) NSData *lastStreamToken;
  282. @end
  283. NS_ASSUME_NONNULL_END