FSTUserDataConverter.mm 20 KB

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