FSTHelpers.mm 20 KB

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