FSTUserDataConverter.mm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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/Source/API/FSTUserDataConverter.h"
  17. #include <memory>
  18. #include <set>
  19. #include <string>
  20. #include <utility>
  21. #include <vector>
  22. #import "FIRGeoPoint.h"
  23. #import "FIRTimestamp.h"
  24. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  25. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  26. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  27. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  28. #import "Firestore/Source/Model/FSTFieldValue.h"
  29. #import "Firestore/Source/Model/FSTMutation.h"
  30. #import "Firestore/Source/Util/FSTUsageValidation.h"
  31. #include "Firestore/core/src/firebase/firestore/core/user_data.h"
  32. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  33. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  34. #include "Firestore/core/src/firebase/firestore/model/field_mask.h"
  35. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  36. #include "Firestore/core/src/firebase/firestore/model/field_transform.h"
  37. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  38. #include "Firestore/core/src/firebase/firestore/model/transform_operations.h"
  39. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  40. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  41. #include "absl/memory/memory.h"
  42. #include "absl/strings/match.h"
  43. namespace util = firebase::firestore::util;
  44. using firebase::firestore::core::ParsedSetData;
  45. using firebase::firestore::core::ParsedUpdateData;
  46. using firebase::firestore::core::ParseAccumulator;
  47. using firebase::firestore::core::ParseContext;
  48. using firebase::firestore::core::UserDataSource;
  49. using firebase::firestore::model::ArrayTransform;
  50. using firebase::firestore::model::DatabaseId;
  51. using firebase::firestore::model::DocumentKey;
  52. using firebase::firestore::model::FieldMask;
  53. using firebase::firestore::model::FieldPath;
  54. using firebase::firestore::model::FieldTransform;
  55. using firebase::firestore::model::NumericIncrementTransform;
  56. using firebase::firestore::model::Precondition;
  57. using firebase::firestore::model::ServerTimestampTransform;
  58. using firebase::firestore::model::TransformOperation;
  59. NS_ASSUME_NONNULL_BEGIN
  60. #pragma mark - FSTDocumentKeyReference
  61. @implementation FSTDocumentKeyReference {
  62. DocumentKey _key;
  63. }
  64. - (instancetype)initWithKey:(DocumentKey)key databaseID:(const DatabaseId *)databaseID {
  65. self = [super init];
  66. if (self) {
  67. _key = std::move(key);
  68. _databaseID = databaseID;
  69. }
  70. return self;
  71. }
  72. - (const firebase::firestore::model::DocumentKey &)key {
  73. return _key;
  74. }
  75. @end
  76. #pragma mark - FSTUserDataConverter
  77. @interface FSTUserDataConverter ()
  78. // Does not own the DatabaseId instance.
  79. @property(assign, nonatomic, readonly) const DatabaseId *databaseID;
  80. @property(strong, nonatomic, readonly) FSTPreConverterBlock preConverter;
  81. @end
  82. @implementation FSTUserDataConverter
  83. - (instancetype)initWithDatabaseID:(const DatabaseId *)databaseID
  84. preConverter:(FSTPreConverterBlock)preConverter {
  85. self = [super init];
  86. if (self) {
  87. _databaseID = databaseID;
  88. _preConverter = preConverter;
  89. }
  90. return self;
  91. }
  92. - (ParsedSetData)parsedSetData:(id)input {
  93. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  94. // Obj-C to verify the type for us.
  95. if (![input isKindOfClass:[NSDictionary class]]) {
  96. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  97. }
  98. ParseAccumulator accumulator{UserDataSource::Set};
  99. FSTFieldValue *updateData = [self parseData:input context:accumulator.RootContext()];
  100. return std::move(accumulator).SetData((FSTObjectValue *)updateData);
  101. }
  102. - (ParsedSetData)parsedMergeData:(id)input fieldMask:(nullable NSArray<id> *)fieldMask {
  103. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  104. // Obj-C to verify the type for us.
  105. if (![input isKindOfClass:[NSDictionary class]]) {
  106. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  107. }
  108. ParseAccumulator accumulator{UserDataSource::MergeSet};
  109. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input
  110. context:accumulator.RootContext()];
  111. if (fieldMask) {
  112. std::set<FieldPath> validatedFieldPaths;
  113. for (id fieldPath in fieldMask) {
  114. FieldPath path;
  115. if ([fieldPath isKindOfClass:[NSString class]]) {
  116. path = [FIRFieldPath pathWithDotSeparatedString:fieldPath].internalValue;
  117. } else if ([fieldPath isKindOfClass:[FIRFieldPath class]]) {
  118. path = ((FIRFieldPath *)fieldPath).internalValue;
  119. } else {
  120. FSTThrowInvalidArgument(
  121. @"All elements in mergeFields: must be NSStrings or FIRFieldPaths.");
  122. }
  123. // Verify that all elements specified in the field mask are part of the parsed context.
  124. if (!accumulator.Contains(path)) {
  125. FSTThrowInvalidArgument(
  126. @"Field '%s' is specified in your field mask but missing from your input data.",
  127. path.CanonicalString().c_str());
  128. }
  129. validatedFieldPaths.insert(path);
  130. }
  131. return std::move(accumulator).MergeData(updateData, FieldMask{std::move(validatedFieldPaths)});
  132. } else {
  133. return std::move(accumulator).MergeData(updateData);
  134. }
  135. }
  136. - (ParsedUpdateData)parsedUpdateData:(id)input {
  137. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  138. // Obj-C to verify the type for us.
  139. if (![input isKindOfClass:[NSDictionary class]]) {
  140. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  141. }
  142. NSDictionary *dict = input;
  143. ParseAccumulator accumulator{UserDataSource::Update};
  144. __block ParseContext context = accumulator.RootContext();
  145. __block FSTObjectValue *updateData = [FSTObjectValue objectValue];
  146. [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
  147. FieldPath path;
  148. if ([key isKindOfClass:[NSString class]]) {
  149. path = [FIRFieldPath pathWithDotSeparatedString:key].internalValue;
  150. } else if ([key isKindOfClass:[FIRFieldPath class]]) {
  151. path = ((FIRFieldPath *)key).internalValue;
  152. } else {
  153. FSTThrowInvalidArgument(
  154. @"Dictionary keys in updateData: must be NSStrings or FIRFieldPaths.");
  155. }
  156. value = self.preConverter(value);
  157. if ([value isKindOfClass:[FSTDeleteFieldValue class]]) {
  158. // Add it to the field mask, but don't add anything to updateData.
  159. context.AddToFieldMask(std::move(path));
  160. } else {
  161. FSTFieldValue *_Nullable parsedValue = [self parseData:value
  162. context:context.ChildContext(path)];
  163. if (parsedValue) {
  164. context.AddToFieldMask(path);
  165. updateData = [updateData objectBySettingValue:parsedValue forPath:path];
  166. }
  167. }
  168. }];
  169. return std::move(accumulator).UpdateData(updateData);
  170. }
  171. - (FSTFieldValue *)parsedQueryValue:(id)input {
  172. ParseAccumulator accumulator{UserDataSource::Argument};
  173. FSTFieldValue *_Nullable parsed = [self parseData:input context:accumulator.RootContext()];
  174. HARD_ASSERT(parsed, "Parsed data should not be nil.");
  175. HARD_ASSERT(accumulator.field_transforms().empty(),
  176. "Field transforms should have been disallowed.");
  177. return parsed;
  178. }
  179. /**
  180. * Internal helper for parsing user data.
  181. *
  182. * @param input Data to be parsed.
  183. * @param context A context object representing the current path being parsed, the source of the
  184. * data being parsed, etc.
  185. *
  186. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  187. * included in the resulting parsed data.
  188. */
  189. - (nullable FSTFieldValue *)parseData:(id)input context:(ParseContext &&)context {
  190. input = self.preConverter(input);
  191. if ([input isKindOfClass:[NSDictionary class]]) {
  192. return [self parseDictionary:(NSDictionary *)input context:std::move(context)];
  193. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  194. // FieldValues usually parse into transforms (except FieldValue.delete()) in which case we
  195. // do not want to include this field in our parsed data (as doing so will overwrite the field
  196. // directly prior to the transform trying to transform it). So we don't call appendToFieldMask
  197. // and we return nil as our parsing result.
  198. [self parseSentinelFieldValue:(FIRFieldValue *)input context:std::move(context)];
  199. return nil;
  200. } else {
  201. // If context path is unset we are already inside an array and we don't support field mask paths
  202. // more granular than the top-level array.
  203. if (context.path()) {
  204. context.AddToFieldMask(*context.path());
  205. }
  206. if ([input isKindOfClass:[NSArray class]]) {
  207. // TODO(b/34871131): Include the path containing the array in the error message.
  208. if (context.array_element()) {
  209. FSTThrowInvalidArgument(@"Nested arrays are not supported");
  210. }
  211. return [self parseArray:(NSArray *)input context:std::move(context)];
  212. } else {
  213. return [self parseScalarValue:input context:std::move(context)];
  214. }
  215. }
  216. }
  217. - (FSTFieldValue *)parseDictionary:(NSDictionary *)dict context:(ParseContext &&)context {
  218. NSMutableDictionary<NSString *, FSTFieldValue *> *result =
  219. [NSMutableDictionary dictionaryWithCapacity:dict.count];
  220. if ([dict count] == 0) {
  221. const FieldPath *path = context.path();
  222. if (path && !path->empty()) {
  223. context.AddToFieldMask(*path);
  224. }
  225. return [FSTObjectValue objectValue];
  226. } else {
  227. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  228. FSTFieldValue *_Nullable parsedValue =
  229. [self parseData:value context:context.ChildContext(util::MakeString(key))];
  230. if (parsedValue) {
  231. result[key] = parsedValue;
  232. }
  233. }];
  234. }
  235. return [[FSTObjectValue alloc] initWithDictionary:result];
  236. }
  237. - (FSTFieldValue *)parseArray:(NSArray *)array context:(ParseContext &&)context {
  238. NSMutableArray<FSTFieldValue *> *result = [NSMutableArray arrayWithCapacity:array.count];
  239. [array enumerateObjectsUsingBlock:^(id entry, NSUInteger idx, BOOL *stop) {
  240. FSTFieldValue *_Nullable parsedEntry = [self parseData:entry context:context.ChildContext(idx)];
  241. if (!parsedEntry) {
  242. // Just include nulls in the array for fields being replaced with a sentinel.
  243. parsedEntry = [FSTNullValue nullValue];
  244. }
  245. [result addObject:parsedEntry];
  246. }];
  247. return [[FSTArrayValue alloc] initWithValueNoCopy:result];
  248. }
  249. /**
  250. * "Parses" the provided FIRFieldValue, adding any necessary transforms to
  251. * context.fieldTransforms.
  252. */
  253. - (void)parseSentinelFieldValue:(FIRFieldValue *)fieldValue context:(ParseContext &&)context {
  254. // Sentinels are only supported with writes, and not within arrays.
  255. if (!context.write()) {
  256. FSTThrowInvalidArgument(@"%@ can only be used with updateData() and setData()%s",
  257. fieldValue.methodName, context.FieldDescription().c_str());
  258. }
  259. if (!context.path()) {
  260. FSTThrowInvalidArgument(@"%@ is not currently supported inside arrays", fieldValue.methodName);
  261. }
  262. if ([fieldValue isKindOfClass:[FSTDeleteFieldValue class]]) {
  263. if (context.data_source() == UserDataSource::MergeSet) {
  264. // No transform to add for a delete, but we need to add it to our fieldMask so it gets
  265. // deleted.
  266. context.AddToFieldMask(*context.path());
  267. } else if (context.data_source() == UserDataSource::Update) {
  268. HARD_ASSERT(context.path()->size() > 0,
  269. "FieldValue.delete() at the top level should have already been handled.");
  270. FSTThrowInvalidArgument(@"FieldValue.delete() can only appear at the top level of your "
  271. "update data%s",
  272. context.FieldDescription().c_str());
  273. } else {
  274. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  275. FSTThrowInvalidArgument(
  276. @"FieldValue.delete() can only be used with updateData() and setData() with "
  277. @"merge:true%s",
  278. context.FieldDescription().c_str());
  279. }
  280. } else if ([fieldValue isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  281. context.AddToFieldTransforms(*context.path(), absl::make_unique<ServerTimestampTransform>(
  282. ServerTimestampTransform::Get()));
  283. } else if ([fieldValue isKindOfClass:[FSTArrayUnionFieldValue class]]) {
  284. std::vector<FSTFieldValue *> parsedElements =
  285. [self parseArrayTransformElements:((FSTArrayUnionFieldValue *)fieldValue).elements];
  286. auto array_union = absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayUnion,
  287. std::move(parsedElements));
  288. context.AddToFieldTransforms(*context.path(), std::move(array_union));
  289. } else if ([fieldValue isKindOfClass:[FSTArrayRemoveFieldValue class]]) {
  290. std::vector<FSTFieldValue *> parsedElements =
  291. [self parseArrayTransformElements:((FSTArrayRemoveFieldValue *)fieldValue).elements];
  292. auto array_remove = absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayRemove,
  293. std::move(parsedElements));
  294. context.AddToFieldTransforms(*context.path(), std::move(array_remove));
  295. } else if ([fieldValue isKindOfClass:[FSTNumericIncrementFieldValue class]]) {
  296. FSTNumericIncrementFieldValue *numericIncrementFieldValue =
  297. (FSTNumericIncrementFieldValue *)fieldValue;
  298. FSTNumberValue *operand =
  299. (FSTNumberValue *)[self parsedQueryValue:numericIncrementFieldValue.operand];
  300. auto numeric_increment = absl::make_unique<NumericIncrementTransform>(operand);
  301. context.AddToFieldTransforms(*context.path(), std::move(numeric_increment));
  302. } else {
  303. HARD_FAIL("Unknown FIRFieldValue type: %s", NSStringFromClass([fieldValue class]));
  304. }
  305. }
  306. /**
  307. * Helper to parse a scalar value (i.e. not an NSDictionary, NSArray, or FIRFieldValue).
  308. *
  309. * Note that it handles all NSNumber values that are encodable as int64_t or doubles
  310. * (depending on the underlying type of the NSNumber). Unsigned integer values are handled though
  311. * any value outside what is representable by int64_t (a signed 64-bit value) will throw an
  312. * exception.
  313. *
  314. * @return The parsed value.
  315. */
  316. - (nullable FSTFieldValue *)parseScalarValue:(nullable id)input context:(ParseContext &&)context {
  317. if (!input || [input isMemberOfClass:[NSNull class]]) {
  318. return [FSTNullValue nullValue];
  319. } else if ([input isKindOfClass:[NSNumber class]]) {
  320. // Recover the underlying type of the number, using the method described here:
  321. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  322. const char *cType = [input objCType];
  323. // Type Encoding values taken from
  324. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  325. // Articles/ocrtTypeEncodings.html
  326. switch (cType[0]) {
  327. case 'q':
  328. return [FSTIntegerValue integerValue:[input longLongValue]];
  329. case 'i': // Falls through.
  330. case 's': // Falls through.
  331. case 'l': // Falls through.
  332. case 'I': // Falls through.
  333. case 'S':
  334. // Coerce integer values that aren't long long. Allow unsigned integer types that are
  335. // guaranteed small enough to skip a length check.
  336. return [FSTIntegerValue integerValue:[input longLongValue]];
  337. case 'L': // Falls through.
  338. case 'Q':
  339. // Unsigned integers that could be too large. Note that the 'L' (long) case is handled here
  340. // because when compiled for LP64, unsigned long is 64 bits and could overflow int64_t.
  341. {
  342. unsigned long long extended = [input unsignedLongLongValue];
  343. if (extended > LLONG_MAX) {
  344. FSTThrowInvalidArgument(@"NSNumber (%llu) is too large%s",
  345. [input unsignedLongLongValue],
  346. context.FieldDescription().c_str());
  347. } else {
  348. return [FSTIntegerValue integerValue:(int64_t)extended];
  349. }
  350. }
  351. case 'f':
  352. return [FSTDoubleValue doubleValue:[input doubleValue]];
  353. case 'd':
  354. // Double values are already the right type, so just reuse the existing boxed double.
  355. //
  356. // Note that NSNumber already performs NaN normalization to a single shared instance
  357. // so there's no need to treat NaN specially here.
  358. return [FSTDoubleValue doubleValue:[input doubleValue]];
  359. case 'B': // Falls through.
  360. case 'c': // Falls through.
  361. case 'C':
  362. // Boolean values are weird.
  363. //
  364. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  365. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  366. // legitimate usage of signed chars is impossible, but this should be rare.
  367. //
  368. // Additionally, for consistency, map unsigned chars to bools in the same way.
  369. return [FSTBooleanValue booleanValue:[input boolValue]];
  370. default:
  371. // All documented codes should be handled above, so this shouldn't happen.
  372. HARD_FAIL("Unknown NSNumber objCType %s on %s", cType, input);
  373. }
  374. } else if ([input isKindOfClass:[NSString class]]) {
  375. return [FSTStringValue stringValue:input];
  376. } else if ([input isKindOfClass:[NSDate class]]) {
  377. return [FSTTimestampValue timestampValue:[FIRTimestamp timestampWithDate:input]];
  378. } else if ([input isKindOfClass:[FIRTimestamp class]]) {
  379. FIRTimestamp *originalTimestamp = (FIRTimestamp *)input;
  380. FIRTimestamp *truncatedTimestamp =
  381. [FIRTimestamp timestampWithSeconds:originalTimestamp.seconds
  382. nanoseconds:originalTimestamp.nanoseconds / 1000 * 1000];
  383. return [FSTTimestampValue timestampValue:truncatedTimestamp];
  384. } else if ([input isKindOfClass:[FIRGeoPoint class]]) {
  385. return [FSTGeoPointValue geoPointValue:input];
  386. } else if ([input isKindOfClass:[NSData class]]) {
  387. return [FSTBlobValue blobValue:input];
  388. } else if ([input isKindOfClass:[FSTDocumentKeyReference class]]) {
  389. FSTDocumentKeyReference *reference = input;
  390. if (*reference.databaseID != *self.databaseID) {
  391. const DatabaseId *other = reference.databaseID;
  392. FSTThrowInvalidArgument(
  393. @"Document Reference is for database %s/%s but should be for database %s/%s%s",
  394. other->project_id().c_str(), other->database_id().c_str(),
  395. self.databaseID->project_id().c_str(), self.databaseID->database_id().c_str(),
  396. context.FieldDescription().c_str());
  397. }
  398. return [FSTReferenceValue referenceValue:[FSTDocumentKey keyWithDocumentKey:reference.key]
  399. databaseID:self.databaseID];
  400. } else {
  401. FSTThrowInvalidArgument(@"Unsupported type: %@%s", NSStringFromClass([input class]),
  402. context.FieldDescription().c_str());
  403. }
  404. }
  405. - (std::vector<FSTFieldValue *>)parseArrayTransformElements:(NSArray<id> *)elements {
  406. ParseAccumulator accumulator{UserDataSource::Argument};
  407. std::vector<FSTFieldValue *> values;
  408. for (NSUInteger i = 0; i < elements.count; i++) {
  409. id element = elements[i];
  410. // Although array transforms are used with writes, the actual elements being unioned or removed
  411. // are not considered writes since they cannot contain any FieldValue sentinels, etc.
  412. ParseContext context = accumulator.RootContext();
  413. FSTFieldValue *parsedElement = [self parseData:element context:context.ChildContext(i)];
  414. HARD_ASSERT(parsedElement && accumulator.field_transforms().size() == 0,
  415. "Failed to properly parse array transform element: %s", element);
  416. values.push_back(parsedElement);
  417. }
  418. return values;
  419. }
  420. @end
  421. NS_ASSUME_NONNULL_END