FSTSerializerBeta.mm 46 KB

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