FSTUserDataConverter.mm 20 KB

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