FSTSerializerBeta.mm 48 KB

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