FSTHelpers.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. #include <inttypes.h>
  18. #include <list>
  19. #import <FirebaseFirestore/FIRFieldPath.h>
  20. #import <FirebaseFirestore/FIRGeoPoint.h>
  21. #import <FirebaseFirestore/FIRTimestamp.h>
  22. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  23. #import "Firestore/Source/API/FSTUserDataConverter.h"
  24. #import "Firestore/Source/Core/FSTQuery.h"
  25. #import "Firestore/Source/Core/FSTSnapshotVersion.h"
  26. #import "Firestore/Source/Core/FSTView.h"
  27. #import "Firestore/Source/Core/FSTViewSnapshot.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/FSTDocumentKey.h"
  32. #import "Firestore/Source/Model/FSTDocumentSet.h"
  33. #import "Firestore/Source/Model/FSTFieldValue.h"
  34. #import "Firestore/Source/Model/FSTMutation.h"
  35. #import "Firestore/Source/Model/FSTPath.h"
  36. #import "Firestore/Source/Remote/FSTRemoteEvent.h"
  37. #import "Firestore/Source/Remote/FSTWatchChange.h"
  38. #import "Firestore/Source/Util/FSTAssert.h"
  39. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  40. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  41. namespace util = firebase::firestore::util;
  42. using firebase::firestore::model::DatabaseId;
  43. NS_ASSUME_NONNULL_BEGIN
  44. /** A string sentinel that can be used with FSTTestPatchMutation() to mark a field for deletion. */
  45. static NSString *const kDeleteSentinel = @"<DELETE>";
  46. static const int kMicrosPerSec = 1000000;
  47. static const int kMillisPerSec = 1000;
  48. FIRTimestamp *FSTTestTimestamp(int year, int month, int day, int hour, int minute, int second) {
  49. NSDate *date = FSTTestDate(year, month, day, hour, minute, second);
  50. return [FIRTimestamp timestampWithDate:date];
  51. }
  52. NSDate *FSTTestDate(int year, int month, int day, int hour, int minute, int second) {
  53. NSDateComponents *comps = FSTTestDateComponents(year, month, day, hour, minute, second);
  54. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  55. }
  56. NSData *FSTTestData(int bytes, ...) {
  57. va_list args;
  58. va_start(args, bytes); /* Initialize the argument list. */
  59. NSMutableData *data = [NSMutableData data];
  60. int next = bytes;
  61. while (next >= 0) {
  62. uint8_t byte = (uint8_t)next;
  63. [data appendBytes:&byte length:1];
  64. next = va_arg(args, int);
  65. }
  66. va_end(args);
  67. return [data copy];
  68. }
  69. FIRGeoPoint *FSTTestGeoPoint(double latitude, double longitude) {
  70. return [[FIRGeoPoint alloc] initWithLatitude:latitude longitude:longitude];
  71. }
  72. NSDateComponents *FSTTestDateComponents(
  73. int year, int month, int day, int hour, int minute, int second) {
  74. NSDateComponents *comps = [[NSDateComponents alloc] init];
  75. comps.year = year;
  76. comps.month = month;
  77. comps.day = day;
  78. comps.hour = hour;
  79. comps.minute = minute;
  80. comps.second = second;
  81. // Force time zone to UTC to avoid these values changing due to daylight saving.
  82. comps.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  83. return comps;
  84. }
  85. FSTFieldPath *FSTTestFieldPath(NSString *field) {
  86. return [FIRFieldPath pathWithDotSeparatedString:field].internalValue;
  87. }
  88. FSTFieldValue *FSTTestFieldValue(id _Nullable value) {
  89. // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  90. static DatabaseId database_id{"project", DatabaseId::kDefault};
  91. FSTUserDataConverter *converter =
  92. [[FSTUserDataConverter alloc] initWithDatabaseID:&database_id
  93. preConverter:^id _Nullable(id _Nullable input) {
  94. return input;
  95. }];
  96. // HACK: We use parsedQueryValue: since it accepts scalars as well as arrays / objects, and
  97. // our tests currently use FSTTestFieldValue() pretty generically so we don't know the intent.
  98. return [converter parsedQueryValue:value];
  99. }
  100. FSTObjectValue *FSTTestObjectValue(NSDictionary<NSString *, id> *data) {
  101. FSTFieldValue *wrapped = FSTTestFieldValue(data);
  102. FSTCAssert([wrapped isKindOfClass:[FSTObjectValue class]], @"Unsupported value: %@", data);
  103. return (FSTObjectValue *)wrapped;
  104. }
  105. FSTDocumentKey *FSTTestDocKey(NSString *path) {
  106. return [FSTDocumentKey keyWithPathString:path];
  107. }
  108. FSTDocumentKeySet *FSTTestDocKeySet(NSArray<FSTDocumentKey *> *keys) {
  109. FSTDocumentKeySet *result = [FSTDocumentKeySet keySet];
  110. for (FSTDocumentKey *key in keys) {
  111. result = [result setByAddingObject:key];
  112. }
  113. return result;
  114. }
  115. FSTSnapshotVersion *FSTTestVersion(FSTTestSnapshotVersion versionMicroseconds) {
  116. int64_t seconds = versionMicroseconds / kMicrosPerSec;
  117. int32_t nanos = (int32_t)(versionMicroseconds % kMicrosPerSec) * kMillisPerSec;
  118. FIRTimestamp *timestamp = [[FIRTimestamp alloc] initWithSeconds:seconds nanoseconds:nanos];
  119. return [FSTSnapshotVersion versionWithTimestamp:timestamp];
  120. }
  121. FSTDocument *FSTTestDoc(NSString *path,
  122. FSTTestSnapshotVersion version,
  123. NSDictionary<NSString *, id> *data,
  124. BOOL hasMutations) {
  125. FSTDocumentKey *key = FSTTestDocKey(path);
  126. return [FSTDocument documentWithData:FSTTestObjectValue(data)
  127. key:key
  128. version:FSTTestVersion(version)
  129. hasLocalMutations:hasMutations];
  130. }
  131. FSTDeletedDocument *FSTTestDeletedDoc(NSString *path, FSTTestSnapshotVersion version) {
  132. FSTDocumentKey *key = FSTTestDocKey(path);
  133. return [FSTDeletedDocument documentWithKey:key version:FSTTestVersion(version)];
  134. }
  135. static NSArray<NSString *> *FSTTestSplitPath(NSString *path) {
  136. if ([path isEqualToString:@""]) {
  137. return @[];
  138. } else {
  139. return [path componentsSeparatedByString:@"/"];
  140. }
  141. }
  142. FSTResourcePath *FSTTestPath(NSString *path) {
  143. return [FSTResourcePath pathWithSegments:FSTTestSplitPath(path)];
  144. }
  145. FSTDocumentKeyReference *FSTTestRef(const absl::string_view projectID,
  146. const absl::string_view database,
  147. NSString *path) {
  148. // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  149. static std::list<DatabaseId> database_ids;
  150. database_ids.emplace_back(projectID, database);
  151. return [[FSTDocumentKeyReference alloc] initWithKey:FSTTestDocKey(path)
  152. databaseID:&database_ids.back()];
  153. }
  154. FSTQuery *FSTTestQuery(NSString *path) {
  155. return [FSTQuery queryWithPath:FSTTestPath(path)];
  156. }
  157. id<FSTFilter> FSTTestFilter(NSString *field, NSString *opString, id value) {
  158. FSTFieldPath *path = FSTTestFieldPath(field);
  159. FSTRelationFilterOperator op;
  160. if ([opString isEqualToString:@"<"]) {
  161. op = FSTRelationFilterOperatorLessThan;
  162. } else if ([opString isEqualToString:@"<="]) {
  163. op = FSTRelationFilterOperatorLessThanOrEqual;
  164. } else if ([opString isEqualToString:@"=="]) {
  165. op = FSTRelationFilterOperatorEqual;
  166. } else if ([opString isEqualToString:@">="]) {
  167. op = FSTRelationFilterOperatorGreaterThanOrEqual;
  168. } else if ([opString isEqualToString:@">"]) {
  169. op = FSTRelationFilterOperatorGreaterThan;
  170. } else {
  171. FSTCFail(@"Unsupported operator type: %@", opString);
  172. }
  173. FSTFieldValue *data = FSTTestFieldValue(value);
  174. if ([data isEqual:[FSTDoubleValue nanValue]]) {
  175. FSTCAssert(op == FSTRelationFilterOperatorEqual, @"Must use == with NAN.");
  176. return [[FSTNanFilter alloc] initWithField:path];
  177. } else if ([data isEqual:[FSTNullValue nullValue]]) {
  178. FSTCAssert(op == FSTRelationFilterOperatorEqual, @"Must use == with Null.");
  179. return [[FSTNullFilter alloc] initWithField:path];
  180. } else {
  181. return [FSTRelationFilter filterWithField:path filterOperator:op value:data];
  182. }
  183. }
  184. FSTSortOrder *FSTTestOrderBy(NSString *field, NSString *direction) {
  185. FSTFieldPath *path = FSTTestFieldPath(field);
  186. BOOL ascending;
  187. if ([direction isEqualToString:@"asc"]) {
  188. ascending = YES;
  189. } else if ([direction isEqualToString:@"desc"]) {
  190. ascending = NO;
  191. } else {
  192. FSTCFail(@"Unsupported direction: %@", direction);
  193. }
  194. return [FSTSortOrder sortOrderWithFieldPath:path ascending:ascending];
  195. }
  196. NSComparator FSTTestDocComparator(NSString *fieldPath) {
  197. FSTQuery *query = [FSTTestQuery(@"docs")
  198. queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:FSTTestFieldPath(fieldPath)
  199. ascending:YES]];
  200. return [query comparator];
  201. }
  202. FSTDocumentSet *FSTTestDocSet(NSComparator comp, NSArray<FSTDocument *> *docs) {
  203. FSTDocumentSet *docSet = [FSTDocumentSet documentSetWithComparator:comp];
  204. for (FSTDocument *doc in docs) {
  205. docSet = [docSet documentSetByAddingDocument:doc];
  206. }
  207. return docSet;
  208. }
  209. FSTSetMutation *FSTTestSetMutation(NSString *path, NSDictionary<NSString *, id> *values) {
  210. return [[FSTSetMutation alloc] initWithKey:FSTTestDocKey(path)
  211. value:FSTTestObjectValue(values)
  212. precondition:[FSTPrecondition none]];
  213. }
  214. FSTPatchMutation *FSTTestPatchMutation(NSString *path,
  215. NSDictionary<NSString *, id> *values,
  216. NSArray<FSTFieldPath *> *_Nullable updateMask) {
  217. BOOL merge = updateMask != nil;
  218. __block FSTObjectValue *objectValue = [FSTObjectValue objectValue];
  219. NSMutableArray<FSTFieldPath *> *fieldMaskPaths = [NSMutableArray array];
  220. [values enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  221. FSTFieldPath *path = FSTTestFieldPath(key);
  222. [fieldMaskPaths addObject:path];
  223. if (![value isEqual:kDeleteSentinel]) {
  224. FSTFieldValue *parsedValue = FSTTestFieldValue(value);
  225. objectValue = [objectValue objectBySettingValue:parsedValue forPath:path];
  226. }
  227. }];
  228. FSTDocumentKey *key = [FSTDocumentKey keyWithPath:FSTTestPath(path)];
  229. FSTFieldMask *mask = [[FSTFieldMask alloc] initWithFields:merge ? updateMask : fieldMaskPaths];
  230. return [[FSTPatchMutation alloc] initWithKey:key
  231. fieldMask:mask
  232. value:objectValue
  233. precondition:[FSTPrecondition preconditionWithExists:YES]];
  234. }
  235. // For now this only creates TransformMutations with server timestamps.
  236. FSTTransformMutation *FSTTestTransformMutation(NSString *path,
  237. NSArray<NSString *> *serverTimestampFields) {
  238. FSTDocumentKey *key = [FSTDocumentKey keyWithPath:FSTTestPath(path)];
  239. NSMutableArray<FSTFieldTransform *> *fieldTransforms = [NSMutableArray array];
  240. for (NSString *field in serverTimestampFields) {
  241. FSTFieldPath *fieldPath = FSTTestFieldPath(field);
  242. id<FSTTransformOperation> transformOp = [FSTServerTimestampTransform serverTimestampTransform];
  243. FSTFieldTransform *transform =
  244. [[FSTFieldTransform alloc] initWithPath:fieldPath transform:transformOp];
  245. [fieldTransforms addObject:transform];
  246. }
  247. return [[FSTTransformMutation alloc] initWithKey:key fieldTransforms:fieldTransforms];
  248. }
  249. FSTDeleteMutation *FSTTestDeleteMutation(NSString *path) {
  250. return [[FSTDeleteMutation alloc] initWithKey:FSTTestDocKey(path)
  251. precondition:[FSTPrecondition none]];
  252. }
  253. FSTMaybeDocumentDictionary *FSTTestDocUpdates(NSArray<FSTMaybeDocument *> *docs) {
  254. FSTMaybeDocumentDictionary *updates = [FSTMaybeDocumentDictionary maybeDocumentDictionary];
  255. for (FSTMaybeDocument *doc in docs) {
  256. updates = [updates dictionaryBySettingObject:doc forKey:doc.key];
  257. }
  258. return updates;
  259. }
  260. FSTViewSnapshot *_Nullable FSTTestApplyChanges(FSTView *view,
  261. NSArray<FSTMaybeDocument *> *docs,
  262. FSTTargetChange *_Nullable targetChange) {
  263. return [view applyChangesToDocuments:[view computeChangesWithDocuments:FSTTestDocUpdates(docs)]
  264. targetChange:targetChange]
  265. .snapshot;
  266. }
  267. FSTRemoteEvent *FSTTestUpdateRemoteEvent(FSTMaybeDocument *doc,
  268. NSArray<NSNumber *> *updatedInTargets,
  269. NSArray<NSNumber *> *removedFromTargets) {
  270. FSTDocumentWatchChange *change =
  271. [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:updatedInTargets
  272. removedTargetIDs:removedFromTargets
  273. documentKey:doc.key
  274. document:doc];
  275. NSMutableDictionary<NSNumber *, FSTQueryData *> *listens = [NSMutableDictionary dictionary];
  276. FSTQueryData *dummyQueryData = [FSTQueryData alloc];
  277. for (NSNumber *targetID in updatedInTargets) {
  278. listens[targetID] = dummyQueryData;
  279. }
  280. for (NSNumber *targetID in removedFromTargets) {
  281. listens[targetID] = dummyQueryData;
  282. }
  283. NSMutableDictionary<NSNumber *, NSNumber *> *pending = [NSMutableDictionary dictionary];
  284. FSTWatchChangeAggregator *aggregator =
  285. [[FSTWatchChangeAggregator alloc] initWithSnapshotVersion:doc.version
  286. listenTargets:listens
  287. pendingTargetResponses:pending];
  288. [aggregator addWatchChange:change];
  289. return [aggregator remoteEvent];
  290. }
  291. /** Creates a resume token to match the given snapshot version. */
  292. NSData *_Nullable FSTTestResumeTokenFromSnapshotVersion(FSTTestSnapshotVersion snapshotVersion) {
  293. if (snapshotVersion == 0) {
  294. return nil;
  295. }
  296. NSString *snapshotString = [NSString stringWithFormat:@"snapshot-%" PRId64, snapshotVersion];
  297. return [snapshotString dataUsingEncoding:NSUTF8StringEncoding];
  298. }
  299. FSTLocalViewChanges *FSTTestViewChanges(FSTQuery *query,
  300. NSArray<NSString *> *addedKeys,
  301. NSArray<NSString *> *removedKeys) {
  302. FSTDocumentKeySet *added = [FSTDocumentKeySet keySet];
  303. for (NSString *keyPath in addedKeys) {
  304. FSTDocumentKey *key = FSTTestDocKey(keyPath);
  305. added = [added setByAddingObject:key];
  306. }
  307. FSTDocumentKeySet *removed = [FSTDocumentKeySet keySet];
  308. for (NSString *keyPath in removedKeys) {
  309. FSTDocumentKey *key = FSTTestDocKey(keyPath);
  310. removed = [removed setByAddingObject:key];
  311. }
  312. return [FSTLocalViewChanges changesForQuery:query addedKeys:added removedKeys:removed];
  313. }
  314. NS_ASSUME_NONNULL_END