FSTUserDataConverter.mm 20 KB

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