FSTSerializerBeta.mm 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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/Remote/FSTSerializerBeta.h"
  17. #include <inttypes.h>
  18. #import <GRPCClient/GRPCCall.h>
  19. #import "FIRTimestamp.h"
  20. #import "Firestore/Protos/objc/google/firestore/v1beta1/Common.pbobjc.h"
  21. #import "Firestore/Protos/objc/google/firestore/v1beta1/Document.pbobjc.h"
  22. #import "Firestore/Protos/objc/google/firestore/v1beta1/Firestore.pbobjc.h"
  23. #import "Firestore/Protos/objc/google/firestore/v1beta1/Query.pbobjc.h"
  24. #import "Firestore/Protos/objc/google/firestore/v1beta1/Write.pbobjc.h"
  25. #import "Firestore/Protos/objc/google/rpc/Status.pbobjc.h"
  26. #import "Firestore/Protos/objc/google/type/Latlng.pbobjc.h"
  27. #import "FIRFirestoreErrors.h"
  28. #import "FIRGeoPoint.h"
  29. #import "Firestore/Source/Core/FSTQuery.h"
  30. #import "Firestore/Source/Core/FSTSnapshotVersion.h"
  31. #import "Firestore/Source/Local/FSTQueryData.h"
  32. #import "Firestore/Source/Model/FSTDocument.h"
  33. #import "Firestore/Source/Model/FSTDocumentKey.h"
  34. #import "Firestore/Source/Model/FSTFieldValue.h"
  35. #import "Firestore/Source/Model/FSTMutation.h"
  36. #import "Firestore/Source/Model/FSTMutationBatch.h"
  37. #import "Firestore/Source/Remote/FSTExistenceFilter.h"
  38. #import "Firestore/Source/Remote/FSTWatchChange.h"
  39. #import "Firestore/Source/Util/FSTAssert.h"
  40. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  41. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  42. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  43. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  44. namespace util = firebase::firestore::util;
  45. using firebase::firestore::model::DatabaseId;
  46. using firebase::firestore::model::FieldPath;
  47. using firebase::firestore::model::ResourcePath;
  48. NS_ASSUME_NONNULL_BEGIN
  49. @interface FSTSerializerBeta ()
  50. // Does not own this DatabaseId.
  51. @property(nonatomic, assign, readonly) const DatabaseId *databaseID;
  52. @end
  53. @implementation FSTSerializerBeta
  54. - (instancetype)initWithDatabaseID:(const DatabaseId *)databaseID {
  55. self = [super init];
  56. if (self) {
  57. _databaseID = databaseID;
  58. }
  59. return self;
  60. }
  61. #pragma mark - FSTSnapshotVersion <=> GPBTimestamp
  62. - (GPBTimestamp *)encodedTimestamp:(FIRTimestamp *)timestamp {
  63. GPBTimestamp *result = [GPBTimestamp message];
  64. result.seconds = timestamp.seconds;
  65. result.nanos = timestamp.nanoseconds;
  66. return result;
  67. }
  68. - (FIRTimestamp *)decodedTimestamp:(GPBTimestamp *)timestamp {
  69. return [[FIRTimestamp alloc] initWithSeconds:timestamp.seconds nanoseconds:timestamp.nanos];
  70. }
  71. - (GPBTimestamp *)encodedVersion:(FSTSnapshotVersion *)version {
  72. return [self encodedTimestamp:version.timestamp];
  73. }
  74. - (FSTSnapshotVersion *)decodedVersion:(GPBTimestamp *)version {
  75. return [FSTSnapshotVersion versionWithTimestamp:[self decodedTimestamp:version]];
  76. }
  77. #pragma mark - FIRGeoPoint <=> GTPLatLng
  78. - (GTPLatLng *)encodedGeoPoint:(FIRGeoPoint *)geoPoint {
  79. GTPLatLng *latLng = [GTPLatLng message];
  80. latLng.latitude = geoPoint.latitude;
  81. latLng.longitude = geoPoint.longitude;
  82. return latLng;
  83. }
  84. - (FIRGeoPoint *)decodedGeoPoint:(GTPLatLng *)latLng {
  85. return [[FIRGeoPoint alloc] initWithLatitude:latLng.latitude longitude:latLng.longitude];
  86. }
  87. #pragma mark - FSTDocumentKey <=> Key proto
  88. - (NSString *)encodedDocumentKey:(FSTDocumentKey *)key {
  89. return [self encodedResourcePathForDatabaseID:self.databaseID path:key.path];
  90. }
  91. - (FSTDocumentKey *)decodedDocumentKey:(NSString *)name {
  92. const ResourcePath path = [self decodedResourcePathWithDatabaseID:name];
  93. FSTAssert(path[1] == self.databaseID->project_id(),
  94. @"Tried to deserialize key from different project.");
  95. FSTAssert(path[3] == self.databaseID->database_id(),
  96. @"Tried to deserialize key from different datbase.");
  97. return [FSTDocumentKey keyWithPath:[self localResourcePathForQualifiedResourcePath:path]];
  98. }
  99. - (NSString *)encodedResourcePathForDatabaseID:(const DatabaseId *)databaseID
  100. path:(const ResourcePath &)path {
  101. return util::WrapNSString([self encodedResourcePathForDatabaseID:databaseID]
  102. .Append("documents")
  103. .Append(path)
  104. .CanonicalString());
  105. }
  106. - (ResourcePath)decodedResourcePathWithDatabaseID:(NSString *)name {
  107. const ResourcePath path = ResourcePath::FromString(util::MakeStringView(name));
  108. FSTAssert([self validQualifiedResourcePath:path], @"Tried to deserialize invalid key %s",
  109. path.CanonicalString().c_str());
  110. return path;
  111. }
  112. - (NSString *)encodedQueryPath:(const ResourcePath &)path {
  113. if (path.size() == 0) {
  114. // If the path is empty, the backend requires we leave off the /documents at the end.
  115. return [self encodedDatabaseID];
  116. }
  117. return [self encodedResourcePathForDatabaseID:self.databaseID path:path];
  118. }
  119. - (ResourcePath)decodedQueryPath:(NSString *)name {
  120. const ResourcePath resource = [self decodedResourcePathWithDatabaseID:name];
  121. if (resource.size() == 4) {
  122. return ResourcePath{};
  123. } else {
  124. return [self localResourcePathForQualifiedResourcePath:resource];
  125. }
  126. }
  127. - (ResourcePath)encodedResourcePathForDatabaseID:(const DatabaseId *)databaseID {
  128. return ResourcePath{"projects", databaseID->project_id(), "databases", databaseID->database_id()};
  129. }
  130. - (ResourcePath)localResourcePathForQualifiedResourcePath:(const ResourcePath &)resourceName {
  131. FSTAssert(resourceName.size() > 4 && resourceName[4] == "documents",
  132. @"Tried to deserialize invalid key %s", resourceName.CanonicalString().c_str());
  133. return resourceName.PopFirst(5);
  134. }
  135. - (BOOL)validQualifiedResourcePath:(const ResourcePath &)path {
  136. return path.size() >= 4 && path[0] == "projects" && path[2] == "databases";
  137. }
  138. - (NSString *)encodedDatabaseID {
  139. return util::WrapNSString(
  140. [self encodedResourcePathForDatabaseID:self.databaseID].CanonicalString());
  141. }
  142. #pragma mark - FSTFieldValue <=> Value proto
  143. - (GCFSValue *)encodedFieldValue:(FSTFieldValue *)fieldValue {
  144. Class fieldClass = [fieldValue class];
  145. if (fieldClass == [FSTNullValue class]) {
  146. return [self encodedNull];
  147. } else if (fieldClass == [FSTBooleanValue class]) {
  148. return [self encodedBool:[[fieldValue value] boolValue]];
  149. } else if (fieldClass == [FSTIntegerValue class]) {
  150. return [self encodedInteger:[[fieldValue value] longLongValue]];
  151. } else if (fieldClass == [FSTDoubleValue class]) {
  152. return [self encodedDouble:[[fieldValue value] doubleValue]];
  153. } else if (fieldClass == [FSTStringValue class]) {
  154. return [self encodedString:[fieldValue value]];
  155. } else if (fieldClass == [FSTTimestampValue class]) {
  156. return [self encodedTimestampValue:((FSTTimestampValue *)fieldValue).internalValue];
  157. } else if (fieldClass == [FSTGeoPointValue class]) {
  158. return [self encodedGeoPointValue:[fieldValue value]];
  159. } else if (fieldClass == [FSTBlobValue class]) {
  160. return [self encodedBlobValue:[fieldValue value]];
  161. } else if (fieldClass == [FSTReferenceValue class]) {
  162. FSTReferenceValue *ref = (FSTReferenceValue *)fieldValue;
  163. return [self encodedReferenceValueForDatabaseID:[ref databaseID] key:[ref value]];
  164. } else if (fieldClass == [FSTObjectValue class]) {
  165. GCFSValue *result = [GCFSValue message];
  166. result.mapValue = [self encodedMapValue:(FSTObjectValue *)fieldValue];
  167. return result;
  168. } else if (fieldClass == [FSTArrayValue class]) {
  169. GCFSValue *result = [GCFSValue message];
  170. result.arrayValue = [self encodedArrayValue:(FSTArrayValue *)fieldValue];
  171. return result;
  172. } else {
  173. FSTFail(@"Unhandled type %@ on %@", NSStringFromClass([fieldValue class]), fieldValue);
  174. }
  175. }
  176. - (FSTFieldValue *)decodedFieldValue:(GCFSValue *)valueProto {
  177. switch (valueProto.valueTypeOneOfCase) {
  178. case GCFSValue_ValueType_OneOfCase_NullValue:
  179. return [FSTNullValue nullValue];
  180. case GCFSValue_ValueType_OneOfCase_BooleanValue:
  181. return [FSTBooleanValue booleanValue:valueProto.booleanValue];
  182. case GCFSValue_ValueType_OneOfCase_IntegerValue:
  183. return [FSTIntegerValue integerValue:valueProto.integerValue];
  184. case GCFSValue_ValueType_OneOfCase_DoubleValue:
  185. return [FSTDoubleValue doubleValue:valueProto.doubleValue];
  186. case GCFSValue_ValueType_OneOfCase_StringValue:
  187. return [FSTStringValue stringValue:valueProto.stringValue];
  188. case GCFSValue_ValueType_OneOfCase_TimestampValue:
  189. return [FSTTimestampValue timestampValue:[self decodedTimestamp:valueProto.timestampValue]];
  190. case GCFSValue_ValueType_OneOfCase_GeoPointValue:
  191. return [FSTGeoPointValue geoPointValue:[self decodedGeoPoint:valueProto.geoPointValue]];
  192. case GCFSValue_ValueType_OneOfCase_BytesValue:
  193. return [FSTBlobValue blobValue:valueProto.bytesValue];
  194. case GCFSValue_ValueType_OneOfCase_ReferenceValue:
  195. return [self decodedReferenceValue:valueProto.referenceValue];
  196. case GCFSValue_ValueType_OneOfCase_ArrayValue:
  197. return [self decodedArrayValue:valueProto.arrayValue];
  198. case GCFSValue_ValueType_OneOfCase_MapValue:
  199. return [self decodedMapValue:valueProto.mapValue];
  200. default:
  201. FSTFail(@"Unhandled type %d on %@", valueProto.valueTypeOneOfCase, valueProto);
  202. }
  203. }
  204. - (GCFSValue *)encodedNull {
  205. GCFSValue *result = [GCFSValue message];
  206. result.nullValue = GPBNullValue_NullValue;
  207. return result;
  208. }
  209. - (GCFSValue *)encodedBool:(BOOL)value {
  210. GCFSValue *result = [GCFSValue message];
  211. result.booleanValue = value;
  212. return result;
  213. }
  214. - (GCFSValue *)encodedDouble:(double)value {
  215. GCFSValue *result = [GCFSValue message];
  216. result.doubleValue = value;
  217. return result;
  218. }
  219. - (GCFSValue *)encodedInteger:(int64_t)value {
  220. GCFSValue *result = [GCFSValue message];
  221. result.integerValue = value;
  222. return result;
  223. }
  224. - (GCFSValue *)encodedString:(NSString *)value {
  225. GCFSValue *result = [GCFSValue message];
  226. result.stringValue = value;
  227. return result;
  228. }
  229. - (GCFSValue *)encodedTimestampValue:(FIRTimestamp *)value {
  230. GCFSValue *result = [GCFSValue message];
  231. result.timestampValue = [self encodedTimestamp:value];
  232. return result;
  233. }
  234. - (GCFSValue *)encodedGeoPointValue:(FIRGeoPoint *)value {
  235. GCFSValue *result = [GCFSValue message];
  236. result.geoPointValue = [self encodedGeoPoint:value];
  237. return result;
  238. }
  239. - (GCFSValue *)encodedBlobValue:(NSData *)value {
  240. GCFSValue *result = [GCFSValue message];
  241. result.bytesValue = value;
  242. return result;
  243. }
  244. - (GCFSValue *)encodedReferenceValueForDatabaseID:(const DatabaseId *)databaseID
  245. key:(FSTDocumentKey *)key {
  246. FSTAssert(*databaseID == *self.databaseID, @"Database %s:%s cannot encode reference from %s:%s",
  247. self.databaseID->project_id().c_str(), self.databaseID->database_id().c_str(),
  248. databaseID->project_id().c_str(), databaseID->database_id().c_str());
  249. GCFSValue *result = [GCFSValue message];
  250. result.referenceValue = [self encodedResourcePathForDatabaseID:databaseID path:key.path];
  251. return result;
  252. }
  253. - (FSTReferenceValue *)decodedReferenceValue:(NSString *)resourceName {
  254. const ResourcePath path = [self decodedResourcePathWithDatabaseID:resourceName];
  255. const std::string &project = path[1];
  256. const std::string &database = path[3];
  257. FSTDocumentKey *key =
  258. [FSTDocumentKey keyWithPath:[self localResourcePathForQualifiedResourcePath:path]];
  259. const DatabaseId database_id(project, database);
  260. FSTAssert(database_id == *self.databaseID, @"Database %s:%s cannot encode reference from %s:%s",
  261. self.databaseID->project_id().c_str(), self.databaseID->database_id().c_str(),
  262. database_id.project_id().c_str(), database_id.database_id().c_str());
  263. return [FSTReferenceValue referenceValue:key databaseID:self.databaseID];
  264. }
  265. - (GCFSArrayValue *)encodedArrayValue:(FSTArrayValue *)arrayValue {
  266. GCFSArrayValue *proto = [GCFSArrayValue message];
  267. NSMutableArray<GCFSValue *> *protoContents = [proto valuesArray];
  268. [[arrayValue internalValue]
  269. enumerateObjectsUsingBlock:^(FSTFieldValue *value, NSUInteger idx, BOOL *stop) {
  270. GCFSValue *converted = [self encodedFieldValue:value];
  271. [protoContents addObject:converted];
  272. }];
  273. return proto;
  274. }
  275. - (FSTArrayValue *)decodedArrayValue:(GCFSArrayValue *)arrayValue {
  276. NSMutableArray<FSTFieldValue *> *contents =
  277. [NSMutableArray arrayWithCapacity:arrayValue.valuesArray_Count];
  278. [arrayValue.valuesArray
  279. enumerateObjectsUsingBlock:^(GCFSValue *value, NSUInteger idx, BOOL *stop) {
  280. [contents addObject:[self decodedFieldValue:value]];
  281. }];
  282. return [[FSTArrayValue alloc] initWithValueNoCopy:contents];
  283. }
  284. - (GCFSMapValue *)encodedMapValue:(FSTObjectValue *)value {
  285. GCFSMapValue *result = [GCFSMapValue message];
  286. result.fields = [self encodedFields:value];
  287. return result;
  288. }
  289. - (FSTObjectValue *)decodedMapValue:(GCFSMapValue *)map {
  290. return [self decodedFields:map.fields];
  291. }
  292. /**
  293. * Encodes an FSTObjectValue into a dictionary.
  294. * @return a new dictionary that can be assigned to a field in another proto.
  295. */
  296. - (NSMutableDictionary<NSString *, GCFSValue *> *)encodedFields:(FSTObjectValue *)value {
  297. FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *fields = value.internalValue;
  298. NSMutableDictionary<NSString *, GCFSValue *> *result = [NSMutableDictionary dictionary];
  299. [fields enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *obj, BOOL *stop) {
  300. GCFSValue *converted = [self encodedFieldValue:obj];
  301. result[key] = converted;
  302. }];
  303. return result;
  304. }
  305. - (FSTObjectValue *)decodedFields:(NSDictionary<NSString *, GCFSValue *> *)fields {
  306. __block FSTObjectValue *result = [FSTObjectValue objectValue];
  307. [fields enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, GCFSValue *_Nonnull obj,
  308. BOOL *_Nonnull stop) {
  309. FieldPath path{util::MakeString(key)};
  310. FSTFieldValue *value = [self decodedFieldValue:obj];
  311. result = [result objectBySettingValue:value forPath:path];
  312. }];
  313. return result;
  314. }
  315. #pragma mark - FSTObjectValue <=> Document proto
  316. - (GCFSDocument *)encodedDocumentWithFields:(FSTObjectValue *)objectValue
  317. key:(FSTDocumentKey *)key {
  318. GCFSDocument *proto = [GCFSDocument message];
  319. proto.name = [self encodedDocumentKey:key];
  320. proto.fields = [self encodedFields:objectValue];
  321. return proto;
  322. }
  323. #pragma mark - FSTMaybeDocument <= BatchGetDocumentsResponse proto
  324. - (FSTMaybeDocument *)decodedMaybeDocumentFromBatch:(GCFSBatchGetDocumentsResponse *)response {
  325. switch (response.resultOneOfCase) {
  326. case GCFSBatchGetDocumentsResponse_Result_OneOfCase_Found:
  327. return [self decodedFoundDocument:response];
  328. case GCFSBatchGetDocumentsResponse_Result_OneOfCase_Missing:
  329. return [self decodedDeletedDocument:response];
  330. default:
  331. FSTFail(@"Unknown document type: %@", response);
  332. }
  333. }
  334. - (FSTDocument *)decodedFoundDocument:(GCFSBatchGetDocumentsResponse *)response {
  335. FSTAssert(!!response.found, @"Tried to deserialize a found document from a deleted document.");
  336. FSTDocumentKey *key = [self decodedDocumentKey:response.found.name];
  337. FSTObjectValue *value = [self decodedFields:response.found.fields];
  338. FSTSnapshotVersion *version = [self decodedVersion:response.found.updateTime];
  339. FSTAssert(![version isEqual:[FSTSnapshotVersion noVersion]],
  340. @"Got a document response with no snapshot version");
  341. return [FSTDocument documentWithData:value key:key version:version hasLocalMutations:NO];
  342. }
  343. - (FSTDeletedDocument *)decodedDeletedDocument:(GCFSBatchGetDocumentsResponse *)response {
  344. FSTAssert(!!response.missing, @"Tried to deserialize a deleted document from a found document.");
  345. FSTDocumentKey *key = [self decodedDocumentKey:response.missing];
  346. FSTSnapshotVersion *version = [self decodedVersion:response.readTime];
  347. FSTAssert(![version isEqual:[FSTSnapshotVersion noVersion]],
  348. @"Got a no document response with no snapshot version");
  349. return [FSTDeletedDocument documentWithKey:key version:version];
  350. }
  351. #pragma mark - FSTMutation => GCFSWrite proto
  352. - (GCFSWrite *)encodedMutation:(FSTMutation *)mutation {
  353. GCFSWrite *proto = [GCFSWrite message];
  354. Class mutationClass = [mutation class];
  355. if (mutationClass == [FSTSetMutation class]) {
  356. FSTSetMutation *set = (FSTSetMutation *)mutation;
  357. proto.update = [self encodedDocumentWithFields:set.value key:set.key];
  358. } else if (mutationClass == [FSTPatchMutation class]) {
  359. FSTPatchMutation *patch = (FSTPatchMutation *)mutation;
  360. proto.update = [self encodedDocumentWithFields:patch.value key:patch.key];
  361. proto.updateMask = [self encodedFieldMask:patch.fieldMask];
  362. } else if (mutationClass == [FSTTransformMutation class]) {
  363. FSTTransformMutation *transform = (FSTTransformMutation *)mutation;
  364. proto.transform = [GCFSDocumentTransform message];
  365. proto.transform.document = [self encodedDocumentKey:transform.key];
  366. proto.transform.fieldTransformsArray = [self encodedFieldTransforms:transform.fieldTransforms];
  367. // NOTE: We set a precondition of exists: true as a safety-check, since we always combine
  368. // FSTTransformMutations with an FSTSetMutation or FSTPatchMutation which (if successful) should
  369. // end up with an existing document.
  370. proto.currentDocument.exists = YES;
  371. } else if (mutationClass == [FSTDeleteMutation class]) {
  372. FSTDeleteMutation *deleteMutation = (FSTDeleteMutation *)mutation;
  373. proto.delete_p = [self encodedDocumentKey:deleteMutation.key];
  374. } else {
  375. FSTFail(@"Unknown mutation type %@", NSStringFromClass(mutationClass));
  376. }
  377. if (!mutation.precondition.isNone) {
  378. proto.currentDocument = [self encodedPrecondition:mutation.precondition];
  379. }
  380. return proto;
  381. }
  382. - (FSTMutation *)decodedMutation:(GCFSWrite *)mutation {
  383. FSTPrecondition *precondition = [mutation hasCurrentDocument]
  384. ? [self decodedPrecondition:mutation.currentDocument]
  385. : [FSTPrecondition none];
  386. switch (mutation.operationOneOfCase) {
  387. case GCFSWrite_Operation_OneOfCase_Update:
  388. if (mutation.hasUpdateMask) {
  389. return [[FSTPatchMutation alloc] initWithKey:[self decodedDocumentKey:mutation.update.name]
  390. fieldMask:[self decodedFieldMask:mutation.updateMask]
  391. value:[self decodedFields:mutation.update.fields]
  392. precondition:precondition];
  393. } else {
  394. return [[FSTSetMutation alloc] initWithKey:[self decodedDocumentKey:mutation.update.name]
  395. value:[self decodedFields:mutation.update.fields]
  396. precondition:precondition];
  397. }
  398. case GCFSWrite_Operation_OneOfCase_Delete_p:
  399. return [[FSTDeleteMutation alloc] initWithKey:[self decodedDocumentKey:mutation.delete_p]
  400. precondition:precondition];
  401. case GCFSWrite_Operation_OneOfCase_Transform: {
  402. FSTPreconditionExists exists = precondition.exists;
  403. FSTAssert(exists == FSTPreconditionExistsYes,
  404. @"Transforms must have precondition \"exists == true\"");
  405. return [[FSTTransformMutation alloc]
  406. initWithKey:[self decodedDocumentKey:mutation.transform.document]
  407. fieldTransforms:[self decodedFieldTransforms:mutation.transform.fieldTransformsArray]];
  408. }
  409. default:
  410. // Note that insert is intentionally unhandled, since we don't ever deal in them.
  411. FSTFail(@"Unknown mutation operation: %d", mutation.operationOneOfCase);
  412. }
  413. }
  414. - (GCFSPrecondition *)encodedPrecondition:(FSTPrecondition *)precondition {
  415. FSTAssert(!precondition.isNone, @"Can't serialize an empty precondition");
  416. GCFSPrecondition *message = [GCFSPrecondition message];
  417. if (precondition.updateTime) {
  418. message.updateTime = [self encodedVersion:precondition.updateTime];
  419. } else if (precondition.exists != FSTPreconditionExistsNotSet) {
  420. message.exists = precondition.exists == FSTPreconditionExistsYes;
  421. } else {
  422. FSTFail(@"Unknown precondition: %@", precondition);
  423. }
  424. return message;
  425. }
  426. - (FSTPrecondition *)decodedPrecondition:(GCFSPrecondition *)precondition {
  427. switch (precondition.conditionTypeOneOfCase) {
  428. case GCFSPrecondition_ConditionType_OneOfCase_GPBUnsetOneOfCase:
  429. return [FSTPrecondition none];
  430. case GCFSPrecondition_ConditionType_OneOfCase_Exists:
  431. return [FSTPrecondition preconditionWithExists:precondition.exists];
  432. case GCFSPrecondition_ConditionType_OneOfCase_UpdateTime:
  433. return [FSTPrecondition
  434. preconditionWithUpdateTime:[self decodedVersion:precondition.updateTime]];
  435. default:
  436. FSTFail(@"Unrecognized Precondition one-of case %@", precondition);
  437. }
  438. }
  439. - (GCFSDocumentMask *)encodedFieldMask:(FSTFieldMask *)fieldMask {
  440. GCFSDocumentMask *mask = [GCFSDocumentMask message];
  441. for (const FieldPath &field : fieldMask.fields) {
  442. [mask.fieldPathsArray addObject:util::WrapNSString(field.CanonicalString())];
  443. }
  444. return mask;
  445. }
  446. - (FSTFieldMask *)decodedFieldMask:(GCFSDocumentMask *)fieldMask {
  447. std::vector<FieldPath> fields{};
  448. fields.reserve(fieldMask.fieldPathsArray_Count);
  449. for (NSString *path in fieldMask.fieldPathsArray) {
  450. fields.push_back(FieldPath::FromServerFormat(util::MakeStringView(path)));
  451. }
  452. return [[FSTFieldMask alloc] initWithFields:std::move(fields)];
  453. }
  454. - (NSMutableArray<GCFSDocumentTransform_FieldTransform *> *)encodedFieldTransforms:
  455. (NSArray<FSTFieldTransform *> *)fieldTransforms {
  456. NSMutableArray *protos = [NSMutableArray array];
  457. for (FSTFieldTransform *fieldTransform in fieldTransforms) {
  458. FSTAssert([fieldTransform.transform isKindOfClass:[FSTServerTimestampTransform class]],
  459. @"Unknown transform: %@", fieldTransform.transform);
  460. GCFSDocumentTransform_FieldTransform *proto = [GCFSDocumentTransform_FieldTransform message];
  461. proto.fieldPath = util::WrapNSString(fieldTransform.path.CanonicalString());
  462. proto.setToServerValue = GCFSDocumentTransform_FieldTransform_ServerValue_RequestTime;
  463. [protos addObject:proto];
  464. }
  465. return protos;
  466. }
  467. - (NSArray<FSTFieldTransform *> *)decodedFieldTransforms:
  468. (NSArray<GCFSDocumentTransform_FieldTransform *> *)protos {
  469. NSMutableArray<FSTFieldTransform *> *fieldTransforms = [NSMutableArray array];
  470. for (GCFSDocumentTransform_FieldTransform *proto in protos) {
  471. FSTAssert(
  472. proto.setToServerValue == GCFSDocumentTransform_FieldTransform_ServerValue_RequestTime,
  473. @"Unknown transform setToServerValue: %d", proto.setToServerValue);
  474. [fieldTransforms
  475. addObject:[[FSTFieldTransform alloc]
  476. initWithPath:FieldPath::FromServerFormat(
  477. util::MakeStringView(proto.fieldPath))
  478. transform:[FSTServerTimestampTransform serverTimestampTransform]]];
  479. }
  480. return fieldTransforms;
  481. }
  482. #pragma mark - FSTMutationResult <= GCFSWriteResult proto
  483. - (FSTMutationResult *)decodedMutationResult:(GCFSWriteResult *)mutation {
  484. // NOTE: Deletes don't have an updateTime.
  485. FSTSnapshotVersion *_Nullable version =
  486. mutation.updateTime ? [self decodedVersion:mutation.updateTime] : nil;
  487. NSMutableArray *_Nullable transformResults = nil;
  488. if (mutation.transformResultsArray.count > 0) {
  489. transformResults = [NSMutableArray array];
  490. for (GCFSValue *result in mutation.transformResultsArray) {
  491. [transformResults addObject:[self decodedFieldValue:result]];
  492. }
  493. }
  494. return [[FSTMutationResult alloc] initWithVersion:version transformResults:transformResults];
  495. }
  496. #pragma mark - FSTQueryData => GCFSTarget proto
  497. - (nullable NSMutableDictionary<NSString *, NSString *> *)encodedListenRequestLabelsForQueryData:
  498. (FSTQueryData *)queryData {
  499. NSString *value = [self encodedLabelForPurpose:queryData.purpose];
  500. if (!value) {
  501. return nil;
  502. }
  503. NSMutableDictionary<NSString *, NSString *> *result =
  504. [NSMutableDictionary dictionaryWithCapacity:1];
  505. [result setObject:value forKey:@"goog-listen-tags"];
  506. return result;
  507. }
  508. - (nullable NSString *)encodedLabelForPurpose:(FSTQueryPurpose)purpose {
  509. switch (purpose) {
  510. case FSTQueryPurposeListen:
  511. return nil;
  512. case FSTQueryPurposeExistenceFilterMismatch:
  513. return @"existence-filter-mismatch";
  514. case FSTQueryPurposeLimboResolution:
  515. return @"limbo-document";
  516. default:
  517. FSTFail(@"Unrecognized query purpose: %lu", (unsigned long)purpose);
  518. }
  519. }
  520. - (GCFSTarget *)encodedTarget:(FSTQueryData *)queryData {
  521. GCFSTarget *result = [GCFSTarget message];
  522. FSTQuery *query = queryData.query;
  523. if ([query isDocumentQuery]) {
  524. result.documents = [self encodedDocumentsTarget:query];
  525. } else {
  526. result.query = [self encodedQueryTarget:query];
  527. }
  528. result.targetId = queryData.targetID;
  529. if (queryData.resumeToken.length > 0) {
  530. result.resumeToken = queryData.resumeToken;
  531. }
  532. return result;
  533. }
  534. - (GCFSTarget_DocumentsTarget *)encodedDocumentsTarget:(FSTQuery *)query {
  535. GCFSTarget_DocumentsTarget *result = [GCFSTarget_DocumentsTarget message];
  536. NSMutableArray<NSString *> *docs = result.documentsArray;
  537. [docs addObject:[self encodedQueryPath:query.path]];
  538. return result;
  539. }
  540. - (FSTQuery *)decodedQueryFromDocumentsTarget:(GCFSTarget_DocumentsTarget *)target {
  541. NSArray<NSString *> *documents = target.documentsArray;
  542. FSTAssert(documents.count == 1, @"DocumentsTarget contained other than 1 document %lu",
  543. (unsigned long)documents.count);
  544. NSString *name = documents[0];
  545. return [FSTQuery queryWithPath:[self decodedQueryPath:name]];
  546. }
  547. - (GCFSTarget_QueryTarget *)encodedQueryTarget:(FSTQuery *)query {
  548. // Dissect the path into parent, collectionId, and optional key filter.
  549. GCFSTarget_QueryTarget *queryTarget = [GCFSTarget_QueryTarget message];
  550. if (query.path.size() == 0) {
  551. queryTarget.parent = [self encodedQueryPath:query.path];
  552. } else {
  553. const ResourcePath &path = query.path;
  554. FSTAssert(path.size() % 2 != 0, @"Document queries with filters are not supported.");
  555. queryTarget.parent = [self encodedQueryPath:path.PopLast()];
  556. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  557. from.collectionId = util::WrapNSString(path.last_segment());
  558. [queryTarget.structuredQuery.fromArray addObject:from];
  559. }
  560. // Encode the filters.
  561. GCFSStructuredQuery_Filter *_Nullable where = [self encodedFilters:query.filters];
  562. if (where) {
  563. queryTarget.structuredQuery.where = where;
  564. }
  565. NSArray<GCFSStructuredQuery_Order *> *orders = [self encodedSortOrders:query.sortOrders];
  566. if (orders.count) {
  567. [queryTarget.structuredQuery.orderByArray addObjectsFromArray:orders];
  568. }
  569. if (query.limit != NSNotFound) {
  570. queryTarget.structuredQuery.limit.value = (int32_t)query.limit;
  571. }
  572. if (query.startAt) {
  573. queryTarget.structuredQuery.startAt = [self encodedBound:query.startAt];
  574. }
  575. if (query.endAt) {
  576. queryTarget.structuredQuery.endAt = [self encodedBound:query.endAt];
  577. }
  578. return queryTarget;
  579. }
  580. - (FSTQuery *)decodedQueryFromQueryTarget:(GCFSTarget_QueryTarget *)target {
  581. ResourcePath path = [self decodedQueryPath:target.parent];
  582. GCFSStructuredQuery *query = target.structuredQuery;
  583. NSUInteger fromCount = query.fromArray_Count;
  584. if (fromCount > 0) {
  585. FSTAssert(fromCount == 1,
  586. @"StructuredQuery.from with more than one collection is not supported.");
  587. GCFSStructuredQuery_CollectionSelector *from = query.fromArray[0];
  588. path = path.Append(util::MakeString(from.collectionId));
  589. }
  590. NSArray<id<FSTFilter>> *filterBy;
  591. if (query.hasWhere) {
  592. filterBy = [self decodedFilters:query.where];
  593. } else {
  594. filterBy = @[];
  595. }
  596. NSArray<FSTSortOrder *> *orderBy;
  597. if (query.orderByArray_Count > 0) {
  598. orderBy = [self decodedSortOrders:query.orderByArray];
  599. } else {
  600. orderBy = @[];
  601. }
  602. NSInteger limit = NSNotFound;
  603. if (query.hasLimit) {
  604. limit = query.limit.value;
  605. }
  606. FSTBound *_Nullable startAt;
  607. if (query.hasStartAt) {
  608. startAt = [self decodedBound:query.startAt];
  609. }
  610. FSTBound *_Nullable endAt;
  611. if (query.hasEndAt) {
  612. endAt = [self decodedBound:query.endAt];
  613. }
  614. return [[FSTQuery alloc] initWithPath:path
  615. filterBy:filterBy
  616. orderBy:orderBy
  617. limit:limit
  618. startAt:startAt
  619. endAt:endAt];
  620. }
  621. #pragma mark Filters
  622. - (GCFSStructuredQuery_Filter *_Nullable)encodedFilters:(NSArray<id<FSTFilter>> *)filters {
  623. if (filters.count == 0) {
  624. return nil;
  625. }
  626. NSMutableArray<GCFSStructuredQuery_Filter *> *protos = [NSMutableArray array];
  627. for (id<FSTFilter> filter in filters) {
  628. if ([filter isKindOfClass:[FSTRelationFilter class]]) {
  629. [protos addObject:[self encodedRelationFilter:filter]];
  630. } else {
  631. [protos addObject:[self encodedUnaryFilter:filter]];
  632. }
  633. }
  634. if (protos.count == 1) {
  635. // Special case: no existing filters and we only need to add one filter. This can be made the
  636. // single root filter without a composite filter.
  637. return protos[0];
  638. }
  639. GCFSStructuredQuery_Filter *composite = [GCFSStructuredQuery_Filter message];
  640. composite.compositeFilter.op = GCFSStructuredQuery_CompositeFilter_Operator_And;
  641. composite.compositeFilter.filtersArray = protos;
  642. return composite;
  643. }
  644. - (NSArray<id<FSTFilter>> *)decodedFilters:(GCFSStructuredQuery_Filter *)proto {
  645. NSMutableArray<id<FSTFilter>> *result = [NSMutableArray array];
  646. NSArray<GCFSStructuredQuery_Filter *> *filters;
  647. if (proto.filterTypeOneOfCase ==
  648. GCFSStructuredQuery_Filter_FilterType_OneOfCase_CompositeFilter) {
  649. FSTAssert(proto.compositeFilter.op == GCFSStructuredQuery_CompositeFilter_Operator_And,
  650. @"Only AND-type composite filters are supported, got %d", proto.compositeFilter.op);
  651. filters = proto.compositeFilter.filtersArray;
  652. } else {
  653. filters = @[ proto ];
  654. }
  655. for (GCFSStructuredQuery_Filter *filter in filters) {
  656. switch (filter.filterTypeOneOfCase) {
  657. case GCFSStructuredQuery_Filter_FilterType_OneOfCase_CompositeFilter:
  658. FSTFail(@"Nested composite filters are not supported");
  659. case GCFSStructuredQuery_Filter_FilterType_OneOfCase_FieldFilter:
  660. [result addObject:[self decodedRelationFilter:filter.fieldFilter]];
  661. break;
  662. case GCFSStructuredQuery_Filter_FilterType_OneOfCase_UnaryFilter:
  663. [result addObject:[self decodedUnaryFilter:filter.unaryFilter]];
  664. break;
  665. default:
  666. FSTFail(@"Unrecognized Filter.filterType %d", filter.filterTypeOneOfCase);
  667. }
  668. }
  669. return result;
  670. }
  671. - (GCFSStructuredQuery_Filter *)encodedRelationFilter:(FSTRelationFilter *)filter {
  672. GCFSStructuredQuery_Filter *proto = [GCFSStructuredQuery_Filter message];
  673. GCFSStructuredQuery_FieldFilter *fieldFilter = proto.fieldFilter;
  674. fieldFilter.field = [self encodedFieldPath:filter.field];
  675. fieldFilter.op = [self encodedRelationFilterOperator:filter.filterOperator];
  676. fieldFilter.value = [self encodedFieldValue:filter.value];
  677. return proto;
  678. }
  679. - (FSTRelationFilter *)decodedRelationFilter:(GCFSStructuredQuery_FieldFilter *)proto {
  680. FieldPath fieldPath = FieldPath::FromServerFormat(util::MakeString(proto.field.fieldPath));
  681. FSTRelationFilterOperator filterOperator = [self decodedRelationFilterOperator:proto.op];
  682. FSTFieldValue *value = [self decodedFieldValue:proto.value];
  683. return [FSTRelationFilter filterWithField:fieldPath filterOperator:filterOperator value:value];
  684. }
  685. - (GCFSStructuredQuery_Filter *)encodedUnaryFilter:(id<FSTFilter>)filter {
  686. GCFSStructuredQuery_Filter *proto = [GCFSStructuredQuery_Filter message];
  687. proto.unaryFilter.field = [self encodedFieldPath:filter.field];
  688. if ([filter isKindOfClass:[FSTNanFilter class]]) {
  689. proto.unaryFilter.op = GCFSStructuredQuery_UnaryFilter_Operator_IsNan;
  690. } else if ([filter isKindOfClass:[FSTNullFilter class]]) {
  691. proto.unaryFilter.op = GCFSStructuredQuery_UnaryFilter_Operator_IsNull;
  692. } else {
  693. FSTFail(@"Unrecognized filter: %@", filter);
  694. }
  695. return proto;
  696. }
  697. - (id<FSTFilter>)decodedUnaryFilter:(GCFSStructuredQuery_UnaryFilter *)proto {
  698. FieldPath field = FieldPath::FromServerFormat(util::MakeString(proto.field.fieldPath));
  699. switch (proto.op) {
  700. case GCFSStructuredQuery_UnaryFilter_Operator_IsNan:
  701. return [[FSTNanFilter alloc] initWithField:field];
  702. case GCFSStructuredQuery_UnaryFilter_Operator_IsNull:
  703. return [[FSTNullFilter alloc] initWithField:field];
  704. default:
  705. FSTFail(@"Unrecognized UnaryFilter.operator %d", proto.op);
  706. }
  707. }
  708. - (GCFSStructuredQuery_FieldReference *)encodedFieldPath:(const FieldPath &)fieldPath {
  709. GCFSStructuredQuery_FieldReference *ref = [GCFSStructuredQuery_FieldReference message];
  710. ref.fieldPath = util::WrapNSString(fieldPath.CanonicalString());
  711. return ref;
  712. }
  713. - (GCFSStructuredQuery_FieldFilter_Operator)encodedRelationFilterOperator:
  714. (FSTRelationFilterOperator)filterOperator {
  715. switch (filterOperator) {
  716. case FSTRelationFilterOperatorLessThan:
  717. return GCFSStructuredQuery_FieldFilter_Operator_LessThan;
  718. case FSTRelationFilterOperatorLessThanOrEqual:
  719. return GCFSStructuredQuery_FieldFilter_Operator_LessThanOrEqual;
  720. case FSTRelationFilterOperatorEqual:
  721. return GCFSStructuredQuery_FieldFilter_Operator_Equal;
  722. case FSTRelationFilterOperatorGreaterThanOrEqual:
  723. return GCFSStructuredQuery_FieldFilter_Operator_GreaterThanOrEqual;
  724. case FSTRelationFilterOperatorGreaterThan:
  725. return GCFSStructuredQuery_FieldFilter_Operator_GreaterThan;
  726. default:
  727. FSTFail(@"Unhandled FSTRelationFilterOperator: %ld", (long)filterOperator);
  728. }
  729. }
  730. - (FSTRelationFilterOperator)decodedRelationFilterOperator:
  731. (GCFSStructuredQuery_FieldFilter_Operator)filterOperator {
  732. switch (filterOperator) {
  733. case GCFSStructuredQuery_FieldFilter_Operator_LessThan:
  734. return FSTRelationFilterOperatorLessThan;
  735. case GCFSStructuredQuery_FieldFilter_Operator_LessThanOrEqual:
  736. return FSTRelationFilterOperatorLessThanOrEqual;
  737. case GCFSStructuredQuery_FieldFilter_Operator_Equal:
  738. return FSTRelationFilterOperatorEqual;
  739. case GCFSStructuredQuery_FieldFilter_Operator_GreaterThanOrEqual:
  740. return FSTRelationFilterOperatorGreaterThanOrEqual;
  741. case GCFSStructuredQuery_FieldFilter_Operator_GreaterThan:
  742. return FSTRelationFilterOperatorGreaterThan;
  743. default:
  744. FSTFail(@"Unhandled FieldFilter.operator: %d", filterOperator);
  745. }
  746. }
  747. #pragma mark Property Orders
  748. - (NSArray<GCFSStructuredQuery_Order *> *)encodedSortOrders:(NSArray<FSTSortOrder *> *)orders {
  749. NSMutableArray<GCFSStructuredQuery_Order *> *protos = [NSMutableArray array];
  750. for (FSTSortOrder *order in orders) {
  751. [protos addObject:[self encodedSortOrder:order]];
  752. }
  753. return protos;
  754. }
  755. - (NSArray<FSTSortOrder *> *)decodedSortOrders:(NSArray<GCFSStructuredQuery_Order *> *)protos {
  756. NSMutableArray<FSTSortOrder *> *result = [NSMutableArray arrayWithCapacity:protos.count];
  757. for (GCFSStructuredQuery_Order *orderProto in protos) {
  758. [result addObject:[self decodedSortOrder:orderProto]];
  759. }
  760. return result;
  761. }
  762. - (GCFSStructuredQuery_Order *)encodedSortOrder:(FSTSortOrder *)sortOrder {
  763. GCFSStructuredQuery_Order *proto = [GCFSStructuredQuery_Order message];
  764. proto.field = [self encodedFieldPath:sortOrder.field];
  765. if (sortOrder.ascending) {
  766. proto.direction = GCFSStructuredQuery_Direction_Ascending;
  767. } else {
  768. proto.direction = GCFSStructuredQuery_Direction_Descending;
  769. }
  770. return proto;
  771. }
  772. - (FSTSortOrder *)decodedSortOrder:(GCFSStructuredQuery_Order *)proto {
  773. FieldPath fieldPath = FieldPath::FromServerFormat(util::MakeString(proto.field.fieldPath));
  774. BOOL ascending;
  775. switch (proto.direction) {
  776. case GCFSStructuredQuery_Direction_Ascending:
  777. ascending = YES;
  778. break;
  779. case GCFSStructuredQuery_Direction_Descending:
  780. ascending = NO;
  781. break;
  782. default:
  783. FSTFail(@"Unrecognized GCFSStructuredQuery_Direction %d", proto.direction);
  784. }
  785. return [FSTSortOrder sortOrderWithFieldPath:fieldPath ascending:ascending];
  786. }
  787. #pragma mark - Bounds/Cursors
  788. - (GCFSCursor *)encodedBound:(FSTBound *)bound {
  789. GCFSCursor *proto = [GCFSCursor message];
  790. proto.before = bound.isBefore;
  791. for (FSTFieldValue *fieldValue in bound.position) {
  792. GCFSValue *value = [self encodedFieldValue:fieldValue];
  793. [proto.valuesArray addObject:value];
  794. }
  795. return proto;
  796. }
  797. - (FSTBound *)decodedBound:(GCFSCursor *)proto {
  798. NSMutableArray<FSTFieldValue *> *indexComponents = [NSMutableArray array];
  799. for (GCFSValue *valueProto in proto.valuesArray) {
  800. FSTFieldValue *value = [self decodedFieldValue:valueProto];
  801. [indexComponents addObject:value];
  802. }
  803. return [FSTBound boundWithPosition:indexComponents isBefore:proto.before];
  804. }
  805. #pragma mark - FSTWatchChange <= GCFSListenResponse proto
  806. - (FSTWatchChange *)decodedWatchChange:(GCFSListenResponse *)watchChange {
  807. switch (watchChange.responseTypeOneOfCase) {
  808. case GCFSListenResponse_ResponseType_OneOfCase_TargetChange:
  809. return [self decodedTargetChangeFromWatchChange:watchChange.targetChange];
  810. case GCFSListenResponse_ResponseType_OneOfCase_DocumentChange:
  811. return [self decodedDocumentChange:watchChange.documentChange];
  812. case GCFSListenResponse_ResponseType_OneOfCase_DocumentDelete:
  813. return [self decodedDocumentDelete:watchChange.documentDelete];
  814. case GCFSListenResponse_ResponseType_OneOfCase_DocumentRemove:
  815. return [self decodedDocumentRemove:watchChange.documentRemove];
  816. case GCFSListenResponse_ResponseType_OneOfCase_Filter:
  817. return [self decodedExistenceFilterWatchChange:watchChange.filter];
  818. default:
  819. FSTFail(@"Unknown WatchChange.changeType %" PRId32, watchChange.responseTypeOneOfCase);
  820. }
  821. }
  822. - (FSTSnapshotVersion *)versionFromListenResponse:(GCFSListenResponse *)watchChange {
  823. // We have only reached a consistent snapshot for the entire stream if there is a read_time set
  824. // and it applies to all targets (i.e. the list of targets is empty). The backend is guaranteed to
  825. // send such responses.
  826. if (watchChange.responseTypeOneOfCase != GCFSListenResponse_ResponseType_OneOfCase_TargetChange) {
  827. return [FSTSnapshotVersion noVersion];
  828. }
  829. if (watchChange.targetChange.targetIdsArray.count != 0) {
  830. return [FSTSnapshotVersion noVersion];
  831. }
  832. return [self decodedVersion:watchChange.targetChange.readTime];
  833. }
  834. - (FSTWatchTargetChange *)decodedTargetChangeFromWatchChange:(GCFSTargetChange *)change {
  835. FSTWatchTargetChangeState state = [self decodedWatchTargetChangeState:change.targetChangeType];
  836. NSMutableArray<NSNumber *> *targetIDs =
  837. [NSMutableArray arrayWithCapacity:change.targetIdsArray_Count];
  838. [change.targetIdsArray enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) {
  839. [targetIDs addObject:@(value)];
  840. }];
  841. NSError *cause = nil;
  842. if (change.hasCause) {
  843. cause = [NSError errorWithDomain:FIRFirestoreErrorDomain
  844. code:change.cause.code
  845. userInfo:@{NSLocalizedDescriptionKey : change.cause.message}];
  846. }
  847. return [[FSTWatchTargetChange alloc] initWithState:state
  848. targetIDs:targetIDs
  849. resumeToken:change.resumeToken
  850. cause:cause];
  851. }
  852. - (FSTWatchTargetChangeState)decodedWatchTargetChangeState:
  853. (GCFSTargetChange_TargetChangeType)state {
  854. switch (state) {
  855. case GCFSTargetChange_TargetChangeType_NoChange:
  856. return FSTWatchTargetChangeStateNoChange;
  857. case GCFSTargetChange_TargetChangeType_Add:
  858. return FSTWatchTargetChangeStateAdded;
  859. case GCFSTargetChange_TargetChangeType_Remove:
  860. return FSTWatchTargetChangeStateRemoved;
  861. case GCFSTargetChange_TargetChangeType_Current:
  862. return FSTWatchTargetChangeStateCurrent;
  863. case GCFSTargetChange_TargetChangeType_Reset:
  864. return FSTWatchTargetChangeStateReset;
  865. default:
  866. FSTFail(@"Unexpected TargetChange.state: %" PRId32, state);
  867. }
  868. }
  869. - (NSArray<NSNumber *> *)decodedIntegerArray:(GPBInt32Array *)values {
  870. NSMutableArray<NSNumber *> *result = [NSMutableArray arrayWithCapacity:values.count];
  871. [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) {
  872. [result addObject:@(value)];
  873. }];
  874. return result;
  875. }
  876. - (FSTDocumentWatchChange *)decodedDocumentChange:(GCFSDocumentChange *)change {
  877. FSTObjectValue *value = [self decodedFields:change.document.fields];
  878. FSTDocumentKey *key = [self decodedDocumentKey:change.document.name];
  879. FSTSnapshotVersion *version = [self decodedVersion:change.document.updateTime];
  880. FSTAssert(![version isEqual:[FSTSnapshotVersion noVersion]],
  881. @"Got a document change with no snapshot version");
  882. FSTMaybeDocument *document =
  883. [FSTDocument documentWithData:value key:key version:version hasLocalMutations:NO];
  884. NSArray<NSNumber *> *updatedTargetIds = [self decodedIntegerArray:change.targetIdsArray];
  885. NSArray<NSNumber *> *removedTargetIds = [self decodedIntegerArray:change.removedTargetIdsArray];
  886. return [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:updatedTargetIds
  887. removedTargetIDs:removedTargetIds
  888. documentKey:document.key
  889. document:document];
  890. }
  891. - (FSTDocumentWatchChange *)decodedDocumentDelete:(GCFSDocumentDelete *)change {
  892. FSTDocumentKey *key = [self decodedDocumentKey:change.document];
  893. // Note that version might be unset in which case we use [FSTSnapshotVersion noVersion]
  894. FSTSnapshotVersion *version = [self decodedVersion:change.readTime];
  895. FSTMaybeDocument *document = [FSTDeletedDocument documentWithKey:key version:version];
  896. NSArray<NSNumber *> *removedTargetIds = [self decodedIntegerArray:change.removedTargetIdsArray];
  897. return [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:@[]
  898. removedTargetIDs:removedTargetIds
  899. documentKey:document.key
  900. document:document];
  901. }
  902. - (FSTDocumentWatchChange *)decodedDocumentRemove:(GCFSDocumentRemove *)change {
  903. FSTDocumentKey *key = [self decodedDocumentKey:change.document];
  904. NSArray<NSNumber *> *removedTargetIds = [self decodedIntegerArray:change.removedTargetIdsArray];
  905. return [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:@[]
  906. removedTargetIDs:removedTargetIds
  907. documentKey:key
  908. document:nil];
  909. }
  910. - (FSTExistenceFilterWatchChange *)decodedExistenceFilterWatchChange:(GCFSExistenceFilter *)filter {
  911. // TODO(dimond): implement existence filter parsing
  912. FSTExistenceFilter *existenceFilter = [FSTExistenceFilter filterWithCount:filter.count];
  913. FSTTargetID targetID = filter.targetId;
  914. return [FSTExistenceFilterWatchChange changeWithFilter:existenceFilter targetID:targetID];
  915. }
  916. @end
  917. NS_ASSUME_NONNULL_END