FSTEventManager.mm 11 KB

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