FSTSerializerBeta.mm 46 KB

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