FSTUserDataConverter.mm 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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 <utility>
  19. #include <vector>
  20. #import "FIRGeoPoint.h"
  21. #import "FIRTimestamp.h"
  22. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  23. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  24. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  25. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  26. #import "Firestore/Source/Model/FSTFieldValue.h"
  27. #import "Firestore/Source/Model/FSTMutation.h"
  28. #import "Firestore/Source/Util/FSTUsageValidation.h"
  29. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  30. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  31. #include "Firestore/core/src/firebase/firestore/model/field_mask.h"
  32. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  33. #include "Firestore/core/src/firebase/firestore/model/field_transform.h"
  34. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  35. #include "Firestore/core/src/firebase/firestore/model/transform_operations.h"
  36. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  37. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  38. #include "absl/memory/memory.h"
  39. namespace util = firebase::firestore::util;
  40. using firebase::firestore::model::ArrayTransform;
  41. using firebase::firestore::model::DatabaseId;
  42. using firebase::firestore::model::DocumentKey;
  43. using firebase::firestore::model::FieldMask;
  44. using firebase::firestore::model::FieldPath;
  45. using firebase::firestore::model::FieldTransform;
  46. using firebase::firestore::model::Precondition;
  47. using firebase::firestore::model::ServerTimestampTransform;
  48. using firebase::firestore::model::TransformOperation;
  49. NS_ASSUME_NONNULL_BEGIN
  50. static NSString *const RESERVED_FIELD_DESIGNATOR = @"__";
  51. #pragma mark - FSTParsedSetData
  52. @implementation FSTParsedSetData {
  53. FieldMask _fieldMask;
  54. std::vector<FieldTransform> _fieldTransforms;
  55. }
  56. - (instancetype)initWithData:(FSTObjectValue *)data
  57. fieldTransforms:(std::vector<FieldTransform>)fieldTransforms {
  58. self = [super init];
  59. if (self) {
  60. _data = data;
  61. _fieldTransforms = std::move(fieldTransforms);
  62. _isPatch = NO;
  63. }
  64. return self;
  65. }
  66. - (instancetype)initWithData:(FSTObjectValue *)data
  67. fieldMask:(FieldMask)fieldMask
  68. fieldTransforms:(std::vector<FieldTransform>)fieldTransforms {
  69. self = [super init];
  70. if (self) {
  71. _data = data;
  72. _fieldMask = std::move(fieldMask);
  73. _fieldTransforms = std::move(fieldTransforms);
  74. _isPatch = YES;
  75. }
  76. return self;
  77. }
  78. - (const std::vector<FieldTransform> &)fieldTransforms {
  79. return _fieldTransforms;
  80. }
  81. - (NSArray<FSTMutation *> *)mutationsWithKey:(const DocumentKey &)key
  82. precondition:(const Precondition &)precondition {
  83. NSMutableArray<FSTMutation *> *mutations = [NSMutableArray array];
  84. if (self.isPatch) {
  85. [mutations addObject:[[FSTPatchMutation alloc] initWithKey:key
  86. fieldMask:_fieldMask
  87. value:self.data
  88. precondition:precondition]];
  89. } else {
  90. [mutations addObject:[[FSTSetMutation alloc] initWithKey:key
  91. value:self.data
  92. precondition:precondition]];
  93. }
  94. if (!self.fieldTransforms.empty()) {
  95. [mutations addObject:[[FSTTransformMutation alloc] initWithKey:key
  96. fieldTransforms:self.fieldTransforms]];
  97. }
  98. return mutations;
  99. }
  100. @end
  101. #pragma mark - FSTParsedUpdateData
  102. @implementation FSTParsedUpdateData {
  103. FieldMask _fieldMask;
  104. std::vector<FieldTransform> _fieldTransforms;
  105. }
  106. - (instancetype)initWithData:(FSTObjectValue *)data
  107. fieldMask:(FieldMask)fieldMask
  108. fieldTransforms:(std::vector<FieldTransform>)fieldTransforms {
  109. self = [super init];
  110. if (self) {
  111. _data = data;
  112. _fieldMask = std::move(fieldMask);
  113. _fieldTransforms = std::move(fieldTransforms);
  114. }
  115. return self;
  116. }
  117. - (NSArray<FSTMutation *> *)mutationsWithKey:(const DocumentKey &)key
  118. precondition:(const Precondition &)precondition {
  119. NSMutableArray<FSTMutation *> *mutations = [NSMutableArray array];
  120. [mutations addObject:[[FSTPatchMutation alloc] initWithKey:key
  121. fieldMask:self.fieldMask
  122. value:self.data
  123. precondition:precondition]];
  124. if (!self.fieldTransforms.empty()) {
  125. [mutations addObject:[[FSTTransformMutation alloc] initWithKey:key
  126. fieldTransforms:self.fieldTransforms]];
  127. }
  128. return mutations;
  129. }
  130. - (const firebase::firestore::model::FieldMask &)fieldMask {
  131. return _fieldMask;
  132. }
  133. - (const std::vector<FieldTransform> &)fieldTransforms {
  134. return _fieldTransforms;
  135. }
  136. @end
  137. /**
  138. * Represents what type of API method provided the data being parsed; useful for determining which
  139. * error conditions apply during parsing and providing better error messages.
  140. */
  141. typedef NS_ENUM(NSInteger, FSTUserDataSource) {
  142. FSTUserDataSourceSet,
  143. FSTUserDataSourceMergeSet,
  144. FSTUserDataSourceUpdate,
  145. /**
  146. * Indicates the source is a where clause, cursor bound, arrayUnion() element, etc. In particular,
  147. * this will result in [FSTParseContext isWrite] returning NO.
  148. */
  149. FSTUserDataSourceArgument,
  150. };
  151. #pragma mark - FSTParseContext
  152. /**
  153. * A "context" object passed around while parsing user data.
  154. */
  155. @interface FSTParseContext : NSObject
  156. /** Whether or not this context corresponds to an element of an array. */
  157. @property(nonatomic, assign, readonly, getter=isArrayElement) BOOL arrayElement;
  158. /**
  159. * What type of API method provided the data being parsed; useful for determining which error
  160. * conditions apply during parsing and providing better error messages.
  161. */
  162. @property(nonatomic, assign) FSTUserDataSource dataSource;
  163. - (instancetype)init NS_UNAVAILABLE;
  164. /**
  165. * Initializes a FSTParseContext with the given source and path.
  166. *
  167. * @param dataSource Indicates what kind of API method this data came from.
  168. * @param path A path within the object being parsed. This could be an empty path (in which case
  169. * the context represents the root of the data being parsed), or a nonempty path (indicating the
  170. * context represents a nested location within the data).
  171. *
  172. * TODO(b/34871131): We don't support array paths right now, so path can be nullptr to indicate
  173. * the context represents any location within an array (in which case certain features will not work
  174. * and errors will be somewhat compromised).
  175. */
  176. - (instancetype)initWithSource:(FSTUserDataSource)dataSource
  177. path:(std::unique_ptr<FieldPath>)path
  178. arrayElement:(BOOL)arrayElement
  179. fieldTransforms:(std::shared_ptr<std::vector<FieldTransform>>)fieldTransforms
  180. fieldMask:(std::shared_ptr<std::vector<FieldPath>>)fieldMask
  181. NS_DESIGNATED_INITIALIZER;
  182. // Helpers to get a FSTParseContext for a child field.
  183. - (instancetype)contextForField:(NSString *)fieldName;
  184. - (instancetype)contextForFieldPath:(const FieldPath &)fieldPath;
  185. - (instancetype)contextForArrayIndex:(NSUInteger)index;
  186. /** Returns true for the non-query parse contexts (Set, MergeSet and Update) */
  187. - (BOOL)isWrite;
  188. - (const FieldPath *)path;
  189. - (const std::vector<FieldPath> *)fieldMask;
  190. - (void)appendToFieldMaskWithFieldPath:(FieldPath)fieldPath;
  191. - (const std::vector<FieldTransform> *)fieldTransforms;
  192. - (void)appendToFieldTransformsWithFieldPath:(FieldPath)fieldPath
  193. transformOperation:
  194. (std::unique_ptr<TransformOperation>)transformOperation;
  195. @end
  196. @implementation FSTParseContext {
  197. /** The current path being parsed. */
  198. // TODO(b/34871131): path should never be nullptr, but we don't support array paths right now.
  199. std::unique_ptr<FieldPath> _path;
  200. // _fieldMask and _fieldTransforms are shared across all active context objects to accumulate the
  201. // result. For example, the result of calling any of contextForField, contextForFieldPath and
  202. // contextForArrayIndex shares the ownership of _fieldMask and _fieldTransforms.
  203. std::shared_ptr<std::vector<FieldPath>> _fieldMask;
  204. std::shared_ptr<std::vector<FieldTransform>> _fieldTransforms;
  205. }
  206. + (instancetype)contextWithSource:(FSTUserDataSource)dataSource
  207. path:(std::unique_ptr<FieldPath>)path {
  208. FSTParseContext *context =
  209. [[FSTParseContext alloc] initWithSource:dataSource
  210. path:std::move(path)
  211. arrayElement:NO
  212. fieldTransforms:std::make_shared<std::vector<FieldTransform>>()
  213. fieldMask:std::make_shared<std::vector<FieldPath>>()];
  214. [context validatePath];
  215. return context;
  216. }
  217. - (instancetype)initWithSource:(FSTUserDataSource)dataSource
  218. path:(std::unique_ptr<FieldPath>)path
  219. arrayElement:(BOOL)arrayElement
  220. fieldTransforms:(std::shared_ptr<std::vector<FieldTransform>>)fieldTransforms
  221. fieldMask:(std::shared_ptr<std::vector<FieldPath>>)fieldMask {
  222. if (self = [super init]) {
  223. _dataSource = dataSource;
  224. _path = std::move(path);
  225. _arrayElement = arrayElement;
  226. _fieldTransforms = std::move(fieldTransforms);
  227. _fieldMask = std::move(fieldMask);
  228. }
  229. return self;
  230. }
  231. - (instancetype)contextForField:(NSString *)fieldName {
  232. std::unique_ptr<FieldPath> path;
  233. if (_path) {
  234. path = absl::make_unique<FieldPath>(_path->Append(util::MakeString(fieldName)));
  235. }
  236. FSTParseContext *context = [[FSTParseContext alloc] initWithSource:self.dataSource
  237. path:std::move(path)
  238. arrayElement:NO
  239. fieldTransforms:_fieldTransforms
  240. fieldMask:_fieldMask];
  241. [context validatePathSegment:fieldName];
  242. return context;
  243. }
  244. - (instancetype)contextForFieldPath:(const FieldPath &)fieldPath {
  245. std::unique_ptr<FieldPath> path;
  246. if (_path) {
  247. path = absl::make_unique<FieldPath>(_path->Append(fieldPath));
  248. }
  249. FSTParseContext *context = [[FSTParseContext alloc] initWithSource:self.dataSource
  250. path:std::move(path)
  251. arrayElement:NO
  252. fieldTransforms:_fieldTransforms
  253. fieldMask:_fieldMask];
  254. [context validatePath];
  255. return context;
  256. }
  257. - (instancetype)contextForArrayIndex:(NSUInteger)index {
  258. // TODO(b/34871131): We don't support array paths right now; so make path nil.
  259. return [[FSTParseContext alloc] initWithSource:self.dataSource
  260. path:nil
  261. arrayElement:YES
  262. fieldTransforms:_fieldTransforms
  263. fieldMask:_fieldMask];
  264. }
  265. /**
  266. * Returns a string that can be appended to error messages indicating what field caused the error.
  267. */
  268. - (NSString *)fieldDescription {
  269. // TODO(b/34871131): Remove nil check once we have proper paths for fields within arrays.
  270. if (!_path || _path->empty()) {
  271. return @"";
  272. } else {
  273. return [NSString stringWithFormat:@" (found in field %s)", _path->CanonicalString().c_str()];
  274. }
  275. }
  276. - (BOOL)isWrite {
  277. switch (self.dataSource) {
  278. case FSTUserDataSourceSet: // Falls through.
  279. case FSTUserDataSourceMergeSet: // Falls through.
  280. case FSTUserDataSourceUpdate:
  281. return YES;
  282. case FSTUserDataSourceArgument:
  283. return NO;
  284. default:
  285. FSTThrowInvalidArgument(@"Unexpected case for FSTUserDataSource: %d", self.dataSource);
  286. }
  287. }
  288. - (void)validatePath {
  289. // TODO(b/34871131): Remove nil check once we have proper paths for fields within arrays.
  290. if (_path == nullptr) {
  291. return;
  292. }
  293. for (const auto &segment : *_path) {
  294. [self validatePathSegment:util::WrapNSStringNoCopy(segment)];
  295. }
  296. }
  297. - (void)validatePathSegment:(NSString *)segment {
  298. if ([self isWrite] && [segment hasPrefix:RESERVED_FIELD_DESIGNATOR] &&
  299. [segment hasSuffix:RESERVED_FIELD_DESIGNATOR]) {
  300. FSTThrowInvalidArgument(@"Document fields cannot begin and end with %@%@",
  301. RESERVED_FIELD_DESIGNATOR, [self fieldDescription]);
  302. }
  303. }
  304. - (const FieldPath *)path {
  305. return _path.get();
  306. }
  307. - (const std::vector<FieldPath> *)fieldMask {
  308. return _fieldMask.get();
  309. }
  310. - (void)appendToFieldMaskWithFieldPath:(FieldPath)fieldPath {
  311. _fieldMask->push_back(std::move(fieldPath));
  312. }
  313. - (const std::vector<FieldTransform> *)fieldTransforms {
  314. return _fieldTransforms.get();
  315. }
  316. - (void)appendToFieldTransformsWithFieldPath:(FieldPath)fieldPath
  317. transformOperation:
  318. (std::unique_ptr<TransformOperation>)transformOperation {
  319. _fieldTransforms->emplace_back(std::move(fieldPath), std::move(transformOperation));
  320. }
  321. @end
  322. #pragma mark - FSTDocumentKeyReference
  323. @implementation FSTDocumentKeyReference {
  324. DocumentKey _key;
  325. }
  326. - (instancetype)initWithKey:(DocumentKey)key databaseID:(const DatabaseId *)databaseID {
  327. self = [super init];
  328. if (self) {
  329. _key = std::move(key);
  330. _databaseID = databaseID;
  331. }
  332. return self;
  333. }
  334. - (const firebase::firestore::model::DocumentKey &)key {
  335. return _key;
  336. }
  337. @end
  338. #pragma mark - FSTUserDataConverter
  339. @interface FSTUserDataConverter ()
  340. // Does not own the DatabaseId instance.
  341. @property(assign, nonatomic, readonly) const DatabaseId *databaseID;
  342. @property(strong, nonatomic, readonly) FSTPreConverterBlock preConverter;
  343. @end
  344. @implementation FSTUserDataConverter
  345. - (instancetype)initWithDatabaseID:(const DatabaseId *)databaseID
  346. preConverter:(FSTPreConverterBlock)preConverter {
  347. self = [super init];
  348. if (self) {
  349. _databaseID = databaseID;
  350. _preConverter = preConverter;
  351. }
  352. return self;
  353. }
  354. - (FSTParsedSetData *)parsedMergeData:(id)input fieldMask:(nullable NSArray<id> *)fieldMask {
  355. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  356. // Obj-C to verify the type for us.
  357. if (![input isKindOfClass:[NSDictionary class]]) {
  358. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  359. }
  360. FSTParseContext *context =
  361. [FSTParseContext contextWithSource:FSTUserDataSourceMergeSet
  362. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  363. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input context:context];
  364. FieldMask convertedFieldMask;
  365. std::vector<FieldTransform> convertedFieldTransform;
  366. if (fieldMask) {
  367. __block std::vector<FieldPath> fieldMaskPaths;
  368. [fieldMask enumerateObjectsUsingBlock:^(id fieldPath, NSUInteger idx, BOOL *stop) {
  369. FieldPath path;
  370. if ([fieldPath isKindOfClass:[NSString class]]) {
  371. path = [FIRFieldPath pathWithDotSeparatedString:fieldPath].internalValue;
  372. } else if ([fieldPath isKindOfClass:[FIRFieldPath class]]) {
  373. path = ((FIRFieldPath *)fieldPath).internalValue;
  374. } else {
  375. FSTThrowInvalidArgument(
  376. @"All elements in mergeFields: must be NSStrings or FIRFieldPaths.");
  377. }
  378. if ([updateData valueForPath:path] == nil) {
  379. FSTThrowInvalidArgument(
  380. @"Field '%s' is specified in your field mask but missing from your input data.",
  381. path.CanonicalString().c_str());
  382. }
  383. fieldMaskPaths.push_back(path);
  384. }];
  385. convertedFieldMask = FieldMask(fieldMaskPaths);
  386. std::copy_if(context.fieldTransforms->begin(), context.fieldTransforms->end(),
  387. std::back_inserter(convertedFieldTransform),
  388. [&](const FieldTransform &fieldTransform) {
  389. return convertedFieldMask.covers(fieldTransform.path());
  390. });
  391. } else {
  392. convertedFieldMask = FieldMask{*context.fieldMask};
  393. convertedFieldTransform = *context.fieldTransforms;
  394. }
  395. return [[FSTParsedSetData alloc] initWithData:updateData
  396. fieldMask:convertedFieldMask
  397. fieldTransforms:convertedFieldTransform];
  398. }
  399. - (FSTParsedSetData *)parsedSetData:(id)input {
  400. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  401. // Obj-C to verify the type for us.
  402. if (![input isKindOfClass:[NSDictionary class]]) {
  403. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  404. }
  405. FSTParseContext *context =
  406. [FSTParseContext contextWithSource:FSTUserDataSourceSet
  407. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  408. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input context:context];
  409. return
  410. [[FSTParsedSetData alloc] initWithData:updateData fieldTransforms:*context.fieldTransforms];
  411. }
  412. - (FSTParsedUpdateData *)parsedUpdateData:(id)input {
  413. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  414. // Obj-C to verify the type for us.
  415. if (![input isKindOfClass:[NSDictionary class]]) {
  416. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  417. }
  418. NSDictionary *dict = input;
  419. __block std::vector<FieldPath> fieldMaskPaths;
  420. __block FSTObjectValue *updateData = [FSTObjectValue objectValue];
  421. FSTParseContext *context =
  422. [FSTParseContext contextWithSource:FSTUserDataSourceUpdate
  423. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  424. [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
  425. FieldPath path;
  426. if ([key isKindOfClass:[NSString class]]) {
  427. path = [FIRFieldPath pathWithDotSeparatedString:key].internalValue;
  428. } else if ([key isKindOfClass:[FIRFieldPath class]]) {
  429. path = ((FIRFieldPath *)key).internalValue;
  430. } else {
  431. FSTThrowInvalidArgument(
  432. @"Dictionary keys in updateData: must be NSStrings or FIRFieldPaths.");
  433. }
  434. value = self.preConverter(value);
  435. if ([value isKindOfClass:[FSTDeleteFieldValue class]]) {
  436. // Add it to the field mask, but don't add anything to updateData.
  437. fieldMaskPaths.push_back(path);
  438. } else {
  439. FSTFieldValue *_Nullable parsedValue =
  440. [self parseData:value context:[context contextForFieldPath:path]];
  441. if (parsedValue) {
  442. fieldMaskPaths.push_back(path);
  443. updateData = [updateData objectBySettingValue:parsedValue forPath:path];
  444. }
  445. }
  446. }];
  447. return [[FSTParsedUpdateData alloc] initWithData:updateData
  448. fieldMask:FieldMask{fieldMaskPaths}
  449. fieldTransforms:*context.fieldTransforms];
  450. }
  451. - (FSTFieldValue *)parsedQueryValue:(id)input {
  452. FSTParseContext *context =
  453. [FSTParseContext contextWithSource:FSTUserDataSourceArgument
  454. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  455. FSTFieldValue *_Nullable parsed = [self parseData:input context:context];
  456. HARD_ASSERT(parsed, "Parsed data should not be nil.");
  457. HARD_ASSERT(context.fieldTransforms->empty(), "Field transforms should have been disallowed.");
  458. return parsed;
  459. }
  460. /**
  461. * Internal helper for parsing user data.
  462. *
  463. * @param input Data to be parsed.
  464. * @param context A context object representing the current path being parsed, the source of the
  465. * data being parsed, etc.
  466. *
  467. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  468. * included in the resulting parsed data.
  469. */
  470. - (nullable FSTFieldValue *)parseData:(id)input context:(FSTParseContext *)context {
  471. input = self.preConverter(input);
  472. if ([input isKindOfClass:[NSDictionary class]]) {
  473. return [self parseDictionary:(NSDictionary *)input context:context];
  474. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  475. // FieldValues usually parse into transforms (except FieldValue.delete()) in which case we
  476. // do not want to include this field in our parsed data (as doing so will overwrite the field
  477. // directly prior to the transform trying to transform it). So we don't call appendToFieldMask
  478. // and we return nil as our parsing result.
  479. [self parseSentinelFieldValue:(FIRFieldValue *)input context:context];
  480. return nil;
  481. } else {
  482. // If context.path is nil we are already inside an array and we don't support field mask paths
  483. // more granular than the top-level array.
  484. if (context.path) {
  485. [context appendToFieldMaskWithFieldPath:*context.path];
  486. }
  487. if ([input isKindOfClass:[NSArray class]]) {
  488. // TODO(b/34871131): Include the path containing the array in the error message.
  489. if (context.isArrayElement) {
  490. FSTThrowInvalidArgument(@"Nested arrays are not supported");
  491. }
  492. return [self parseArray:(NSArray *)input context:context];
  493. } else {
  494. return [self parseScalarValue:input context:context];
  495. }
  496. }
  497. }
  498. - (FSTFieldValue *)parseDictionary:(NSDictionary *)dict context:(FSTParseContext *)context {
  499. NSMutableDictionary<NSString *, FSTFieldValue *> *result =
  500. [NSMutableDictionary dictionaryWithCapacity:dict.count];
  501. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  502. FSTFieldValue *_Nullable parsedValue =
  503. [self parseData:value context:[context contextForField:key]];
  504. if (parsedValue) {
  505. result[key] = parsedValue;
  506. }
  507. }];
  508. return [[FSTObjectValue alloc] initWithDictionary:result];
  509. }
  510. - (FSTFieldValue *)parseArray:(NSArray *)array context:(FSTParseContext *)context {
  511. NSMutableArray<FSTFieldValue *> *result = [NSMutableArray arrayWithCapacity:array.count];
  512. [array enumerateObjectsUsingBlock:^(id entry, NSUInteger idx, BOOL *stop) {
  513. FSTFieldValue *_Nullable parsedEntry =
  514. [self parseData:entry context:[context contextForArrayIndex:idx]];
  515. if (!parsedEntry) {
  516. // Just include nulls in the array for fields being replaced with a sentinel.
  517. parsedEntry = [FSTNullValue nullValue];
  518. }
  519. [result addObject:parsedEntry];
  520. }];
  521. return [[FSTArrayValue alloc] initWithValueNoCopy:result];
  522. }
  523. /**
  524. * "Parses" the provided FIRFieldValue, adding any necessary transforms to
  525. * context.fieldTransforms.
  526. */
  527. - (void)parseSentinelFieldValue:(FIRFieldValue *)fieldValue context:(FSTParseContext *)context {
  528. // Sentinels are only supported with writes, and not within arrays.
  529. if (![context isWrite]) {
  530. FSTThrowInvalidArgument(@"%@ can only be used with updateData() and setData()%@",
  531. fieldValue.methodName, [context fieldDescription]);
  532. }
  533. if (!context.path) {
  534. FSTThrowInvalidArgument(@"%@ is not currently supported inside arrays", fieldValue.methodName);
  535. }
  536. if ([fieldValue isKindOfClass:[FSTDeleteFieldValue class]]) {
  537. if (context.dataSource == FSTUserDataSourceMergeSet) {
  538. // No transform to add for a delete, but we need to add it to our fieldMask so it gets
  539. // deleted.
  540. [context appendToFieldMaskWithFieldPath:*context.path];
  541. } else if (context.dataSource == FSTUserDataSourceUpdate) {
  542. HARD_ASSERT(context.path->size() > 0,
  543. "FieldValue.delete() at the top level should have already been handled.");
  544. FSTThrowInvalidArgument(
  545. @"FieldValue.delete() can only appear at the top level of your "
  546. "update data%@",
  547. [context fieldDescription]);
  548. } else {
  549. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  550. FSTThrowInvalidArgument(
  551. @"FieldValue.delete() can only be used with updateData() and setData() with "
  552. @"merge:true%@",
  553. [context fieldDescription]);
  554. }
  555. } else if ([fieldValue isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  556. [context appendToFieldTransformsWithFieldPath:*context.path
  557. transformOperation:absl::make_unique<ServerTimestampTransform>(
  558. ServerTimestampTransform::Get())];
  559. } else if ([fieldValue isKindOfClass:[FSTArrayUnionFieldValue class]]) {
  560. std::vector<FSTFieldValue *> parsedElements =
  561. [self parseArrayTransformElements:((FSTArrayUnionFieldValue *)fieldValue).elements];
  562. auto array_union = absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayUnion,
  563. std::move(parsedElements));
  564. [context appendToFieldTransformsWithFieldPath:*context.path
  565. transformOperation:std::move(array_union)];
  566. } else if ([fieldValue isKindOfClass:[FSTArrayRemoveFieldValue class]]) {
  567. std::vector<FSTFieldValue *> parsedElements =
  568. [self parseArrayTransformElements:((FSTArrayRemoveFieldValue *)fieldValue).elements];
  569. auto array_remove = absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayRemove,
  570. std::move(parsedElements));
  571. [context appendToFieldTransformsWithFieldPath:*context.path
  572. transformOperation:std::move(array_remove)];
  573. } else {
  574. HARD_FAIL("Unknown FIRFieldValue type: %s", NSStringFromClass([fieldValue class]));
  575. }
  576. }
  577. /**
  578. * Helper to parse a scalar value (i.e. not an NSDictionary, NSArray, or FIRFieldValue).
  579. *
  580. * Note that it handles all NSNumber values that are encodable as int64_t or doubles
  581. * (depending on the underlying type of the NSNumber). Unsigned integer values are handled though
  582. * any value outside what is representable by int64_t (a signed 64-bit value) will throw an
  583. * exception.
  584. *
  585. * @return The parsed value.
  586. */
  587. - (FSTFieldValue *)parseScalarValue:(nullable id)input context:(FSTParseContext *)context {
  588. if (!input || [input isMemberOfClass:[NSNull class]]) {
  589. return [FSTNullValue nullValue];
  590. } else if ([input isKindOfClass:[NSNumber class]]) {
  591. // Recover the underlying type of the number, using the method described here:
  592. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  593. const char *cType = [input objCType];
  594. // Type Encoding values taken from
  595. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  596. // Articles/ocrtTypeEncodings.html
  597. switch (cType[0]) {
  598. case 'q':
  599. return [FSTIntegerValue integerValue:[input longLongValue]];
  600. case 'i': // Falls through.
  601. case 's': // Falls through.
  602. case 'l': // Falls through.
  603. case 'I': // Falls through.
  604. case 'S':
  605. // Coerce integer values that aren't long long. Allow unsigned integer types that are
  606. // guaranteed small enough to skip a length check.
  607. return [FSTIntegerValue integerValue:[input longLongValue]];
  608. case 'L': // Falls through.
  609. case 'Q':
  610. // Unsigned integers that could be too large. Note that the 'L' (long) case is handled here
  611. // because when compiled for LP64, unsigned long is 64 bits and could overflow int64_t.
  612. {
  613. unsigned long long extended = [input unsignedLongLongValue];
  614. if (extended > LLONG_MAX) {
  615. FSTThrowInvalidArgument(@"NSNumber (%llu) is too large%@",
  616. [input unsignedLongLongValue], [context fieldDescription]);
  617. } else {
  618. return [FSTIntegerValue integerValue:(int64_t)extended];
  619. }
  620. }
  621. case 'f':
  622. return [FSTDoubleValue doubleValue:[input doubleValue]];
  623. case 'd':
  624. // Double values are already the right type, so just reuse the existing boxed double.
  625. //
  626. // Note that NSNumber already performs NaN normalization to a single shared instance
  627. // so there's no need to treat NaN specially here.
  628. return [FSTDoubleValue doubleValue:[input doubleValue]];
  629. case 'B': // Falls through.
  630. case 'c': // Falls through.
  631. case 'C':
  632. // Boolean values are weird.
  633. //
  634. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  635. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  636. // legitimate usage of signed chars is impossible, but this should be rare.
  637. //
  638. // Additionally, for consistency, map unsigned chars to bools in the same way.
  639. return [FSTBooleanValue booleanValue:[input boolValue]];
  640. default:
  641. // All documented codes should be handled above, so this shouldn't happen.
  642. HARD_FAIL("Unknown NSNumber objCType %s on %s", cType, input);
  643. }
  644. } else if ([input isKindOfClass:[NSString class]]) {
  645. return [FSTStringValue stringValue:input];
  646. } else if ([input isKindOfClass:[NSDate class]]) {
  647. return [FSTTimestampValue timestampValue:[FIRTimestamp timestampWithDate:input]];
  648. } else if ([input isKindOfClass:[FIRTimestamp class]]) {
  649. FIRTimestamp *originalTimestamp = (FIRTimestamp *)input;
  650. FIRTimestamp *truncatedTimestamp =
  651. [FIRTimestamp timestampWithSeconds:originalTimestamp.seconds
  652. nanoseconds:originalTimestamp.nanoseconds / 1000 * 1000];
  653. return [FSTTimestampValue timestampValue:truncatedTimestamp];
  654. } else if ([input isKindOfClass:[FIRGeoPoint class]]) {
  655. return [FSTGeoPointValue geoPointValue:input];
  656. } else if ([input isKindOfClass:[NSData class]]) {
  657. return [FSTBlobValue blobValue:input];
  658. } else if ([input isKindOfClass:[FSTDocumentKeyReference class]]) {
  659. FSTDocumentKeyReference *reference = input;
  660. if (*reference.databaseID != *self.databaseID) {
  661. const DatabaseId *other = reference.databaseID;
  662. FSTThrowInvalidArgument(
  663. @"Document Reference is for database %s/%s but should be for database %s/%s%@",
  664. other->project_id().c_str(), other->database_id().c_str(),
  665. self.databaseID->project_id().c_str(), self.databaseID->database_id().c_str(),
  666. [context fieldDescription]);
  667. }
  668. return [FSTReferenceValue referenceValue:reference.key databaseID:self.databaseID];
  669. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  670. if ([input isKindOfClass:[FSTDeleteFieldValue class]]) {
  671. if (context.dataSource == FSTUserDataSourceMergeSet) {
  672. return nil;
  673. } else if (context.dataSource == FSTUserDataSourceUpdate) {
  674. HARD_ASSERT(context.path->size() > 0,
  675. "FieldValue.delete() at the top level should have already been handled.");
  676. FSTThrowInvalidArgument(
  677. @"FieldValue.delete() can only appear at the top level of your update data%@",
  678. [context fieldDescription]);
  679. } else {
  680. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  681. FSTThrowInvalidArgument(
  682. @"FieldValue.delete() can only be used with updateData() and setData() with "
  683. @"merge: true.");
  684. }
  685. } else if ([input isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  686. if (![context isWrite]) {
  687. FSTThrowInvalidArgument(
  688. @"FieldValue.serverTimestamp() can only be used with setData() and updateData().");
  689. }
  690. if (!context.path) {
  691. FSTThrowInvalidArgument(
  692. @"FieldValue.serverTimestamp() is not currently supported inside arrays%@",
  693. [context fieldDescription]);
  694. }
  695. [context appendToFieldTransformsWithFieldPath:*context.path
  696. transformOperation:absl::make_unique<ServerTimestampTransform>(
  697. ServerTimestampTransform::Get())];
  698. // Return nil so this value is omitted from the parsed result.
  699. return nil;
  700. } else {
  701. HARD_FAIL("Unknown FIRFieldValue type: %s", NSStringFromClass([input class]));
  702. }
  703. } else {
  704. FSTThrowInvalidArgument(@"Unsupported type: %@%@", NSStringFromClass([input class]),
  705. [context fieldDescription]);
  706. }
  707. }
  708. - (std::vector<FSTFieldValue *>)parseArrayTransformElements:(NSArray<id> *)elements {
  709. std::vector<FSTFieldValue *> results;
  710. for (NSUInteger i = 0; i < elements.count; i++) {
  711. id element = elements[i];
  712. // Although array transforms are used with writes, the actual elements being unioned or removed
  713. // are not considered writes since they cannot contain any FieldValue sentinels, etc.
  714. FSTParseContext *context =
  715. [FSTParseContext contextWithSource:FSTUserDataSourceArgument
  716. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  717. FSTFieldValue *parsedElement =
  718. [self parseData:element context:[context contextForArrayIndex:i]];
  719. HARD_ASSERT(parsedElement && context.fieldTransforms->size() == 0,
  720. "Failed to properly parse array transform element: %s", element);
  721. results.push_back(parsedElement);
  722. }
  723. return results;
  724. }
  725. @end
  726. NS_ASSUME_NONNULL_END