FSTEventManager.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. mutatedKeys:snapshot.mutatedKeys
  113. syncStateChanged:snapshot.syncStateChanged
  114. excludesMetadataChanges:YES];
  115. }
  116. if (!self.raisedInitialEvent) {
  117. if ([self shouldRaiseInitialEventForSnapshot:snapshot onlineState:self.onlineState]) {
  118. [self raiseInitialEventForSnapshot:snapshot];
  119. }
  120. } else if ([self shouldRaiseEventForSnapshot:snapshot]) {
  121. self.viewSnapshotHandler(snapshot, nil);
  122. }
  123. self.snapshot = snapshot;
  124. }
  125. - (void)queryDidError:(NSError *)error {
  126. self.viewSnapshotHandler(nil, error);
  127. }
  128. - (void)applyChangedOnlineState:(OnlineState)onlineState {
  129. self.onlineState = onlineState;
  130. if (self.snapshot && !self.raisedInitialEvent &&
  131. [self shouldRaiseInitialEventForSnapshot:self.snapshot onlineState:onlineState]) {
  132. [self raiseInitialEventForSnapshot:self.snapshot];
  133. }
  134. }
  135. - (BOOL)shouldRaiseInitialEventForSnapshot:(FSTViewSnapshot *)snapshot
  136. onlineState:(OnlineState)onlineState {
  137. HARD_ASSERT(!self.raisedInitialEvent,
  138. "Determining whether to raise initial event, but already had first event.");
  139. // Always raise the first event when we're synced
  140. if (!snapshot.fromCache) {
  141. return YES;
  142. }
  143. // NOTE: We consider OnlineState.Unknown as online (it should become Offline or Online if we
  144. // wait long enough).
  145. BOOL maybeOnline = onlineState != OnlineState::Offline;
  146. // Don't raise the event if we're online, aren't synced yet (checked
  147. // above) and are waiting for a sync.
  148. if (self.options.waitForSyncWhenOnline && maybeOnline) {
  149. HARD_ASSERT(snapshot.fromCache, "Waiting for sync, but snapshot is not from cache.");
  150. return NO;
  151. }
  152. // Raise data from cache if we have any documents or we are offline
  153. return !snapshot.documents.isEmpty || onlineState == OnlineState::Offline;
  154. }
  155. - (BOOL)shouldRaiseEventForSnapshot:(FSTViewSnapshot *)snapshot {
  156. // We don't need to handle includeDocumentMetadataChanges here because the Metadata only changes
  157. // have already been stripped out if needed. At this point the only changes we will see are the
  158. // ones we should propagate.
  159. if (snapshot.documentChanges.count > 0) {
  160. return YES;
  161. }
  162. BOOL hasPendingWritesChanged =
  163. self.snapshot && self.snapshot.hasPendingWrites != snapshot.hasPendingWrites;
  164. if (snapshot.syncStateChanged || hasPendingWritesChanged) {
  165. return self.options.includeQueryMetadataChanges;
  166. }
  167. // Generally we should have hit one of the cases above, but it's possible to get here if there
  168. // were only metadata docChanges and they got stripped out.
  169. return NO;
  170. }
  171. - (void)raiseInitialEventForSnapshot:(FSTViewSnapshot *)snapshot {
  172. HARD_ASSERT(!self.raisedInitialEvent, "Trying to raise initial events for second time");
  173. snapshot = [FSTViewSnapshot snapshotForInitialDocuments:snapshot.documents
  174. query:snapshot.query
  175. mutatedKeys:snapshot.mutatedKeys
  176. fromCache:snapshot.fromCache
  177. excludesMetadataChanges:snapshot.excludesMetadataChanges];
  178. self.raisedInitialEvent = YES;
  179. self.viewSnapshotHandler(snapshot, nil);
  180. }
  181. @end
  182. #pragma mark - FSTEventManager
  183. @interface FSTEventManager () <FSTSyncEngineDelegate>
  184. - (instancetype)initWithSyncEngine:(FSTSyncEngine *)syncEngine NS_DESIGNATED_INITIALIZER;
  185. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  186. @property(nonatomic, strong, readonly)
  187. NSMutableDictionary<FSTQuery *, FSTQueryListenersInfo *> *queries;
  188. @property(nonatomic, assign) OnlineState onlineState;
  189. @end
  190. @implementation FSTEventManager
  191. + (instancetype)eventManagerWithSyncEngine:(FSTSyncEngine *)syncEngine {
  192. return [[FSTEventManager alloc] initWithSyncEngine:syncEngine];
  193. }
  194. - (instancetype)initWithSyncEngine:(FSTSyncEngine *)syncEngine {
  195. if (self = [super init]) {
  196. _syncEngine = syncEngine;
  197. _queries = [NSMutableDictionary dictionary];
  198. _syncEngine.syncEngineDelegate = self;
  199. }
  200. return self;
  201. }
  202. - (TargetId)addListener:(FSTQueryListener *)listener {
  203. FSTQuery *query = listener.query;
  204. BOOL firstListen = NO;
  205. FSTQueryListenersInfo *queryInfo = self.queries[query];
  206. if (!queryInfo) {
  207. firstListen = YES;
  208. queryInfo = [[FSTQueryListenersInfo alloc] init];
  209. self.queries[query] = queryInfo;
  210. }
  211. [queryInfo.listeners addObject:listener];
  212. [listener applyChangedOnlineState:self.onlineState];
  213. if (queryInfo.viewSnapshot) {
  214. [listener queryDidChangeViewSnapshot:queryInfo.viewSnapshot];
  215. }
  216. if (firstListen) {
  217. queryInfo.targetID = [self.syncEngine listenToQuery:query];
  218. }
  219. return queryInfo.targetID;
  220. }
  221. - (void)removeListener:(FSTQueryListener *)listener {
  222. FSTQuery *query = listener.query;
  223. BOOL lastListen = NO;
  224. FSTQueryListenersInfo *queryInfo = self.queries[query];
  225. if (queryInfo) {
  226. [queryInfo.listeners removeObject:listener];
  227. lastListen = (queryInfo.listeners.count == 0);
  228. }
  229. if (lastListen) {
  230. [self.queries removeObjectForKey:query];
  231. [self.syncEngine stopListeningToQuery:query];
  232. }
  233. }
  234. - (void)handleViewSnapshots:(NSArray<FSTViewSnapshot *> *)viewSnapshots {
  235. for (FSTViewSnapshot *viewSnapshot in viewSnapshots) {
  236. FSTQuery *query = viewSnapshot.query;
  237. FSTQueryListenersInfo *queryInfo = self.queries[query];
  238. if (queryInfo) {
  239. for (FSTQueryListener *listener in queryInfo.listeners) {
  240. [listener queryDidChangeViewSnapshot:viewSnapshot];
  241. }
  242. queryInfo.viewSnapshot = viewSnapshot;
  243. }
  244. }
  245. }
  246. - (void)handleError:(NSError *)error forQuery:(FSTQuery *)query {
  247. FSTQueryListenersInfo *queryInfo = self.queries[query];
  248. if (queryInfo) {
  249. for (FSTQueryListener *listener in queryInfo.listeners) {
  250. [listener queryDidError:error];
  251. }
  252. }
  253. // Remove all listeners. NOTE: We don't need to call [FSTSyncEngine stopListening] after an error.
  254. [self.queries removeObjectForKey:query];
  255. }
  256. - (void)applyChangedOnlineState:(OnlineState)onlineState {
  257. self.onlineState = onlineState;
  258. for (FSTQueryListenersInfo *info in self.queries.objectEnumerator) {
  259. for (FSTQueryListener *listener in info.listeners) {
  260. [listener applyChangedOnlineState:onlineState];
  261. }
  262. }
  263. }
  264. @end
  265. NS_ASSUME_NONNULL_END