FSTHelpers.mm 19 KB

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