FSTUserDataConverter.mm 21 KB

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