FSTHelpers.m 14 KB

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