FSTSerializerBeta.mm 47 KB

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