FIRPipelineBridge.mm 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. /*
  2. * Copyright 2025 Google LLC
  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 "FIRPipelineBridge.h"
  17. #import <FirebaseCore/FIRTimestamp.h>
  18. #include <memory>
  19. #import "Firestore/Source/API/FIRCollectionReference+Internal.h"
  20. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  21. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  22. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  23. #import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
  24. #import "Firestore/Source/API/FIRPipelineBridge+Internal.h"
  25. #import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
  26. #import "Firestore/Source/API/FSTUserDataReader.h"
  27. #import "Firestore/Source/API/FSTUserDataWriter.h"
  28. #import "Firestore/Source/API/converters.h"
  29. #import "Firestore/Source/Public/FirebaseFirestore/FIRVectorValue.h"
  30. #include "Firestore/Protos/nanopb/google/firestore/v1/document.nanopb.h"
  31. #include "Firestore/core/src/api/aggregate_expressions.h"
  32. #include "Firestore/core/src/api/document_reference.h"
  33. #include "Firestore/core/src/api/expressions.h"
  34. #include "Firestore/core/src/api/ordering.h"
  35. #include "Firestore/core/src/api/pipeline.h"
  36. #include "Firestore/core/src/api/pipeline_result.h"
  37. #include "Firestore/core/src/api/pipeline_result_change.h"
  38. #include "Firestore/core/src/api/pipeline_snapshot.h"
  39. #include "Firestore/core/src/api/query_listener_registration.h"
  40. #include "Firestore/core/src/api/realtime_pipeline.h"
  41. #include "Firestore/core/src/api/realtime_pipeline_snapshot.h"
  42. #include "Firestore/core/src/api/snapshot_metadata.h"
  43. #include "Firestore/core/src/api/stages.h"
  44. #include "Firestore/core/src/core/event_listener.h"
  45. #include "Firestore/core/src/core/firestore_client.h"
  46. #include "Firestore/core/src/core/listen_options.h"
  47. #include "Firestore/core/src/core/view_snapshot.h"
  48. #include "Firestore/core/src/util/comparison.h"
  49. #include "Firestore/core/src/util/error_apple.h"
  50. #include "Firestore/core/src/util/status.h"
  51. #include "Firestore/core/src/util/string_apple.h"
  52. using firebase::firestore::api::AddFields;
  53. using firebase::firestore::api::AggregateFunction;
  54. using firebase::firestore::api::AggregateStage;
  55. using firebase::firestore::api::CollectionGroupSource;
  56. using firebase::firestore::api::CollectionSource;
  57. using firebase::firestore::api::Constant;
  58. using firebase::firestore::api::DatabaseSource;
  59. using firebase::firestore::api::DistinctStage;
  60. using firebase::firestore::api::DocumentChange;
  61. using firebase::firestore::api::DocumentReference;
  62. using firebase::firestore::api::DocumentsSource;
  63. using firebase::firestore::api::Expr;
  64. using firebase::firestore::api::Field;
  65. using firebase::firestore::api::FindNearestStage;
  66. using firebase::firestore::api::FunctionExpr;
  67. using firebase::firestore::api::LimitStage;
  68. using firebase::firestore::api::MakeFIRTimestamp;
  69. using firebase::firestore::api::OffsetStage;
  70. using firebase::firestore::api::Ordering;
  71. using firebase::firestore::api::Pipeline;
  72. using firebase::firestore::api::PipelineResultChange;
  73. using firebase::firestore::api::QueryListenerRegistration;
  74. using firebase::firestore::api::RealtimePipeline;
  75. using firebase::firestore::api::RealtimePipelineSnapshot;
  76. using firebase::firestore::api::RawStage;
  77. using firebase::firestore::api::RemoveFieldsStage;
  78. using firebase::firestore::api::ReplaceWith;
  79. using firebase::firestore::api::Sample;
  80. using firebase::firestore::api::SelectStage;
  81. using firebase::firestore::api::SnapshotMetadata;
  82. using firebase::firestore::api::SortStage;
  83. using firebase::firestore::api::Union;
  84. using firebase::firestore::api::Unnest;
  85. using firebase::firestore::api::Where;
  86. using firebase::firestore::core::EventListener;
  87. using firebase::firestore::core::ViewSnapshot;
  88. using firebase::firestore::model::DeepClone;
  89. using firebase::firestore::model::FieldPath;
  90. using firebase::firestore::nanopb::MakeSharedMessage;
  91. using firebase::firestore::nanopb::SharedMessage;
  92. using firebase::firestore::util::ComparisonResult;
  93. using firebase::firestore::util::MakeCallback;
  94. using firebase::firestore::util::MakeNSString;
  95. using firebase::firestore::util::MakeString;
  96. using firebase::firestore::util::ThrowInvalidArgument;
  97. NS_ASSUME_NONNULL_BEGIN
  98. inline std::string EnsureLeadingSlash(const std::string &path) {
  99. if (!path.empty() && path[0] == '/') {
  100. return path;
  101. }
  102. return "/" + path;
  103. }
  104. @implementation FIRExprBridge
  105. @end
  106. @implementation FIRFieldBridge {
  107. FIRFieldPath *field_path;
  108. std::shared_ptr<Field> field;
  109. }
  110. - (id)initWithName:(NSString *)name {
  111. self = [super init];
  112. if (self) {
  113. field_path = [FIRFieldPath pathWithDotSeparatedString:name];
  114. field = std::make_shared<Field>([field_path internalValue].CanonicalString());
  115. }
  116. return self;
  117. }
  118. - (id)initWithPath:(FIRFieldPath *)path {
  119. self = [super init];
  120. if (self) {
  121. field_path = path;
  122. field = std::make_shared<Field>([field_path internalValue].CanonicalString());
  123. }
  124. return self;
  125. }
  126. - (std::shared_ptr<api::Expr>)cppExprWithReader:(FSTUserDataReader *)reader {
  127. return field;
  128. }
  129. - (NSString *)field_name {
  130. return MakeNSString([field_path internalValue].CanonicalString());
  131. }
  132. @end
  133. @implementation FIRConstantBridge {
  134. std::shared_ptr<Constant> cpp_constant;
  135. id _input;
  136. Boolean isUserDataRead;
  137. }
  138. - (id)init:(id)input {
  139. self = [super init];
  140. _input = input;
  141. isUserDataRead = NO;
  142. return self;
  143. }
  144. - (std::shared_ptr<api::Expr>)cppExprWithReader:(FSTUserDataReader *)reader {
  145. if (!isUserDataRead) {
  146. cpp_constant = std::make_shared<Constant>([reader parsedQueryValue:_input]);
  147. }
  148. isUserDataRead = YES;
  149. return cpp_constant;
  150. }
  151. @end
  152. @implementation FIRFunctionExprBridge {
  153. std::shared_ptr<FunctionExpr> cpp_function;
  154. NSString *_name;
  155. NSArray<FIRExprBridge *> *_args;
  156. Boolean isUserDataRead;
  157. }
  158. - (nonnull id)initWithName:(NSString *)name Args:(nonnull NSArray<FIRExprBridge *> *)args {
  159. self = [super init];
  160. _name = name;
  161. _args = args;
  162. isUserDataRead = NO;
  163. return self;
  164. }
  165. - (std::shared_ptr<api::Expr>)cppExprWithReader:(FSTUserDataReader *)reader {
  166. if (!isUserDataRead) {
  167. std::vector<std::shared_ptr<Expr>> cpp_args;
  168. for (FIRExprBridge *arg in _args) {
  169. cpp_args.push_back([arg cppExprWithReader:reader]);
  170. }
  171. cpp_function = std::make_shared<FunctionExpr>(MakeString(_name), std::move(cpp_args));
  172. }
  173. isUserDataRead = YES;
  174. return cpp_function;
  175. }
  176. @end
  177. @implementation FIRAggregateFunctionBridge {
  178. std::shared_ptr<AggregateFunction> cpp_function;
  179. NSString *_name;
  180. NSArray<FIRExprBridge *> *_args;
  181. Boolean isUserDataRead;
  182. }
  183. - (nonnull id)initWithName:(NSString *)name Args:(nonnull NSArray<FIRExprBridge *> *)args {
  184. _name = name;
  185. _args = args;
  186. isUserDataRead = NO;
  187. return self;
  188. }
  189. - (std::shared_ptr<AggregateFunction>)cppExprWithReader:(FSTUserDataReader *)reader {
  190. if (!isUserDataRead) {
  191. std::vector<std::shared_ptr<Expr>> cpp_args;
  192. for (FIRExprBridge *arg in _args) {
  193. cpp_args.push_back([arg cppExprWithReader:reader]);
  194. }
  195. cpp_function = std::make_shared<AggregateFunction>(MakeString(_name), std::move(cpp_args));
  196. }
  197. isUserDataRead = YES;
  198. return cpp_function;
  199. }
  200. @end
  201. @implementation FIROrderingBridge {
  202. std::unique_ptr<Ordering> cpp_ordering;
  203. NSString *_direction;
  204. FIRExprBridge *_expr;
  205. Boolean isUserDataRead;
  206. }
  207. - (nonnull id)initWithExpr:(FIRExprBridge *)expr Direction:(NSString *)direction {
  208. _expr = expr;
  209. _direction = direction;
  210. isUserDataRead = NO;
  211. return self;
  212. }
  213. - (Ordering)cppOrderingWithReader:(FSTUserDataReader *)reader {
  214. if (!isUserDataRead) {
  215. cpp_ordering = std::make_unique<Ordering>(
  216. [_expr cppExprWithReader:reader], Ordering::DirectionFromString(MakeString(_direction)));
  217. }
  218. isUserDataRead = YES;
  219. return *cpp_ordering;
  220. }
  221. @end
  222. @implementation FIRStageBridge
  223. @end
  224. @implementation FIRCollectionSourceStageBridge {
  225. std::shared_ptr<CollectionSource> collection_source;
  226. }
  227. - (id)initWithRef:(FIRCollectionReference *)ref firestore:(FIRFirestore *)db {
  228. self = [super init];
  229. if (self) {
  230. if (ref.firestore.databaseID.CompareTo(db.databaseID) != ComparisonResult::Same) {
  231. ThrowInvalidArgument(
  232. "Invalid CollectionReference. The project ID (\"%s\") or the database (\"%s\") does not "
  233. "match "
  234. "the project ID (\"%s\") and database (\"%s\") of the target database of this Pipeline.",
  235. ref.firestore.databaseID.project_id(), ref.firestore.databaseID.database_id(),
  236. db.databaseID.project_id(), db.databaseID.project_id());
  237. }
  238. collection_source =
  239. std::make_shared<CollectionSource>(EnsureLeadingSlash(MakeString(ref.path)));
  240. }
  241. return self;
  242. }
  243. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  244. return collection_source;
  245. }
  246. @end
  247. @implementation FIRDatabaseSourceStageBridge {
  248. std::shared_ptr<DatabaseSource> cpp_database_source;
  249. }
  250. - (id)init {
  251. self = [super init];
  252. if (self) {
  253. cpp_database_source = std::make_shared<DatabaseSource>();
  254. }
  255. return self;
  256. }
  257. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  258. return cpp_database_source;
  259. }
  260. @end
  261. @implementation FIRCollectionGroupSourceStageBridge {
  262. std::shared_ptr<CollectionGroupSource> cpp_collection_group_source;
  263. }
  264. - (id)initWithCollectionId:(NSString *)id {
  265. self = [super init];
  266. if (self) {
  267. cpp_collection_group_source = std::make_shared<CollectionGroupSource>(MakeString(id));
  268. }
  269. return self;
  270. }
  271. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  272. return cpp_collection_group_source;
  273. }
  274. @end
  275. @implementation FIRDocumentsSourceStageBridge {
  276. std::shared_ptr<DocumentsSource> cpp_document_source;
  277. }
  278. - (id)initWithDocuments:(NSArray<FIRDocumentReference *> *)documents firestore:(FIRFirestore *)db {
  279. self = [super init];
  280. if (self) {
  281. std::vector<std::string> cpp_documents;
  282. for (FIRDocumentReference *doc in documents) {
  283. if (doc.firestore.databaseID.CompareTo(db.databaseID) != ComparisonResult::Same) {
  284. ThrowInvalidArgument("Invalid DocumentReference. The project ID (\"%s\") or the database "
  285. "(\"%s\") does not match "
  286. "the project ID (\"%s\") and database (\"%s\") of the target database "
  287. "of this Pipeline.",
  288. doc.firestore.databaseID.project_id(),
  289. doc.firestore.databaseID.database_id(), db.databaseID.project_id(),
  290. db.databaseID.project_id());
  291. }
  292. cpp_documents.push_back(EnsureLeadingSlash(MakeString(doc.path)));
  293. }
  294. cpp_document_source = std::make_shared<DocumentsSource>(std::move(cpp_documents));
  295. }
  296. return self;
  297. }
  298. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  299. return cpp_document_source;
  300. }
  301. @end
  302. @implementation FIRWhereStageBridge {
  303. FIRExprBridge *_exprBridge;
  304. Boolean isUserDataRead;
  305. std::shared_ptr<Where> cpp_where;
  306. }
  307. - (id)initWithExpr:(FIRExprBridge *)expr {
  308. self = [super init];
  309. if (self) {
  310. _exprBridge = expr;
  311. isUserDataRead = NO;
  312. }
  313. return self;
  314. }
  315. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  316. if (!isUserDataRead) {
  317. cpp_where = std::make_shared<Where>([_exprBridge cppExprWithReader:reader]);
  318. }
  319. isUserDataRead = YES;
  320. return cpp_where;
  321. }
  322. @end
  323. @implementation FIRLimitStageBridge {
  324. Boolean isUserDataRead;
  325. std::shared_ptr<LimitStage> cpp_limit_stage;
  326. int32_t limit;
  327. }
  328. - (id)initWithLimit:(NSInteger)value {
  329. self = [super init];
  330. if (self) {
  331. isUserDataRead = NO;
  332. limit = static_cast<int32_t>(value);
  333. }
  334. return self;
  335. }
  336. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  337. if (!isUserDataRead) {
  338. cpp_limit_stage = std::make_shared<LimitStage>(limit);
  339. }
  340. isUserDataRead = YES;
  341. return cpp_limit_stage;
  342. }
  343. @end
  344. @implementation FIROffsetStageBridge {
  345. Boolean isUserDataRead;
  346. std::shared_ptr<OffsetStage> cpp_offset_stage;
  347. int32_t offset;
  348. }
  349. - (id)initWithOffset:(NSInteger)value {
  350. self = [super init];
  351. if (self) {
  352. isUserDataRead = NO;
  353. offset = static_cast<int32_t>(value);
  354. }
  355. return self;
  356. }
  357. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  358. if (!isUserDataRead) {
  359. cpp_offset_stage = std::make_shared<OffsetStage>(offset);
  360. }
  361. isUserDataRead = YES;
  362. return cpp_offset_stage;
  363. }
  364. @end
  365. // TBD
  366. @implementation FIRAddFieldsStageBridge {
  367. NSDictionary<NSString *, FIRExprBridge *> *_fields;
  368. Boolean isUserDataRead;
  369. std::shared_ptr<AddFields> cpp_add_fields;
  370. }
  371. - (id)initWithFields:(NSDictionary<NSString *, FIRExprBridge *> *)fields {
  372. self = [super init];
  373. if (self) {
  374. _fields = fields;
  375. isUserDataRead = NO;
  376. }
  377. return self;
  378. }
  379. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  380. if (!isUserDataRead) {
  381. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_fields;
  382. for (NSString *key in _fields) {
  383. cpp_fields[MakeString(key)] = [_fields[key] cppExprWithReader:reader];
  384. }
  385. cpp_add_fields = std::make_shared<AddFields>(std::move(cpp_fields));
  386. }
  387. isUserDataRead = YES;
  388. return cpp_add_fields;
  389. }
  390. @end
  391. @implementation FIRRemoveFieldsStageBridge {
  392. NSArray<NSString *> *_fields;
  393. Boolean isUserDataRead;
  394. std::shared_ptr<RemoveFieldsStage> cpp_remove_fields;
  395. }
  396. - (id)initWithFields:(NSArray<id> *)fields {
  397. self = [super init];
  398. if (self) {
  399. _fields = fields;
  400. isUserDataRead = NO;
  401. }
  402. return self;
  403. }
  404. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  405. if (!isUserDataRead) {
  406. std::vector<Field> cpp_fields;
  407. for (id field in _fields) {
  408. cpp_fields.push_back(Field(MakeString(field)));
  409. }
  410. cpp_remove_fields = std::make_shared<RemoveFieldsStage>(std::move(cpp_fields));
  411. }
  412. isUserDataRead = YES;
  413. return cpp_remove_fields;
  414. }
  415. @end
  416. @implementation FIRSelectStageBridge {
  417. NSDictionary<NSString *, FIRExprBridge *> *_selections;
  418. Boolean isUserDataRead;
  419. std::shared_ptr<SelectStage> cpp_select;
  420. }
  421. - (id)initWithSelections:(NSDictionary<NSString *, FIRExprBridge *> *)selections {
  422. self = [super init];
  423. if (self) {
  424. _selections = selections;
  425. isUserDataRead = NO;
  426. }
  427. return self;
  428. }
  429. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  430. if (!isUserDataRead) {
  431. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_selections;
  432. for (NSString *key in _selections) {
  433. cpp_selections[MakeString(key)] = [_selections[key] cppExprWithReader:reader];
  434. }
  435. cpp_select = std::make_shared<SelectStage>(std::move(cpp_selections));
  436. }
  437. isUserDataRead = YES;
  438. return cpp_select;
  439. }
  440. @end
  441. @implementation FIRDistinctStageBridge {
  442. NSDictionary<NSString *, FIRExprBridge *> *_groups;
  443. Boolean isUserDataRead;
  444. std::shared_ptr<DistinctStage> cpp_distinct;
  445. }
  446. - (id)initWithGroups:(NSDictionary<NSString *, FIRExprBridge *> *)groups {
  447. self = [super init];
  448. if (self) {
  449. _groups = groups;
  450. isUserDataRead = NO;
  451. }
  452. return self;
  453. }
  454. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  455. if (!isUserDataRead) {
  456. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_groups;
  457. for (NSString *key in _groups) {
  458. cpp_groups[MakeString(key)] = [_groups[key] cppExprWithReader:reader];
  459. }
  460. cpp_distinct = std::make_shared<DistinctStage>(std::move(cpp_groups));
  461. }
  462. isUserDataRead = YES;
  463. return cpp_distinct;
  464. }
  465. @end
  466. @implementation FIRAggregateStageBridge {
  467. NSDictionary<NSString *, FIRAggregateFunctionBridge *> *_accumulators;
  468. NSDictionary<NSString *, FIRExprBridge *> *_groups;
  469. Boolean isUserDataRead;
  470. std::shared_ptr<AggregateStage> cpp_aggregate;
  471. }
  472. - (id)initWithAccumulators:(NSDictionary<NSString *, FIRAggregateFunctionBridge *> *)accumulators
  473. groups:(NSDictionary<NSString *, FIRExprBridge *> *)groups {
  474. self = [super init];
  475. if (self) {
  476. _accumulators = accumulators;
  477. _groups = groups;
  478. isUserDataRead = NO;
  479. }
  480. return self;
  481. }
  482. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  483. if (!isUserDataRead) {
  484. std::unordered_map<std::string, std::shared_ptr<AggregateFunction>> cpp_accumulators;
  485. for (NSString *key in _accumulators) {
  486. cpp_accumulators[MakeString(key)] = [_accumulators[key] cppExprWithReader:reader];
  487. }
  488. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_groups;
  489. for (NSString *key in _groups) {
  490. cpp_groups[MakeString(key)] = [_groups[key] cppExprWithReader:reader];
  491. }
  492. cpp_aggregate =
  493. std::make_shared<AggregateStage>(std::move(cpp_accumulators), std::move(cpp_groups));
  494. }
  495. isUserDataRead = YES;
  496. return cpp_aggregate;
  497. }
  498. @end
  499. @implementation FIRFindNearestStageBridge {
  500. FIRFieldBridge *_field;
  501. FIRVectorValue *_vectorValue;
  502. NSString *_distanceMeasure;
  503. NSNumber *_limit;
  504. FIRExprBridge *_Nullable _distanceField;
  505. Boolean isUserDataRead;
  506. std::shared_ptr<FindNearestStage> cpp_find_nearest;
  507. }
  508. - (id)initWithField:(FIRFieldBridge *)field
  509. vectorValue:(FIRVectorValue *)vectorValue
  510. distanceMeasure:(NSString *)distanceMeasure
  511. limit:(NSNumber *_Nullable)limit
  512. distanceField:(FIRExprBridge *_Nullable)distanceField {
  513. self = [super init];
  514. if (self) {
  515. _field = field;
  516. _vectorValue = vectorValue;
  517. _distanceMeasure = distanceMeasure;
  518. _limit = limit;
  519. _distanceField = distanceField;
  520. isUserDataRead = NO;
  521. }
  522. return self;
  523. }
  524. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  525. if (!isUserDataRead) {
  526. std::unordered_map<std::string, firebase::firestore::google_firestore_v1_Value> optional_value;
  527. if (_limit) {
  528. optional_value.emplace(std::make_pair(
  529. std::string("limit"), *DeepClone(*[reader parsedQueryValue:_limit]).release()));
  530. }
  531. if (_distanceField) {
  532. std::shared_ptr<Expr> cpp_distance_field = [_distanceField cppExprWithReader:reader];
  533. optional_value.emplace(
  534. std::make_pair(std::string("distance_field"), cpp_distance_field->to_proto()));
  535. }
  536. FindNearestStage::DistanceMeasure::Measure measure_enum;
  537. if ([_distanceMeasure isEqualToString:@"cosine"]) {
  538. measure_enum = FindNearestStage::DistanceMeasure::COSINE;
  539. } else if ([_distanceMeasure isEqualToString:@"dot_product"]) {
  540. measure_enum = FindNearestStage::DistanceMeasure::DOT_PRODUCT;
  541. } else {
  542. measure_enum = FindNearestStage::DistanceMeasure::EUCLIDEAN;
  543. }
  544. cpp_find_nearest = std::make_shared<FindNearestStage>(
  545. [_field cppExprWithReader:reader], [reader parsedQueryValue:_vectorValue],
  546. FindNearestStage::DistanceMeasure(measure_enum), optional_value);
  547. }
  548. isUserDataRead = YES;
  549. return cpp_find_nearest;
  550. }
  551. @end
  552. @implementation FIRSorStageBridge {
  553. NSArray<FIROrderingBridge *> *_orderings;
  554. Boolean isUserDataRead;
  555. std::shared_ptr<SortStage> cpp_sort;
  556. }
  557. - (id)initWithOrderings:(NSArray<id> *)orderings {
  558. self = [super init];
  559. if (self) {
  560. _orderings = orderings;
  561. isUserDataRead = NO;
  562. }
  563. return self;
  564. }
  565. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  566. if (!isUserDataRead) {
  567. std::vector<Ordering> cpp_orderings;
  568. for (FIROrderingBridge *ordering in _orderings) {
  569. cpp_orderings.push_back([ordering cppOrderingWithReader:reader]);
  570. }
  571. cpp_sort = std::make_shared<SortStage>(std::move(cpp_orderings));
  572. }
  573. isUserDataRead = YES;
  574. return cpp_sort;
  575. }
  576. @end
  577. @implementation FIRReplaceWithStageBridge {
  578. FIRExprBridge *_expr;
  579. Boolean isUserDataRead;
  580. std::shared_ptr<ReplaceWith> cpp_replace_with;
  581. }
  582. - (id)initWithExpr:(FIRExprBridge *)expr {
  583. self = [super init];
  584. if (self) {
  585. _expr = expr;
  586. isUserDataRead = NO;
  587. }
  588. return self;
  589. }
  590. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  591. if (!isUserDataRead) {
  592. cpp_replace_with = std::make_shared<ReplaceWith>([_expr cppExprWithReader:reader]);
  593. }
  594. isUserDataRead = YES;
  595. return cpp_replace_with;
  596. }
  597. @end
  598. @implementation FIRSampleStageBridge {
  599. int64_t _count;
  600. double _percentage;
  601. Boolean isUserDataRead;
  602. NSString *type;
  603. std::shared_ptr<Sample> cpp_sample;
  604. }
  605. - (id)initWithCount:(int64_t)count {
  606. self = [super init];
  607. if (self) {
  608. _count = count;
  609. _percentage = 0;
  610. type = @"count";
  611. isUserDataRead = NO;
  612. }
  613. return self;
  614. }
  615. - (id)initWithPercentage:(double)percentage {
  616. self = [super init];
  617. if (self) {
  618. _percentage = percentage;
  619. _count = 0;
  620. type = @"percentage";
  621. isUserDataRead = NO;
  622. }
  623. return self;
  624. }
  625. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  626. if (!isUserDataRead) {
  627. if ([type isEqualToString:@"count"]) {
  628. cpp_sample =
  629. std::make_shared<Sample>(Sample::SampleMode(Sample::SampleMode::DOCUMENTS), _count, 0);
  630. } else {
  631. cpp_sample =
  632. std::make_shared<Sample>(Sample::SampleMode(Sample::SampleMode::PERCENT), 0, _percentage);
  633. }
  634. }
  635. isUserDataRead = YES;
  636. return cpp_sample;
  637. }
  638. @end
  639. @implementation FIRUnionStageBridge {
  640. FIRPipelineBridge *_other;
  641. Boolean isUserDataRead;
  642. std::shared_ptr<Union> cpp_union_stage;
  643. }
  644. - (id)initWithOther:(FIRPipelineBridge *)other {
  645. self = [super init];
  646. if (self) {
  647. _other = other;
  648. isUserDataRead = NO;
  649. }
  650. return self;
  651. }
  652. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  653. if (!isUserDataRead) {
  654. cpp_union_stage = std::make_shared<Union>([_other cppPipelineWithReader:reader]);
  655. }
  656. isUserDataRead = YES;
  657. return cpp_union_stage;
  658. }
  659. @end
  660. @implementation FIRUnnestStageBridge {
  661. FIRExprBridge *_field;
  662. FIRExprBridge *_Nullable _index_field;
  663. FIRExprBridge *_alias;
  664. Boolean isUserDataRead;
  665. std::shared_ptr<Unnest> cpp_unnest;
  666. }
  667. - (id)initWithField:(FIRExprBridge *)field
  668. alias:(FIRExprBridge *)alias
  669. indexField:(FIRExprBridge *_Nullable)index_field {
  670. self = [super init];
  671. if (self) {
  672. _field = field;
  673. _alias = alias;
  674. _index_field = index_field;
  675. isUserDataRead = NO;
  676. }
  677. return self;
  678. }
  679. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  680. if (!isUserDataRead) {
  681. absl::optional<std::shared_ptr<Expr>> cpp_index_field;
  682. if (_index_field != nil) {
  683. cpp_index_field = [_index_field cppExprWithReader:reader];
  684. } else {
  685. cpp_index_field = absl::nullopt;
  686. }
  687. cpp_unnest = std::make_shared<Unnest>([_field cppExprWithReader:reader],
  688. [_alias cppExprWithReader:reader], cpp_index_field);
  689. }
  690. isUserDataRead = YES;
  691. return cpp_unnest;
  692. }
  693. @end
  694. @implementation FIRRawStageBridge {
  695. NSString *_name;
  696. NSArray<id> *_params;
  697. NSDictionary<NSString *, FIRExprBridge *> *_Nullable _options;
  698. Boolean isUserDataRead;
  699. std::shared_ptr<RawStage> cpp_generic_stage;
  700. }
  701. - (id)initWithName:(NSString *)name
  702. params:(NSArray<id> *)params
  703. options:(NSDictionary<NSString *, FIRExprBridge *> *_Nullable)options {
  704. self = [super init];
  705. if (self) {
  706. _name = name;
  707. _params = params;
  708. _options = options;
  709. isUserDataRead = NO;
  710. }
  711. return self;
  712. }
  713. - (firebase::firestore::google_firestore_v1_Value)convertIdToV1Value:(id)value
  714. reader:(FSTUserDataReader *)reader {
  715. if ([value isKindOfClass:[FIRExprBridge class]]) {
  716. return [((FIRExprBridge *)value) cppExprWithReader:reader]->to_proto();
  717. } else if ([value isKindOfClass:[FIRAggregateFunctionBridge class]]) {
  718. return [((FIRAggregateFunctionBridge *)value) cppExprWithReader:reader]->to_proto();
  719. } else if ([value isKindOfClass:[NSDictionary class]]) {
  720. NSDictionary<NSString *, id> *dictionary = (NSDictionary<NSString *, id> *)value;
  721. std::unordered_map<std::string, firebase::firestore::google_firestore_v1_Value> cpp_dictionary;
  722. for (NSString *key in dictionary) {
  723. if ([dictionary[key] isKindOfClass:[FIRExprBridge class]]) {
  724. cpp_dictionary[MakeString(key)] =
  725. [((FIRExprBridge *)dictionary[key]) cppExprWithReader:reader]->to_proto();
  726. } else if ([dictionary[key] isKindOfClass:[FIRAggregateFunctionBridge class]]) {
  727. cpp_dictionary[MakeString(key)] =
  728. [((FIRAggregateFunctionBridge *)dictionary[key]) cppExprWithReader:reader]->to_proto();
  729. } else {
  730. ThrowInvalidArgument(
  731. "Dictionary value must be an FIRExprBridge or FIRAggregateFunctionBridge.");
  732. }
  733. }
  734. firebase::firestore::google_firestore_v1_Value result;
  735. result.which_value_type = google_firestore_v1_Value_map_value_tag;
  736. nanopb::SetRepeatedField(
  737. &result.map_value.fields, &result.map_value.fields_count, cpp_dictionary,
  738. [](const std::pair<std::string, firebase::firestore::google_firestore_v1_Value> &entry) {
  739. return firebase::firestore::_google_firestore_v1_MapValue_FieldsEntry{
  740. nanopb::MakeBytesArray(entry.first), entry.second};
  741. });
  742. return result;
  743. } else {
  744. ThrowInvalidArgument("Invalid value to convert to google_firestore_v1_Value.");
  745. }
  746. }
  747. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  748. if (!isUserDataRead) {
  749. std::vector<firebase::firestore::google_firestore_v1_Value> cpp_params;
  750. for (id param in _params) {
  751. cpp_params.push_back([self convertIdToV1Value:param reader:reader]);
  752. }
  753. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_options;
  754. if (_options) {
  755. for (NSString *key in _options) {
  756. cpp_options[MakeString(key)] = [_options[key] cppExprWithReader:reader];
  757. }
  758. }
  759. cpp_generic_stage = std::make_shared<RawStage>(MakeString(_name), std::move(cpp_params),
  760. std::move(cpp_options));
  761. }
  762. isUserDataRead = YES;
  763. return cpp_generic_stage;
  764. }
  765. @end
  766. @interface __FIRPipelineSnapshotBridge ()
  767. @property(nonatomic, strong, readwrite) NSArray<__FIRPipelineResultBridge *> *results;
  768. @end
  769. @implementation __FIRPipelineSnapshotBridge {
  770. absl::optional<api::PipelineSnapshot> snapshot_;
  771. NSMutableArray<__FIRPipelineResultBridge *> *results_;
  772. }
  773. - (id)initWithCppSnapshot:(api::PipelineSnapshot)snapshot {
  774. self = [super init];
  775. if (self) {
  776. snapshot_ = std::move(snapshot);
  777. if (!snapshot_.has_value()) {
  778. results_ = nil;
  779. } else {
  780. NSMutableArray<__FIRPipelineResultBridge *> *results = [NSMutableArray array];
  781. for (auto &result : snapshot_.value().results()) {
  782. [results addObject:[[__FIRPipelineResultBridge alloc]
  783. initWithCppResult:result
  784. db:snapshot_.value().firestore()]];
  785. }
  786. results_ = results;
  787. }
  788. }
  789. return self;
  790. }
  791. - (NSArray<__FIRPipelineResultBridge *> *)results {
  792. return results_;
  793. }
  794. - (FIRTimestamp *)execution_time {
  795. if (!snapshot_.has_value()) {
  796. return nil;
  797. } else {
  798. return MakeFIRTimestamp(snapshot_.value().execution_time().timestamp());
  799. }
  800. }
  801. @end
  802. @implementation __FIRPipelineResultBridge {
  803. api::PipelineResult _result;
  804. std::shared_ptr<api::Firestore> _db;
  805. }
  806. - (nullable FIRDocumentReference *)reference {
  807. if (!_result.internal_key().has_value()) return nil;
  808. return [[FIRDocumentReference alloc] initWithKey:_result.internal_key().value() firestore:_db];
  809. }
  810. - (nullable NSString *)documentID {
  811. if (!_result.document_id().has_value()) {
  812. return nil;
  813. }
  814. return MakeNSString(_result.document_id().value());
  815. }
  816. - (nullable FIRTimestamp *)create_time {
  817. if (!_result.create_time().has_value()) {
  818. return nil;
  819. }
  820. return MakeFIRTimestamp(_result.create_time().value().timestamp());
  821. }
  822. - (nullable FIRTimestamp *)update_time {
  823. if (!_result.update_time().has_value()) {
  824. return nil;
  825. }
  826. return MakeFIRTimestamp(_result.update_time().value().timestamp());
  827. }
  828. - (id)initWithCppResult:(api::PipelineResult)result db:(std::shared_ptr<api::Firestore>)db {
  829. self = [super init];
  830. if (self) {
  831. _result = std::move(result);
  832. _db = std::move(db);
  833. }
  834. return self;
  835. }
  836. - (NSDictionary<NSString *, id> *)data {
  837. return [self dataWithServerTimestampBehavior:FIRServerTimestampBehaviorNone];
  838. }
  839. - (NSDictionary<NSString *, id> *)dataWithServerTimestampBehavior:
  840. (FIRServerTimestampBehavior)serverTimestampBehavior {
  841. absl::optional<firebase::firestore::google_firestore_v1_Value> data =
  842. _result.internal_value()->Get();
  843. if (!data) return [NSDictionary dictionary];
  844. FSTUserDataWriter *dataWriter =
  845. [[FSTUserDataWriter alloc] initWithFirestore:_db
  846. serverTimestampBehavior:serverTimestampBehavior];
  847. NSDictionary<NSString *, id> *dictionary = [dataWriter convertedValue:*data];
  848. NSLog(@"Dictionary contents: %@", dictionary);
  849. return dictionary;
  850. }
  851. - (nullable id)get:(id)field {
  852. return [self get:field serverTimestampBehavior:FIRServerTimestampBehaviorNone];
  853. }
  854. - (nullable id)get:(id)field
  855. serverTimestampBehavior:(FIRServerTimestampBehavior)serverTimestampBehavior {
  856. FieldPath fieldPath;
  857. if ([field isKindOfClass:[NSString class]]) {
  858. fieldPath = FieldPath::FromDotSeparatedString(MakeString(field));
  859. } else if ([field isKindOfClass:[FIRFieldPath class]]) {
  860. fieldPath = ((FIRFieldPath *)field).internalValue;
  861. } else {
  862. ThrowInvalidArgument("Subscript key must be an NSString or FIRFieldPath.");
  863. }
  864. absl::optional<firebase::firestore::google_firestore_v1_Value> fieldValue =
  865. _result.internal_value()->Get(fieldPath);
  866. if (!fieldValue) return nil;
  867. FSTUserDataWriter *dataWriter =
  868. [[FSTUserDataWriter alloc] initWithFirestore:_db
  869. serverTimestampBehavior:serverTimestampBehavior];
  870. return [dataWriter convertedValue:*fieldValue];
  871. }
  872. @end
  873. @implementation __FIRPipelineResultChangeBridge {
  874. api::PipelineResultChange change_;
  875. std::shared_ptr<api::Firestore> db_;
  876. }
  877. - (FIRDocumentChangeType)type {
  878. switch (change_.type()) {
  879. case PipelineResultChange::Type::Added:
  880. return FIRDocumentChangeTypeAdded;
  881. case PipelineResultChange::Type::Modified:
  882. return FIRDocumentChangeTypeModified;
  883. case PipelineResultChange::Type::Removed:
  884. return FIRDocumentChangeTypeRemoved;
  885. }
  886. HARD_FAIL("Unknown PipelineResultChange::Type: %s", change_.type());
  887. }
  888. - (__FIRPipelineResultBridge *)result {
  889. return [[__FIRPipelineResultBridge alloc] initWithCppResult:change_.result() db:db_];
  890. }
  891. - (NSUInteger)oldIndex {
  892. return change_.old_index() == PipelineResultChange::npos ? NSNotFound : change_.old_index();
  893. }
  894. - (NSUInteger)newIndex {
  895. return change_.new_index() == PipelineResultChange::npos ? NSNotFound : change_.new_index();
  896. }
  897. - (id)initWithCppChange:(api::PipelineResultChange)change db:(std::shared_ptr<api::Firestore>)db {
  898. self = [super init];
  899. if (self) {
  900. change_ = std::move(change);
  901. db_ = std::move(db);
  902. }
  903. return self;
  904. }
  905. @end
  906. @implementation FIRPipelineBridge {
  907. NSArray<FIRStageBridge *> *_stages;
  908. FIRFirestore *firestore;
  909. Boolean isUserDataRead;
  910. std::shared_ptr<Pipeline> cpp_pipeline;
  911. }
  912. - (id)initWithStages:(NSArray<FIRStageBridge *> *)stages db:(FIRFirestore *)db {
  913. _stages = stages;
  914. firestore = db;
  915. isUserDataRead = NO;
  916. return [super init];
  917. }
  918. - (void)executeWithCompletion:(void (^)(__FIRPipelineSnapshotBridge *_Nullable result,
  919. NSError *_Nullable error))completion {
  920. [self cppPipelineWithReader:firestore.dataReader]->execute(
  921. [completion](StatusOr<api::PipelineSnapshot> maybe_value) {
  922. if (maybe_value.ok()) {
  923. __FIRPipelineSnapshotBridge *bridge = [[__FIRPipelineSnapshotBridge alloc]
  924. initWithCppSnapshot:std::move(maybe_value).ValueOrDie()];
  925. completion(bridge, nil);
  926. } else {
  927. completion(nil, MakeNSError(std::move(maybe_value).status()));
  928. }
  929. });
  930. }
  931. - (std::shared_ptr<api::Pipeline>)cppPipelineWithReader:(FSTUserDataReader *)reader {
  932. if (!isUserDataRead) {
  933. std::vector<std::shared_ptr<firebase::firestore::api::Stage>> cpp_stages;
  934. for (FIRStageBridge *stage in _stages) {
  935. cpp_stages.push_back([stage cppStageWithReader:firestore.dataReader]);
  936. }
  937. cpp_pipeline = std::make_shared<Pipeline>(cpp_stages, firestore.wrapped);
  938. }
  939. isUserDataRead = YES;
  940. return cpp_pipeline;
  941. }
  942. @end
  943. @interface __FIRRealtimePipelineSnapshotBridge ()
  944. @property(nonatomic, strong, readwrite) NSArray<__FIRPipelineResultBridge *> *results;
  945. @property(nonatomic, strong, readwrite) NSArray<__FIRPipelineResultChangeBridge *> *changes;
  946. @end
  947. @implementation __FIRRealtimePipelineSnapshotBridge {
  948. absl::optional<api::RealtimePipelineSnapshot> snapshot_;
  949. NSMutableArray<__FIRPipelineResultBridge *> *results_;
  950. NSMutableArray<__FIRPipelineResultChangeBridge *> *changes_;
  951. FIRSnapshotMetadata *_metadata;
  952. }
  953. - (id)initWithCppSnapshot:(api::RealtimePipelineSnapshot)snapshot {
  954. self = [super init];
  955. if (self) {
  956. snapshot_ = std::move(snapshot);
  957. if (!snapshot_.has_value()) {
  958. results_ = nil;
  959. } else {
  960. _metadata =
  961. [[FIRSnapshotMetadata alloc] initWithMetadata:snapshot_.value().snapshot_metadata()];
  962. NSMutableArray<__FIRPipelineResultBridge *> *results = [NSMutableArray array];
  963. for (auto &result : snapshot_.value().view_snapshot().documents()) {
  964. [results addObject:[[__FIRPipelineResultBridge alloc]
  965. initWithCppResult:api::PipelineResult(result)
  966. db:snapshot_.value().firestore()]];
  967. }
  968. results_ = results;
  969. NSMutableArray<__FIRPipelineResultChangeBridge *> *changes = [NSMutableArray array];
  970. for (auto &change : snapshot_.value().CalculateResultChanges(false)) {
  971. [changes addObject:[[__FIRPipelineResultChangeBridge alloc]
  972. initWithCppChange:change
  973. db:snapshot_.value().firestore()]];
  974. }
  975. changes_ = changes;
  976. }
  977. }
  978. return self;
  979. }
  980. - (NSArray<__FIRPipelineResultBridge *> *)results {
  981. return results_;
  982. }
  983. - (NSArray<__FIRPipelineResultChangeBridge *> *)changes {
  984. return changes_;
  985. }
  986. - (FIRSnapshotMetadata *)metadata {
  987. return _metadata;
  988. }
  989. @end
  990. @implementation __FIRPipelineListenOptionsBridge
  991. - (instancetype)initWithServerTimestampBehavior:(NSString *)serverTimestampBehavior
  992. includeMetadata:(BOOL)includeMetadata
  993. source:(FIRListenSource)source {
  994. // Call the designated initializer of the superclass (NSObject).
  995. self = [super init];
  996. if (self) {
  997. // Assign the passed-in values to the backing instance variables
  998. // for the readonly properties.
  999. // We use `copy` here for the string to ensure our object owns an immutable version.
  1000. _serverTimestampBehavior = [serverTimestampBehavior copy];
  1001. _includeMetadata = includeMetadata;
  1002. _source = source;
  1003. }
  1004. return self;
  1005. }
  1006. @end
  1007. @implementation FIRRealtimePipelineBridge {
  1008. NSArray<FIRStageBridge *> *_stages;
  1009. FIRFirestore *firestore;
  1010. std::shared_ptr<api::RealtimePipeline> cpp_pipeline;
  1011. }
  1012. - (id)initWithStages:(NSArray<FIRStageBridge *> *)stages db:(FIRFirestore *)db {
  1013. _stages = stages;
  1014. firestore = db;
  1015. return [super init];
  1016. }
  1017. core::ListenOptions ToListenOptions(__FIRPipelineListenOptionsBridge *_Nullable bridge) {
  1018. // If the bridge object is nil, return a default-constructed ListenOptions.
  1019. if (bridge == nil) {
  1020. return core::ListenOptions::DefaultOptions();
  1021. }
  1022. // 1. Translate include_metadata_changes
  1023. bool include_metadata = bridge.includeMetadata;
  1024. // 2. Translate ListenSource
  1025. core::ListenSource source = core::ListenSource::Default;
  1026. switch (bridge.source) {
  1027. case FIRListenSourceDefault:
  1028. source = core::ListenSource::Default;
  1029. break;
  1030. case FIRListenSourceCache:
  1031. source = core::ListenSource::Cache;
  1032. break;
  1033. }
  1034. // 3. Translate ServerTimestampBehavior
  1035. core::ListenOptions::ServerTimestampBehavior behavior =
  1036. core::ListenOptions::ServerTimestampBehavior::kNone;
  1037. if ([bridge.serverTimestampBehavior isEqual:@"estimate"]) {
  1038. behavior = core::ListenOptions::ServerTimestampBehavior::kEstimate;
  1039. } else if ([bridge.serverTimestampBehavior isEqual:@"previous"]) {
  1040. behavior = core::ListenOptions::ServerTimestampBehavior::kPrevious;
  1041. } else {
  1042. // "none" or any other value defaults to kNone.
  1043. behavior = core::ListenOptions::ServerTimestampBehavior::kNone;
  1044. }
  1045. // 4. Construct the final C++ object using the canonical private constructor.
  1046. // Note: wait_for_sync_when_online is not part of the bridge, so we use 'false'
  1047. // to match the behavior of the existing static factories.
  1048. return core::ListenOptions(
  1049. /*include_query_metadata_changes=*/include_metadata,
  1050. /*include_document_metadata_changes=*/include_metadata,
  1051. /*wait_for_sync_when_online=*/false, source, behavior);
  1052. }
  1053. - (id<FIRListenerRegistration>)
  1054. addSnapshotListenerWithOptions:(__FIRPipelineListenOptionsBridge *)options
  1055. listener:
  1056. (void (^)(__FIRRealtimePipelineSnapshotBridge *_Nullable snapshot,
  1057. NSError *_Nullable error))listener {
  1058. std::shared_ptr<api::Firestore> wrapped_firestore = firestore.wrapped;
  1059. std::vector<std::shared_ptr<firebase::firestore::api::EvaluableStage>> cpp_stages;
  1060. for (FIRStageBridge *stage in _stages) {
  1061. auto evaluable_stage = std::dynamic_pointer_cast<api::EvaluableStage>(
  1062. [stage cppStageWithReader:firestore.dataReader]);
  1063. if (evaluable_stage) {
  1064. cpp_stages.push_back(evaluable_stage);
  1065. } else {
  1066. HARD_FAIL("Failed to convert cpp stage to EvaluableStage for RealtimePipeline");
  1067. }
  1068. }
  1069. cpp_pipeline = std::make_shared<RealtimePipeline>(
  1070. cpp_stages, std::make_unique<remote::Serializer>(wrapped_firestore->database_id()));
  1071. // Convert from ViewSnapshots to RealtimePipelineSnapshots.
  1072. auto view_listener = EventListener<ViewSnapshot>::Create(
  1073. [listener, wrapped_firestore](StatusOr<ViewSnapshot> maybe_snapshot) {
  1074. if (!maybe_snapshot.status().ok()) {
  1075. listener(nil, MakeNSError(maybe_snapshot.status()));
  1076. return;
  1077. }
  1078. ViewSnapshot snapshot = std::move(maybe_snapshot).ValueOrDie();
  1079. SnapshotMetadata metadata(snapshot.has_pending_writes(), snapshot.from_cache());
  1080. listener(
  1081. [[__FIRRealtimePipelineSnapshotBridge alloc]
  1082. initWithCppSnapshot:RealtimePipelineSnapshot(wrapped_firestore, std::move(snapshot),
  1083. std::move(metadata))],
  1084. nil);
  1085. });
  1086. // Call the view_listener on the user Executor.
  1087. auto async_listener = core::AsyncEventListener<ViewSnapshot>::Create(
  1088. wrapped_firestore->client()->user_executor(), std::move(view_listener));
  1089. std::shared_ptr<core::QueryListener> query_listener = wrapped_firestore->client()->ListenToQuery(
  1090. *cpp_pipeline, ToListenOptions(options), async_listener);
  1091. return [[FSTListenerRegistration alloc]
  1092. initWithRegistration:absl::make_unique<QueryListenerRegistration>(wrapped_firestore->client(),
  1093. std::move(async_listener),
  1094. std::move(query_listener))];
  1095. }
  1096. - (std::shared_ptr<api::RealtimePipeline>)cppPipelineWithReader:(FSTUserDataReader *)reader {
  1097. return cpp_pipeline;
  1098. }
  1099. @end
  1100. NS_ASSUME_NONNULL_END