FSTHelpers.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 <utility>
  24. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  25. #import "Firestore/Source/API/FSTUserDataConverter.h"
  26. #include "Firestore/core/src/firebase/firestore/core/filter.h"
  27. #include "Firestore/core/src/firebase/firestore/core/view.h"
  28. #include "Firestore/core/src/firebase/firestore/core/view_snapshot.h"
  29. #include "Firestore/core/src/firebase/firestore/local/local_view_changes.h"
  30. #include "Firestore/core/src/firebase/firestore/local/query_data.h"
  31. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  32. #include "Firestore/core/src/firebase/firestore/model/delete_mutation.h"
  33. #include "Firestore/core/src/firebase/firestore/model/document.h"
  34. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  35. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  36. #include "Firestore/core/src/firebase/firestore/model/document_set.h"
  37. #include "Firestore/core/src/firebase/firestore/model/field_mask.h"
  38. #include "Firestore/core/src/firebase/firestore/model/field_transform.h"
  39. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  40. #include "Firestore/core/src/firebase/firestore/model/patch_mutation.h"
  41. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  42. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  43. #include "Firestore/core/src/firebase/firestore/model/set_mutation.h"
  44. #include "Firestore/core/src/firebase/firestore/model/transform_mutation.h"
  45. #include "Firestore/core/src/firebase/firestore/model/transform_operation.h"
  46. #include "Firestore/core/src/firebase/firestore/remote/remote_event.h"
  47. #include "Firestore/core/src/firebase/firestore/remote/watch_change.h"
  48. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  49. #include "Firestore/core/test/firebase/firestore/remote/fake_target_metadata_provider.h"
  50. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  51. #include "absl/memory/memory.h"
  52. namespace testutil = firebase::firestore::testutil;
  53. namespace util = firebase::firestore::util;
  54. using firebase::firestore::core::Direction;
  55. using firebase::firestore::core::Filter;
  56. using firebase::firestore::core::ParsedUpdateData;
  57. using firebase::firestore::core::Query;
  58. using firebase::firestore::core::View;
  59. using firebase::firestore::core::ViewChange;
  60. using firebase::firestore::core::ViewSnapshot;
  61. using firebase::firestore::local::LocalViewChanges;
  62. using firebase::firestore::local::QueryData;
  63. using firebase::firestore::local::QueryPurpose;
  64. using firebase::firestore::model::DatabaseId;
  65. using firebase::firestore::model::DeleteMutation;
  66. using firebase::firestore::model::Document;
  67. using firebase::firestore::model::DocumentComparator;
  68. using firebase::firestore::model::DocumentKey;
  69. using firebase::firestore::model::DocumentKeySet;
  70. using firebase::firestore::model::DocumentSet;
  71. using firebase::firestore::model::DocumentState;
  72. using firebase::firestore::model::FieldMask;
  73. using firebase::firestore::model::FieldPath;
  74. using firebase::firestore::model::FieldTransform;
  75. using firebase::firestore::model::FieldValue;
  76. using firebase::firestore::model::MaybeDocument;
  77. using firebase::firestore::model::MaybeDocumentMap;
  78. using firebase::firestore::model::NoDocument;
  79. using firebase::firestore::model::ObjectValue;
  80. using firebase::firestore::model::PatchMutation;
  81. using firebase::firestore::model::Precondition;
  82. using firebase::firestore::model::ResourcePath;
  83. using firebase::firestore::model::SetMutation;
  84. using firebase::firestore::model::ServerTimestampTransform;
  85. using firebase::firestore::model::SnapshotVersion;
  86. using firebase::firestore::model::TargetId;
  87. using firebase::firestore::model::TransformMutation;
  88. using firebase::firestore::model::TransformOperation;
  89. using firebase::firestore::model::UnknownDocument;
  90. using firebase::firestore::nanopb::ByteString;
  91. using firebase::firestore::remote::DocumentWatchChange;
  92. using firebase::firestore::remote::FakeTargetMetadataProvider;
  93. using firebase::firestore::remote::RemoteEvent;
  94. using firebase::firestore::remote::TargetChange;
  95. using firebase::firestore::remote::WatchChangeAggregator;
  96. using firebase::firestore::testutil::OrderBy;
  97. using firebase::firestore::testutil::Query;
  98. NS_ASSUME_NONNULL_BEGIN
  99. /** A string sentinel that can be used with FSTTestPatchMutation() to mark a field for deletion. */
  100. static NSString *const kDeleteSentinel = @"<DELETE>";
  101. FIRTimestamp *FSTTestTimestamp(int year, int month, int day, int hour, int minute, int second) {
  102. NSDate *date = FSTTestDate(year, month, day, hour, minute, second);
  103. return [FIRTimestamp timestampWithDate:date];
  104. }
  105. NSDate *FSTTestDate(int year, int month, int day, int hour, int minute, int second) {
  106. NSDateComponents *comps = FSTTestDateComponents(year, month, day, hour, minute, second);
  107. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  108. }
  109. NSData *FSTTestData(int bytes, ...) {
  110. va_list args;
  111. va_start(args, bytes); /* Initialize the argument list. */
  112. NSMutableData *data = [NSMutableData data];
  113. int next = bytes;
  114. while (next >= 0) {
  115. uint8_t byte = (uint8_t)next;
  116. [data appendBytes:&byte length:1];
  117. next = va_arg(args, int);
  118. }
  119. va_end(args);
  120. return [data copy];
  121. }
  122. FIRGeoPoint *FSTTestGeoPoint(double latitude, double longitude) {
  123. return [[FIRGeoPoint alloc] initWithLatitude:latitude longitude:longitude];
  124. }
  125. NSDateComponents *FSTTestDateComponents(
  126. int year, int month, int day, int hour, int minute, int second) {
  127. NSDateComponents *comps = [[NSDateComponents alloc] init];
  128. comps.year = year;
  129. comps.month = month;
  130. comps.day = day;
  131. comps.hour = hour;
  132. comps.minute = minute;
  133. comps.second = second;
  134. // Force time zone to UTC to avoid these values changing due to daylight saving.
  135. comps.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  136. return comps;
  137. }
  138. FSTUserDataConverter *FSTTestUserDataConverter() {
  139. FSTUserDataConverter *converter =
  140. [[FSTUserDataConverter alloc] initWithDatabaseID:DatabaseId("project")
  141. preConverter:^id _Nullable(id _Nullable input) {
  142. return input;
  143. }];
  144. return converter;
  145. }
  146. FieldValue FSTTestFieldValue(id _Nullable value) {
  147. FSTUserDataConverter *converter = FSTTestUserDataConverter();
  148. // HACK: We use parsedQueryValue: since it accepts scalars as well as arrays / objects, and
  149. // our tests currently use FSTTestFieldValue() pretty generically so we don't know the intent.
  150. return [converter parsedQueryValue:value];
  151. }
  152. ObjectValue FSTTestObjectValue(NSDictionary<NSString *, id> *data) {
  153. FieldValue wrapped = FSTTestFieldValue(data);
  154. HARD_ASSERT(wrapped.type() == FieldValue::Type::Object, "Unsupported value: %s", data);
  155. return ObjectValue(std::move(wrapped));
  156. }
  157. DocumentKey FSTTestDocKey(NSString *path) {
  158. return DocumentKey::FromPathString(util::MakeString(path));
  159. }
  160. FSTDocumentKeyReference *FSTTestRef(std::string projectID, std::string database, NSString *path) {
  161. return [[FSTDocumentKeyReference alloc] initWithKey:FSTTestDocKey(path)
  162. databaseID:DatabaseId(projectID, database)];
  163. }
  164. SetMutation FSTTestSetMutation(NSString *path, NSDictionary<NSString *, id> *values) {
  165. return SetMutation(FSTTestDocKey(path), FSTTestObjectValue(values), Precondition::None());
  166. }
  167. PatchMutation FSTTestPatchMutation(const absl::string_view path,
  168. NSDictionary<NSString *, id> *values,
  169. const std::vector<FieldPath> &updateMask) {
  170. BOOL merge = !updateMask.empty();
  171. __block ObjectValue objectValue = ObjectValue::Empty();
  172. __block std::set<FieldPath> fieldMaskPaths;
  173. [values enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  174. const FieldPath path = testutil::Field(util::MakeString(key));
  175. fieldMaskPaths.insert(path);
  176. if (![value isEqual:kDeleteSentinel]) {
  177. FieldValue parsedValue = FSTTestFieldValue(value);
  178. objectValue = objectValue.Set(path, std::move(parsedValue));
  179. }
  180. }];
  181. DocumentKey key = testutil::Key(path);
  182. Precondition precondition = merge ? Precondition::None() : Precondition::Exists(true);
  183. FieldMask mask(merge ? std::set<FieldPath>(updateMask.begin(), updateMask.end())
  184. : fieldMaskPaths);
  185. return PatchMutation(key, objectValue, mask, precondition);
  186. }
  187. TransformMutation FSTTestTransformMutation(NSString *path, NSDictionary<NSString *, id> *data) {
  188. DocumentKey key{testutil::Resource(util::MakeString(path))};
  189. FSTUserDataConverter *converter = FSTTestUserDataConverter();
  190. ParsedUpdateData result = [converter parsedUpdateData:data];
  191. HARD_ASSERT(result.data().size() == 0,
  192. "FSTTestTransformMutation() only expects transforms; no other data");
  193. return TransformMutation(key, result.field_transforms());
  194. }
  195. DeleteMutation FSTTestDeleteMutation(NSString *path) {
  196. return DeleteMutation(FSTTestDocKey(path), Precondition::None());
  197. }
  198. MaybeDocumentMap FSTTestDocUpdates(const std::vector<MaybeDocument> &docs) {
  199. MaybeDocumentMap updates;
  200. for (const MaybeDocument &doc : docs) {
  201. updates = updates.insert(doc.key(), doc);
  202. }
  203. return updates;
  204. }
  205. absl::optional<ViewSnapshot> FSTTestApplyChanges(View *view,
  206. const std::vector<MaybeDocument> &docs,
  207. const absl::optional<TargetChange> &targetChange) {
  208. ViewChange change =
  209. view->ApplyChanges(view->ComputeDocumentChanges(FSTTestDocUpdates(docs)), targetChange);
  210. return change.snapshot();
  211. }
  212. RemoteEvent FSTTestAddedRemoteEvent(const MaybeDocument &doc,
  213. const std::vector<TargetId> &addedToTargets) {
  214. std::vector<MaybeDocument> docs{doc};
  215. return FSTTestAddedRemoteEvent(docs, addedToTargets);
  216. }
  217. RemoteEvent FSTTestAddedRemoteEvent(const std::vector<MaybeDocument> &docs,
  218. const std::vector<TargetId> &addedToTargets) {
  219. HARD_ASSERT(!docs.empty(), "Cannot pass empty docs array");
  220. const ResourcePath &collectionPath = docs[0].key().path().PopLast();
  221. auto metadataProvider =
  222. FakeTargetMetadataProvider::CreateEmptyResultProvider(collectionPath, addedToTargets);
  223. WatchChangeAggregator aggregator{&metadataProvider};
  224. for (const MaybeDocument &doc : docs) {
  225. HARD_ASSERT(!doc.is_document() || !Document(doc).has_local_mutations(),
  226. "Docs from remote updates shouldn't have local changes.");
  227. DocumentWatchChange change{addedToTargets, {}, doc.key(), doc};
  228. aggregator.HandleDocumentChange(change);
  229. }
  230. return aggregator.CreateRemoteEvent(docs[0].version());
  231. }
  232. TargetChange FSTTestTargetChangeMarkCurrent() {
  233. return {ByteString(),
  234. /*current=*/true,
  235. /*added_documents=*/DocumentKeySet{},
  236. /*modified_documents=*/DocumentKeySet{},
  237. /*removed_documents=*/DocumentKeySet{}};
  238. }
  239. TargetChange FSTTestTargetChangeAckDocuments(DocumentKeySet docs) {
  240. return {ByteString(),
  241. /*current=*/true,
  242. /*added_documents*/ std::move(docs),
  243. /*modified_documents*/ DocumentKeySet{},
  244. /*removed_documents*/ DocumentKeySet{}};
  245. }
  246. RemoteEvent FSTTestUpdateRemoteEventWithLimboTargets(
  247. const MaybeDocument &doc,
  248. const std::vector<TargetId> &updatedInTargets,
  249. const std::vector<TargetId> &removedFromTargets,
  250. const std::vector<TargetId> &limboTargets) {
  251. HARD_ASSERT(!doc.is_document() || !Document(doc).has_local_mutations(),
  252. "Docs from remote updates shouldn't have local changes.");
  253. DocumentWatchChange change{updatedInTargets, removedFromTargets, doc.key(), doc};
  254. std::vector<TargetId> listens = updatedInTargets;
  255. listens.insert(listens.end(), removedFromTargets.begin(), removedFromTargets.end());
  256. auto metadataProvider =
  257. FakeTargetMetadataProvider::CreateSingleResultProvider(doc.key(), listens, limboTargets);
  258. WatchChangeAggregator aggregator{&metadataProvider};
  259. aggregator.HandleDocumentChange(change);
  260. return aggregator.CreateRemoteEvent(doc.version());
  261. }
  262. RemoteEvent FSTTestUpdateRemoteEvent(const MaybeDocument &doc,
  263. const std::vector<TargetId> &updatedInTargets,
  264. const std::vector<TargetId> &removedFromTargets) {
  265. return FSTTestUpdateRemoteEventWithLimboTargets(doc, updatedInTargets, removedFromTargets, {});
  266. }
  267. /** Creates a resume token to match the given snapshot version. */
  268. NSData *_Nullable FSTTestResumeTokenFromSnapshotVersion(FSTTestSnapshotVersion snapshotVersion) {
  269. if (snapshotVersion == 0) {
  270. return nil;
  271. }
  272. NSString *snapshotString = [NSString stringWithFormat:@"snapshot-%" PRId64, snapshotVersion];
  273. return [snapshotString dataUsingEncoding:NSUTF8StringEncoding];
  274. }
  275. LocalViewChanges TestViewChanges(TargetId targetID,
  276. NSArray<NSString *> *addedKeys,
  277. NSArray<NSString *> *removedKeys) {
  278. DocumentKeySet added;
  279. for (NSString *keyPath in addedKeys) {
  280. added = added.insert(testutil::Key(util::MakeString(keyPath)));
  281. }
  282. DocumentKeySet removed;
  283. for (NSString *keyPath in removedKeys) {
  284. removed = removed.insert(testutil::Key(util::MakeString(keyPath)));
  285. }
  286. return LocalViewChanges(targetID, std::move(added), std::move(removed));
  287. }
  288. NS_ASSUME_NONNULL_END