FSTHelpers.mm 20 KB

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