1use std::collections::HashMap;
5use std::fs;
6use std::net::IpAddr;
7use std::net::Ipv4Addr;
8use std::net::SocketAddr;
9use std::path::Path;
10use std::time::Duration;
11
12use anyhow::Context;
13use anyhow::ensure;
14use diesel::ExpressionMethods;
15use diesel::OptionalExtension;
16use diesel::QueryDsl;
17use diesel_async::RunQueryDsl;
18use prost::Message;
19use reqwest::Client;
20use serde_json::Value;
21use serde_json::json;
22use simulacrum::AdvanceEpochConfig;
23use simulacrum::Simulacrum;
24use sui_futures::service::Service;
25use sui_indexer_alt::BootstrapGenesis;
26use sui_indexer_alt::config::IndexerConfig;
27use sui_indexer_alt::setup_indexer;
28use sui_indexer_alt_consistent_api::proto::rpc::consistent::v1alpha::AvailableRangeRequest;
29use sui_indexer_alt_consistent_api::proto::rpc::consistent::v1alpha::consistent_service_client::ConsistentServiceClient;
30use sui_indexer_alt_consistent_store::args::RpcArgs as ConsistentArgs;
31use sui_indexer_alt_consistent_store::args::TlsArgs as ConsistentTlsArgs;
32use sui_indexer_alt_consistent_store::config::ServiceConfig as ConsistentConfig;
33use sui_indexer_alt_consistent_store::start_service as start_consistent_store;
34use sui_indexer_alt_framework::IndexerArgs;
35use sui_indexer_alt_framework::ingestion::ClientArgs;
36use sui_indexer_alt_framework::ingestion::ingestion_client::IngestionClientArgs;
37use sui_indexer_alt_framework::pipeline::CommitterConfig;
38use sui_indexer_alt_framework::postgres::schema::watermarks;
39use sui_indexer_alt_graphql::RpcArgs as GraphQlArgs;
40use sui_indexer_alt_graphql::args::SubscriptionArgs;
41use sui_indexer_alt_graphql::config::RpcConfig as GraphQlConfig;
42use sui_indexer_alt_graphql::start_rpc as start_graphql;
43use sui_indexer_alt_reader::consistent_reader::ConsistentReaderArgs;
44use sui_indexer_alt_reader::fullnode_client::FullnodeArgs;
45use sui_indexer_alt_reader::kv_loader::KvArgs;
46use sui_indexer_alt_reader::system_package_task::SystemPackageTaskArgs;
47use sui_kv_rpc::KvRpcConfig;
48use sui_kv_rpc::KvRpcServer;
49use sui_kvstore::ALL_PIPELINE_NAMES;
50use sui_kvstore::ALPHA_PIPELINE_NAMES;
51use sui_kvstore::BigTableClient;
52use sui_kvstore::BigTableIndexer;
53use sui_kvstore::BitmapSchema;
54use sui_kvstore::CHECKPOINTS_PIPELINE;
55use sui_kvstore::IndexerConfig as BtIndexerConfig;
56use sui_kvstore::IngestionConfig as BtIngestionConfig;
57use sui_kvstore::KeyValueStoreReader;
58use sui_kvstore::PipelineLayer;
59use sui_kvstore::testing::BigTableEmulator;
60use sui_kvstore::testing::INSTANCE_ID;
61use sui_kvstore::testing::create_tables;
62use sui_pg_db::Db;
63use sui_pg_db::DbArgs;
64use sui_pg_db::temp::TempDb;
65use sui_pg_db::temp::get_available_port;
66use sui_protocol_config::Chain;
67use sui_rpc::field::FieldMask;
68use sui_rpc::field::FieldMaskUtil;
69use sui_rpc::merge::Merge;
70use sui_rpc::proto::sui::rpc;
71use sui_types::base_types::ObjectRef;
72use sui_types::base_types::SuiAddress;
73use sui_types::crypto::AccountKeyPair;
74use sui_types::effects::TransactionEffects;
75use sui_types::error::ExecutionError;
76use sui_types::full_checkpoint_content::Checkpoint;
77use sui_types::messages_checkpoint::VerifiedCheckpoint;
78use sui_types::transaction::Transaction;
79use tempfile::TempDir;
80use tokio::time::error::Elapsed;
81use tokio::time::interval;
82use tokio::try_join;
83use url::Url;
84
85pub mod coin_registry;
86pub mod find;
87pub mod graphql;
88pub mod move_helpers;
89pub mod transaction;
90
91pub struct FullCluster {
94 executor: Simulacrum,
96
97 offchain: OffchainCluster,
100
101 #[allow(unused)]
103 temp_dir: TempDir,
104}
105
106pub struct OffchainCluster {
114 consistent_listen_address: SocketAddr,
116
117 graphql_listen_address: SocketAddr,
119
120 kv_rpc_listen_address: SocketAddr,
122
123 kv_rpc_plaintext_listen_address: Option<SocketAddr>,
126
127 bigtable_client: BigTableClient,
129
130 db: Db,
132
133 pipelines: Vec<&'static str>,
135
136 bigtable_pipelines: Vec<&'static str>,
139
140 #[allow(unused)]
143 services: Service,
144
145 #[allow(unused)]
147 bigtable_emulator: BigTableEmulator,
148
149 #[allow(unused)]
151 database: TempDb,
152
153 #[allow(unused)]
156 dir: TempDir,
157}
158
159pub struct OffchainClusterConfig {
160 pub indexer_args: IndexerArgs,
161 pub consistent_indexer_args: IndexerArgs,
162 pub fullnode_args: FullnodeArgs,
163 pub indexer_config: IndexerConfig,
164 pub consistent_config: ConsistentConfig,
165 pub graphql_config: GraphQlConfig,
166 pub bootstrap_genesis: Option<BootstrapGenesis>,
167 pub kv_rpc_config: KvRpcConfig,
168 pub bt_pipeline_layer: PipelineLayer,
170 pub kv_rpc_plaintext_listener: bool,
174}
175
176impl FullCluster {
177 pub async fn new() -> anyhow::Result<Self> {
180 Self::new_with_configs(
181 Simulacrum::new(),
182 OffchainClusterConfig::default(),
183 &prometheus::Registry::new(),
184 )
185 .await
186 }
187
188 pub async fn new_with_configs(
192 mut executor: Simulacrum,
193 offchain_cluster_config: OffchainClusterConfig,
194 registry: &prometheus::Registry,
195 ) -> anyhow::Result<Self> {
196 let (client_args, temp_dir) = local_ingestion_client_args();
197 executor.set_data_ingestion_path(temp_dir.path().to_owned());
198
199 let offchain = OffchainCluster::new(client_args, offchain_cluster_config, registry)
200 .await
201 .context("Failed to create off-chain cluster")?;
202
203 Ok(Self {
204 executor,
205 offchain,
206 temp_dir,
207 })
208 }
209
210 pub fn reference_gas_price(&self) -> u64 {
212 self.executor.reference_gas_price()
213 }
214
215 pub fn funded_account(
218 &mut self,
219 amount: u64,
220 ) -> anyhow::Result<(SuiAddress, AccountKeyPair, ObjectRef)> {
221 self.executor.funded_account(amount)
222 }
223
224 pub fn request_gas(
227 &mut self,
228 address: SuiAddress,
229 amount: u64,
230 ) -> anyhow::Result<TransactionEffects> {
231 self.executor.request_gas(address, amount)
232 }
233
234 pub fn execute_transaction(
236 &mut self,
237 tx: Transaction,
238 ) -> anyhow::Result<(TransactionEffects, Option<ExecutionError>)> {
239 self.executor.execute_transaction(tx)
240 }
241
242 pub fn advance_clock(&mut self, duration: Duration) -> TransactionEffects {
244 self.executor.advance_clock(duration)
245 }
246
247 pub fn advance_epoch(&mut self) {
251 self.executor.advance_epoch(AdvanceEpochConfig::default());
252 }
253
254 pub async fn create_checkpoint(&mut self) -> VerifiedCheckpoint {
258 let checkpoint = self.executor.create_checkpoint();
259 let timeout = Duration::from_secs(100);
260 let indexer = self
261 .offchain
262 .wait_for_indexer(checkpoint.sequence_number, timeout);
263 let consistent_store = self
264 .offchain
265 .wait_for_consistent_store(checkpoint.sequence_number, timeout);
266 let graphql = self
267 .offchain
268 .wait_for_graphql(checkpoint.sequence_number, timeout);
269 let bigtable = self.offchain.wait_for_bigtable(
270 &self.offchain.bigtable_pipelines,
271 checkpoint.sequence_number,
272 timeout,
273 );
274 let kv_rpc = self
275 .offchain
276 .wait_for_kv_rpc(checkpoint.sequence_number, timeout);
277
278 try_join!(indexer, consistent_store, graphql, bigtable, kv_rpc)
279 .expect("Timed out waiting for off-chain services");
280
281 checkpoint
282 }
283
284 pub async fn create_checkpoint_before_list_apis_sync(&mut self) -> VerifiedCheckpoint {
292 let checkpoint = self.executor.create_checkpoint();
293 let timeout = Duration::from_secs(100);
294 self.offchain
295 .wait_for_bigtable(&[CHECKPOINTS_PIPELINE], checkpoint.sequence_number, timeout)
296 .await
297 .expect("Timed out waiting for the base checkpoints pipeline");
298
299 checkpoint
300 }
301
302 pub async fn wait_for_bigtable(
305 &self,
306 pipelines: &[&str],
307 checkpoint: u64,
308 timeout: Duration,
309 ) -> Result<(), Elapsed> {
310 self.offchain
311 .wait_for_bigtable(pipelines, checkpoint, timeout)
312 .await
313 }
314
315 pub fn db_url(&self) -> Url {
317 self.offchain.db_url()
318 }
319
320 pub fn consistent_store_url(&self) -> Url {
322 self.offchain.consistent_store_url()
323 }
324
325 pub fn graphql_url(&self) -> Url {
327 self.offchain.graphql_url()
328 }
329
330 pub fn kv_rpc_url(&self) -> Url {
332 self.offchain.kv_rpc_url()
333 }
334
335 pub fn kv_rpc_plaintext_url(&self) -> Option<Url> {
338 self.offchain.kv_rpc_plaintext_url()
339 }
340
341 pub async fn latest_checkpoint(&self) -> anyhow::Result<Option<u64>> {
344 self.offchain.latest_checkpoint().await
345 }
346
347 pub async fn wait_for_indexer(
350 &self,
351 checkpoint: u64,
352 timeout: Duration,
353 ) -> Result<(), Elapsed> {
354 self.offchain.wait_for_indexer(checkpoint, timeout).await
355 }
356
357 pub async fn wait_for_pruner(
360 &self,
361 pipeline: &str,
362 checkpoint: u64,
363 timeout: Duration,
364 ) -> Result<(), Elapsed> {
365 self.offchain
366 .wait_for_pruner(pipeline, checkpoint, timeout)
367 .await
368 }
369
370 pub async fn wait_for_graphql(
373 &self,
374 checkpoint: u64,
375 timeout: Duration,
376 ) -> Result<(), Elapsed> {
377 self.offchain.wait_for_graphql(checkpoint, timeout).await
378 }
379
380 pub async fn wait_for_kv_rpc(&self, checkpoint: u64, timeout: Duration) -> Result<(), Elapsed> {
382 self.offchain.wait_for_kv_rpc(checkpoint, timeout).await
383 }
384}
385
386impl OffchainCluster {
387 pub async fn new(
394 client_args: ClientArgs,
395 OffchainClusterConfig {
396 indexer_args,
397 consistent_indexer_args,
398 fullnode_args,
399 indexer_config,
400 consistent_config,
401 graphql_config,
402 bootstrap_genesis,
403 kv_rpc_config,
404 bt_pipeline_layer,
405 kv_rpc_plaintext_listener,
406 }: OffchainClusterConfig,
407 registry: &prometheus::Registry,
408 ) -> anyhow::Result<Self> {
409 let consistent_port = get_available_port();
410 let consistent_listen_address =
411 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), consistent_port);
412
413 let graphql_port = get_available_port();
414 let graphql_listen_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), graphql_port);
415
416 let kv_rpc_port = get_available_port();
417 let kv_rpc_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), kv_rpc_port);
418
419 let kv_rpc_plaintext_address = kv_rpc_plaintext_listener.then(|| {
420 let port = get_available_port();
421 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)
422 });
423
424 let database = TempDb::new().context("Failed to create database")?;
425 let database_url = database.database().url();
426
427 let dir = tempfile::tempdir().context("Failed to create temporary directory")?;
428 let rocksdb_path = dir.path().join("rocksdb");
429
430 let consistent_args = ConsistentArgs {
431 rpc_listen_address: consistent_listen_address,
432 tls: ConsistentTlsArgs::default(),
433 };
434
435 let graphql_args = GraphQlArgs {
436 rpc_listen_address: graphql_listen_address,
437 no_ide: true,
438 };
439
440 let db = Db::for_read(database_url.clone(), DbArgs::default())
441 .await
442 .context("Failed to connect to database")?;
443
444 let indexer = setup_indexer(
445 database_url.clone(),
446 DbArgs::default(),
447 indexer_args,
448 client_args.clone(),
449 indexer_config,
450 bootstrap_genesis,
451 registry,
452 )
453 .await
454 .context("Failed to setup indexer")?;
455
456 let pipelines: Vec<_> = indexer.pipelines().collect();
457 let indexer = indexer.run().await.context("Failed to start indexer")?;
458
459 let consistent_store = start_consistent_store(
460 rocksdb_path,
461 consistent_indexer_args,
462 client_args.clone(),
463 consistent_args,
464 "0.0.0",
465 consistent_config,
466 registry,
467 )
468 .await
469 .context("Failed to start Consistent Store")?;
470
471 let consistent_reader_args = ConsistentReaderArgs {
472 consistent_store_url: Some(
473 Url::parse(&format!("http://{consistent_listen_address}")).unwrap(),
474 ),
475 ..Default::default()
476 };
477
478 let (bigtable_client, bigtable_emulator, archival_service) = start_archival(
479 client_args.clone(),
480 kv_rpc_address,
481 kv_rpc_plaintext_address,
482 kv_rpc_config,
483 bt_pipeline_layer,
484 registry,
485 )
486 .await?;
487
488 let kv_args = KvArgs {
489 ledger_grpc_url: Some(
490 format!("http://{kv_rpc_address}")
491 .parse()
492 .expect("Failed to parse kv-rpc URI"),
493 ),
494 ..Default::default()
495 };
496
497 let graphql = start_graphql(
498 Some(database_url.clone()),
499 fullnode_args,
500 DbArgs::default(),
501 kv_args,
502 consistent_reader_args,
503 graphql_args,
504 SystemPackageTaskArgs::default(),
505 SubscriptionArgs::default(),
506 "0.0.0",
507 graphql_config,
508 pipelines.iter().map(|p| p.to_string()).collect(),
509 registry,
510 )
511 .await
512 .context("Failed to start GraphQL server")?;
513
514 let services = indexer
515 .merge(consistent_store)
516 .merge(graphql)
517 .merge(archival_service);
518
519 Ok(Self {
520 consistent_listen_address,
521 graphql_listen_address,
522 kv_rpc_listen_address: kv_rpc_address,
523 kv_rpc_plaintext_listen_address: kv_rpc_plaintext_address,
524 bigtable_client,
525 db,
526 pipelines,
527 bigtable_pipelines: ALL_PIPELINE_NAMES
528 .iter()
529 .chain(&ALPHA_PIPELINE_NAMES)
530 .copied()
531 .collect(),
532 services,
533 bigtable_emulator,
534 database,
535 dir,
536 })
537 }
538
539 pub fn db_url(&self) -> Url {
541 self.database.database().url().clone()
542 }
543
544 pub fn consistent_store_url(&self) -> Url {
546 Url::parse(&format!("http://{}/", self.consistent_listen_address))
547 .expect("Failed to parse RPC URL")
548 }
549
550 pub fn graphql_url(&self) -> Url {
552 Url::parse(&format!("http://{}/graphql", self.graphql_listen_address))
553 .expect("Failed to parse RPC URL")
554 }
555
556 pub fn kv_rpc_url(&self) -> Url {
558 Url::parse(&format!("http://{}/", self.kv_rpc_listen_address))
559 .expect("Failed to parse RPC URL")
560 }
561
562 pub fn kv_rpc_plaintext_url(&self) -> Option<Url> {
565 let address = self.kv_rpc_plaintext_listen_address?;
566 Some(Url::parse(&format!("http://{address}/")).expect("Failed to parse RPC URL"))
567 }
568
569 pub async fn latest_checkpoint(&self) -> anyhow::Result<Option<u64>> {
572 use watermarks::dsl as w;
573
574 let mut conn = self
575 .db
576 .connect()
577 .await
578 .context("Failed to connect to database")?;
579
580 let latest: HashMap<String, i64> = w::watermarks
581 .select((w::pipeline, w::checkpoint_hi_inclusive))
582 .filter(w::pipeline.eq_any(&self.pipelines))
583 .filter(w::reader_lo.le(w::checkpoint_hi_inclusive))
584 .load(&mut conn)
585 .await?
586 .into_iter()
587 .collect();
588
589 if latest.len() != self.pipelines.len() {
590 return Ok(None);
591 }
592
593 Ok(latest.into_values().min().map(|l| l as u64))
594 }
595
596 pub async fn latest_pruner_checkpoint(&self, pipeline: &str) -> anyhow::Result<Option<u64>> {
599 use watermarks::dsl as w;
600
601 let mut conn = self
602 .db
603 .connect()
604 .await
605 .context("Failed to connect to database")?;
606
607 let latest: Option<i64> = w::watermarks
608 .select(w::reader_lo)
609 .filter(w::pipeline.eq(pipeline))
610 .first(&mut conn)
611 .await
612 .optional()?;
613
614 Ok(latest.map(|l| l as u64))
615 }
616
617 pub async fn latest_consistent_store_checkpoint(&self) -> anyhow::Result<u64> {
619 ConsistentServiceClient::connect(self.consistent_store_url().to_string())
620 .await
621 .context("Failed to connect to Consistent Store")?
622 .available_range(AvailableRangeRequest {})
623 .await
624 .context("Failed to fetch available range from Consistent Store")?
625 .into_inner()
626 .max_checkpoint
627 .context("Consistent Store has not started yet")
628 }
629
630 pub async fn latest_graphql_checkpoint(&self) -> anyhow::Result<u64> {
632 let query = json!({
633 "query": "query { checkpoint { sequenceNumber } }"
634 });
635
636 let client = Client::new();
637 let request = client.post(self.graphql_url()).json(&query);
638 let response = request
639 .send()
640 .await
641 .context("Request to GraphQL server failed")?;
642
643 let body: Value = response
644 .json()
645 .await
646 .context("Failed to parse GraphQL response")?;
647
648 let sequence_number = body
649 .pointer("/data/checkpoint/sequenceNumber")
650 .context("Failed to find checkpoint sequence number in response")?;
651
652 let sequence_number: i64 = serde_json::from_value(sequence_number.clone())
653 .context("Failed to parse sequence number as i64")?;
654
655 ensure!(sequence_number != i64::MAX, "Indexer has not started yet");
656
657 Ok(sequence_number as u64)
658 }
659
660 pub async fn latest_graphql_epoch(&self) -> anyhow::Result<u64> {
662 let query = json!({
663 "query": "query { epoch { epochId } }"
664 });
665
666 let client = Client::new();
667 let request = client.post(self.graphql_url()).json(&query);
668 let response = request
669 .send()
670 .await
671 .context("Request to GraphQL server failed")?;
672
673 let body: Value = response
674 .json()
675 .await
676 .context("Failed to parse GraphQL response")?;
677
678 let epoch_id = body
679 .pointer("/data/epoch/epochId")
680 .context("Failed to find epochId in response")?;
681
682 let epoch_id: i64 =
683 serde_json::from_value(epoch_id.clone()).context("Failed to parse epochId as i64")?;
684
685 ensure!(epoch_id != i64::MAX, "Indexer has not started yet");
686
687 Ok(epoch_id as u64)
688 }
689
690 pub async fn wait_for_indexer(
693 &self,
694 checkpoint: u64,
695 timeout: Duration,
696 ) -> Result<(), Elapsed> {
697 tokio::time::timeout(timeout, async move {
698 let mut interval = interval(Duration::from_millis(200));
699 loop {
700 interval.tick().await;
701 if matches!(self.latest_checkpoint().await, Ok(Some(l)) if l >= checkpoint) {
702 break;
703 }
704 }
705 })
706 .await
707 }
708
709 pub async fn wait_for_pruner(
712 &self,
713 pipeline: &str,
714 checkpoint: u64,
715 timeout: Duration,
716 ) -> Result<(), Elapsed> {
717 tokio::time::timeout(timeout, async move {
718 let mut interval = interval(Duration::from_millis(200));
719 loop {
720 interval.tick().await;
721 if matches!(self.latest_pruner_checkpoint(pipeline).await, Ok(Some(l)) if l >= checkpoint) {
722 break;
723 }
724 }
725 }).await
726 }
727
728 pub async fn wait_for_consistent_store(
731 &self,
732 checkpoint: u64,
733 timeout: Duration,
734 ) -> Result<(), Elapsed> {
735 tokio::time::timeout(timeout, async move {
736 let mut interval = interval(Duration::from_millis(200));
737 loop {
738 interval.tick().await;
739 if matches!(self.latest_consistent_store_checkpoint().await, Ok(l) if l >= checkpoint) {
740 break;
741 }
742 }
743 })
744 .await
745 }
746
747 pub async fn wait_for_graphql(
750 &self,
751 checkpoint: u64,
752 timeout: Duration,
753 ) -> Result<(), Elapsed> {
754 tokio::time::timeout(timeout, async move {
755 let mut interval = interval(Duration::from_millis(200));
756 loop {
757 interval.tick().await;
758 if matches!(self.latest_graphql_checkpoint().await, Ok(l) if l >= checkpoint) {
759 break;
760 }
761 }
762 })
763 .await
764 }
765
766 pub async fn wait_for_kv_rpc(&self, checkpoint: u64, timeout: Duration) -> Result<(), Elapsed> {
771 let url = self.kv_rpc_url().to_string();
772 tokio::time::timeout(timeout, async move {
773 let mut interval = interval(Duration::from_millis(200));
774 let mut client = None;
775 loop {
776 interval.tick().await;
777 if client.is_none() {
778 client =
779 rpc::v2::ledger_service_client::LedgerServiceClient::connect(url.clone())
780 .await
781 .ok();
782 }
783 let Some(client) = client.as_mut() else {
784 continue;
785 };
786 if client
787 .get_service_info(rpc::v2::GetServiceInfoRequest::default())
788 .await
789 .is_ok_and(|response| {
790 response
791 .into_inner()
792 .checkpoint_height
793 .is_some_and(|cp| cp >= checkpoint)
794 })
795 {
796 break;
797 }
798 }
799 })
800 .await
801 }
802
803 pub async fn wait_for_bigtable(
806 &self,
807 pipelines: &[&str],
808 checkpoint: u64,
809 timeout: Duration,
810 ) -> Result<(), Elapsed> {
811 let mut client = self.bigtable_client.clone();
812 tokio::time::timeout(timeout, async move {
813 let mut interval = interval(Duration::from_millis(200));
814 loop {
815 interval.tick().await;
816 if client
817 .get_watermark_for_pipelines(pipelines)
818 .await
819 .is_ok_and(|wm| {
820 wm.is_some_and(|wm| {
821 wm.checkpoint_hi_inclusive
822 .is_some_and(|cp| cp >= checkpoint)
823 })
824 })
825 {
826 break;
827 }
828 }
829 })
830 .await
831 }
832}
833
834impl Default for OffchainClusterConfig {
835 fn default() -> Self {
836 Self {
837 indexer_args: Default::default(),
838 consistent_indexer_args: Default::default(),
839 fullnode_args: FullnodeArgs::default(),
840 indexer_config: IndexerConfig::for_test(),
841 consistent_config: ConsistentConfig::for_test(),
842 graphql_config: Default::default(),
843 bootstrap_genesis: None,
844 kv_rpc_config: KvRpcConfig::default(),
845 bt_pipeline_layer: PipelineLayer::default(),
846 kv_rpc_plaintext_listener: false,
847 }
848 }
849}
850
851pub fn local_ingestion_client_args() -> (ClientArgs, TempDir) {
853 let temp_dir = tempfile::tempdir()
854 .context("Failed to create data ingestion path")
855 .unwrap();
856 let client_args = ClientArgs {
857 ingestion: IngestionClientArgs {
858 local_ingestion_path: Some(temp_dir.path().to_owned()),
859 ..Default::default()
860 },
861 ..Default::default()
862 };
863 (client_args, temp_dir)
864}
865
866pub async fn write_checkpoint(path: &Path, checkpoint: Checkpoint) -> anyhow::Result<()> {
868 let sequence_number = checkpoint.summary.sequence_number;
869
870 let mask = FieldMask::from_paths([
871 rpc::v2::Checkpoint::path_builder().sequence_number(),
872 rpc::v2::Checkpoint::path_builder().summary().bcs().value(),
873 rpc::v2::Checkpoint::path_builder().signature().finish(),
874 rpc::v2::Checkpoint::path_builder().contents().bcs().value(),
875 rpc::v2::Checkpoint::path_builder()
876 .transactions()
877 .transaction()
878 .bcs()
879 .value(),
880 rpc::v2::Checkpoint::path_builder()
881 .transactions()
882 .effects()
883 .bcs()
884 .value(),
885 rpc::v2::Checkpoint::path_builder()
886 .transactions()
887 .effects()
888 .unchanged_loaded_runtime_objects()
889 .finish(),
890 rpc::v2::Checkpoint::path_builder()
891 .transactions()
892 .events()
893 .bcs()
894 .value(),
895 rpc::v2::Checkpoint::path_builder()
896 .objects()
897 .objects()
898 .bcs()
899 .value(),
900 ]);
901
902 let proto_checkpoint = rpc::v2::Checkpoint::merge_from(&checkpoint, &mask.into());
903 let proto_bytes = proto_checkpoint.encode_to_vec();
904 let compressed = zstd::encode_all(&proto_bytes[..], 3)?;
905
906 let file_name = format!("{}.binpb.zst", sequence_number);
907 let file_path = path.join(file_name);
908 fs::write(file_path, compressed)?;
909 Ok(())
910}
911
912async fn start_archival(
914 client_args: ClientArgs,
915 kv_rpc_address: SocketAddr,
916 kv_rpc_plaintext_address: Option<SocketAddr>,
917 kv_rpc_config: KvRpcConfig,
918 bt_pipeline_layer: PipelineLayer,
919 registry: &prometheus::Registry,
920) -> anyhow::Result<(BigTableClient, BigTableEmulator, Service)> {
921 let emulator = tokio::task::spawn_blocking(BigTableEmulator::start)
922 .await
923 .context("spawn_blocking panicked")?
924 .context("Failed to start BigTable emulator")?;
925
926 create_tables(emulator.host(), INSTANCE_ID)
927 .await
928 .context("Failed to create BigTable tables")?;
929
930 let bigtable_client =
931 BigTableClient::new_local(emulator.host().to_string(), INSTANCE_ID.to_string())
932 .await
933 .context("Failed to create BigTable client")?;
934
935 let indexer_client =
936 BigTableClient::new_local(emulator.host().to_string(), INSTANCE_ID.to_string())
937 .await
938 .context("Failed to create BigTable client for indexer")?;
939 let bt_indexer = BigTableIndexer::new(
940 indexer_client,
941 IndexerArgs::default(),
942 client_args,
943 BtIngestionConfig::default(),
944 CommitterConfig::default(),
945 BtIndexerConfig::default(),
946 bt_pipeline_layer,
947 &ALPHA_PIPELINE_NAMES,
950 Chain::Unknown,
951 registry,
952 )
953 .await
954 .context("Failed to create BigTable indexer")?;
955
956 let bt_indexer_service = bt_indexer
959 .run()
960 .await
961 .context("Failed to start BigTable indexer")?;
962
963 let mut ledger_history = kv_rpc_config.ledger_history();
965 ledger_history.bitmap_schema = Some(BitmapSchema::V2);
966 let kv_rpc_server = KvRpcServer::new_local_with_config(
967 emulator.host().to_string(),
968 INSTANCE_ID.to_string(),
969 None,
970 ledger_history,
971 kv_rpc_config.request_bigtable_concurrency(),
972 kv_rpc_config.monotonic_read_wait_timeout(),
973 kv_rpc_config.stages(),
974 kv_rpc_config.watermark_source(),
975 kv_rpc_config.alpha_features(),
976 )
977 .await
978 .context("Failed to create KvRpcServer")?;
979 let kv_rpc_service = kv_rpc_server
980 .start_service(
981 kv_rpc_address,
982 sui_kv_rpc::ServerConfig {
983 plaintext_address: kv_rpc_plaintext_address,
984 ..Default::default()
985 },
986 )
987 .await
988 .context("Failed to start kv-rpc server")?;
989
990 let service = bt_indexer_service.merge(kv_rpc_service);
991 Ok((bigtable_client, emulator, service))
992}