FSTEventManager.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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/Core/FSTEventManager.h"
  17. #import "Firestore/Source/Core/FSTQuery.h"
  18. #import "Firestore/Source/Core/FSTSyncEngine.h"
  19. #import "Firestore/Source/Model/FSTDocumentSet.h"
  20. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  21. NS_ASSUME_NONNULL_BEGIN
  22. #pragma mark - FSTListenOptions
  23. @implementation FSTListenOptions
  24. + (instancetype)defaultOptions {
  25. static FSTListenOptions *defaultOptions;
  26. static dispatch_once_t onceToken;
  27. dispatch_once(&onceToken, ^{
  28. defaultOptions = [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:NO
  29. includeDocumentMetadataChanges:NO
  30. waitForSyncWhenOnline:NO];
  31. });
  32. return defaultOptions;
  33. }
  34. - (instancetype)initWithIncludeQueryMetadataChanges:(BOOL)includeQueryMetadataChanges
  35. includeDocumentMetadataChanges:(BOOL)includeDocumentMetadataChanges
  36. waitForSyncWhenOnline:(BOOL)waitForSyncWhenOnline {
  37. if (self = [super init]) {
  38. _includeQueryMetadataChanges = includeQueryMetadataChanges;
  39. _includeDocumentMetadataChanges = includeDocumentMetadataChanges;
  40. _waitForSyncWhenOnline = waitForSyncWhenOnline;
  41. }
  42. return self;
  43. }
  44. - (instancetype)init {
  45. HARD_FAIL("FSTListenOptions init not supported");
  46. return nil;
  47. }
  48. @end
  49. #pragma mark - FSTQueryListenersInfo
  50. /**
  51. * Holds the listeners and the last received ViewSnapshot for a query being tracked by
  52. * EventManager.
  53. */
  54. @interface FSTQueryListenersInfo : NSObject
  55. @property(nonatomic, strong, nullable, readwrite) FSTViewSnapshot *viewSnapshot;
  56. @property(nonatomic, assign, readwrite) FSTTargetID targetID;
  57. @property(nonatomic, strong, readonly) NSMutableArray<FSTQueryListener *> *listeners;
  58. @end
  59. @implementation FSTQueryListenersInfo
  60. - (instancetype)init {
  61. if (self = [super init]) {
  62. _listeners = [NSMutableArray array];
  63. }
  64. return self;
  65. }
  66. @end
  67. #pragma mark - FSTQueryListener
  68. @interface FSTQueryListener ()
  69. /** The last received view snapshot. */
  70. @property(nonatomic, strong, nullable) FSTViewSnapshot *snapshot;
  71. @property(nonatomic, strong, readonly) FSTListenOptions *options;
  72. /**
  73. * Initial snapshots (e.g. from cache) may not be propagated to the FSTViewSnapshotHandler.
  74. * This flag is set to YES once we've actually raised an event.
  75. */
  76. @property(nonatomic, assign, readwrite) BOOL raisedInitialEvent;
  77. /** The last online state this query listener got. */
  78. @property(nonatomic, assign, readwrite) FSTOnlineState onlineState;
  79. /** The FSTViewSnapshotHandler associated with this query listener. */
  80. @property(nonatomic, copy, nullable) FSTViewSnapshotHandler viewSnapshotHandler;
  81. @end
  82. @implementation FSTQueryListener
  83. - (instancetype)initWithQuery:(FSTQuery *)query
  84. options:(FSTListenOptions *)options
  85. viewSnapshotHandler:(FSTViewSnapshotHandler)viewSnapshotHandler {
  86. if (self = [super init]) {
  87. _query = query;
  88. _options = options;
  89. _viewSnapshotHandler = viewSnapshotHandler;
  90. _raisedInitialEvent = NO;
  91. }
  92. return self;
  93. }
  94. - (void)queryDidChangeViewSnapshot:(FSTViewSnapshot *)snapshot {
  95. HARD_ASSERT(snapshot.documentChanges.count > 0 || snapshot.syncStateChanged,
  96. "We got a new snapshot with no changes?");
  97. if (!self.options.includeDocumentMetadataChanges) {
  98. // Remove the metadata-only changes.
  99. NSMutableArray<FSTDocumentViewChange *> *changes = [NSMutableArray array];
  100. for (FSTDocumentViewChange *change in snapshot.documentChanges) {
  101. if (change.type != FSTDocumentViewChangeTypeMetadata) {
  102. [changes addObject:change];
  103. }
  104. }
  105. snapshot = [[FSTViewSnapshot alloc] initWithQuery:snapshot.query
  106. documents:snapshot.documents
  107. oldDocuments:snapshot.oldDocuments
  108. documentChanges:changes
  109. fromCache:snapshot.fromCache
  110. hasPendingWrites:snapshot.hasPendingWrites
  111. syncStateChanged:snapshot.syncStateChanged];
  112. }
  113. if (!self.raisedInitialEvent) {
  114. if ([self shouldRaiseInitialEventForSnapshot:snapshot onlineState:self.onlineState]) {
  115. [self raiseInitialEventForSnapshot:snapshot];
  116. }
  117. } else if ([self shouldRaiseEventForSnapshot:snapshot]) {
  118. self.viewSnapshotHandler(snapshot, nil);
  119. }
  120. self.snapshot = snapshot;
  121. }
  122. - (void)queryDidError:(NSError *)error {
  123. self.viewSnapshotHandler(nil, error);
  124. }
  125. - (void)applyChangedOnlineState:(FSTOnlineState)onlineState {
  126. self.onlineState = onlineState;
  127. if (self.snapshot && !self.raisedInitialEvent &&
  128. [self shouldRaiseInitialEventForSnapshot:self.snapshot onlineState:onlineState]) {
  129. [self raiseInitialEventForSnapshot:self.snapshot];
  130. }
  131. }
  132. - (BOOL)shouldRaiseInitialEventForSnapshot:(FSTViewSnapshot *)snapshot
  133. onlineState:(FSTOnlineState)onlineState {
  134. HARD_ASSERT(!self.raisedInitialEvent,
  135. "Determining whether to raise initial event, but already had first event.");
  136. // Always raise the first event when we're synced
  137. if (!snapshot.fromCache) {
  138. return YES;
  139. }
  140. // NOTE: We consider OnlineState.Unknown as online (it should become Offline or Online if we
  141. // wait long enough).
  142. BOOL maybeOnline = onlineState != FSTOnlineStateOffline;
  143. // Don't raise the event if we're online, aren't synced yet (checked
  144. // above) and are waiting for a sync.
  145. if (self.options.waitForSyncWhenOnline && maybeOnline) {
  146. HARD_ASSERT(snapshot.fromCache, "Waiting for sync, but snapshot is not from cache.");
  147. return NO;
  148. }
  149. // Raise data from cache if we have any documents or we are offline
  150. return !snapshot.documents.isEmpty || onlineState == FSTOnlineStateOffline;
  151. }
  152. - (BOOL)shouldRaiseEventForSnapshot:(FSTViewSnapshot *)snapshot {
  153. // We don't need to handle includeDocumentMetadataChanges here because the Metadata only changes
  154. // have already been stripped out if needed. At this point the only changes we will see are the
  155. // ones we should propagate.
  156. if (snapshot.documentChanges.count > 0) {
  157. return YES;
  158. }
  159. BOOL hasPendingWritesChanged =
  160. self.snapshot && self.snapshot.hasPendingWrites != snapshot.hasPendingWrites;
  161. if (snapshot.syncStateChanged || hasPendingWritesChanged) {
  162. return self.options.includeQueryMetadataChanges;
  163. }
  164. // Generally we should have hit one of the cases above, but it's possible to get here if there
  165. // were only metadata docChanges and they got stripped out.
  166. return NO;
  167. }
  168. - (void)raiseInitialEventForSnapshot:(FSTViewSnapshot *)snapshot {
  169. HARD_ASSERT(!self.raisedInitialEvent, "Trying to raise initial events for second time");
  170. snapshot = [[FSTViewSnapshot alloc]
  171. initWithQuery:snapshot.query
  172. documents:snapshot.documents
  173. oldDocuments:[FSTDocumentSet documentSetWithComparator:snapshot.query.comparator]
  174. documentChanges:[FSTQueryListener getInitialViewChangesFor:snapshot]
  175. fromCache:snapshot.fromCache
  176. hasPendingWrites:snapshot.hasPendingWrites
  177. syncStateChanged:YES];
  178. self.raisedInitialEvent = YES;
  179. self.viewSnapshotHandler(snapshot, nil);
  180. }
  181. + (NSArray<FSTDocumentViewChange *> *)getInitialViewChangesFor:(FSTViewSnapshot *)snapshot {
  182. NSMutableArray<FSTDocumentViewChange *> *result = [NSMutableArray array];
  183. for (FSTDocument *doc in snapshot.documents.documentEnumerator) {
  184. [result addObject:[FSTDocumentViewChange changeWithDocument:doc
  185. type:FSTDocumentViewChangeTypeAdded]];
  186. }
  187. return result;
  188. }
  189. @end
  190. #pragma mark - FSTEventManager
  191. @interface FSTEventManager () <FSTSyncEngineDelegate>
  192. - (instancetype)initWithSyncEngine:(FSTSyncEngine *)syncEngine NS_DESIGNATED_INITIALIZER;
  193. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  194. @property(nonatomic, strong, readonly)
  195. NSMutableDictionary<FSTQuery *, FSTQueryListenersInfo *> *queries;
  196. @property(nonatomic, assign) FSTOnlineState onlineState;
  197. @end
  198. @implementation FSTEventManager
  199. + (instancetype)eventManagerWithSyncEngine:(FSTSyncEngine *)syncEngine {
  200. return [[FSTEventManager alloc] initWithSyncEngine:syncEngine];
  201. }
  202. - (instancetype)initWithSyncEngine:(FSTSyncEngine *)syncEngine {
  203. if (self = [super init]) {
  204. _syncEngine = syncEngine;
  205. _queries = [NSMutableDictionary dictionary];
  206. _syncEngine.delegate = self;
  207. }
  208. return self;
  209. }
  210. - (FSTTargetID)addListener:(FSTQueryListener *)listener {
  211. FSTQuery *query = listener.query;
  212. BOOL firstListen = NO;
  213. FSTQueryListenersInfo *queryInfo = self.queries[query];
  214. if (!queryInfo) {
  215. firstListen = YES;
  216. queryInfo = [[FSTQueryListenersInfo alloc] init];
  217. self.queries[query] = queryInfo;
  218. }
  219. [queryInfo.listeners addObject:listener];
  220. [listener applyChangedOnlineState:self.onlineState];
  221. if (queryInfo.viewSnapshot) {
  222. [listener queryDidChangeViewSnapshot:queryInfo.viewSnapshot];
  223. }
  224. if (firstListen) {
  225. queryInfo.targetID = [self.syncEngine listenToQuery:query];
  226. }
  227. return queryInfo.targetID;
  228. }
  229. - (void)removeListener:(FSTQueryListener *)listener {
  230. FSTQuery *query = listener.query;
  231. BOOL lastListen = NO;
  232. FSTQueryListenersInfo *queryInfo = self.queries[query];
  233. if (queryInfo) {
  234. [queryInfo.listeners removeObject:listener];
  235. lastListen = (queryInfo.listeners.count == 0);
  236. }
  237. if (lastListen) {
  238. [self.queries removeObjectForKey:query];
  239. [self.syncEngine stopListeningToQuery:query];
  240. }
  241. }
  242. - (void)handleViewSnapshots:(NSArray<FSTViewSnapshot *> *)viewSnapshots {
  243. for (FSTViewSnapshot *viewSnapshot in viewSnapshots) {
  244. FSTQuery *query = viewSnapshot.query;
  245. FSTQueryListenersInfo *queryInfo = self.queries[query];
  246. if (queryInfo) {
  247. for (FSTQueryListener *listener in queryInfo.listeners) {
  248. [listener queryDidChangeViewSnapshot:viewSnapshot];
  249. }
  250. queryInfo.viewSnapshot = viewSnapshot;
  251. }
  252. }
  253. }
  254. - (void)handleError:(NSError *)error forQuery:(FSTQuery *)query {
  255. FSTQueryListenersInfo *queryInfo = self.queries[query];
  256. if (queryInfo) {
  257. for (FSTQueryListener *listener in queryInfo.listeners) {
  258. [listener queryDidError:error];
  259. }
  260. }
  261. // Remove all listeners. NOTE: We don't need to call [FSTSyncEngine stopListening] after an error.
  262. [self.queries removeObjectForKey:query];
  263. }
  264. - (void)applyChangedOnlineState:(FSTOnlineState)onlineState {
  265. self.onlineState = onlineState;
  266. for (FSTQueryListenersInfo *info in self.queries.objectEnumerator) {
  267. for (FSTQueryListener *listener in info.listeners) {
  268. [listener applyChangedOnlineState:onlineState];
  269. }
  270. }
  271. }
  272. @end
  273. NS_ASSUME_NONNULL_END