FSTHelpers.mm 18 KB

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