FSTHelpers.mm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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/Example/Tests/Util/FSTHelpers.h"
  17. #import <FirebaseFirestore/FIRFieldPath.h>
  18. #import <FirebaseFirestore/FIRGeoPoint.h>
  19. #import <FirebaseFirestore/FIRTimestamp.h>
  20. #include <cinttypes>
  21. #include <list>
  22. #include <set>
  23. #include <utility>
  24. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  25. #import "Firestore/Source/API/FSTUserDataConverter.h"
  26. #import "Firestore/Source/Core/FSTView.h"
  27. #import "Firestore/Source/Local/FSTQueryData.h"
  28. #import "Firestore/Source/Model/FSTDocument.h"
  29. #import "Firestore/Source/Model/FSTMutation.h"
  30. #include "Firestore/core/src/firebase/firestore/core/filter.h"
  31. #include "Firestore/core/src/firebase/firestore/core/view_snapshot.h"
  32. #include "Firestore/core/src/firebase/firestore/local/local_view_changes.h"
  33. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  34. #include "Firestore/core/src/firebase/firestore/model/document.h"
  35. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  36. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  37. #include "Firestore/core/src/firebase/firestore/model/document_set.h"
  38. #include "Firestore/core/src/firebase/firestore/model/field_mask.h"
  39. #include "Firestore/core/src/firebase/firestore/model/field_transform.h"
  40. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  41. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  42. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  43. #include "Firestore/core/src/firebase/firestore/model/transform_operations.h"
  44. #include "Firestore/core/src/firebase/firestore/remote/remote_event.h"
  45. #include "Firestore/core/src/firebase/firestore/remote/watch_change.h"
  46. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  47. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  48. #include "absl/memory/memory.h"
  49. namespace testutil = firebase::firestore::testutil;
  50. namespace util = firebase::firestore::util;
  51. using firebase::firestore::core::Direction;
  52. using firebase::firestore::core::Filter;
  53. using firebase::firestore::core::ParsedUpdateData;
  54. using firebase::firestore::core::Query;
  55. using firebase::firestore::core::ViewSnapshot;
  56. using firebase::firestore::local::LocalViewChanges;
  57. using firebase::firestore::model::DatabaseId;
  58. using firebase::firestore::model::DocumentComparator;
  59. using firebase::firestore::model::DocumentKey;
  60. using firebase::firestore::model::DocumentKeySet;
  61. using firebase::firestore::model::DocumentSet;
  62. using firebase::firestore::model::DocumentState;
  63. using firebase::firestore::model::FieldMask;
  64. using firebase::firestore::model::FieldPath;
  65. using firebase::firestore::model::FieldTransform;
  66. using firebase::firestore::model::FieldValue;
  67. using firebase::firestore::model::MaybeDocumentMap;
  68. using firebase::firestore::model::ObjectValue;
  69. using firebase::firestore::model::Precondition;
  70. using firebase::firestore::model::ResourcePath;
  71. using firebase::firestore::model::ServerTimestampTransform;
  72. using firebase::firestore::model::SnapshotVersion;
  73. using firebase::firestore::model::TargetId;
  74. using firebase::firestore::model::TransformOperation;
  75. using firebase::firestore::remote::DocumentWatchChange;
  76. using firebase::firestore::remote::RemoteEvent;
  77. using firebase::firestore::remote::TargetChange;
  78. using firebase::firestore::remote::WatchChangeAggregator;
  79. using firebase::firestore::testutil::OrderBy;
  80. using firebase::firestore::testutil::Query;
  81. NS_ASSUME_NONNULL_BEGIN
  82. /** A string sentinel that can be used with FSTTestPatchMutation() to mark a field for deletion. */
  83. static NSString *const kDeleteSentinel = @"<DELETE>";
  84. FIRTimestamp *FSTTestTimestamp(int year, int month, int day, int hour, int minute, int second) {
  85. NSDate *date = FSTTestDate(year, month, day, hour, minute, second);
  86. return [FIRTimestamp timestampWithDate:date];
  87. }
  88. NSDate *FSTTestDate(int year, int month, int day, int hour, int minute, int second) {
  89. NSDateComponents *comps = FSTTestDateComponents(year, month, day, hour, minute, second);
  90. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  91. }
  92. NSData *FSTTestData(int bytes, ...) {
  93. va_list args;
  94. va_start(args, bytes); /* Initialize the argument list. */
  95. NSMutableData *data = [NSMutableData data];
  96. int next = bytes;
  97. while (next >= 0) {
  98. uint8_t byte = (uint8_t)next;
  99. [data appendBytes:&byte length:1];
  100. next = va_arg(args, int);
  101. }
  102. va_end(args);
  103. return [data copy];
  104. }
  105. FIRGeoPoint *FSTTestGeoPoint(double latitude, double longitude) {
  106. return [[FIRGeoPoint alloc] initWithLatitude:latitude longitude:longitude];
  107. }
  108. NSDateComponents *FSTTestDateComponents(
  109. int year, int month, int day, int hour, int minute, int second) {
  110. NSDateComponents *comps = [[NSDateComponents alloc] init];
  111. comps.year = year;
  112. comps.month = month;
  113. comps.day = day;
  114. comps.hour = hour;
  115. comps.minute = minute;
  116. comps.second = second;
  117. // Force time zone to UTC to avoid these values changing due to daylight saving.
  118. comps.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  119. return comps;
  120. }
  121. FSTUserDataConverter *FSTTestUserDataConverter() {
  122. FSTUserDataConverter *converter =
  123. [[FSTUserDataConverter alloc] initWithDatabaseID:DatabaseId("project")
  124. preConverter:^id _Nullable(id _Nullable input) {
  125. return input;
  126. }];
  127. return converter;
  128. }
  129. FieldValue FSTTestFieldValue(id _Nullable value) {
  130. FSTUserDataConverter *converter = FSTTestUserDataConverter();
  131. // HACK: We use parsedQueryValue: since it accepts scalars as well as arrays / objects, and
  132. // our tests currently use FSTTestFieldValue() pretty generically so we don't know the intent.
  133. return [converter parsedQueryValue:value];
  134. }
  135. ObjectValue FSTTestObjectValue(NSDictionary<NSString *, id> *data) {
  136. FieldValue wrapped = FSTTestFieldValue(data);
  137. HARD_ASSERT(wrapped.type() == FieldValue::Type::Object, "Unsupported value: %s", data);
  138. return ObjectValue(std::move(wrapped));
  139. }
  140. DocumentKey FSTTestDocKey(NSString *path) {
  141. return DocumentKey::FromPathString(util::MakeString(path));
  142. }
  143. FSTDocument *FSTTestDoc(const absl::string_view path,
  144. FSTTestSnapshotVersion version,
  145. NSDictionary<NSString *, id> *data,
  146. DocumentState documentState) {
  147. DocumentKey key = testutil::Key(path);
  148. return [FSTDocument documentWithData:FSTTestObjectValue(data)
  149. key:key
  150. version:testutil::Version(version)
  151. state:documentState];
  152. }
  153. FSTDeletedDocument *FSTTestDeletedDoc(const absl::string_view path,
  154. FSTTestSnapshotVersion version,
  155. BOOL hasCommittedMutations) {
  156. DocumentKey key = testutil::Key(path);
  157. return [FSTDeletedDocument documentWithKey:key
  158. version:testutil::Version(version)
  159. hasCommittedMutations:hasCommittedMutations];
  160. }
  161. FSTUnknownDocument *FSTTestUnknownDoc(const absl::string_view path,
  162. FSTTestSnapshotVersion version) {
  163. DocumentKey key = testutil::Key(path);
  164. return [FSTUnknownDocument documentWithKey:key version:testutil::Version(version)];
  165. }
  166. FSTDocumentKeyReference *FSTTestRef(std::string projectID, std::string database, NSString *path) {
  167. return [[FSTDocumentKeyReference alloc] initWithKey:FSTTestDocKey(path)
  168. databaseID:DatabaseId(projectID, database)];
  169. }
  170. DocumentComparator FSTTestDocComparator(const absl::string_view fieldPath) {
  171. return Query("docs").AddingOrderBy(OrderBy(fieldPath)).Comparator();
  172. }
  173. DocumentSet FSTTestDocSet(DocumentComparator comp, NSArray<FSTDocument *> *docs) {
  174. DocumentSet docSet{std::move(comp)};
  175. for (FSTDocument *doc in docs) {
  176. docSet = docSet.insert(doc);
  177. }
  178. return docSet;
  179. }
  180. FSTSetMutation *FSTTestSetMutation(NSString *path, NSDictionary<NSString *, id> *values) {
  181. return [[FSTSetMutation alloc] initWithKey:FSTTestDocKey(path)
  182. value:FSTTestObjectValue(values)
  183. precondition:Precondition::None()];
  184. }
  185. FSTPatchMutation *FSTTestPatchMutation(const absl::string_view path,
  186. NSDictionary<NSString *, id> *values,
  187. const std::vector<FieldPath> &updateMask) {
  188. BOOL merge = !updateMask.empty();
  189. __block ObjectValue objectValue = ObjectValue::Empty();
  190. __block std::set<FieldPath> fieldMaskPaths;
  191. [values enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  192. const FieldPath path = testutil::Field(util::MakeString(key));
  193. fieldMaskPaths.insert(path);
  194. if (![value isEqual:kDeleteSentinel]) {
  195. FieldValue parsedValue = FSTTestFieldValue(value);
  196. objectValue = objectValue.Set(path, std::move(parsedValue));
  197. }
  198. }];
  199. DocumentKey key = testutil::Key(path);
  200. FieldMask mask(merge ? std::set<FieldPath>(updateMask.begin(), updateMask.end())
  201. : fieldMaskPaths);
  202. return [[FSTPatchMutation alloc]
  203. initWithKey:key
  204. fieldMask:mask
  205. value:objectValue
  206. precondition:merge ? Precondition::None() : Precondition::Exists(true)];
  207. }
  208. FSTTransformMutation *FSTTestTransformMutation(NSString *path, NSDictionary<NSString *, id> *data) {
  209. DocumentKey key{testutil::Resource(util::MakeString(path))};
  210. FSTUserDataConverter *converter = FSTTestUserDataConverter();
  211. ParsedUpdateData result = [converter parsedUpdateData:data];
  212. HARD_ASSERT(result.data().size() == 0,
  213. "FSTTestTransformMutation() only expects transforms; no other data");
  214. return [[FSTTransformMutation alloc] initWithKey:key fieldTransforms:result.field_transforms()];
  215. }
  216. FSTDeleteMutation *FSTTestDeleteMutation(NSString *path) {
  217. return [[FSTDeleteMutation alloc] initWithKey:FSTTestDocKey(path)
  218. precondition:Precondition::None()];
  219. }
  220. MaybeDocumentMap FSTTestDocUpdates(NSArray<FSTMaybeDocument *> *docs) {
  221. MaybeDocumentMap updates;
  222. for (FSTMaybeDocument *doc in docs) {
  223. updates = updates.insert(doc.key, doc);
  224. }
  225. return updates;
  226. }
  227. absl::optional<ViewSnapshot> FSTTestApplyChanges(FSTView *view,
  228. NSArray<FSTMaybeDocument *> *docs,
  229. const absl::optional<TargetChange> &targetChange) {
  230. FSTViewChange *change =
  231. [view applyChangesToDocuments:[view computeChangesWithDocuments:FSTTestDocUpdates(docs)]
  232. targetChange:targetChange];
  233. return std::move(change.snapshot);
  234. }
  235. namespace firebase {
  236. namespace firestore {
  237. namespace remote {
  238. TestTargetMetadataProvider TestTargetMetadataProvider::CreateSingleResultProvider(
  239. DocumentKey document_key,
  240. const std::vector<TargetId> &listen_targets,
  241. const std::vector<TargetId> &limbo_targets) {
  242. TestTargetMetadataProvider metadata_provider;
  243. core::Query query(document_key.path());
  244. for (TargetId target_id : listen_targets) {
  245. FSTQueryData *query_data = [[FSTQueryData alloc] initWithQuery:query
  246. targetID:target_id
  247. listenSequenceNumber:0
  248. purpose:FSTQueryPurposeListen];
  249. metadata_provider.SetSyncedKeys(DocumentKeySet{document_key}, query_data);
  250. }
  251. for (TargetId target_id : limbo_targets) {
  252. FSTQueryData *query_data = [[FSTQueryData alloc] initWithQuery:query
  253. targetID:target_id
  254. listenSequenceNumber:0
  255. purpose:FSTQueryPurposeLimboResolution];
  256. metadata_provider.SetSyncedKeys(DocumentKeySet{document_key}, query_data);
  257. }
  258. return metadata_provider;
  259. }
  260. TestTargetMetadataProvider TestTargetMetadataProvider::CreateSingleResultProvider(
  261. DocumentKey document_key, const std::vector<TargetId> &targets) {
  262. return CreateSingleResultProvider(document_key, targets, /*limbo_targets=*/{});
  263. }
  264. TestTargetMetadataProvider TestTargetMetadataProvider::CreateEmptyResultProvider(
  265. const DocumentKey &document_key, const std::vector<TargetId> &targets) {
  266. TestTargetMetadataProvider metadata_provider;
  267. core::Query query(document_key.path());
  268. for (TargetId target_id : targets) {
  269. FSTQueryData *query_data = [[FSTQueryData alloc] initWithQuery:query
  270. targetID:target_id
  271. listenSequenceNumber:0
  272. purpose:FSTQueryPurposeListen];
  273. metadata_provider.SetSyncedKeys(DocumentKeySet{}, query_data);
  274. }
  275. return metadata_provider;
  276. }
  277. void TestTargetMetadataProvider::SetSyncedKeys(DocumentKeySet keys, FSTQueryData *query_data) {
  278. synced_keys_[query_data.targetID] = keys;
  279. query_data_[query_data.targetID] = query_data;
  280. }
  281. DocumentKeySet TestTargetMetadataProvider::GetRemoteKeysForTarget(TargetId target_id) const {
  282. auto it = synced_keys_.find(target_id);
  283. HARD_ASSERT(it != synced_keys_.end(), "Cannot process unknown target %s", target_id);
  284. return it->second;
  285. }
  286. FSTQueryData *TestTargetMetadataProvider::GetQueryDataForTarget(TargetId target_id) const {
  287. auto it = query_data_.find(target_id);
  288. HARD_ASSERT(it != query_data_.end(), "Cannot process unknown target %s", target_id);
  289. return it->second;
  290. }
  291. } // namespace remote
  292. } // namespace firestore
  293. } // namespace firebase
  294. using firebase::firestore::remote::TestTargetMetadataProvider;
  295. RemoteEvent FSTTestAddedRemoteEvent(FSTMaybeDocument *doc,
  296. const std::vector<TargetId> &addedToTargets) {
  297. HARD_ASSERT(![doc isKindOfClass:[FSTDocument class]] || ![(FSTDocument *)doc hasLocalMutations],
  298. "Docs from remote updates shouldn't have local changes.");
  299. DocumentWatchChange change{addedToTargets, {}, doc.key, doc};
  300. auto metadataProvider =
  301. TestTargetMetadataProvider::CreateEmptyResultProvider(doc.key, addedToTargets);
  302. WatchChangeAggregator aggregator{&metadataProvider};
  303. aggregator.HandleDocumentChange(change);
  304. return aggregator.CreateRemoteEvent(doc.version);
  305. }
  306. TargetChange FSTTestTargetChangeMarkCurrent() {
  307. return {[NSData data],
  308. /*current=*/true,
  309. /*added_documents=*/DocumentKeySet{},
  310. /*modified_documents=*/DocumentKeySet{},
  311. /*removed_documents=*/DocumentKeySet{}};
  312. }
  313. TargetChange FSTTestTargetChangeAckDocuments(DocumentKeySet docs) {
  314. return {[NSData data],
  315. /*current=*/true,
  316. /*added_documents*/ std::move(docs),
  317. /*modified_documents*/ DocumentKeySet{},
  318. /*removed_documents*/ DocumentKeySet{}};
  319. }
  320. RemoteEvent FSTTestUpdateRemoteEventWithLimboTargets(
  321. FSTMaybeDocument *doc,
  322. const std::vector<TargetId> &updatedInTargets,
  323. const std::vector<TargetId> &removedFromTargets,
  324. const std::vector<TargetId> &limboTargets) {
  325. HARD_ASSERT(![doc isKindOfClass:[FSTDocument class]] || ![(FSTDocument *)doc hasLocalMutations],
  326. "Docs from remote updates shouldn't have local changes.");
  327. DocumentWatchChange change{updatedInTargets, removedFromTargets, doc.key, doc};
  328. std::vector<TargetId> listens = updatedInTargets;
  329. listens.insert(listens.end(), removedFromTargets.begin(), removedFromTargets.end());
  330. auto metadataProvider =
  331. TestTargetMetadataProvider::CreateSingleResultProvider(doc.key, listens, limboTargets);
  332. WatchChangeAggregator aggregator{&metadataProvider};
  333. aggregator.HandleDocumentChange(change);
  334. return aggregator.CreateRemoteEvent(doc.version);
  335. }
  336. RemoteEvent FSTTestUpdateRemoteEvent(FSTMaybeDocument *doc,
  337. const std::vector<TargetId> &updatedInTargets,
  338. const std::vector<TargetId> &removedFromTargets) {
  339. return FSTTestUpdateRemoteEventWithLimboTargets(doc, updatedInTargets, removedFromTargets, {});
  340. }
  341. /** Creates a resume token to match the given snapshot version. */
  342. NSData *_Nullable FSTTestResumeTokenFromSnapshotVersion(FSTTestSnapshotVersion snapshotVersion) {
  343. if (snapshotVersion == 0) {
  344. return nil;
  345. }
  346. NSString *snapshotString = [NSString stringWithFormat:@"snapshot-%" PRId64, snapshotVersion];
  347. return [snapshotString dataUsingEncoding:NSUTF8StringEncoding];
  348. }
  349. LocalViewChanges TestViewChanges(TargetId targetID,
  350. NSArray<NSString *> *addedKeys,
  351. NSArray<NSString *> *removedKeys) {
  352. DocumentKeySet added;
  353. for (NSString *keyPath in addedKeys) {
  354. added = added.insert(testutil::Key(util::MakeString(keyPath)));
  355. }
  356. DocumentKeySet removed;
  357. for (NSString *keyPath in removedKeys) {
  358. removed = removed.insert(testutil::Key(util::MakeString(keyPath)));
  359. }
  360. return LocalViewChanges(targetID, std::move(added), std::move(removed));
  361. }
  362. NS_ASSUME_NONNULL_END