FSTUserDataConverter.mm 20 KB

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