FSTEventManager.mm 11 KB

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