FSTStream.h 12 KB

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