FSTHelpers.mm 21 KB

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