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