FSTUserDataConverter.mm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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/api/input_validation.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/field_value.h"
  38. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  39. #include "Firestore/core/src/firebase/firestore/model/transform_operation.h"
  40. #include "Firestore/core/src/firebase/firestore/nanopb/nanopb_util.h"
  41. #include "Firestore/core/src/firebase/firestore/timestamp_internal.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::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::ObjectValue;
  66. using firebase::firestore::model::Precondition;
  67. using firebase::firestore::model::ServerTimestampTransform;
  68. using firebase::firestore::model::TransformOperation;
  69. using firebase::firestore::nanopb::MakeByteString;
  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 = [FIRFieldPath pathWithDotSeparatedString:key].internalValue;
  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. ParseAccumulator accumulator{UserDataSource::Argument};
  190. absl::optional<FieldValue> parsed = [self parseData:input context:accumulator.RootContext()];
  191. HARD_ASSERT(parsed, "Parsed data should not be nil.");
  192. HARD_ASSERT(accumulator.field_transforms().empty(),
  193. "Field transforms should have been disallowed.");
  194. return *parsed;
  195. }
  196. /**
  197. * Internal helper for parsing user data.
  198. *
  199. * @param input Data to be parsed.
  200. * @param context A context object representing the current path being parsed, the source of the
  201. * data being parsed, etc.
  202. *
  203. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  204. * included in the resulting parsed data.
  205. */
  206. - (absl::optional<FieldValue>)parseData:(id)input context:(ParseContext &&)context {
  207. input = self.preConverter(input);
  208. if ([input isKindOfClass:[NSDictionary class]]) {
  209. return [self parseDictionary:(NSDictionary *)input context:std::move(context)];
  210. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  211. // FieldValues usually parse into transforms (except FieldValue.delete()) in which case we
  212. // do not want to include this field in our parsed data (as doing so will overwrite the field
  213. // directly prior to the transform trying to transform it). So we don't call appendToFieldMask
  214. // and we return nil as our parsing result.
  215. [self parseSentinelFieldValue:(FIRFieldValue *)input context:std::move(context)];
  216. return absl::nullopt;
  217. } else {
  218. // If context path is unset we are already inside an array and we don't support field mask paths
  219. // more granular than the top-level array.
  220. if (context.path()) {
  221. context.AddToFieldMask(*context.path());
  222. }
  223. if ([input isKindOfClass:[NSArray class]]) {
  224. // TODO(b/34871131): Include the path containing the array in the error message.
  225. if (context.array_element()) {
  226. ThrowInvalidArgument("Nested arrays are not supported");
  227. }
  228. return [self parseArray:(NSArray *)input context:std::move(context)];
  229. } else {
  230. return [self parseScalarValue:input context:std::move(context)];
  231. }
  232. }
  233. }
  234. - (FieldValue)parseDictionary:(NSDictionary<NSString *, id> *)dict
  235. context:(ParseContext &&)context {
  236. if (dict.count == 0) {
  237. const FieldPath *path = context.path();
  238. if (path && !path->empty()) {
  239. context.AddToFieldMask(*path);
  240. }
  241. return ObjectValue::Empty().AsFieldValue();
  242. } else {
  243. __block ObjectValue result = ObjectValue::Empty();
  244. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  245. absl::optional<FieldValue> parsedValue =
  246. [self parseData:value context:context.ChildContext(util::MakeString(key))];
  247. if (parsedValue) {
  248. FieldPath path = FieldPath{util::MakeString(key)};
  249. result = result.Set(path, *parsedValue);
  250. }
  251. }];
  252. return result;
  253. }
  254. }
  255. - (FieldValue)parseArray:(NSArray<id> *)array context:(ParseContext &&)context {
  256. __block FieldValue::Array result;
  257. result.reserve(array.count);
  258. [array enumerateObjectsUsingBlock:^(id entry, NSUInteger idx, BOOL *stop) {
  259. absl::optional<FieldValue> parsedEntry = [self parseData:entry
  260. context:context.ChildContext(idx)];
  261. if (!parsedEntry) {
  262. // Just include nulls in the array for fields being replaced with a sentinel.
  263. parsedEntry = FieldValue::Null();
  264. }
  265. result.push_back(*parsedEntry);
  266. }];
  267. return FieldValue::FromArray(std::move(result));
  268. }
  269. /**
  270. * "Parses" the provided FIRFieldValue, adding any necessary transforms to
  271. * context.fieldTransforms.
  272. */
  273. - (void)parseSentinelFieldValue:(FIRFieldValue *)fieldValue context:(ParseContext &&)context {
  274. // Sentinels are only supported with writes, and not within arrays.
  275. if (!context.write()) {
  276. ThrowInvalidArgument("%s can only be used with updateData() and setData()%s",
  277. fieldValue.methodName, context.FieldDescription());
  278. }
  279. if (!context.path()) {
  280. ThrowInvalidArgument("%s is not currently supported inside arrays", fieldValue.methodName);
  281. }
  282. if ([fieldValue isKindOfClass:[FSTDeleteFieldValue class]]) {
  283. if (context.data_source() == UserDataSource::MergeSet) {
  284. // No transform to add for a delete, but we need to add it to our fieldMask so it gets
  285. // deleted.
  286. context.AddToFieldMask(*context.path());
  287. } else if (context.data_source() == UserDataSource::Update) {
  288. HARD_ASSERT(context.path()->size() > 0,
  289. "FieldValue.delete() at the top level should have already been handled.");
  290. ThrowInvalidArgument("FieldValue.delete() can only appear at the top level of your "
  291. "update data%s",
  292. context.FieldDescription());
  293. } else {
  294. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  295. ThrowInvalidArgument(
  296. "FieldValue.delete() can only be used with updateData() and setData() with merge:true%s",
  297. context.FieldDescription());
  298. }
  299. } else if ([fieldValue isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  300. context.AddToFieldTransforms(*context.path(), ServerTimestampTransform());
  301. } else if ([fieldValue isKindOfClass:[FSTArrayUnionFieldValue class]]) {
  302. std::vector<FieldValue> parsedElements =
  303. [self parseArrayTransformElements:((FSTArrayUnionFieldValue *)fieldValue).elements];
  304. ArrayTransform array_union(TransformOperation::Type::ArrayUnion, std::move(parsedElements));
  305. context.AddToFieldTransforms(*context.path(), std::move(array_union));
  306. } else if ([fieldValue isKindOfClass:[FSTArrayRemoveFieldValue class]]) {
  307. std::vector<FieldValue> parsedElements =
  308. [self parseArrayTransformElements:((FSTArrayRemoveFieldValue *)fieldValue).elements];
  309. ArrayTransform array_remove(TransformOperation::Type::ArrayRemove, std::move(parsedElements));
  310. context.AddToFieldTransforms(*context.path(), std::move(array_remove));
  311. } else if ([fieldValue isKindOfClass:[FSTNumericIncrementFieldValue class]]) {
  312. FSTNumericIncrementFieldValue *numericIncrementFieldValue =
  313. (FSTNumericIncrementFieldValue *)fieldValue;
  314. FieldValue operand = [self parsedQueryValue:numericIncrementFieldValue.operand];
  315. NumericIncrementTransform numeric_increment(std::move(operand));
  316. context.AddToFieldTransforms(*context.path(), std::move(numeric_increment));
  317. } else {
  318. HARD_FAIL("Unknown FIRFieldValue type: %s", NSStringFromClass([fieldValue class]));
  319. }
  320. }
  321. /**
  322. * Helper to parse a scalar value (i.e. not an NSDictionary, NSArray, or FIRFieldValue).
  323. *
  324. * Note that it handles all NSNumber values that are encodable as int64_t or doubles
  325. * (depending on the underlying type of the NSNumber). Unsigned integer values are handled though
  326. * any value outside what is representable by int64_t (a signed 64-bit value) will throw an
  327. * exception.
  328. *
  329. * @return The parsed value.
  330. */
  331. - (absl::optional<FieldValue>)parseScalarValue:(nullable id)input context:(ParseContext &&)context {
  332. if (!input || [input isMemberOfClass:[NSNull class]]) {
  333. return FieldValue::Null();
  334. } else if ([input isKindOfClass:[NSNumber class]]) {
  335. // Recover the underlying type of the number, using the method described here:
  336. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  337. const char *cType = [input objCType];
  338. // Type Encoding values taken from
  339. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  340. // Articles/ocrtTypeEncodings.html
  341. switch (cType[0]) {
  342. case 'q':
  343. return FieldValue::FromInteger([input longLongValue]);
  344. case 'i': // Falls through.
  345. case 's': // Falls through.
  346. case 'l': // Falls through.
  347. case 'I': // Falls through.
  348. case 'S':
  349. // Coerce integer values that aren't long long. Allow unsigned integer types that are
  350. // guaranteed small enough to skip a length check.
  351. return FieldValue::FromInteger([input longLongValue]);
  352. case 'L': // Falls through.
  353. case 'Q':
  354. // Unsigned integers that could be too large. Note that the 'L' (long) case is handled here
  355. // because when compiled for LP64, unsigned long is 64 bits and could overflow int64_t.
  356. {
  357. unsigned long long extended = [input unsignedLongLongValue];
  358. if (extended > LLONG_MAX) {
  359. ThrowInvalidArgument("NSNumber (%s) is too large%s", [input unsignedLongLongValue],
  360. context.FieldDescription());
  361. } else {
  362. return FieldValue::FromInteger(static_cast<int64_t>(extended));
  363. }
  364. }
  365. case 'f':
  366. return FieldValue::FromDouble([input doubleValue]);
  367. case 'd':
  368. // Double values are already the right type, so just reuse the existing boxed double.
  369. //
  370. // Note that NSNumber already performs NaN normalization to a single shared instance
  371. // so there's no need to treat NaN specially here.
  372. return FieldValue::FromDouble([input doubleValue]);
  373. case 'B': // Falls through.
  374. case 'c': // Falls through.
  375. case 'C':
  376. // Boolean values are weird.
  377. //
  378. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  379. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  380. // legitimate usage of signed chars is impossible, but this should be rare.
  381. //
  382. // Additionally, for consistency, map unsigned chars to bools in the same way.
  383. return FieldValue::FromBoolean([input boolValue]);
  384. default:
  385. // All documented codes should be handled above, so this shouldn't happen.
  386. HARD_FAIL("Unknown NSNumber objCType %s on %s", cType, input);
  387. }
  388. } else if ([input isKindOfClass:[NSString class]]) {
  389. return FieldValue::FromString(util::MakeString(input));
  390. } else if ([input isKindOfClass:[NSDate class]]) {
  391. NSDate *inputDate = input;
  392. return FieldValue::FromTimestamp(api::MakeTimestamp(inputDate));
  393. } else if ([input isKindOfClass:[FIRTimestamp class]]) {
  394. FIRTimestamp *inputTimestamp = input;
  395. Timestamp timestamp = TimestampInternal::Truncate(api::MakeTimestamp(inputTimestamp));
  396. return FieldValue::FromTimestamp(timestamp);
  397. } else if ([input isKindOfClass:[FIRGeoPoint class]]) {
  398. return FieldValue::FromGeoPoint(api::MakeGeoPoint(input));
  399. } else if ([input isKindOfClass:[NSData class]]) {
  400. NSData *inputData = input;
  401. return FieldValue::FromBlob(MakeByteString(inputData));
  402. } else if ([input isKindOfClass:[FSTDocumentKeyReference class]]) {
  403. FSTDocumentKeyReference *reference = input;
  404. if (reference.databaseID != _databaseID) {
  405. const DatabaseId &other = reference.databaseID;
  406. ThrowInvalidArgument(
  407. "Document Reference is for database %s/%s but should be for database %s/%s%s",
  408. other.project_id(), other.database_id(), _databaseID.project_id(),
  409. _databaseID.database_id(), context.FieldDescription());
  410. }
  411. return FieldValue::FromReference(_databaseID, reference.key);
  412. } else {
  413. ThrowInvalidArgument("Unsupported type: %s%s", NSStringFromClass([input class]),
  414. context.FieldDescription());
  415. }
  416. }
  417. - (std::vector<FieldValue>)parseArrayTransformElements:(NSArray<id> *)elements {
  418. ParseAccumulator accumulator{UserDataSource::Argument};
  419. std::vector<FieldValue> values;
  420. for (NSUInteger i = 0; i < elements.count; i++) {
  421. id element = elements[i];
  422. // Although array transforms are used with writes, the actual elements being unioned or removed
  423. // are not considered writes since they cannot contain any FieldValue sentinels, etc.
  424. ParseContext context = accumulator.RootContext();
  425. absl::optional<FieldValue> parsedElement = [self parseData:element
  426. context:context.ChildContext(i)];
  427. HARD_ASSERT(parsedElement && accumulator.field_transforms().size() == 0,
  428. "Failed to properly parse array transform element: %s", element);
  429. values.push_back(*parsedElement);
  430. }
  431. return values;
  432. }
  433. @end
  434. NS_ASSUME_NONNULL_END