reth_engine_tree/tree/
persistence_state.rs

1use alloy_eips::BlockNumHash;
2use alloy_primitives::B256;
3use std::time::Instant;
4use tokio::sync::oneshot;
5use tracing::trace;
6
7/// The state of the persistence task.
8#[derive(Default, Debug)]
9pub struct PersistenceState {
10    /// Hash and number of the last block persisted.
11    ///
12    /// This tracks the chain height that is persisted on disk
13    pub(crate) last_persisted_block: BlockNumHash,
14    /// Receiver end of channel where the result of the persistence task will be
15    /// sent when done. A None value means there's no persistence task in progress.
16    pub(crate) rx:
17        Option<(oneshot::Receiver<Option<BlockNumHash>>, Instant, CurrentPersistenceAction)>,
18}
19
20impl PersistenceState {
21    /// Determines if there is a persistence task in progress by checking if the
22    /// receiver is set.
23    pub(crate) const fn in_progress(&self) -> bool {
24        self.rx.is_some()
25    }
26
27    /// Sets the state for a block removal operation.
28    pub(crate) fn start_remove(
29        &mut self,
30        new_tip_num: u64,
31        rx: oneshot::Receiver<Option<BlockNumHash>>,
32    ) {
33        self.rx =
34            Some((rx, Instant::now(), CurrentPersistenceAction::RemovingBlocks { new_tip_num }));
35    }
36
37    /// Sets the state for a block save operation.
38    pub(crate) fn start_save(
39        &mut self,
40        highest: BlockNumHash,
41        rx: oneshot::Receiver<Option<BlockNumHash>>,
42    ) {
43        self.rx = Some((rx, Instant::now(), CurrentPersistenceAction::SavingBlocks { highest }));
44    }
45
46    /// Returns the current persistence action. If there is no persistence task in progress, then
47    /// this returns `None`.
48    pub(crate) fn current_action(&self) -> Option<&CurrentPersistenceAction> {
49        self.rx.as_ref().map(|rx| &rx.2)
50    }
51
52    /// Sets state for a finished persistence task.
53    pub(crate) fn finish(
54        &mut self,
55        last_persisted_block_hash: B256,
56        last_persisted_block_number: u64,
57    ) {
58        trace!(target: "engine::tree", block= %last_persisted_block_number, hash=%last_persisted_block_hash, "updating persistence state");
59        self.rx = None;
60        self.last_persisted_block =
61            BlockNumHash::new(last_persisted_block_number, last_persisted_block_hash);
62    }
63}
64
65/// The currently running persistence action.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub(crate) enum CurrentPersistenceAction {
68    /// The persistence task is saving blocks.
69    SavingBlocks {
70        /// The highest block being saved.
71        highest: BlockNumHash,
72    },
73    /// The persistence task is removing blocks.
74    RemovingBlocks {
75        /// The tip, above which we are removing blocks.
76        new_tip_num: u64,
77    },
78}