FSTUserDataConverter.mm 34 KB

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