FSTUserDataConverter.mm 20 KB

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