FSTEventManager.mm 11 KB

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