FSTSerializerBeta.mm 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  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/include/firebase/firestore/geo_point.h"
  40. #include "Firestore/core/src/firebase/firestore/core/filter.h"
  41. #include "Firestore/core/src/firebase/firestore/core/query.h"
  42. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  43. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  44. #include "Firestore/core/src/firebase/firestore/model/field_mask.h"
  45. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  46. #include "Firestore/core/src/firebase/firestore/model/field_transform.h"
  47. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  48. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  49. #include "Firestore/core/src/firebase/firestore/model/transform_operations.h"
  50. #include "Firestore/core/src/firebase/firestore/nanopb/nanopb_util.h"
  51. #include "Firestore/core/src/firebase/firestore/remote/existence_filter.h"
  52. #include "Firestore/core/src/firebase/firestore/remote/watch_change.h"
  53. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  54. #include "Firestore/core/src/firebase/firestore/util/status.h"
  55. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  56. #include "absl/memory/memory.h"
  57. #include "absl/types/optional.h"
  58. namespace util = firebase::firestore::util;
  59. using firebase::Timestamp;
  60. using firebase::firestore::FirestoreErrorCode;
  61. using firebase::firestore::GeoPoint;
  62. using firebase::firestore::core::Filter;
  63. using firebase::firestore::core::Query;
  64. using firebase::firestore::model::ArrayTransform;
  65. using firebase::firestore::model::DatabaseId;
  66. using firebase::firestore::model::DocumentKey;
  67. using firebase::firestore::model::FieldMask;
  68. using firebase::firestore::model::FieldPath;
  69. using firebase::firestore::model::FieldTransform;
  70. using firebase::firestore::model::FieldValue;
  71. using firebase::firestore::model::NumericIncrementTransform;
  72. using firebase::firestore::model::Precondition;
  73. using firebase::firestore::model::ResourcePath;
  74. using firebase::firestore::model::ServerTimestampTransform;
  75. using firebase::firestore::model::SnapshotVersion;
  76. using firebase::firestore::model::TargetId;
  77. using firebase::firestore::model::TransformOperation;
  78. using firebase::firestore::nanopb::MakeByteString;
  79. using firebase::firestore::remote::DocumentWatchChange;
  80. using firebase::firestore::remote::ExistenceFilter;
  81. using firebase::firestore::remote::ExistenceFilterWatchChange;
  82. using firebase::firestore::remote::WatchChange;
  83. using firebase::firestore::remote::WatchTargetChange;
  84. using firebase::firestore::remote::WatchTargetChangeState;
  85. NS_ASSUME_NONNULL_BEGIN
  86. @implementation FSTSerializerBeta {
  87. DatabaseId _databaseID;
  88. }
  89. - (instancetype)initWithDatabaseID:(DatabaseId)databaseID {
  90. self = [super init];
  91. if (self) {
  92. _databaseID = std::move(databaseID);
  93. }
  94. return self;
  95. }
  96. #pragma mark - SnapshotVersion <=> GPBTimestamp
  97. - (GPBTimestamp *)encodedTimestamp:(const Timestamp &)timestamp {
  98. GPBTimestamp *result = [GPBTimestamp message];
  99. result.seconds = timestamp.seconds();
  100. result.nanos = timestamp.nanoseconds();
  101. return result;
  102. }
  103. - (Timestamp)decodedTimestamp:(GPBTimestamp *)timestamp {
  104. return Timestamp{timestamp.seconds, timestamp.nanos};
  105. }
  106. - (GPBTimestamp *)encodedVersion:(const SnapshotVersion &)version {
  107. return [self encodedTimestamp:version.timestamp()];
  108. }
  109. - (SnapshotVersion)decodedVersion:(GPBTimestamp *)version {
  110. return SnapshotVersion{[self decodedTimestamp:version]};
  111. }
  112. #pragma mark - FIRGeoPoint <=> GTPLatLng
  113. - (GTPLatLng *)encodedGeoPoint:(FIRGeoPoint *)geoPoint {
  114. GTPLatLng *latLng = [GTPLatLng message];
  115. latLng.latitude = geoPoint.latitude;
  116. latLng.longitude = geoPoint.longitude;
  117. return latLng;
  118. }
  119. - (GeoPoint)decodedGeoPoint:(GTPLatLng *)latLng {
  120. return GeoPoint(latLng.latitude, latLng.longitude);
  121. }
  122. #pragma mark - DocumentKey <=> Key proto
  123. - (NSString *)encodedDocumentKey:(const DocumentKey &)key {
  124. return [self encodedResourcePathForDatabaseID:_databaseID path:key.path()];
  125. }
  126. - (DocumentKey)decodedDocumentKey:(NSString *)name {
  127. const ResourcePath path = [self decodedResourcePathWithDatabaseID:name];
  128. HARD_ASSERT(path[1] == _databaseID.project_id(),
  129. "Tried to deserialize key from different project.");
  130. HARD_ASSERT(path[3] == _databaseID.database_id(),
  131. "Tried to deserialize key from different datbase.");
  132. return DocumentKey{[self localResourcePathForQualifiedResourcePath:path]};
  133. }
  134. - (NSString *)encodedResourcePathForDatabaseID:(const DatabaseId &)databaseID
  135. path:(const ResourcePath &)path {
  136. return util::WrapNSString([self encodedResourcePathForDatabaseID:databaseID]
  137. .Append("documents")
  138. .Append(path)
  139. .CanonicalString());
  140. }
  141. - (ResourcePath)decodedResourcePathWithDatabaseID:(NSString *)name {
  142. const ResourcePath path = ResourcePath::FromString(util::MakeString(name));
  143. HARD_ASSERT([self validQualifiedResourcePath:path], "Tried to deserialize invalid key %s",
  144. path.CanonicalString());
  145. return path;
  146. }
  147. - (NSString *)encodedQueryPath:(const ResourcePath &)path {
  148. return [self encodedResourcePathForDatabaseID:_databaseID path:path];
  149. }
  150. - (ResourcePath)decodedQueryPath:(NSString *)name {
  151. const ResourcePath resource = [self decodedResourcePathWithDatabaseID:name];
  152. if (resource.size() == 4) {
  153. // In v1beta1 queries for collections at the root did not have a trailing "/documents". In v1
  154. // all resource paths contain "/documents". Preserve the ability to read the v1beta1 form for
  155. // compatibility with queries persisted in the local query cache.
  156. return ResourcePath{};
  157. } else {
  158. return [self localResourcePathForQualifiedResourcePath:resource];
  159. }
  160. }
  161. - (ResourcePath)encodedResourcePathForDatabaseID:(const DatabaseId &)databaseID {
  162. return ResourcePath{"projects", databaseID.project_id(), "databases", databaseID.database_id()};
  163. }
  164. - (ResourcePath)localResourcePathForQualifiedResourcePath:(const ResourcePath &)resourceName {
  165. HARD_ASSERT(resourceName.size() > 4 && resourceName[4] == "documents",
  166. "Tried to deserialize invalid key %s", resourceName.CanonicalString());
  167. return resourceName.PopFirst(5);
  168. }
  169. - (BOOL)validQualifiedResourcePath:(const ResourcePath &)path {
  170. return path.size() >= 4 && path[0] == "projects" && path[2] == "databases";
  171. }
  172. - (NSString *)encodedDatabaseID {
  173. return util::WrapNSString([self encodedResourcePathForDatabaseID:_databaseID].CanonicalString());
  174. }
  175. #pragma mark - FSTFieldValue <=> Value proto
  176. - (GCFSValue *)encodedFieldValue:(FSTFieldValue *)fieldValue {
  177. switch (fieldValue.type) {
  178. case FieldValue::Type::Null:
  179. return [self encodedNull];
  180. case FieldValue::Type::Boolean:
  181. return [self encodedBool:[[fieldValue value] boolValue]];
  182. case FieldValue::Type::Integer:
  183. return [self encodedInteger:[[fieldValue value] longLongValue]];
  184. case FieldValue::Type::Double:
  185. return [self encodedDouble:[[fieldValue value] doubleValue]];
  186. case FieldValue::Type::Timestamp: {
  187. FIRTimestamp *value = static_cast<FIRTimestamp *>([fieldValue value]);
  188. return [self encodedTimestampValue:Timestamp{value.seconds, value.nanoseconds}];
  189. }
  190. case FieldValue::Type::String:
  191. return [self encodedString:[fieldValue value]];
  192. case FieldValue::Type::Blob:
  193. return [self encodedBlobValue:[fieldValue value]];
  194. case FieldValue::Type::Reference: {
  195. FSTReferenceValue *ref = (FSTReferenceValue *)fieldValue;
  196. DocumentKey key = [[ref value] key];
  197. return [self encodedReferenceValueForDatabaseID:[ref databaseID] key:key];
  198. }
  199. case FieldValue::Type::GeoPoint:
  200. return [self encodedGeoPointValue:[fieldValue value]];
  201. case FieldValue::Type::Array: {
  202. GCFSValue *result = [GCFSValue message];
  203. result.arrayValue = [self encodedArrayValue:(FSTArrayValue *)fieldValue];
  204. return result;
  205. }
  206. case FieldValue::Type::Object: {
  207. GCFSValue *result = [GCFSValue message];
  208. result.mapValue = [self encodedMapValue:(FSTObjectValue *)fieldValue];
  209. return result;
  210. }
  211. case FieldValue::Type::ServerTimestamp:
  212. HARD_FAIL("Unhandled type %s on %s", NSStringFromClass([fieldValue class]), fieldValue);
  213. }
  214. UNREACHABLE();
  215. }
  216. - (FSTFieldValue *)decodedFieldValue:(GCFSValue *)valueProto {
  217. switch (valueProto.valueTypeOneOfCase) {
  218. case GCFSValue_ValueType_OneOfCase_NullValue:
  219. return FieldValue::Null().Wrap();
  220. case GCFSValue_ValueType_OneOfCase_BooleanValue:
  221. return FieldValue::FromBoolean(valueProto.booleanValue).Wrap();
  222. case GCFSValue_ValueType_OneOfCase_IntegerValue:
  223. return FieldValue::FromInteger(valueProto.integerValue).Wrap();
  224. case GCFSValue_ValueType_OneOfCase_DoubleValue:
  225. return FieldValue::FromDouble(valueProto.doubleValue).Wrap();
  226. case GCFSValue_ValueType_OneOfCase_StringValue:
  227. return FieldValue::FromString(util::MakeString(valueProto.stringValue)).Wrap();
  228. case GCFSValue_ValueType_OneOfCase_TimestampValue: {
  229. Timestamp value = [self decodedTimestamp:valueProto.timestampValue];
  230. return FieldValue::FromTimestamp(value).Wrap();
  231. }
  232. case GCFSValue_ValueType_OneOfCase_GeoPointValue:
  233. return FieldValue::FromGeoPoint([self decodedGeoPoint:valueProto.geoPointValue]).Wrap();
  234. case GCFSValue_ValueType_OneOfCase_BytesValue:
  235. return FieldValue::FromBlob(MakeByteString(valueProto.bytesValue)).Wrap();
  236. case GCFSValue_ValueType_OneOfCase_ReferenceValue:
  237. return [self decodedReferenceValue:valueProto.referenceValue];
  238. case GCFSValue_ValueType_OneOfCase_ArrayValue:
  239. return [self decodedArrayValue:valueProto.arrayValue];
  240. case GCFSValue_ValueType_OneOfCase_MapValue:
  241. return [self decodedMapValue:valueProto.mapValue];
  242. default:
  243. HARD_FAIL("Unhandled type %s on %s", valueProto.valueTypeOneOfCase, valueProto);
  244. }
  245. }
  246. - (GCFSValue *)encodedNull {
  247. GCFSValue *result = [GCFSValue message];
  248. result.nullValue = GPBNullValue_NullValue;
  249. return result;
  250. }
  251. - (GCFSValue *)encodedBool:(BOOL)value {
  252. GCFSValue *result = [GCFSValue message];
  253. result.booleanValue = value;
  254. return result;
  255. }
  256. - (GCFSValue *)encodedDouble:(double)value {
  257. GCFSValue *result = [GCFSValue message];
  258. result.doubleValue = value;
  259. return result;
  260. }
  261. - (GCFSValue *)encodedInteger:(int64_t)value {
  262. GCFSValue *result = [GCFSValue message];
  263. result.integerValue = value;
  264. return result;
  265. }
  266. - (GCFSValue *)encodedString:(NSString *)value {
  267. GCFSValue *result = [GCFSValue message];
  268. result.stringValue = value;
  269. return result;
  270. }
  271. - (GCFSValue *)encodedTimestampValue:(const Timestamp &)value {
  272. GCFSValue *result = [GCFSValue message];
  273. result.timestampValue = [self encodedTimestamp:value];
  274. return result;
  275. }
  276. - (GCFSValue *)encodedGeoPointValue:(FIRGeoPoint *)value {
  277. GCFSValue *result = [GCFSValue message];
  278. result.geoPointValue = [self encodedGeoPoint:value];
  279. return result;
  280. }
  281. - (GCFSValue *)encodedBlobValue:(NSData *)value {
  282. GCFSValue *result = [GCFSValue message];
  283. result.bytesValue = value;
  284. return result;
  285. }
  286. - (GCFSValue *)encodedReferenceValueForDatabaseID:(const DatabaseId &)databaseID
  287. key:(const DocumentKey &)key {
  288. HARD_ASSERT(databaseID == _databaseID, "Database %s:%s cannot encode reference from %s:%s",
  289. _databaseID.project_id(), _databaseID.database_id(), databaseID.project_id(),
  290. databaseID.database_id());
  291. GCFSValue *result = [GCFSValue message];
  292. result.referenceValue = [self encodedResourcePathForDatabaseID:databaseID path:key.path()];
  293. return result;
  294. }
  295. - (FSTReferenceValue *)decodedReferenceValue:(NSString *)resourceName {
  296. const ResourcePath path = [self decodedResourcePathWithDatabaseID:resourceName];
  297. const std::string &project = path[1];
  298. const std::string &database = path[3];
  299. const DocumentKey key{[self localResourcePathForQualifiedResourcePath:path]};
  300. const DatabaseId database_id(project, database);
  301. HARD_ASSERT(database_id == _databaseID, "Database %s:%s cannot encode reference from %s:%s",
  302. _databaseID.project_id(), _databaseID.database_id(), database_id.project_id(),
  303. database_id.database_id());
  304. return [FSTReferenceValue referenceValue:[FSTDocumentKey keyWithDocumentKey:key]
  305. databaseID:_databaseID];
  306. }
  307. - (GCFSArrayValue *)encodedArrayValue:(FSTArrayValue *)arrayValue {
  308. GCFSArrayValue *proto = [GCFSArrayValue message];
  309. NSMutableArray<GCFSValue *> *protoContents = [proto valuesArray];
  310. [[arrayValue internalValue]
  311. enumerateObjectsUsingBlock:^(FSTFieldValue *value, NSUInteger idx, BOOL *stop) {
  312. GCFSValue *converted = [self encodedFieldValue:value];
  313. [protoContents addObject:converted];
  314. }];
  315. return proto;
  316. }
  317. - (FSTArrayValue *)decodedArrayValue:(GCFSArrayValue *)arrayValue {
  318. NSMutableArray<FSTFieldValue *> *contents =
  319. [NSMutableArray arrayWithCapacity:arrayValue.valuesArray_Count];
  320. [arrayValue.valuesArray
  321. enumerateObjectsUsingBlock:^(GCFSValue *value, NSUInteger idx, BOOL *stop) {
  322. [contents addObject:[self decodedFieldValue:value]];
  323. }];
  324. return [[FSTArrayValue alloc] initWithValueNoCopy:contents];
  325. }
  326. - (GCFSMapValue *)encodedMapValue:(FSTObjectValue *)value {
  327. GCFSMapValue *result = [GCFSMapValue message];
  328. result.fields = [self encodedFields:value];
  329. return result;
  330. }
  331. - (FSTObjectValue *)decodedMapValue:(GCFSMapValue *)map {
  332. return [self decodedFields:map.fields];
  333. }
  334. /**
  335. * Encodes an FSTObjectValue into a dictionary.
  336. * @return a new dictionary that can be assigned to a field in another proto.
  337. */
  338. - (NSMutableDictionary<NSString *, GCFSValue *> *)encodedFields:(FSTObjectValue *)value {
  339. FSTImmutableSortedDictionary<NSString *, FSTFieldValue *> *fields = value.internalValue;
  340. NSMutableDictionary<NSString *, GCFSValue *> *result = [NSMutableDictionary dictionary];
  341. [fields enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *obj, BOOL *stop) {
  342. GCFSValue *converted = [self encodedFieldValue:obj];
  343. result[key] = converted;
  344. }];
  345. return result;
  346. }
  347. - (FSTObjectValue *)decodedFields:(NSDictionary<NSString *, GCFSValue *> *)fields {
  348. __block FSTObjectValue *result = [FSTObjectValue objectValue];
  349. [fields enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, GCFSValue *_Nonnull obj,
  350. BOOL *_Nonnull stop) {
  351. FieldPath path{util::MakeString(key)};
  352. FSTFieldValue *value = [self decodedFieldValue:obj];
  353. result = [result objectBySettingValue:value forPath:path];
  354. }];
  355. return result;
  356. }
  357. #pragma mark - FSTObjectValue <=> Document proto
  358. - (GCFSDocument *)encodedDocumentWithFields:(FSTObjectValue *)objectValue
  359. key:(const DocumentKey &)key {
  360. GCFSDocument *proto = [GCFSDocument message];
  361. proto.name = [self encodedDocumentKey:key];
  362. proto.fields = [self encodedFields:objectValue];
  363. return proto;
  364. }
  365. #pragma mark - FSTMaybeDocument <= BatchGetDocumentsResponse proto
  366. - (FSTMaybeDocument *)decodedMaybeDocumentFromBatch:(GCFSBatchGetDocumentsResponse *)response {
  367. switch (response.resultOneOfCase) {
  368. case GCFSBatchGetDocumentsResponse_Result_OneOfCase_Found:
  369. return [self decodedFoundDocument:response];
  370. case GCFSBatchGetDocumentsResponse_Result_OneOfCase_Missing:
  371. return [self decodedDeletedDocument:response];
  372. default:
  373. HARD_FAIL("Unknown document type: %s", response);
  374. }
  375. }
  376. - (FSTDocument *)decodedFoundDocument:(GCFSBatchGetDocumentsResponse *)response {
  377. HARD_ASSERT(!!response.found, "Tried to deserialize a found document from a deleted document.");
  378. const DocumentKey key = [self decodedDocumentKey:response.found.name];
  379. FSTObjectValue *value = [self decodedFields:response.found.fields];
  380. SnapshotVersion version = [self decodedVersion:response.found.updateTime];
  381. HARD_ASSERT(version != SnapshotVersion::None(),
  382. "Got a document response with no snapshot version");
  383. return [FSTDocument documentWithData:value
  384. key:key
  385. version:version
  386. state:FSTDocumentStateSynced
  387. proto:response.found];
  388. }
  389. - (FSTDeletedDocument *)decodedDeletedDocument:(GCFSBatchGetDocumentsResponse *)response {
  390. HARD_ASSERT(!!response.missing, "Tried to deserialize a deleted document from a found document.");
  391. const DocumentKey key = [self decodedDocumentKey:response.missing];
  392. SnapshotVersion version = [self decodedVersion:response.readTime];
  393. HARD_ASSERT(version != SnapshotVersion::None(),
  394. "Got a no document response with no snapshot version");
  395. return [FSTDeletedDocument documentWithKey:key version:version hasCommittedMutations:NO];
  396. }
  397. #pragma mark - FSTMutation => GCFSWrite proto
  398. - (GCFSWrite *)encodedMutation:(FSTMutation *)mutation {
  399. GCFSWrite *proto = [GCFSWrite message];
  400. Class mutationClass = [mutation class];
  401. if (mutationClass == [FSTSetMutation class]) {
  402. FSTSetMutation *set = (FSTSetMutation *)mutation;
  403. proto.update = [self encodedDocumentWithFields:set.value key:set.key];
  404. } else if (mutationClass == [FSTPatchMutation class]) {
  405. FSTPatchMutation *patch = (FSTPatchMutation *)mutation;
  406. proto.update = [self encodedDocumentWithFields:patch.value key:patch.key];
  407. proto.updateMask = [self encodedFieldMask:*(patch.fieldMask)];
  408. } else if (mutationClass == [FSTTransformMutation class]) {
  409. FSTTransformMutation *transform = (FSTTransformMutation *)mutation;
  410. proto.transform = [GCFSDocumentTransform message];
  411. proto.transform.document = [self encodedDocumentKey:transform.key];
  412. proto.transform.fieldTransformsArray = [self encodedFieldTransforms:transform.fieldTransforms];
  413. // NOTE: We set a precondition of exists: true as a safety-check, since we always combine
  414. // FSTTransformMutations with an FSTSetMutation or FSTPatchMutation which (if successful) should
  415. // end up with an existing document.
  416. proto.currentDocument.exists = YES;
  417. } else if (mutationClass == [FSTDeleteMutation class]) {
  418. FSTDeleteMutation *deleteMutation = (FSTDeleteMutation *)mutation;
  419. proto.delete_p = [self encodedDocumentKey:deleteMutation.key];
  420. } else {
  421. HARD_FAIL("Unknown mutation type %s", NSStringFromClass(mutationClass));
  422. }
  423. if (!mutation.precondition.IsNone()) {
  424. proto.currentDocument = [self encodedPrecondition:mutation.precondition];
  425. }
  426. return proto;
  427. }
  428. - (FSTMutation *)decodedMutation:(GCFSWrite *)mutation {
  429. Precondition precondition = [mutation hasCurrentDocument]
  430. ? [self decodedPrecondition:mutation.currentDocument]
  431. : Precondition::None();
  432. switch (mutation.operationOneOfCase) {
  433. case GCFSWrite_Operation_OneOfCase_Update:
  434. if (mutation.hasUpdateMask) {
  435. return [[FSTPatchMutation alloc] initWithKey:[self decodedDocumentKey:mutation.update.name]
  436. fieldMask:[self decodedFieldMask:mutation.updateMask]
  437. value:[self decodedFields:mutation.update.fields]
  438. precondition:precondition];
  439. } else {
  440. return [[FSTSetMutation alloc] initWithKey:[self decodedDocumentKey:mutation.update.name]
  441. value:[self decodedFields:mutation.update.fields]
  442. precondition:precondition];
  443. }
  444. case GCFSWrite_Operation_OneOfCase_Delete_p:
  445. return [[FSTDeleteMutation alloc] initWithKey:[self decodedDocumentKey:mutation.delete_p]
  446. precondition:precondition];
  447. case GCFSWrite_Operation_OneOfCase_Transform: {
  448. HARD_ASSERT(precondition == Precondition::Exists(true),
  449. "Transforms must have precondition \"exists == true\"");
  450. return [[FSTTransformMutation alloc]
  451. initWithKey:[self decodedDocumentKey:mutation.transform.document]
  452. fieldTransforms:[self decodedFieldTransforms:mutation.transform.fieldTransformsArray]];
  453. }
  454. default:
  455. // Note that insert is intentionally unhandled, since we don't ever deal in them.
  456. HARD_FAIL("Unknown mutation operation: %s", mutation.operationOneOfCase);
  457. }
  458. }
  459. - (GCFSPrecondition *)encodedPrecondition:(const Precondition &)precondition {
  460. HARD_ASSERT(!precondition.IsNone(), "Can't serialize an empty precondition");
  461. GCFSPrecondition *message = [GCFSPrecondition message];
  462. if (precondition.type() == Precondition::Type::UpdateTime) {
  463. message.updateTime = [self encodedVersion:precondition.update_time()];
  464. } else if (precondition.type() == Precondition::Type::Exists) {
  465. message.exists = precondition == Precondition::Exists(true);
  466. } else {
  467. HARD_FAIL("Unknown precondition: %s", precondition.description());
  468. }
  469. return message;
  470. }
  471. - (Precondition)decodedPrecondition:(GCFSPrecondition *)precondition {
  472. switch (precondition.conditionTypeOneOfCase) {
  473. case GCFSPrecondition_ConditionType_OneOfCase_GPBUnsetOneOfCase:
  474. return Precondition::None();
  475. case GCFSPrecondition_ConditionType_OneOfCase_Exists:
  476. return Precondition::Exists(precondition.exists);
  477. case GCFSPrecondition_ConditionType_OneOfCase_UpdateTime:
  478. return Precondition::UpdateTime([self decodedVersion:precondition.updateTime]);
  479. default:
  480. HARD_FAIL("Unrecognized Precondition one-of case %s", precondition);
  481. }
  482. }
  483. - (GCFSDocumentMask *)encodedFieldMask:(const FieldMask &)fieldMask {
  484. GCFSDocumentMask *mask = [GCFSDocumentMask message];
  485. for (const FieldPath &field : fieldMask) {
  486. [mask.fieldPathsArray addObject:util::WrapNSString(field.CanonicalString())];
  487. }
  488. return mask;
  489. }
  490. - (FieldMask)decodedFieldMask:(GCFSDocumentMask *)fieldMask {
  491. std::set<FieldPath> fields;
  492. for (NSString *path in fieldMask.fieldPathsArray) {
  493. fields.insert(FieldPath::FromServerFormat(util::MakeString(path)));
  494. }
  495. return FieldMask(std::move(fields));
  496. }
  497. - (NSMutableArray<GCFSDocumentTransform_FieldTransform *> *)encodedFieldTransforms:
  498. (const std::vector<FieldTransform> &)fieldTransforms {
  499. NSMutableArray *protos = [NSMutableArray array];
  500. for (const FieldTransform &fieldTransform : fieldTransforms) {
  501. GCFSDocumentTransform_FieldTransform *proto = [self encodedFieldTransform:fieldTransform];
  502. [protos addObject:proto];
  503. }
  504. return protos;
  505. }
  506. - (GCFSDocumentTransform_FieldTransform *)encodedFieldTransform:
  507. (const FieldTransform &)fieldTransform {
  508. GCFSDocumentTransform_FieldTransform *proto = [GCFSDocumentTransform_FieldTransform message];
  509. proto.fieldPath = util::WrapNSString(fieldTransform.path().CanonicalString());
  510. if (fieldTransform.transformation().type() == TransformOperation::Type::ServerTimestamp) {
  511. proto.setToServerValue = GCFSDocumentTransform_FieldTransform_ServerValue_RequestTime;
  512. } else if (fieldTransform.transformation().type() == TransformOperation::Type::ArrayUnion) {
  513. proto.appendMissingElements = [self
  514. encodedArrayTransformElements:ArrayTransform::Elements(fieldTransform.transformation())];
  515. } else if (fieldTransform.transformation().type() == TransformOperation::Type::ArrayRemove) {
  516. proto.removeAllFromArray_p = [self
  517. encodedArrayTransformElements:ArrayTransform::Elements(fieldTransform.transformation())];
  518. } else if (fieldTransform.transformation().type() == TransformOperation::Type::Increment) {
  519. const NumericIncrementTransform &incrementTransform =
  520. static_cast<const NumericIncrementTransform &>(fieldTransform.transformation());
  521. proto.increment = [self encodedFieldValue:incrementTransform.operand()];
  522. } else {
  523. HARD_FAIL("Unknown transform: %s type", fieldTransform.transformation().type());
  524. }
  525. return proto;
  526. }
  527. - (GCFSArrayValue *)encodedArrayTransformElements:(const std::vector<FSTFieldValue *> &)elements {
  528. GCFSArrayValue *proto = [GCFSArrayValue message];
  529. NSMutableArray<GCFSValue *> *protoContents = [proto valuesArray];
  530. for (FSTFieldValue *element : elements) {
  531. GCFSValue *converted = [self encodedFieldValue:element];
  532. [protoContents addObject:converted];
  533. }
  534. return proto;
  535. }
  536. - (std::vector<FieldTransform>)decodedFieldTransforms:
  537. (NSArray<GCFSDocumentTransform_FieldTransform *> *)protos {
  538. std::vector<FieldTransform> fieldTransforms;
  539. fieldTransforms.reserve(protos.count);
  540. for (GCFSDocumentTransform_FieldTransform *proto in protos) {
  541. switch (proto.transformTypeOneOfCase) {
  542. case GCFSDocumentTransform_FieldTransform_TransformType_OneOfCase_SetToServerValue: {
  543. HARD_ASSERT(
  544. proto.setToServerValue == GCFSDocumentTransform_FieldTransform_ServerValue_RequestTime,
  545. "Unknown transform setToServerValue: %s", proto.setToServerValue);
  546. fieldTransforms.emplace_back(
  547. FieldPath::FromServerFormat(util::MakeString(proto.fieldPath)),
  548. absl::make_unique<ServerTimestampTransform>(ServerTimestampTransform::Get()));
  549. break;
  550. }
  551. case GCFSDocumentTransform_FieldTransform_TransformType_OneOfCase_AppendMissingElements: {
  552. std::vector<FSTFieldValue *> elements =
  553. [self decodedArrayTransformElements:proto.appendMissingElements];
  554. fieldTransforms.emplace_back(
  555. FieldPath::FromServerFormat(util::MakeString(proto.fieldPath)),
  556. absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayUnion,
  557. std::move(elements)));
  558. break;
  559. }
  560. case GCFSDocumentTransform_FieldTransform_TransformType_OneOfCase_RemoveAllFromArray_p: {
  561. std::vector<FSTFieldValue *> elements =
  562. [self decodedArrayTransformElements:proto.removeAllFromArray_p];
  563. fieldTransforms.emplace_back(
  564. FieldPath::FromServerFormat(util::MakeString(proto.fieldPath)),
  565. absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayRemove,
  566. std::move(elements)));
  567. break;
  568. }
  569. case GCFSDocumentTransform_FieldTransform_TransformType_OneOfCase_Increment: {
  570. FSTFieldValue *operand = [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 != Query::kNoLimit) {
  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. int32_t limit = Query::kNoLimit;
  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