FSTUserDataConverter.mm 20 KB

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