1use std::{
5 num::NonZeroUsize,
6 path::{Path, PathBuf},
7 sync::Arc,
8 time::Duration,
9};
10
11use backoff::backoff::Backoff;
12use futures::{StreamExt, TryStreamExt};
13use iota_config::object_storage_config::{ObjectStoreConfig, ObjectStoreType};
14use iota_grpc_client::GrpcClient;
15use iota_metrics::spawn_monitored_task;
16use iota_types::{
17 full_checkpoint_content::CheckpointData, messages_checkpoint::CheckpointSequenceNumber,
18};
19use object_store::ObjectStore;
20use serde::{Deserialize, Serialize};
21use tap::Pipe;
22use tokio::{
23 sync::{mpsc, watch},
24 task::JoinHandle,
25 time::timeout,
26};
27use tokio_util::sync::CancellationToken;
28use tracing::{debug, error};
29
30#[cfg(not(target_os = "macos"))]
31use crate::reader::fetch::init_watcher;
32use crate::{
33 IngestionError, IngestionResult, MAX_CHECKPOINTS_IN_PROGRESS,
34 config::CheckpointReaderConfigExt,
35 create_remote_store_client,
36 history::reader::{HistoricalReader, HistoricalReaderConfig},
37 reader::{
38 ReaderOptions,
39 common::DataLimiter,
40 fetch::{
41 GRPC_MAX_DECODING_MESSAGE_SIZE_BYTES, LocalCheckpoints, LocalRead, ReadSource,
42 fetch_from_object_store,
43 },
44 filters::fullnode::TransactionFilter,
45 },
46};
47
48#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
55pub enum RemoteUrl {
56 Fullnode(String),
64 HybridHistoricalStore {
67 historical_url: String,
75 live_url: Option<String>,
83 },
84}
85
86enum RemoteStore {
92 Fullnode(GrpcClient),
93 HybridHistoricalStore {
94 historical: HistoricalReader,
95 live: Option<Box<dyn ObjectStore>>,
96 },
97}
98
99impl RemoteStore {
100 async fn new(
101 remote_url: RemoteUrl,
102 batch_size: usize,
103 timeout_secs: u64,
104 ) -> IngestionResult<Self> {
105 let store = match remote_url {
106 RemoteUrl::Fullnode(ref url) => {
107 let grpc_client = GrpcClient::new(url).map(|client| {
108 client.with_max_decoding_message_size(GRPC_MAX_DECODING_MESSAGE_SIZE_BYTES)
109 })?;
110 RemoteStore::Fullnode(grpc_client)
111 }
112 RemoteUrl::HybridHistoricalStore {
113 historical_url,
114 live_url,
115 } => {
116 let remote_store_config = if let Some(dir) = historical_url.strip_prefix("file://")
117 {
118 ObjectStoreConfig {
119 object_store: Some(ObjectStoreType::File),
120 directory: Some(PathBuf::from(dir)),
121 ..Default::default()
122 }
123 } else {
124 ObjectStoreConfig {
125 object_store: Some(ObjectStoreType::S3),
126 object_store_connection_limit: 20,
127 aws_endpoint: Some(historical_url),
128 aws_virtual_hosted_style_request: true,
129 no_sign_request: true,
130 ..Default::default()
131 }
132 };
133 let config = HistoricalReaderConfig {
134 download_concurrency: NonZeroUsize::new(batch_size)
135 .expect("batch size must be greater than zero"),
136 remote_store_config,
137 };
138 let historical = HistoricalReader::new(config)
139 .inspect_err(|e| error!("unable to instantiate historical reader: {e}"))?;
140
141 let live = live_url
142 .map(|url| create_remote_store_client(url, Default::default(), timeout_secs))
143 .transpose()?;
144
145 RemoteStore::HybridHistoricalStore { historical, live }
146 }
147 };
148 Ok(store)
149 }
150}
151
152#[derive(Default, Clone)]
155pub struct CheckpointReaderConfig {
156 pub reader_options: ReaderOptions,
158 pub ingestion_path: Option<PathBuf>,
161 pub remote_store_url: Option<RemoteUrl>,
163}
164
165struct CheckpointReaderActor {
189 path: PathBuf,
191 current_checkpoint_number: CheckpointSequenceNumber,
193 last_pruned_watermark: CheckpointSequenceNumber,
196 checkpoint_tx: mpsc::Sender<Arc<CheckpointData>>,
198 gc_signal_rx: watch::Receiver<CheckpointSequenceNumber>,
201 remote_store: Option<Arc<RemoteStore>>,
203 token: CancellationToken,
205 reader_options: ReaderOptions,
207 data_limiter: DataLimiter,
209 fullnode_transaction_filter: Option<TransactionFilter>,
211}
212
213impl LocalRead for CheckpointReaderActor {
214 fn exceeds_capacity(&self, checkpoint_number: CheckpointSequenceNumber) -> bool {
215 ((MAX_CHECKPOINTS_IN_PROGRESS as u64 + self.last_pruned_watermark) <= checkpoint_number)
216 || self.data_limiter.exceeds()
217 }
218
219 fn path(&self) -> &Path {
220 &self.path
221 }
222
223 fn current_checkpoint_number(&self) -> CheckpointSequenceNumber {
224 self.current_checkpoint_number
225 }
226
227 fn update_last_pruned_watermark(&mut self, watermark: CheckpointSequenceNumber) {
228 self.last_pruned_watermark = watermark;
229 }
230}
231
232impl CheckpointReaderActor {
233 fn should_fetch_from_remote(&self, checkpoints: &LocalCheckpoints) -> bool {
234 self.remote_store.is_some() && checkpoints.is_empty()
235 }
236
237 async fn relay_from_historical(
240 &mut self,
241 historical_reader: &HistoricalReader,
242 ) -> IngestionResult<()> {
243 if self.current_checkpoint_number > historical_reader.latest_available_checkpoint().await? {
247 timeout(
248 Duration::from_secs(self.reader_options.timeout_secs),
249 historical_reader.sync_manifest_once(),
250 )
251 .await
252 .map_err(|_| {
253 IngestionError::HistoryRead("reading manifest exceeded the timeout".into())
254 })??;
255
256 if self.current_checkpoint_number
259 > historical_reader.latest_available_checkpoint().await?
260 {
261 return Err(IngestionError::CheckpointNotAvailableYet);
262 }
263 }
264
265 let manifest = historical_reader.get_manifest().await;
266
267 let files = historical_reader.verify_and_get_manifest_files(manifest)?;
268
269 let start_index = match files.binary_search_by_key(&self.current_checkpoint_number, |s| {
270 s.checkpoint_seq_range.start
271 }) {
272 Ok(index) => index,
273 Err(index) => index - 1,
274 };
275
276 for metadata in files
277 .into_iter()
278 .enumerate()
279 .filter_map(|(index, metadata)| (index >= start_index).then_some(metadata))
280 {
281 if self.exceeds_capacity(self.current_checkpoint_number) {
285 return Err(IngestionError::MaxCheckpointsCapacityReached);
286 }
287
288 let checkpoints = timeout(
289 Duration::from_secs(self.reader_options.timeout_secs),
290 historical_reader.iter_for_file(metadata.file_path()),
291 )
292 .await
293 .map_err(|_| {
294 IngestionError::HistoryRead(format!(
295 "reading checkpoint {} exceeded the timeout",
296 metadata.file_path()
297 ))
298 })??
299 .filter(|c| c.checkpoint_summary.sequence_number >= self.current_checkpoint_number)
300 .collect::<Vec<CheckpointData>>();
301
302 let expected = self.current_checkpoint_number..metadata.checkpoint_seq_range.end;
305 if !checkpoints
306 .iter()
307 .map(|c| c.checkpoint_summary.sequence_number)
308 .eq(expected.clone())
309 {
310 return Err(IngestionError::HistoryRead(format!(
311 "checkpoint file {} does not hold checkpoints {expected:?}",
312 metadata.file_path()
313 )));
314 }
315
316 for checkpoint in checkpoints {
317 let size = bcs::serialized_size(&checkpoint)?;
318 self.data_limiter.add(&checkpoint, size);
319 self.send_checkpoint_to_channel(Arc::new(checkpoint))
320 .await?;
321 }
322 }
323
324 Ok(())
325 }
326
327 async fn relay_from_live(
330 &mut self,
331 batch_size: usize,
332 live: &dyn ObjectStore,
333 ) -> IngestionResult<()> {
334 let mut checkpoint_stream = (self.current_checkpoint_number..u64::MAX)
335 .map(|checkpoint_number| fetch_from_object_store(live, checkpoint_number))
336 .pipe(futures::stream::iter)
337 .buffered(batch_size);
338 while let Some((checkpoint, size)) = self
339 .token
340 .run_until_cancelled(checkpoint_stream.try_next())
341 .await
342 .transpose()?
343 .flatten()
344 {
345 self.send_remote_checkpoint_with_capacity_check(checkpoint, size)
346 .await?;
347 }
348 Ok(())
349 }
350
351 async fn relay_from_fullnode(&mut self, client: &mut GrpcClient) -> IngestionResult<()> {
354 let mut query = client
355 .checkpoints_stream()
356 .start_sequence_number(self.current_checkpoint_number)
357 .read_mask(iota_grpc_client::CHECKPOINT_RESPONSE_CHECKPOINT_DATA);
358 if let Some(filter) = self.fullnode_transaction_filter.clone() {
359 query = query.transactions_filter(filter.into());
360 }
361 let mut checkpoints_stream = query
362 .await
363 .map_err(|e| {
364 IngestionError::Grpc(format!("failed to initialize the checkpoint stream: {e}"))
365 })?
366 .into_inner();
367
368 while let Some(grpc_checkpoint) = self
369 .token
370 .run_until_cancelled(checkpoints_stream.try_next())
371 .await
372 .transpose()?
373 .flatten()
374 {
375 let checkpoint = grpc_checkpoint.checkpoint_data()?.try_into()?;
376 let size = bcs::serialized_size(&checkpoint)?;
377 self.send_remote_checkpoint_with_capacity_check(Arc::new(checkpoint), size)
378 .await?;
379 }
380
381 Ok(())
382 }
383
384 async fn fetch_and_send_to_channel(&mut self) -> IngestionResult<()> {
391 let Some(remote_store) = self.remote_store.as_ref().map(Arc::clone) else {
392 return Ok(());
393 };
394 let batch_size = self.reader_options.batch_size;
395 match remote_store.as_ref() {
396 RemoteStore::Fullnode(client) => {
397 self.relay_from_fullnode(&mut client.clone()).await?;
398 }
399 RemoteStore::HybridHistoricalStore { historical, live } => {
400 if let Some(Err(err)) = self
401 .token
402 .clone()
403 .run_until_cancelled(self.relay_from_historical(historical))
404 .await
405 {
406 if matches!(err, IngestionError::CheckpointNotAvailableYet) {
407 let live = live.as_ref().ok_or(err)?;
408 return self.relay_from_live(batch_size, live).await;
409 }
410 return Err(err);
411 }
412 }
413 };
414 Ok(())
415 }
416
417 async fn fetch_and_send_to_channel_with_retry(&mut self) {
421 let mut backoff = backoff::ExponentialBackoff::default();
422 backoff.max_elapsed_time = Some(Duration::from_secs(60));
423 backoff.initial_interval = Duration::from_millis(100);
424 backoff.current_interval = backoff.initial_interval;
425 backoff.multiplier = 1.0;
426
427 loop {
428 match self.fetch_and_send_to_channel().await {
429 Ok(_) => break,
430 Err(IngestionError::MaxCheckpointsCapacityReached) => break,
431 Err(IngestionError::CheckpointNotAvailableYet) => {
432 break debug!("historical reader does not have the requested checkpoint yet");
433 }
434 Err(err) => match backoff.next_backoff() {
435 Some(duration) => {
436 if !err.to_string().to_lowercase().contains("not found") {
437 debug!(
438 "remote reader retry in {} ms. Error is {err:?}",
439 duration.as_millis(),
440 );
441 }
442 if self
443 .token
444 .run_until_cancelled(tokio::time::sleep(duration))
445 .await
446 .is_none()
447 {
448 break;
449 }
450 }
451 None => {
452 break error!("remote reader transient error {err:?}");
453 }
454 },
455 }
456 }
457 }
458
459 async fn send_remote_checkpoint_with_capacity_check(
472 &mut self,
473 checkpoint: Arc<CheckpointData>,
474 size: usize,
475 ) -> IngestionResult<()> {
476 let sequence_number = checkpoint.checkpoint_summary.sequence_number;
477 if sequence_number != self.current_checkpoint_number {
478 return Err(IngestionError::Verification(format!(
479 "expected checkpoint {}, the remote source sent {sequence_number}",
480 self.current_checkpoint_number
481 )));
482 }
483 if self.exceeds_capacity(sequence_number) {
484 return Err(IngestionError::MaxCheckpointsCapacityReached);
485 }
486 self.data_limiter.add(&checkpoint, size);
487 self.send_checkpoint_to_channel(checkpoint).await
488 }
489
490 async fn send_local_checkpoints_to_channel(
496 &mut self,
497 checkpoints: LocalCheckpoints,
498 ) -> IngestionResult<()> {
499 for checkpoint in checkpoints.into_iter() {
500 self.send_checkpoint_to_channel(checkpoint).await?;
501 }
502 Ok(())
503 }
504
505 async fn send_checkpoint_to_channel(
508 &mut self,
509 checkpoint: Arc<CheckpointData>,
510 ) -> IngestionResult<()> {
511 self.checkpoint_tx.send(checkpoint).await.map_err(|_| {
512 IngestionError::Channel(
513 "unable to send checkpoint to executor, receiver half closed".to_owned(),
514 )
515 })?;
516 self.current_checkpoint_number += 1;
517 Ok(())
518 }
519
520 async fn sync(&mut self) -> IngestionResult<()> {
528 let mut remote_source = ReadSource::Local;
529 let checkpoints = self.read_local_files_with_retry().await?;
530 let should_fetch_from_remote = self.should_fetch_from_remote(&checkpoints);
531
532 if should_fetch_from_remote {
533 remote_source = ReadSource::Remote;
534 self.fetch_and_send_to_channel_with_retry().await;
535 } else {
536 self.send_local_checkpoints_to_channel(checkpoints).await?;
537 }
538
539 debug!(
540 "Read from {remote_source}. Current checkpoint number: {}, pruning watermark: {}",
541 self.current_checkpoint_number, self.last_pruned_watermark,
542 );
543
544 Ok(())
545 }
546
547 async fn run(mut self) {
549 let (_inotify_tx, mut inotify_rx) = mpsc::channel::<()>(1);
550 std::fs::create_dir_all(self.path()).expect("failed to create a directory");
551
552 #[cfg(not(target_os = "macos"))]
553 let _watcher = init_watcher(_inotify_tx, self.path());
554
555 self.data_limiter.gc(self.last_pruned_watermark);
556 self.gc_processed_files(self.last_pruned_watermark)
557 .expect("failed to clean the directory");
558
559 loop {
560 tokio::select! {
561 _ = self.token.cancelled() => break,
562 Ok(()) = self.gc_signal_rx.changed() => {
563 let watermark = *self.gc_signal_rx.borrow_and_update();
564 self.data_limiter.gc(watermark);
565 self.gc_processed_files(watermark).expect("failed to clean the directory");
566 }
567 Ok(Some(_)) | Err(_) = timeout(Duration::from_millis(self.reader_options.tick_interval_ms), inotify_rx.recv()) => {
568 if let Err(err) = self.sync().await {
569 break error!("checkpoint reader stopped: {err}");
570 }
571 }
572 }
573 }
574 }
575}
576
577pub(crate) struct CheckpointReader {
584 handle: JoinHandle<()>,
585 gc_signal_tx: watch::Sender<CheckpointSequenceNumber>,
586 checkpoint_rx: mpsc::Receiver<Arc<CheckpointData>>,
587 token: CancellationToken,
588}
589
590impl CheckpointReader {
591 pub(crate) async fn new(
592 starting_checkpoint_number: CheckpointSequenceNumber,
593 config: CheckpointReaderConfigExt,
594 ) -> IngestionResult<Self> {
595 if config.fullnode_transaction_filter.is_some()
596 && !matches!(config.base.remote_store_url, Some(RemoteUrl::Fullnode(_)))
597 {
598 return Err(IngestionError::Unsupported(
599 "filter is only supported on `RemoteUrl::Fullnode` connections".into(),
600 ));
601 }
602
603 let (checkpoint_tx, checkpoint_rx) = mpsc::channel(MAX_CHECKPOINTS_IN_PROGRESS);
604 let (gc_signal_tx, gc_signal_rx) = watch::channel(starting_checkpoint_number);
605
606 let remote_store = if let Some(url) = config.base.remote_store_url {
607 Some(Arc::new(
608 RemoteStore::new(
609 url,
610 config.base.reader_options.batch_size,
611 config.base.reader_options.timeout_secs,
612 )
613 .await?,
614 ))
615 } else {
616 None
617 };
618
619 let path = match config.base.ingestion_path {
620 Some(p) => p,
621 None => tempfile::tempdir()?.keep(),
622 };
623 let token = CancellationToken::new();
624 let reader = CheckpointReaderActor {
625 path,
626 current_checkpoint_number: starting_checkpoint_number,
627 last_pruned_watermark: starting_checkpoint_number,
628 checkpoint_tx,
629 gc_signal_rx,
630 remote_store,
631 token: token.clone(),
632 data_limiter: DataLimiter::new(config.base.reader_options.data_limit),
633 reader_options: config.base.reader_options,
634 fullnode_transaction_filter: config.fullnode_transaction_filter,
635 };
636
637 let handle = spawn_monitored_task!(reader.run());
638
639 Ok(Self {
640 handle,
641 gc_signal_tx,
642 checkpoint_rx,
643 token,
644 })
645 }
646
647 pub(crate) async fn checkpoint(&mut self) -> Option<Arc<CheckpointData>> {
649 self.checkpoint_rx.recv().await
650 }
651
652 pub(crate) fn send_gc_signal(
663 &self,
664 watermark: CheckpointSequenceNumber,
665 ) -> IngestionResult<()> {
666 self.gc_signal_tx.send(watermark).map_err(|_| {
667 IngestionError::Channel(
668 "unable to send GC operation to checkpoint reader, receiver half closed".into(),
669 )
670 })
671 }
672
673 pub(crate) async fn shutdown(self) -> IngestionResult<()> {
679 self.token.cancel();
680 self.handle.await.map_err(|err| IngestionError::Shutdown {
681 component: "checkpoint reader".into(),
682 msg: err.to_string(),
683 })
684 }
685}