1use alloy_eips::BlockNumHash;
2use alloy_primitives::B256;
3use std::time::Instant;
4use tokio::sync::oneshot;
5use tracing::trace;
67/// 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
13pub(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.
16pub(crate) rx:
17Option<(oneshot::Receiver<Option<BlockNumHash>>, Instant, CurrentPersistenceAction)>,
18}
1920impl PersistenceState {
21/// Determines if there is a persistence task in progress by checking if the
22 /// receiver is set.
23pub(crate) const fn in_progress(&self) -> bool {
24self.rx.is_some()
25 }
2627/// Sets the state for a block removal operation.
28pub(crate) fn start_remove(
29&mut self,
30 new_tip_num: u64,
31 rx: oneshot::Receiver<Option<BlockNumHash>>,
32 ) {
33self.rx =
34Some((rx, Instant::now(), CurrentPersistenceAction::RemovingBlocks { new_tip_num }));
35 }
3637/// Sets the state for a block save operation.
38pub(crate) fn start_save(
39&mut self,
40 highest: BlockNumHash,
41 rx: oneshot::Receiver<Option<BlockNumHash>>,
42 ) {
43self.rx = Some((rx, Instant::now(), CurrentPersistenceAction::SavingBlocks { highest }));
44 }
4546/// Returns the current persistence action. If there is no persistence task in progress, then
47 /// this returns `None`.
48pub(crate) fn current_action(&self) -> Option<&CurrentPersistenceAction> {
49self.rx.as_ref().map(|rx| &rx.2)
50 }
5152/// Sets state for a finished persistence task.
53pub(crate) fn finish(
54&mut self,
55 last_persisted_block_hash: B256,
56 last_persisted_block_number: u64,
57 ) {
58trace!(target: "engine::tree", block= %last_persisted_block_number, hash=%last_persisted_block_hash, "updating persistence state");
59self.rx = None;
60self.last_persisted_block =
61 BlockNumHash::new(last_persisted_block_number, last_persisted_block_hash);
62 }
63}
6465/// The currently running persistence action.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub(crate) enum CurrentPersistenceAction {
68/// The persistence task is saving blocks.
69SavingBlocks {
70/// The highest block being saved.
71highest: BlockNumHash,
72 },
73/// The persistence task is removing blocks.
74RemovingBlocks {
75/// The tip, above which we are removing blocks.
76new_tip_num: u64,
77 },
78}