FSTHelpers.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. FSTSortOrder *FSTTestOrderBy(const absl::string_view field, NSString *direction) {
  170. const FieldPath path = testutil::Field(field);
  171. BOOL ascending;
  172. if ([direction isEqualToString:@"asc"]) {
  173. ascending = YES;
  174. } else if ([direction isEqualToString:@"desc"]) {
  175. ascending = NO;
  176. } else {
  177. HARD_FAIL("Unsupported direction: %s", direction);
  178. }
  179. return [FSTSortOrder sortOrderWithFieldPath:path ascending:ascending];
  180. }
  181. DocumentComparator FSTTestDocComparator(const absl::string_view fieldPath) {
  182. FSTQuery *query = [FSTTestQuery("docs")
  183. queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:testutil::Field(fieldPath)
  184. ascending:YES]];
  185. return [query comparator];
  186. }
  187. DocumentSet FSTTestDocSet(DocumentComparator comp, NSArray<FSTDocument *> *docs) {
  188. DocumentSet docSet{std::move(comp)};
  189. for (FSTDocument *doc in docs) {
  190. docSet = docSet.insert(doc);
  191. }
  192. return docSet;
  193. }
  194. FSTSetMutation *FSTTestSetMutation(NSString *path, NSDictionary<NSString *, id> *values) {
  195. return [[FSTSetMutation alloc] initWithKey:FSTTestDocKey(path)
  196. value:FSTTestObjectValue(values)
  197. precondition:Precondition::None()];
  198. }
  199. FSTPatchMutation *FSTTestPatchMutation(const absl::string_view path,
  200. NSDictionary<NSString *, id> *values,
  201. const std::vector<FieldPath> &updateMask) {
  202. BOOL merge = !updateMask.empty();
  203. __block ObjectValue objectValue = ObjectValue::Empty();
  204. __block std::set<FieldPath> fieldMaskPaths;
  205. [values enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  206. const FieldPath path = testutil::Field(util::MakeString(key));
  207. fieldMaskPaths.insert(path);
  208. if (![value isEqual:kDeleteSentinel]) {
  209. FieldValue parsedValue = FSTTestFieldValue(value);
  210. objectValue = objectValue.Set(path, std::move(parsedValue));
  211. }
  212. }];
  213. DocumentKey key = testutil::Key(path);
  214. FieldMask mask(merge ? std::set<FieldPath>(updateMask.begin(), updateMask.end())
  215. : fieldMaskPaths);
  216. return [[FSTPatchMutation alloc]
  217. initWithKey:key
  218. fieldMask:mask
  219. value:objectValue
  220. precondition:merge ? Precondition::None() : Precondition::Exists(true)];
  221. }
  222. FSTTransformMutation *FSTTestTransformMutation(NSString *path, NSDictionary<NSString *, id> *data) {
  223. DocumentKey key{testutil::Resource(util::MakeString(path))};
  224. FSTUserDataConverter *converter = FSTTestUserDataConverter();
  225. ParsedUpdateData result = [converter parsedUpdateData:data];
  226. HARD_ASSERT(result.data().size() == 0,
  227. "FSTTestTransformMutation() only expects transforms; no other data");
  228. return [[FSTTransformMutation alloc] initWithKey:key fieldTransforms:result.field_transforms()];
  229. }
  230. FSTDeleteMutation *FSTTestDeleteMutation(NSString *path) {
  231. return [[FSTDeleteMutation alloc] initWithKey:FSTTestDocKey(path)
  232. precondition:Precondition::None()];
  233. }
  234. MaybeDocumentMap FSTTestDocUpdates(NSArray<FSTMaybeDocument *> *docs) {
  235. MaybeDocumentMap updates;
  236. for (FSTMaybeDocument *doc in docs) {
  237. updates = updates.insert(doc.key, doc);
  238. }
  239. return updates;
  240. }
  241. absl::optional<ViewSnapshot> FSTTestApplyChanges(FSTView *view,
  242. NSArray<FSTMaybeDocument *> *docs,
  243. const absl::optional<TargetChange> &targetChange) {
  244. FSTViewChange *change =
  245. [view applyChangesToDocuments:[view computeChangesWithDocuments:FSTTestDocUpdates(docs)]
  246. targetChange:targetChange];
  247. return std::move(change.snapshot);
  248. }
  249. namespace firebase {
  250. namespace firestore {
  251. namespace remote {
  252. TestTargetMetadataProvider TestTargetMetadataProvider::CreateSingleResultProvider(
  253. DocumentKey document_key,
  254. const std::vector<TargetId> &listen_targets,
  255. const std::vector<TargetId> &limbo_targets) {
  256. TestTargetMetadataProvider metadata_provider;
  257. FSTQuery *query = [FSTQuery queryWithPath:document_key.path()];
  258. for (TargetId target_id : listen_targets) {
  259. FSTQueryData *query_data = [[FSTQueryData alloc] initWithQuery:query
  260. targetID:target_id
  261. listenSequenceNumber:0
  262. purpose:FSTQueryPurposeListen];
  263. metadata_provider.SetSyncedKeys(DocumentKeySet{document_key}, query_data);
  264. }
  265. for (TargetId target_id : limbo_targets) {
  266. FSTQueryData *query_data = [[FSTQueryData alloc] initWithQuery:query
  267. targetID:target_id
  268. listenSequenceNumber:0
  269. purpose:FSTQueryPurposeLimboResolution];
  270. metadata_provider.SetSyncedKeys(DocumentKeySet{document_key}, query_data);
  271. }
  272. return metadata_provider;
  273. }
  274. TestTargetMetadataProvider TestTargetMetadataProvider::CreateSingleResultProvider(
  275. DocumentKey document_key, const std::vector<TargetId> &targets) {
  276. return CreateSingleResultProvider(document_key, targets, /*limbo_targets=*/{});
  277. }
  278. TestTargetMetadataProvider TestTargetMetadataProvider::CreateEmptyResultProvider(
  279. const DocumentKey &document_key, const std::vector<TargetId> &targets) {
  280. TestTargetMetadataProvider metadata_provider;
  281. FSTQuery *query = [FSTQuery queryWithPath:document_key.path()];
  282. for (TargetId target_id : targets) {
  283. FSTQueryData *query_data = [[FSTQueryData alloc] initWithQuery:query
  284. targetID:target_id
  285. listenSequenceNumber:0
  286. purpose:FSTQueryPurposeListen];
  287. metadata_provider.SetSyncedKeys(DocumentKeySet{}, query_data);
  288. }
  289. return metadata_provider;
  290. }
  291. void TestTargetMetadataProvider::SetSyncedKeys(DocumentKeySet keys, FSTQueryData *query_data) {
  292. synced_keys_[query_data.targetID] = keys;
  293. query_data_[query_data.targetID] = query_data;
  294. }
  295. DocumentKeySet TestTargetMetadataProvider::GetRemoteKeysForTarget(TargetId target_id) const {
  296. auto it = synced_keys_.find(target_id);
  297. HARD_ASSERT(it != synced_keys_.end(), "Cannot process unknown target %s", target_id);
  298. return it->second;
  299. }
  300. FSTQueryData *TestTargetMetadataProvider::GetQueryDataForTarget(TargetId target_id) const {
  301. auto it = query_data_.find(target_id);
  302. HARD_ASSERT(it != query_data_.end(), "Cannot process unknown target %s", target_id);
  303. return it->second;
  304. }
  305. } // namespace remote
  306. } // namespace firestore
  307. } // namespace firebase
  308. using firebase::firestore::remote::TestTargetMetadataProvider;
  309. RemoteEvent FSTTestAddedRemoteEvent(FSTMaybeDocument *doc,
  310. const std::vector<TargetId> &addedToTargets) {
  311. HARD_ASSERT(![doc isKindOfClass:[FSTDocument class]] || ![(FSTDocument *)doc hasLocalMutations],
  312. "Docs from remote updates shouldn't have local changes.");
  313. DocumentWatchChange change{addedToTargets, {}, doc.key, doc};
  314. auto metadataProvider =
  315. TestTargetMetadataProvider::CreateEmptyResultProvider(doc.key, addedToTargets);
  316. WatchChangeAggregator aggregator{&metadataProvider};
  317. aggregator.HandleDocumentChange(change);
  318. return aggregator.CreateRemoteEvent(doc.version);
  319. }
  320. TargetChange FSTTestTargetChangeMarkCurrent() {
  321. return {[NSData data],
  322. /*current=*/true,
  323. /*added_documents=*/DocumentKeySet{},
  324. /*modified_documents=*/DocumentKeySet{},
  325. /*removed_documents=*/DocumentKeySet{}};
  326. }
  327. TargetChange FSTTestTargetChangeAckDocuments(DocumentKeySet docs) {
  328. return {[NSData data],
  329. /*current=*/true,
  330. /*added_documents*/ std::move(docs),
  331. /*modified_documents*/ DocumentKeySet{},
  332. /*removed_documents*/ DocumentKeySet{}};
  333. }
  334. RemoteEvent FSTTestUpdateRemoteEventWithLimboTargets(
  335. FSTMaybeDocument *doc,
  336. const std::vector<TargetId> &updatedInTargets,
  337. const std::vector<TargetId> &removedFromTargets,
  338. const std::vector<TargetId> &limboTargets) {
  339. HARD_ASSERT(![doc isKindOfClass:[FSTDocument class]] || ![(FSTDocument *)doc hasLocalMutations],
  340. "Docs from remote updates shouldn't have local changes.");
  341. DocumentWatchChange change{updatedInTargets, removedFromTargets, doc.key, doc};
  342. std::vector<TargetId> listens = updatedInTargets;
  343. listens.insert(listens.end(), removedFromTargets.begin(), removedFromTargets.end());
  344. auto metadataProvider =
  345. TestTargetMetadataProvider::CreateSingleResultProvider(doc.key, listens, limboTargets);
  346. WatchChangeAggregator aggregator{&metadataProvider};
  347. aggregator.HandleDocumentChange(change);
  348. return aggregator.CreateRemoteEvent(doc.version);
  349. }
  350. RemoteEvent FSTTestUpdateRemoteEvent(FSTMaybeDocument *doc,
  351. const std::vector<TargetId> &updatedInTargets,
  352. const std::vector<TargetId> &removedFromTargets) {
  353. return FSTTestUpdateRemoteEventWithLimboTargets(doc, updatedInTargets, removedFromTargets, {});
  354. }
  355. /** Creates a resume token to match the given snapshot version. */
  356. NSData *_Nullable FSTTestResumeTokenFromSnapshotVersion(FSTTestSnapshotVersion snapshotVersion) {
  357. if (snapshotVersion == 0) {
  358. return nil;
  359. }
  360. NSString *snapshotString = [NSString stringWithFormat:@"snapshot-%" PRId64, snapshotVersion];
  361. return [snapshotString dataUsingEncoding:NSUTF8StringEncoding];
  362. }
  363. FSTLocalViewChanges *FSTTestViewChanges(TargetId targetID,
  364. NSArray<NSString *> *addedKeys,
  365. NSArray<NSString *> *removedKeys) {
  366. DocumentKeySet added;
  367. for (NSString *keyPath in addedKeys) {
  368. added = added.insert(testutil::Key(util::MakeString(keyPath)));
  369. }
  370. DocumentKeySet removed;
  371. for (NSString *keyPath in removedKeys) {
  372. removed = removed.insert(testutil::Key(util::MakeString(keyPath)));
  373. }
  374. return [FSTLocalViewChanges changesForTarget:targetID
  375. addedKeys:std::move(added)
  376. removedKeys:std::move(removed)];
  377. }
  378. NS_ASSUME_NONNULL_END