FSTSerializerBeta.mm 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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:key databaseID:self.databaseID];
  295. }
  296. - (GCFSArrayValue *)encodedArrayValue:(FSTArrayValue *)arrayValue {
  297. GCFSArrayValue *proto = [GCFSArrayValue message];
  298. NSMutableArray<GCFSValue *> *protoContents = [proto valuesArray];
  299. [[arrayValue internalValue]
  300. enumerateObjectsUsingBlock:^(FSTFieldValue *value, NSUInteger idx, BOOL *stop) {
  301. GCFSValue *converted = [self encodedFieldValue:value];
  302. [protoContents addObject:converted];
  303. }];
  304. return proto;
  305. }
  306. - (FSTArrayValue *)decodedArrayValue:(GCFSArrayValue *)arrayValue {
  307. NSMutableArray<FSTFieldValue *> *contents =
  308. [NSMutableArray arrayWithCapacity:arrayValue.valuesArray_Count];
  309. [arrayValue.valuesArray
  310. enumerateObjectsUsingBlock:^(GCFSValue *value, NSUInteger idx, BOOL *stop) {
  311. [contents addObject:[self decodedFieldValue:value]];
  312. }];
  313. return [[FSTArrayValue alloc] initWithValueNoCopy:contents];
  314. }
  315. - (GCFSMapValue *)encodedMapValue:(FSTObjectValue *)value {
  316. GCFSMapValue *result = [GCFSMapValue message];
  317. result.fields = [self encodedFields:value];
  318. return result;
  319. }
  320. - (FSTObjectValue *)decodedMapValue:(GCFSMapValue *)map {
  321. return [self decodedFields:map.fields];
  322. }
  323. /**
  324. * Encodes an FSTObjectValue into a dictionary.
  325. * @return a new dictionary that can be assigned to a field in another proto.
  326. */
  327. - (NSMutableDictionary<NSString *, GCFSValue *> *)encodedFields:(FSTObjectValue *)value {
  328. FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *fields = value.internalValue;
  329. NSMutableDictionary<NSString *, GCFSValue *> *result = [NSMutableDictionary dictionary];
  330. [fields enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *obj, BOOL *stop) {
  331. GCFSValue *converted = [self encodedFieldValue:obj];
  332. result[key] = converted;
  333. }];
  334. return result;
  335. }
  336. - (FSTObjectValue *)decodedFields:(NSDictionary<NSString *, GCFSValue *> *)fields {
  337. __block FSTObjectValue *result = [FSTObjectValue objectValue];
  338. [fields enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, GCFSValue *_Nonnull obj,
  339. BOOL *_Nonnull stop) {
  340. FieldPath path{util::MakeString(key)};
  341. FSTFieldValue *value = [self decodedFieldValue:obj];
  342. result = [result objectBySettingValue:value forPath:path];
  343. }];
  344. return result;
  345. }
  346. #pragma mark - FSTObjectValue <=> Document proto
  347. - (GCFSDocument *)encodedDocumentWithFields:(FSTObjectValue *)objectValue
  348. key:(const DocumentKey &)key {
  349. GCFSDocument *proto = [GCFSDocument message];
  350. proto.name = [self encodedDocumentKey:key];
  351. proto.fields = [self encodedFields:objectValue];
  352. return proto;
  353. }
  354. #pragma mark - FSTMaybeDocument <= BatchGetDocumentsResponse proto
  355. - (FSTMaybeDocument *)decodedMaybeDocumentFromBatch:(GCFSBatchGetDocumentsResponse *)response {
  356. switch (response.resultOneOfCase) {
  357. case GCFSBatchGetDocumentsResponse_Result_OneOfCase_Found:
  358. return [self decodedFoundDocument:response];
  359. case GCFSBatchGetDocumentsResponse_Result_OneOfCase_Missing:
  360. return [self decodedDeletedDocument:response];
  361. default:
  362. HARD_FAIL("Unknown document type: %s", response);
  363. }
  364. }
  365. - (FSTDocument *)decodedFoundDocument:(GCFSBatchGetDocumentsResponse *)response {
  366. HARD_ASSERT(!!response.found, "Tried to deserialize a found document from a deleted document.");
  367. const DocumentKey key = [self decodedDocumentKey:response.found.name];
  368. FSTObjectValue *value = [self decodedFields:response.found.fields];
  369. SnapshotVersion version = [self decodedVersion:response.found.updateTime];
  370. HARD_ASSERT(version != SnapshotVersion::None(),
  371. "Got a document response with no snapshot version");
  372. return [FSTDocument documentWithData:value
  373. key:key
  374. version:version
  375. state:FSTDocumentStateSynced
  376. proto:response.found];
  377. }
  378. - (FSTDeletedDocument *)decodedDeletedDocument:(GCFSBatchGetDocumentsResponse *)response {
  379. HARD_ASSERT(!!response.missing, "Tried to deserialize a deleted document from a found document.");
  380. const DocumentKey key = [self decodedDocumentKey:response.missing];
  381. SnapshotVersion version = [self decodedVersion:response.readTime];
  382. HARD_ASSERT(version != SnapshotVersion::None(),
  383. "Got a no document response with no snapshot version");
  384. return [FSTDeletedDocument documentWithKey:key version:version hasCommittedMutations:NO];
  385. }
  386. #pragma mark - FSTMutation => GCFSWrite proto
  387. - (GCFSWrite *)encodedMutation:(FSTMutation *)mutation {
  388. GCFSWrite *proto = [GCFSWrite message];
  389. Class mutationClass = [mutation class];
  390. if (mutationClass == [FSTSetMutation class]) {
  391. FSTSetMutation *set = (FSTSetMutation *)mutation;
  392. proto.update = [self encodedDocumentWithFields:set.value key:set.key];
  393. } else if (mutationClass == [FSTPatchMutation class]) {
  394. FSTPatchMutation *patch = (FSTPatchMutation *)mutation;
  395. proto.update = [self encodedDocumentWithFields:patch.value key:patch.key];
  396. proto.updateMask = [self encodedFieldMask:patch.fieldMask];
  397. } else if (mutationClass == [FSTTransformMutation class]) {
  398. FSTTransformMutation *transform = (FSTTransformMutation *)mutation;
  399. proto.transform = [GCFSDocumentTransform message];
  400. proto.transform.document = [self encodedDocumentKey:transform.key];
  401. proto.transform.fieldTransformsArray = [self encodedFieldTransforms:transform.fieldTransforms];
  402. // NOTE: We set a precondition of exists: true as a safety-check, since we always combine
  403. // FSTTransformMutations with an FSTSetMutation or FSTPatchMutation which (if successful) should
  404. // end up with an existing document.
  405. proto.currentDocument.exists = YES;
  406. } else if (mutationClass == [FSTDeleteMutation class]) {
  407. FSTDeleteMutation *deleteMutation = (FSTDeleteMutation *)mutation;
  408. proto.delete_p = [self encodedDocumentKey:deleteMutation.key];
  409. } else {
  410. HARD_FAIL("Unknown mutation type %s", NSStringFromClass(mutationClass));
  411. }
  412. if (!mutation.precondition.IsNone()) {
  413. proto.currentDocument = [self encodedPrecondition:mutation.precondition];
  414. }
  415. return proto;
  416. }
  417. - (FSTMutation *)decodedMutation:(GCFSWrite *)mutation {
  418. Precondition precondition = [mutation hasCurrentDocument]
  419. ? [self decodedPrecondition:mutation.currentDocument]
  420. : Precondition::None();
  421. switch (mutation.operationOneOfCase) {
  422. case GCFSWrite_Operation_OneOfCase_Update:
  423. if (mutation.hasUpdateMask) {
  424. return [[FSTPatchMutation alloc] initWithKey:[self decodedDocumentKey:mutation.update.name]
  425. fieldMask:[self decodedFieldMask:mutation.updateMask]
  426. value:[self decodedFields:mutation.update.fields]
  427. precondition:precondition];
  428. } else {
  429. return [[FSTSetMutation alloc] initWithKey:[self decodedDocumentKey:mutation.update.name]
  430. value:[self decodedFields:mutation.update.fields]
  431. precondition:precondition];
  432. }
  433. case GCFSWrite_Operation_OneOfCase_Delete_p:
  434. return [[FSTDeleteMutation alloc] initWithKey:[self decodedDocumentKey:mutation.delete_p]
  435. precondition:precondition];
  436. case GCFSWrite_Operation_OneOfCase_Transform: {
  437. HARD_ASSERT(precondition == Precondition::Exists(true),
  438. "Transforms must have precondition \"exists == true\"");
  439. return [[FSTTransformMutation alloc]
  440. initWithKey:[self decodedDocumentKey:mutation.transform.document]
  441. fieldTransforms:[self decodedFieldTransforms:mutation.transform.fieldTransformsArray]];
  442. }
  443. default:
  444. // Note that insert is intentionally unhandled, since we don't ever deal in them.
  445. HARD_FAIL("Unknown mutation operation: %s", mutation.operationOneOfCase);
  446. }
  447. }
  448. - (GCFSPrecondition *)encodedPrecondition:(const Precondition &)precondition {
  449. HARD_ASSERT(!precondition.IsNone(), "Can't serialize an empty precondition");
  450. GCFSPrecondition *message = [GCFSPrecondition message];
  451. if (precondition.type() == Precondition::Type::UpdateTime) {
  452. message.updateTime = [self encodedVersion:precondition.update_time()];
  453. } else if (precondition.type() == Precondition::Type::Exists) {
  454. message.exists = precondition == Precondition::Exists(true);
  455. } else {
  456. HARD_FAIL("Unknown precondition: %s", precondition.description());
  457. }
  458. return message;
  459. }
  460. - (Precondition)decodedPrecondition:(GCFSPrecondition *)precondition {
  461. switch (precondition.conditionTypeOneOfCase) {
  462. case GCFSPrecondition_ConditionType_OneOfCase_GPBUnsetOneOfCase:
  463. return Precondition::None();
  464. case GCFSPrecondition_ConditionType_OneOfCase_Exists:
  465. return Precondition::Exists(precondition.exists);
  466. case GCFSPrecondition_ConditionType_OneOfCase_UpdateTime:
  467. return Precondition::UpdateTime([self decodedVersion:precondition.updateTime]);
  468. default:
  469. HARD_FAIL("Unrecognized Precondition one-of case %s", precondition);
  470. }
  471. }
  472. - (GCFSDocumentMask *)encodedFieldMask:(const FieldMask &)fieldMask {
  473. GCFSDocumentMask *mask = [GCFSDocumentMask message];
  474. for (const FieldPath &field : fieldMask) {
  475. [mask.fieldPathsArray addObject:util::WrapNSString(field.CanonicalString())];
  476. }
  477. return mask;
  478. }
  479. - (FieldMask)decodedFieldMask:(GCFSDocumentMask *)fieldMask {
  480. std::set<FieldPath> fields;
  481. for (NSString *path in fieldMask.fieldPathsArray) {
  482. fields.insert(FieldPath::FromServerFormat(util::MakeString(path)));
  483. }
  484. return FieldMask(std::move(fields));
  485. }
  486. - (NSMutableArray<GCFSDocumentTransform_FieldTransform *> *)encodedFieldTransforms:
  487. (const std::vector<FieldTransform> &)fieldTransforms {
  488. NSMutableArray *protos = [NSMutableArray array];
  489. for (const FieldTransform &fieldTransform : fieldTransforms) {
  490. GCFSDocumentTransform_FieldTransform *proto = [self encodedFieldTransform:fieldTransform];
  491. [protos addObject:proto];
  492. }
  493. return protos;
  494. }
  495. - (GCFSDocumentTransform_FieldTransform *)encodedFieldTransform:
  496. (const FieldTransform &)fieldTransform {
  497. GCFSDocumentTransform_FieldTransform *proto = [GCFSDocumentTransform_FieldTransform message];
  498. proto.fieldPath = util::WrapNSString(fieldTransform.path().CanonicalString());
  499. if (fieldTransform.transformation().type() == TransformOperation::Type::ServerTimestamp) {
  500. proto.setToServerValue = GCFSDocumentTransform_FieldTransform_ServerValue_RequestTime;
  501. } else if (fieldTransform.transformation().type() == TransformOperation::Type::ArrayUnion) {
  502. proto.appendMissingElements = [self
  503. encodedArrayTransformElements:ArrayTransform::Elements(fieldTransform.transformation())];
  504. } else if (fieldTransform.transformation().type() == TransformOperation::Type::ArrayRemove) {
  505. proto.removeAllFromArray_p = [self
  506. encodedArrayTransformElements:ArrayTransform::Elements(fieldTransform.transformation())];
  507. } else {
  508. HARD_FAIL("Unknown transform: %s type", fieldTransform.transformation().type());
  509. }
  510. return proto;
  511. }
  512. - (GCFSArrayValue *)encodedArrayTransformElements:(const std::vector<FSTFieldValue *> &)elements {
  513. GCFSArrayValue *proto = [GCFSArrayValue message];
  514. NSMutableArray<GCFSValue *> *protoContents = [proto valuesArray];
  515. for (FSTFieldValue *element : elements) {
  516. GCFSValue *converted = [self encodedFieldValue:element];
  517. [protoContents addObject:converted];
  518. }
  519. return proto;
  520. }
  521. - (std::vector<FieldTransform>)decodedFieldTransforms:
  522. (NSArray<GCFSDocumentTransform_FieldTransform *> *)protos {
  523. std::vector<FieldTransform> fieldTransforms;
  524. fieldTransforms.reserve(protos.count);
  525. for (GCFSDocumentTransform_FieldTransform *proto in protos) {
  526. switch (proto.transformTypeOneOfCase) {
  527. case GCFSDocumentTransform_FieldTransform_TransformType_OneOfCase_SetToServerValue: {
  528. HARD_ASSERT(
  529. proto.setToServerValue == GCFSDocumentTransform_FieldTransform_ServerValue_RequestTime,
  530. "Unknown transform setToServerValue: %s", proto.setToServerValue);
  531. fieldTransforms.emplace_back(
  532. FieldPath::FromServerFormat(util::MakeString(proto.fieldPath)),
  533. absl::make_unique<ServerTimestampTransform>(ServerTimestampTransform::Get()));
  534. break;
  535. }
  536. case GCFSDocumentTransform_FieldTransform_TransformType_OneOfCase_AppendMissingElements: {
  537. std::vector<FSTFieldValue *> elements =
  538. [self decodedArrayTransformElements:proto.appendMissingElements];
  539. fieldTransforms.emplace_back(
  540. FieldPath::FromServerFormat(util::MakeString(proto.fieldPath)),
  541. absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayUnion,
  542. std::move(elements)));
  543. break;
  544. }
  545. case GCFSDocumentTransform_FieldTransform_TransformType_OneOfCase_RemoveAllFromArray_p: {
  546. std::vector<FSTFieldValue *> elements =
  547. [self decodedArrayTransformElements:proto.removeAllFromArray_p];
  548. fieldTransforms.emplace_back(
  549. FieldPath::FromServerFormat(util::MakeString(proto.fieldPath)),
  550. absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayRemove,
  551. std::move(elements)));
  552. break;
  553. }
  554. default:
  555. HARD_FAIL("Unknown transform: %s", proto);
  556. }
  557. }
  558. return fieldTransforms;
  559. }
  560. - (std::vector<FSTFieldValue *>)decodedArrayTransformElements:(GCFSArrayValue *)proto {
  561. __block std::vector<FSTFieldValue *> elements;
  562. [proto.valuesArray enumerateObjectsUsingBlock:^(GCFSValue *value, NSUInteger idx, BOOL *stop) {
  563. elements.push_back([self decodedFieldValue:value]);
  564. }];
  565. return elements;
  566. }
  567. #pragma mark - FSTMutationResult <= GCFSWriteResult proto
  568. - (FSTMutationResult *)decodedMutationResult:(GCFSWriteResult *)mutation
  569. commitVersion:(const SnapshotVersion &)commitVersion {
  570. // NOTE: Deletes don't have an updateTime. Use commitVersion instead.
  571. SnapshotVersion version =
  572. mutation.hasUpdateTime ? [self decodedVersion:mutation.updateTime] : commitVersion;
  573. NSMutableArray *_Nullable transformResults = nil;
  574. if (mutation.transformResultsArray.count > 0) {
  575. transformResults = [NSMutableArray array];
  576. for (GCFSValue *result in mutation.transformResultsArray) {
  577. [transformResults addObject:[self decodedFieldValue:result]];
  578. }
  579. }
  580. return [[FSTMutationResult alloc] initWithVersion:std::move(version)
  581. transformResults:transformResults];
  582. }
  583. #pragma mark - FSTQueryData => GCFSTarget proto
  584. - (nullable NSMutableDictionary<NSString *, NSString *> *)encodedListenRequestLabelsForQueryData:
  585. (FSTQueryData *)queryData {
  586. NSString *value = [self encodedLabelForPurpose:queryData.purpose];
  587. if (!value) {
  588. return nil;
  589. }
  590. NSMutableDictionary<NSString *, NSString *> *result =
  591. [NSMutableDictionary dictionaryWithCapacity:1];
  592. [result setObject:value forKey:@"goog-listen-tags"];
  593. return result;
  594. }
  595. - (nullable NSString *)encodedLabelForPurpose:(FSTQueryPurpose)purpose {
  596. switch (purpose) {
  597. case FSTQueryPurposeListen:
  598. return nil;
  599. case FSTQueryPurposeExistenceFilterMismatch:
  600. return @"existence-filter-mismatch";
  601. case FSTQueryPurposeLimboResolution:
  602. return @"limbo-document";
  603. default:
  604. HARD_FAIL("Unrecognized query purpose: %s", purpose);
  605. }
  606. }
  607. - (GCFSTarget *)encodedTarget:(FSTQueryData *)queryData {
  608. GCFSTarget *result = [GCFSTarget message];
  609. FSTQuery *query = queryData.query;
  610. if ([query isDocumentQuery]) {
  611. result.documents = [self encodedDocumentsTarget:query];
  612. } else {
  613. result.query = [self encodedQueryTarget:query];
  614. }
  615. result.targetId = queryData.targetID;
  616. if (queryData.resumeToken.length > 0) {
  617. result.resumeToken = queryData.resumeToken;
  618. }
  619. return result;
  620. }
  621. - (GCFSTarget_DocumentsTarget *)encodedDocumentsTarget:(FSTQuery *)query {
  622. GCFSTarget_DocumentsTarget *result = [GCFSTarget_DocumentsTarget message];
  623. NSMutableArray<NSString *> *docs = result.documentsArray;
  624. [docs addObject:[self encodedQueryPath:query.path]];
  625. return result;
  626. }
  627. - (FSTQuery *)decodedQueryFromDocumentsTarget:(GCFSTarget_DocumentsTarget *)target {
  628. NSArray<NSString *> *documents = target.documentsArray;
  629. HARD_ASSERT(documents.count == 1, "DocumentsTarget contained other than 1 document %s",
  630. (unsigned long)documents.count);
  631. NSString *name = documents[0];
  632. return [FSTQuery queryWithPath:[self decodedQueryPath:name]];
  633. }
  634. - (GCFSTarget_QueryTarget *)encodedQueryTarget:(FSTQuery *)query {
  635. // Dissect the path into parent, collectionId, and optional key filter.
  636. GCFSTarget_QueryTarget *queryTarget = [GCFSTarget_QueryTarget message];
  637. if (query.path.size() == 0) {
  638. queryTarget.parent = [self encodedQueryPath:query.path];
  639. } else {
  640. const ResourcePath &path = query.path;
  641. HARD_ASSERT(path.size() % 2 != 0, "Document queries with filters are not supported.");
  642. queryTarget.parent = [self encodedQueryPath:path.PopLast()];
  643. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  644. from.collectionId = util::WrapNSString(path.last_segment());
  645. [queryTarget.structuredQuery.fromArray addObject:from];
  646. }
  647. // Encode the filters.
  648. GCFSStructuredQuery_Filter *_Nullable where = [self encodedFilters:query.filters];
  649. if (where) {
  650. queryTarget.structuredQuery.where = where;
  651. }
  652. NSArray<GCFSStructuredQuery_Order *> *orders = [self encodedSortOrders:query.sortOrders];
  653. if (orders.count) {
  654. [queryTarget.structuredQuery.orderByArray addObjectsFromArray:orders];
  655. }
  656. if (query.limit != NSNotFound) {
  657. queryTarget.structuredQuery.limit.value = (int32_t)query.limit;
  658. }
  659. if (query.startAt) {
  660. queryTarget.structuredQuery.startAt = [self encodedBound:query.startAt];
  661. }
  662. if (query.endAt) {
  663. queryTarget.structuredQuery.endAt = [self encodedBound:query.endAt];
  664. }
  665. return queryTarget;
  666. }
  667. - (FSTQuery *)decodedQueryFromQueryTarget:(GCFSTarget_QueryTarget *)target {
  668. ResourcePath path = [self decodedQueryPath:target.parent];
  669. GCFSStructuredQuery *query = target.structuredQuery;
  670. NSUInteger fromCount = query.fromArray_Count;
  671. if (fromCount > 0) {
  672. HARD_ASSERT(fromCount == 1,
  673. "StructuredQuery.from with more than one collection is not supported.");
  674. GCFSStructuredQuery_CollectionSelector *from = query.fromArray[0];
  675. path = path.Append(util::MakeString(from.collectionId));
  676. }
  677. NSArray<FSTFilter *> *filterBy;
  678. if (query.hasWhere) {
  679. filterBy = [self decodedFilters:query.where];
  680. } else {
  681. filterBy = @[];
  682. }
  683. NSArray<FSTSortOrder *> *orderBy;
  684. if (query.orderByArray_Count > 0) {
  685. orderBy = [self decodedSortOrders:query.orderByArray];
  686. } else {
  687. orderBy = @[];
  688. }
  689. NSInteger limit = NSNotFound;
  690. if (query.hasLimit) {
  691. limit = query.limit.value;
  692. }
  693. FSTBound *_Nullable startAt;
  694. if (query.hasStartAt) {
  695. startAt = [self decodedBound:query.startAt];
  696. }
  697. FSTBound *_Nullable endAt;
  698. if (query.hasEndAt) {
  699. endAt = [self decodedBound:query.endAt];
  700. }
  701. return [[FSTQuery alloc] initWithPath:path
  702. filterBy:filterBy
  703. orderBy:orderBy
  704. limit:limit
  705. startAt:startAt
  706. endAt:endAt];
  707. }
  708. #pragma mark Filters
  709. - (GCFSStructuredQuery_Filter *_Nullable)encodedFilters:(NSArray<FSTFilter *> *)filters {
  710. if (filters.count == 0) {
  711. return nil;
  712. }
  713. NSMutableArray<GCFSStructuredQuery_Filter *> *protos = [NSMutableArray array];
  714. for (FSTFilter *filter in filters) {
  715. if ([filter isKindOfClass:[FSTRelationFilter class]]) {
  716. [protos addObject:[self encodedRelationFilter:(FSTRelationFilter *)filter]];
  717. } else {
  718. [protos addObject:[self encodedUnaryFilter:filter]];
  719. }
  720. }
  721. if (protos.count == 1) {
  722. // Special case: no existing filters and we only need to add one filter. This can be made the
  723. // single root filter without a composite filter.
  724. return protos[0];
  725. }
  726. GCFSStructuredQuery_Filter *composite = [GCFSStructuredQuery_Filter message];
  727. composite.compositeFilter.op = GCFSStructuredQuery_CompositeFilter_Operator_And;
  728. composite.compositeFilter.filtersArray = protos;
  729. return composite;
  730. }
  731. - (NSArray<FSTFilter *> *)decodedFilters:(GCFSStructuredQuery_Filter *)proto {
  732. NSMutableArray<FSTFilter *> *result = [NSMutableArray array];
  733. NSArray<GCFSStructuredQuery_Filter *> *filters;
  734. if (proto.filterTypeOneOfCase ==
  735. GCFSStructuredQuery_Filter_FilterType_OneOfCase_CompositeFilter) {
  736. HARD_ASSERT(proto.compositeFilter.op == GCFSStructuredQuery_CompositeFilter_Operator_And,
  737. "Only AND-type composite filters are supported, got %s", proto.compositeFilter.op);
  738. filters = proto.compositeFilter.filtersArray;
  739. } else {
  740. filters = @[ proto ];
  741. }
  742. for (GCFSStructuredQuery_Filter *filter in filters) {
  743. switch (filter.filterTypeOneOfCase) {
  744. case GCFSStructuredQuery_Filter_FilterType_OneOfCase_CompositeFilter:
  745. HARD_FAIL("Nested composite filters are not supported");
  746. case GCFSStructuredQuery_Filter_FilterType_OneOfCase_FieldFilter:
  747. [result addObject:[self decodedRelationFilter:filter.fieldFilter]];
  748. break;
  749. case GCFSStructuredQuery_Filter_FilterType_OneOfCase_UnaryFilter:
  750. [result addObject:[self decodedUnaryFilter:filter.unaryFilter]];
  751. break;
  752. default:
  753. HARD_FAIL("Unrecognized Filter.filterType %s", filter.filterTypeOneOfCase);
  754. }
  755. }
  756. return result;
  757. }
  758. - (GCFSStructuredQuery_Filter *)encodedRelationFilter:(FSTRelationFilter *)filter {
  759. GCFSStructuredQuery_Filter *proto = [GCFSStructuredQuery_Filter message];
  760. GCFSStructuredQuery_FieldFilter *fieldFilter = proto.fieldFilter;
  761. fieldFilter.field = [self encodedFieldPath:filter.field];
  762. fieldFilter.op = [self encodedRelationFilterOperator:filter.filterOperator];
  763. fieldFilter.value = [self encodedFieldValue:filter.value];
  764. return proto;
  765. }
  766. - (FSTRelationFilter *)decodedRelationFilter:(GCFSStructuredQuery_FieldFilter *)proto {
  767. FieldPath fieldPath = FieldPath::FromServerFormat(util::MakeString(proto.field.fieldPath));
  768. FSTRelationFilterOperator filterOperator = [self decodedRelationFilterOperator:proto.op];
  769. FSTFieldValue *value = [self decodedFieldValue:proto.value];
  770. return [FSTRelationFilter filterWithField:fieldPath filterOperator:filterOperator value:value];
  771. }
  772. - (GCFSStructuredQuery_Filter *)encodedUnaryFilter:(FSTFilter *)filter {
  773. GCFSStructuredQuery_Filter *proto = [GCFSStructuredQuery_Filter message];
  774. proto.unaryFilter.field = [self encodedFieldPath:filter.field];
  775. if ([filter isKindOfClass:[FSTNanFilter class]]) {
  776. proto.unaryFilter.op = GCFSStructuredQuery_UnaryFilter_Operator_IsNan;
  777. } else if ([filter isKindOfClass:[FSTNullFilter class]]) {
  778. proto.unaryFilter.op = GCFSStructuredQuery_UnaryFilter_Operator_IsNull;
  779. } else {
  780. HARD_FAIL("Unrecognized filter: %s", filter);
  781. }
  782. return proto;
  783. }
  784. - (FSTFilter *)decodedUnaryFilter:(GCFSStructuredQuery_UnaryFilter *)proto {
  785. FieldPath field = FieldPath::FromServerFormat(util::MakeString(proto.field.fieldPath));
  786. switch (proto.op) {
  787. case GCFSStructuredQuery_UnaryFilter_Operator_IsNan:
  788. return [[FSTNanFilter alloc] initWithField:field];
  789. case GCFSStructuredQuery_UnaryFilter_Operator_IsNull:
  790. return [[FSTNullFilter alloc] initWithField:field];
  791. default:
  792. HARD_FAIL("Unrecognized UnaryFilter.operator %s", proto.op);
  793. }
  794. }
  795. - (GCFSStructuredQuery_FieldReference *)encodedFieldPath:(const FieldPath &)fieldPath {
  796. GCFSStructuredQuery_FieldReference *ref = [GCFSStructuredQuery_FieldReference message];
  797. ref.fieldPath = util::WrapNSString(fieldPath.CanonicalString());
  798. return ref;
  799. }
  800. - (GCFSStructuredQuery_FieldFilter_Operator)encodedRelationFilterOperator:
  801. (FSTRelationFilterOperator)filterOperator {
  802. switch (filterOperator) {
  803. case FSTRelationFilterOperatorLessThan:
  804. return GCFSStructuredQuery_FieldFilter_Operator_LessThan;
  805. case FSTRelationFilterOperatorLessThanOrEqual:
  806. return GCFSStructuredQuery_FieldFilter_Operator_LessThanOrEqual;
  807. case FSTRelationFilterOperatorEqual:
  808. return GCFSStructuredQuery_FieldFilter_Operator_Equal;
  809. case FSTRelationFilterOperatorGreaterThanOrEqual:
  810. return GCFSStructuredQuery_FieldFilter_Operator_GreaterThanOrEqual;
  811. case FSTRelationFilterOperatorGreaterThan:
  812. return GCFSStructuredQuery_FieldFilter_Operator_GreaterThan;
  813. case FSTRelationFilterOperatorArrayContains:
  814. return GCFSStructuredQuery_FieldFilter_Operator_ArrayContains;
  815. default:
  816. HARD_FAIL("Unhandled FSTRelationFilterOperator: %s", filterOperator);
  817. }
  818. }
  819. - (FSTRelationFilterOperator)decodedRelationFilterOperator:
  820. (GCFSStructuredQuery_FieldFilter_Operator)filterOperator {
  821. switch (filterOperator) {
  822. case GCFSStructuredQuery_FieldFilter_Operator_LessThan:
  823. return FSTRelationFilterOperatorLessThan;
  824. case GCFSStructuredQuery_FieldFilter_Operator_LessThanOrEqual:
  825. return FSTRelationFilterOperatorLessThanOrEqual;
  826. case GCFSStructuredQuery_FieldFilter_Operator_Equal:
  827. return FSTRelationFilterOperatorEqual;
  828. case GCFSStructuredQuery_FieldFilter_Operator_GreaterThanOrEqual:
  829. return FSTRelationFilterOperatorGreaterThanOrEqual;
  830. case GCFSStructuredQuery_FieldFilter_Operator_GreaterThan:
  831. return FSTRelationFilterOperatorGreaterThan;
  832. case GCFSStructuredQuery_FieldFilter_Operator_ArrayContains:
  833. return FSTRelationFilterOperatorArrayContains;
  834. default:
  835. HARD_FAIL("Unhandled FieldFilter.operator: %s", filterOperator);
  836. }
  837. }
  838. #pragma mark Property Orders
  839. - (NSArray<GCFSStructuredQuery_Order *> *)encodedSortOrders:(NSArray<FSTSortOrder *> *)orders {
  840. NSMutableArray<GCFSStructuredQuery_Order *> *protos = [NSMutableArray array];
  841. for (FSTSortOrder *order in orders) {
  842. [protos addObject:[self encodedSortOrder:order]];
  843. }
  844. return protos;
  845. }
  846. - (NSArray<FSTSortOrder *> *)decodedSortOrders:(NSArray<GCFSStructuredQuery_Order *> *)protos {
  847. NSMutableArray<FSTSortOrder *> *result = [NSMutableArray arrayWithCapacity:protos.count];
  848. for (GCFSStructuredQuery_Order *orderProto in protos) {
  849. [result addObject:[self decodedSortOrder:orderProto]];
  850. }
  851. return result;
  852. }
  853. - (GCFSStructuredQuery_Order *)encodedSortOrder:(FSTSortOrder *)sortOrder {
  854. GCFSStructuredQuery_Order *proto = [GCFSStructuredQuery_Order message];
  855. proto.field = [self encodedFieldPath:sortOrder.field];
  856. if (sortOrder.ascending) {
  857. proto.direction = GCFSStructuredQuery_Direction_Ascending;
  858. } else {
  859. proto.direction = GCFSStructuredQuery_Direction_Descending;
  860. }
  861. return proto;
  862. }
  863. - (FSTSortOrder *)decodedSortOrder:(GCFSStructuredQuery_Order *)proto {
  864. FieldPath fieldPath = FieldPath::FromServerFormat(util::MakeString(proto.field.fieldPath));
  865. BOOL ascending;
  866. switch (proto.direction) {
  867. case GCFSStructuredQuery_Direction_Ascending:
  868. ascending = YES;
  869. break;
  870. case GCFSStructuredQuery_Direction_Descending:
  871. ascending = NO;
  872. break;
  873. default:
  874. HARD_FAIL("Unrecognized GCFSStructuredQuery_Direction %s", proto.direction);
  875. }
  876. return [FSTSortOrder sortOrderWithFieldPath:fieldPath ascending:ascending];
  877. }
  878. #pragma mark - Bounds/Cursors
  879. - (GCFSCursor *)encodedBound:(FSTBound *)bound {
  880. GCFSCursor *proto = [GCFSCursor message];
  881. proto.before = bound.isBefore;
  882. for (FSTFieldValue *fieldValue in bound.position) {
  883. GCFSValue *value = [self encodedFieldValue:fieldValue];
  884. [proto.valuesArray addObject:value];
  885. }
  886. return proto;
  887. }
  888. - (FSTBound *)decodedBound:(GCFSCursor *)proto {
  889. NSMutableArray<FSTFieldValue *> *indexComponents = [NSMutableArray array];
  890. for (GCFSValue *valueProto in proto.valuesArray) {
  891. FSTFieldValue *value = [self decodedFieldValue:valueProto];
  892. [indexComponents addObject:value];
  893. }
  894. return [FSTBound boundWithPosition:indexComponents isBefore:proto.before];
  895. }
  896. #pragma mark - WatchChange <= GCFSListenResponse proto
  897. - (std::unique_ptr<WatchChange>)decodedWatchChange:(GCFSListenResponse *)watchChange {
  898. switch (watchChange.responseTypeOneOfCase) {
  899. case GCFSListenResponse_ResponseType_OneOfCase_TargetChange:
  900. return [self decodedTargetChangeFromWatchChange:watchChange.targetChange];
  901. case GCFSListenResponse_ResponseType_OneOfCase_DocumentChange:
  902. return [self decodedDocumentChange:watchChange.documentChange];
  903. case GCFSListenResponse_ResponseType_OneOfCase_DocumentDelete:
  904. return [self decodedDocumentDelete:watchChange.documentDelete];
  905. case GCFSListenResponse_ResponseType_OneOfCase_DocumentRemove:
  906. return [self decodedDocumentRemove:watchChange.documentRemove];
  907. case GCFSListenResponse_ResponseType_OneOfCase_Filter:
  908. return [self decodedExistenceFilterWatchChange:watchChange.filter];
  909. default:
  910. HARD_FAIL("Unknown WatchChange.changeType %s", watchChange.responseTypeOneOfCase);
  911. }
  912. }
  913. - (SnapshotVersion)versionFromListenResponse:(GCFSListenResponse *)watchChange {
  914. // We have only reached a consistent snapshot for the entire stream if there is a read_time set
  915. // and it applies to all targets (i.e. the list of targets is empty). The backend is guaranteed to
  916. // send such responses.
  917. if (watchChange.responseTypeOneOfCase != GCFSListenResponse_ResponseType_OneOfCase_TargetChange) {
  918. return SnapshotVersion::None();
  919. }
  920. if (watchChange.targetChange.targetIdsArray.count != 0) {
  921. return SnapshotVersion::None();
  922. }
  923. return [self decodedVersion:watchChange.targetChange.readTime];
  924. }
  925. - (std::unique_ptr<WatchChange>)decodedTargetChangeFromWatchChange:(GCFSTargetChange *)change {
  926. WatchTargetChangeState state = [self decodedWatchTargetChangeState:change.targetChangeType];
  927. __block std::vector<TargetId> targetIDs;
  928. [change.targetIdsArray enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) {
  929. targetIDs.push_back(value);
  930. }];
  931. NSData *resumeToken = change.resumeToken;
  932. util::Status cause;
  933. if (change.hasCause) {
  934. cause = util::Status{static_cast<FirestoreErrorCode>(change.cause.code),
  935. util::MakeString(change.cause.message)};
  936. }
  937. return absl::make_unique<WatchTargetChange>(state, std::move(targetIDs), resumeToken,
  938. std::move(cause));
  939. }
  940. - (WatchTargetChangeState)decodedWatchTargetChangeState:(GCFSTargetChange_TargetChangeType)state {
  941. switch (state) {
  942. case GCFSTargetChange_TargetChangeType_NoChange:
  943. return WatchTargetChangeState::NoChange;
  944. case GCFSTargetChange_TargetChangeType_Add:
  945. return WatchTargetChangeState::Added;
  946. case GCFSTargetChange_TargetChangeType_Remove:
  947. return WatchTargetChangeState::Removed;
  948. case GCFSTargetChange_TargetChangeType_Current:
  949. return WatchTargetChangeState::Current;
  950. case GCFSTargetChange_TargetChangeType_Reset:
  951. return WatchTargetChangeState::Reset;
  952. default:
  953. HARD_FAIL("Unexpected TargetChange.state: %s", state);
  954. }
  955. }
  956. - (std::vector<TargetId>)decodedIntegerArray:(GPBInt32Array *)values {
  957. __block std::vector<TargetId> result;
  958. result.reserve(values.count);
  959. [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) {
  960. result.push_back(value);
  961. }];
  962. return result;
  963. }
  964. - (std::unique_ptr<WatchChange>)decodedDocumentChange:(GCFSDocumentChange *)change {
  965. FSTObjectValue *value = [self decodedFields:change.document.fields];
  966. DocumentKey key = [self decodedDocumentKey:change.document.name];
  967. SnapshotVersion version = [self decodedVersion:change.document.updateTime];
  968. HARD_ASSERT(version != SnapshotVersion::None(), "Got a document change with no snapshot version");
  969. // The document may soon be re-serialized back to protos in order to store it in local
  970. // persistence. Memoize the encoded form to avoid encoding it again.
  971. FSTMaybeDocument *document = [FSTDocument documentWithData:value
  972. key:key
  973. version:version
  974. state:FSTDocumentStateSynced
  975. proto:change.document];
  976. std::vector<TargetId> updatedTargetIDs = [self decodedIntegerArray:change.targetIdsArray];
  977. std::vector<TargetId> removedTargetIDs = [self decodedIntegerArray:change.removedTargetIdsArray];
  978. return absl::make_unique<DocumentWatchChange>(
  979. std::move(updatedTargetIDs), std::move(removedTargetIDs), std::move(key), document);
  980. }
  981. - (std::unique_ptr<WatchChange>)decodedDocumentDelete:(GCFSDocumentDelete *)change {
  982. DocumentKey key = [self decodedDocumentKey:change.document];
  983. // Note that version might be unset in which case we use SnapshotVersion::None()
  984. SnapshotVersion version = [self decodedVersion:change.readTime];
  985. FSTMaybeDocument *document = [FSTDeletedDocument documentWithKey:key
  986. version:version
  987. hasCommittedMutations:NO];
  988. std::vector<TargetId> removedTargetIDs = [self decodedIntegerArray:change.removedTargetIdsArray];
  989. return absl::make_unique<DocumentWatchChange>(
  990. std::vector<TargetId>{}, std::move(removedTargetIDs), std::move(key), document);
  991. }
  992. - (std::unique_ptr<WatchChange>)decodedDocumentRemove:(GCFSDocumentRemove *)change {
  993. DocumentKey key = [self decodedDocumentKey:change.document];
  994. std::vector<TargetId> removedTargetIDs = [self decodedIntegerArray:change.removedTargetIdsArray];
  995. return absl::make_unique<DocumentWatchChange>(std::vector<TargetId>{},
  996. std::move(removedTargetIDs), std::move(key), nil);
  997. }
  998. - (std::unique_ptr<WatchChange>)decodedExistenceFilterWatchChange:(GCFSExistenceFilter *)filter {
  999. ExistenceFilter existenceFilter{filter.count};
  1000. TargetId targetID = filter.targetId;
  1001. return absl::make_unique<ExistenceFilterWatchChange>(existenceFilter, targetID);
  1002. }
  1003. @end
  1004. NS_ASSUME_NONNULL_END