FSTSerializerBeta.mm 48 KB

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