FSTHelpers.mm 19 KB

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