Skip to main content

iota_data_ingestion_core/reader/
v2.rs

1// Copyright (c) 2025 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use 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/// Available sources for checkpoint streams supported by the ingestion
49/// framework.
50///
51/// This enum represents the different types of remote sources from which
52/// checkpoint data can be fetched. Each variant corresponds to a supported
53/// backend or combination of backends for checkpoint retrieval.
54#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
55pub enum RemoteUrl {
56    /// The URL to the Fullnode server that exposes
57    /// checkpoint data streaming through gRPC.
58    ///
59    /// # Example
60    /// ```text
61    /// "http://127.0.0.1:50051"
62    /// ```
63    Fullnode(String),
64    /// A hybrid source combining historical object store and optional live
65    /// object store.
66    HybridHistoricalStore {
67        /// The URL path to the historical object store that contains `*.chk`,
68        /// `*.sum` & `MANIFEST` files.
69        ///
70        /// # Example
71        /// ```text
72        /// "https://checkpoints.mainnet.iota.cafe/ingestion/historical"
73        /// ```
74        historical_url: String,
75        /// The URL path to the live object store that contains `*.chk`
76        /// checkpoint files.
77        ///
78        /// # Example
79        /// ```text
80        /// "https://checkpoints.mainnet.iota.cafe/ingestion/live"
81        /// ```
82        live_url: Option<String>,
83    },
84}
85
86/// Represents a remote backend for checkpoint data retrieval.
87///
88/// This enum encapsulates the supported remote storage mechanisms that can be
89/// used by the ingestion framework to fetch checkpoint data. Each variant
90/// corresponds to a different type of remote source.
91enum 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/// Configuration options to control the behavior of a checkpoint
153/// reader.
154#[derive(Default, Clone)]
155pub struct CheckpointReaderConfig {
156    /// Config the checkpoint reader behavior for downloading new checkpoints.
157    pub reader_options: ReaderOptions,
158    /// Local path for checkpoint ingestion. If not provided, checkpoints will
159    /// be ingested from a temporary directory.
160    pub ingestion_path: Option<PathBuf>,
161    /// Remote source for checkpoint data stream.
162    pub remote_store_url: Option<RemoteUrl>,
163}
164
165/// Internal actor responsible for reading and streaming checkpoints.
166///
167/// `CheckpointReaderActor` is the core background task that manages the logic
168/// for fetching, batching, and streaming checkpoint data from local or remote
169/// sources. It handles checkpoint discovery, garbage collection signals, and
170/// coordinates with remote fetchers as needed.
171///
172/// This struct is intended to be run as an asynchronous task and is not
173/// typically interacted with directly. Instead, users should use
174/// [`CheckpointReader`], which provides a safe and ergonomic API for
175/// interacting with the running actor, such as receiving checkpoints, sending
176/// GC signals, or triggering shutdown.
177///
178/// # Responsibilities
179/// - Periodically scans for new checkpoints from configured sources.
180/// - Streams checkpoints to consumers via channels.
181/// - Handles garbage collection signals to prune processed checkpoints.
182/// - Coordinates with remote fetchers for batch downloads and retries.
183///
184/// # Usage
185/// Users should not construct or manage `CheckpointReader` directly. Instead,
186/// use [`CheckpointReader::new`] to spawn the actor and obtain a handle
187/// for interaction.
188struct CheckpointReaderActor {
189    /// Filesystem path to the local checkpoint directory.
190    path: PathBuf,
191    /// Start fetch from the current checkpoint sequence.
192    current_checkpoint_number: CheckpointSequenceNumber,
193    /// Keeps tracks the last processed checkpoint sequence number, used to
194    /// delete checkpoint files from ingestion path.
195    last_pruned_watermark: CheckpointSequenceNumber,
196    /// Channel for sending checkpoints to WorkerPools.
197    checkpoint_tx: mpsc::Sender<Arc<CheckpointData>>,
198    /// Receives the latest garbage collection (GC) signal to prune checkpoint files below
199    /// the specified watermark.
200    gc_signal_rx: watch::Receiver<CheckpointSequenceNumber>,
201    /// Remote checkpoint reader for fetching checkpoints from the network.
202    remote_store: Option<Arc<RemoteStore>>,
203    /// Shutdown signal for the actor.
204    token: CancellationToken,
205    /// Configures the behavior of the checkpoint reader.
206    reader_options: ReaderOptions,
207    /// Limit the amount of downloaded checkpoints held in memory to avoid OOM.
208    data_limiter: DataLimiter,
209    /// Filter applied to transactions within a checkpoint.
210    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    /// Fetches checkpoints from the historical object store and streams them to
238    /// a channel.
239    async fn relay_from_historical(
240        &mut self,
241        historical_reader: &HistoricalReader,
242    ) -> IngestionResult<()> {
243        // Only sync the manifest when needed to avoid unnecessary network calls.
244        // If the requested checkpoint is beyond what's currently available in our
245        // cached manifest, we need to refresh it to check for newer checkpoints.
246        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            // Verify the requested checkpoint is now available after the manifest refresh.
257            // If it's still not available, the checkpoint hasn't been published yet.
258            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            // We check capacity before downloading the file. This way, once its
282            // checkpoints are collected into memory we ensure that all will be
283            // sent through the channel.
284            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            // A file that fails to decode part way ends early, so check that it
303            // holds every checkpoint the manifest lists for it before sending any.
304            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    /// Fetches checkpoints from the live object store and streams them to a
328    /// channel.
329    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    /// Fetches checkpoints from the fullnode through a gRPC streaming
352    /// connection and streams them to a channel.
353    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    /// Fetches remote checkpoints from the remote store and streams them to the
385    /// channel.
386    ///
387    /// For every successfully fetched checkpoint, this function updates the
388    /// current checkpoint number and the data limiter. If an error occurs while
389    /// fetching a checkpoint, the function returns immediately with that error.
390    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    /// Fetches and sends checkpoints to the channel with retry logic.
418    ///
419    /// Uses an exponential backoff strategy to retry failed requests.
420    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    /// Attempts to send a remote checkpoint to the channel and registers it with the data limiter.
460    ///
461    /// The sequence number of the received checkpoint must match the one the reader expects next.
462    /// The reader advances its current checkpoint number by one for every checkpoint it sends, so
463    /// this keeps the checkpoints it sends in order and without gaps.
464    ///
465    /// # Errors
466    ///
467    /// - [`IngestionError::Verification`] if the checkpoint's sequence number is not the one the
468    ///   reader expects next.
469    /// - [`IngestionError::MaxCheckpointsCapacityReached`] if the capacity limit is exceeded.
470    /// - [`IngestionError::Channel`] if the receiver channel is closed.
471    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    /// Sends a batch of local checkpoints to the channel in order.
491    ///
492    /// # Errors
493    ///
494    /// Fails if sending to the channel fails.
495    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    /// Sends a single checkpoint to the channel and advances the current
506    /// checkpoint number.
507    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    /// Sync from either local or remote source new checkpoints to be processed
521    /// by the executor.
522    ///
523    /// # Errors
524    ///
525    /// Fails if the local files can't be read or sending to the channel fails. Errors from a remote
526    /// source are treated as transient, so they are retried and never returned.
527    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    /// Run the main loop of the checkpoint reader actor.
548    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
577/// Public API for interacting with the checkpoint reader actor.
578///
579/// It provides methods to receive streamed checkpoints, send garbage collection
580/// signals, and gracefully shut down the background checkpoint reading task.
581/// Internally, it communicates with a [`CheckpointReaderActor`], which manages
582/// the actual checkpoint fetching and streaming logic.
583pub(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    /// Read downloaded checkpoints from the queue.
648    pub(crate) async fn checkpoint(&mut self) -> Option<Arc<CheckpointData>> {
649        self.checkpoint_rx.recv().await
650    }
651
652    /// Sends a garbage collection (GC) signal to the checkpoint reader.
653    ///
654    /// Transmits a watermark to the checkpoint reader, indicating that all
655    /// checkpoints below this watermark can be safely pruned or cleaned up.
656    /// The new watermark replaces the previous one.
657    ///
658    /// # Errors
659    ///
660    /// Returns [`IngestionError::Channel`] if the checkpoint reader task
661    /// stopped.
662    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    /// Gracefully shuts down the checkpoint reader task.
674    ///
675    /// It signals the background checkpoint reader actor to terminate, then
676    /// awaits its completion. Any in-progress checkpoint reading or streaming
677    /// operations will be stopped as part of the shutdown process.
678    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}