FSTUserDataConverter.mm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. #import "Firestore/Source/Util/FSTUsageValidation.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::core::ParsedSetData;
  45. using firebase::firestore::core::ParsedUpdateData;
  46. using firebase::firestore::core::ParseAccumulator;
  47. using firebase::firestore::core::ParseContext;
  48. using firebase::firestore::core::UserDataSource;
  49. using firebase::firestore::model::ArrayTransform;
  50. using firebase::firestore::model::DatabaseId;
  51. using firebase::firestore::model::DocumentKey;
  52. using firebase::firestore::model::FieldMask;
  53. using firebase::firestore::model::FieldPath;
  54. using firebase::firestore::model::FieldTransform;
  55. using firebase::firestore::model::Precondition;
  56. using firebase::firestore::model::ServerTimestampTransform;
  57. using firebase::firestore::model::TransformOperation;
  58. NS_ASSUME_NONNULL_BEGIN
  59. #pragma mark - FSTDocumentKeyReference
  60. @implementation FSTDocumentKeyReference {
  61. DocumentKey _key;
  62. }
  63. - (instancetype)initWithKey:(DocumentKey)key databaseID:(const DatabaseId *)databaseID {
  64. self = [super init];
  65. if (self) {
  66. _key = std::move(key);
  67. _databaseID = databaseID;
  68. }
  69. return self;
  70. }
  71. - (const firebase::firestore::model::DocumentKey &)key {
  72. return _key;
  73. }
  74. @end
  75. #pragma mark - FSTUserDataConverter
  76. @interface FSTUserDataConverter ()
  77. // Does not own the DatabaseId instance.
  78. @property(assign, nonatomic, readonly) const DatabaseId *databaseID;
  79. @property(strong, nonatomic, readonly) FSTPreConverterBlock preConverter;
  80. @end
  81. @implementation FSTUserDataConverter
  82. - (instancetype)initWithDatabaseID:(const DatabaseId *)databaseID
  83. preConverter:(FSTPreConverterBlock)preConverter {
  84. self = [super init];
  85. if (self) {
  86. _databaseID = databaseID;
  87. _preConverter = preConverter;
  88. }
  89. return self;
  90. }
  91. - (ParsedSetData)parsedSetData:(id)input {
  92. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  93. // Obj-C to verify the type for us.
  94. if (![input isKindOfClass:[NSDictionary class]]) {
  95. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  96. }
  97. ParseAccumulator accumulator{UserDataSource::Set};
  98. FSTFieldValue *updateData = [self parseData:input context:accumulator.RootContext()];
  99. return std::move(accumulator).SetData((FSTObjectValue *)updateData);
  100. }
  101. - (ParsedSetData)parsedMergeData:(id)input fieldMask:(nullable NSArray<id> *)fieldMask {
  102. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  103. // Obj-C to verify the type for us.
  104. if (![input isKindOfClass:[NSDictionary class]]) {
  105. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  106. }
  107. ParseAccumulator accumulator{UserDataSource::MergeSet};
  108. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input
  109. context:accumulator.RootContext()];
  110. if (fieldMask) {
  111. std::set<FieldPath> validatedFieldPaths;
  112. for (id fieldPath in fieldMask) {
  113. FieldPath path;
  114. if ([fieldPath isKindOfClass:[NSString class]]) {
  115. path = [FIRFieldPath pathWithDotSeparatedString:fieldPath].internalValue;
  116. } else if ([fieldPath isKindOfClass:[FIRFieldPath class]]) {
  117. path = ((FIRFieldPath *)fieldPath).internalValue;
  118. } else {
  119. FSTThrowInvalidArgument(
  120. @"All elements in mergeFields: must be NSStrings or FIRFieldPaths.");
  121. }
  122. // Verify that all elements specified in the field mask are part of the parsed context.
  123. if (!accumulator.Contains(path)) {
  124. FSTThrowInvalidArgument(
  125. @"Field '%s' is specified in your field mask but missing from your input data.",
  126. path.CanonicalString().c_str());
  127. }
  128. validatedFieldPaths.insert(path);
  129. }
  130. return std::move(accumulator).MergeData(updateData, FieldMask{std::move(validatedFieldPaths)});
  131. } else {
  132. return std::move(accumulator).MergeData(updateData);
  133. }
  134. }
  135. - (ParsedUpdateData)parsedUpdateData:(id)input {
  136. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  137. // Obj-C to verify the type for us.
  138. if (![input isKindOfClass:[NSDictionary class]]) {
  139. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  140. }
  141. NSDictionary *dict = input;
  142. ParseAccumulator accumulator{UserDataSource::Update};
  143. __block ParseContext context = accumulator.RootContext();
  144. __block FSTObjectValue *updateData = [FSTObjectValue objectValue];
  145. [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
  146. FieldPath path;
  147. if ([key isKindOfClass:[NSString class]]) {
  148. path = [FIRFieldPath pathWithDotSeparatedString:key].internalValue;
  149. } else if ([key isKindOfClass:[FIRFieldPath class]]) {
  150. path = ((FIRFieldPath *)key).internalValue;
  151. } else {
  152. FSTThrowInvalidArgument(
  153. @"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. FSTThrowInvalidArgument(@"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. FSTThrowInvalidArgument(@"%@ can only be used with updateData() and setData()%s",
  256. fieldValue.methodName, context.FieldDescription().c_str());
  257. }
  258. if (!context.path()) {
  259. FSTThrowInvalidArgument(@"%@ 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. FSTThrowInvalidArgument(@"FieldValue.delete() can only appear at the top level of your "
  270. "update data%s",
  271. context.FieldDescription().c_str());
  272. } else {
  273. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  274. FSTThrowInvalidArgument(
  275. @"FieldValue.delete() can only be used with updateData() and setData() with "
  276. @"merge:true%s",
  277. context.FieldDescription().c_str());
  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 {
  295. HARD_FAIL("Unknown FIRFieldValue type: %s", NSStringFromClass([fieldValue class]));
  296. }
  297. }
  298. /**
  299. * Helper to parse a scalar value (i.e. not an NSDictionary, NSArray, or FIRFieldValue).
  300. *
  301. * Note that it handles all NSNumber values that are encodable as int64_t or doubles
  302. * (depending on the underlying type of the NSNumber). Unsigned integer values are handled though
  303. * any value outside what is representable by int64_t (a signed 64-bit value) will throw an
  304. * exception.
  305. *
  306. * @return The parsed value.
  307. */
  308. - (nullable FSTFieldValue *)parseScalarValue:(nullable id)input context:(ParseContext &&)context {
  309. if (!input || [input isMemberOfClass:[NSNull class]]) {
  310. return [FSTNullValue nullValue];
  311. } else if ([input isKindOfClass:[NSNumber class]]) {
  312. // Recover the underlying type of the number, using the method described here:
  313. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  314. const char *cType = [input objCType];
  315. // Type Encoding values taken from
  316. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  317. // Articles/ocrtTypeEncodings.html
  318. switch (cType[0]) {
  319. case 'q':
  320. return [FSTIntegerValue integerValue:[input longLongValue]];
  321. case 'i': // Falls through.
  322. case 's': // Falls through.
  323. case 'l': // Falls through.
  324. case 'I': // Falls through.
  325. case 'S':
  326. // Coerce integer values that aren't long long. Allow unsigned integer types that are
  327. // guaranteed small enough to skip a length check.
  328. return [FSTIntegerValue integerValue:[input longLongValue]];
  329. case 'L': // Falls through.
  330. case 'Q':
  331. // Unsigned integers that could be too large. Note that the 'L' (long) case is handled here
  332. // because when compiled for LP64, unsigned long is 64 bits and could overflow int64_t.
  333. {
  334. unsigned long long extended = [input unsignedLongLongValue];
  335. if (extended > LLONG_MAX) {
  336. FSTThrowInvalidArgument(@"NSNumber (%llu) is too large%s",
  337. [input unsignedLongLongValue],
  338. context.FieldDescription().c_str());
  339. } else {
  340. return [FSTIntegerValue integerValue:(int64_t)extended];
  341. }
  342. }
  343. case 'f':
  344. return [FSTDoubleValue doubleValue:[input doubleValue]];
  345. case 'd':
  346. // Double values are already the right type, so just reuse the existing boxed double.
  347. //
  348. // Note that NSNumber already performs NaN normalization to a single shared instance
  349. // so there's no need to treat NaN specially here.
  350. return [FSTDoubleValue doubleValue:[input doubleValue]];
  351. case 'B': // Falls through.
  352. case 'c': // Falls through.
  353. case 'C':
  354. // Boolean values are weird.
  355. //
  356. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  357. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  358. // legitimate usage of signed chars is impossible, but this should be rare.
  359. //
  360. // Additionally, for consistency, map unsigned chars to bools in the same way.
  361. return [FSTBooleanValue booleanValue:[input boolValue]];
  362. default:
  363. // All documented codes should be handled above, so this shouldn't happen.
  364. HARD_FAIL("Unknown NSNumber objCType %s on %s", cType, input);
  365. }
  366. } else if ([input isKindOfClass:[NSString class]]) {
  367. return [FSTStringValue stringValue:input];
  368. } else if ([input isKindOfClass:[NSDate class]]) {
  369. return [FSTTimestampValue timestampValue:[FIRTimestamp timestampWithDate:input]];
  370. } else if ([input isKindOfClass:[FIRTimestamp class]]) {
  371. FIRTimestamp *originalTimestamp = (FIRTimestamp *)input;
  372. FIRTimestamp *truncatedTimestamp =
  373. [FIRTimestamp timestampWithSeconds:originalTimestamp.seconds
  374. nanoseconds:originalTimestamp.nanoseconds / 1000 * 1000];
  375. return [FSTTimestampValue timestampValue:truncatedTimestamp];
  376. } else if ([input isKindOfClass:[FIRGeoPoint class]]) {
  377. return [FSTGeoPointValue geoPointValue:input];
  378. } else if ([input isKindOfClass:[NSData class]]) {
  379. return [FSTBlobValue blobValue:input];
  380. } else if ([input isKindOfClass:[FSTDocumentKeyReference class]]) {
  381. FSTDocumentKeyReference *reference = input;
  382. if (*reference.databaseID != *self.databaseID) {
  383. const DatabaseId *other = reference.databaseID;
  384. FSTThrowInvalidArgument(
  385. @"Document Reference is for database %s/%s but should be for database %s/%s%s",
  386. other->project_id().c_str(), other->database_id().c_str(),
  387. self.databaseID->project_id().c_str(), self.databaseID->database_id().c_str(),
  388. context.FieldDescription().c_str());
  389. }
  390. return [FSTReferenceValue referenceValue:reference.key databaseID:self.databaseID];
  391. } else {
  392. FSTThrowInvalidArgument(@"Unsupported type: %@%s", NSStringFromClass([input class]),
  393. context.FieldDescription().c_str());
  394. }
  395. }
  396. - (std::vector<FSTFieldValue *>)parseArrayTransformElements:(NSArray<id> *)elements {
  397. ParseAccumulator accumulator{UserDataSource::Argument};
  398. std::vector<FSTFieldValue *> values;
  399. for (NSUInteger i = 0; i < elements.count; i++) {
  400. id element = elements[i];
  401. // Although array transforms are used with writes, the actual elements being unioned or removed
  402. // are not considered writes since they cannot contain any FieldValue sentinels, etc.
  403. ParseContext context = accumulator.RootContext();
  404. FSTFieldValue *parsedElement = [self parseData:element context:context.ChildContext(i)];
  405. HARD_ASSERT(parsedElement && accumulator.field_transforms().size() == 0,
  406. "Failed to properly parse array transform element: %s", element);
  407. values.push_back(parsedElement);
  408. }
  409. return values;
  410. }
  411. @end
  412. NS_ASSUME_NONNULL_END