Skip to main content

reth_storage_api/
metadata.rs

1//! Metadata provider trait for reading and writing node metadata.
2
3use alloc::vec::Vec;
4pub use reth_db_api::models::PipelineUnwind;
5use reth_db_api::models::{SnapAttempt, StorageSettings, SNAP_ATTEMPT_VERSION};
6use reth_storage_errors::provider::{ProviderError, ProviderResult};
7
8/// Metadata keys.
9pub mod keys {
10    /// Storage configuration settings for this node.
11    pub const STORAGE_SETTINGS: &str = "storage_settings";
12
13    /// Presence means the downloader verified the Bodies checkpoint against the selected jars.
14    /// Older downloads could checkpoint the snapshot tip even with its transactions present.
15    pub const VERIFIED_SNAPSHOT_BODIES: &str = "verified_snapshot_bodies";
16
17    /// A pipeline unwind that has not completed.
18    pub const PIPELINE_UNWIND: &str = "pipeline_unwind";
19
20    /// The snap synchronization attempt that owns downloaded state.
21    pub const SNAP_ATTEMPT: &str = "snap_attempt";
22}
23
24/// Client trait for reading node metadata from the database.
25#[auto_impl::auto_impl(&, Arc)]
26pub trait MetadataProvider: Send {
27    /// Get a metadata value by key
28    fn get_metadata(&self, key: &str) -> ProviderResult<Option<Vec<u8>>>;
29
30    /// Returns an interrupted pipeline unwind. Unreadable records must not be ignored because
31    /// stage checkpoints may describe different versions of the state.
32    fn pipeline_unwind(&self) -> ProviderResult<Option<PipelineUnwind>> {
33        self.get_metadata(keys::PIPELINE_UNWIND)?
34            .map(|bytes| serde_json::from_slice(&bytes).map_err(ProviderError::other))
35            .transpose()
36    }
37
38    /// Get storage settings for this node.
39    ///
40    /// If the stored metadata can't be deserialized (e.g. the format changed),
41    /// this returns `None` instead of an error so commands like `db clear` can
42    /// still operate without requiring a compatible metadata schema.
43    fn storage_settings(&self) -> ProviderResult<Option<StorageSettings>> {
44        Ok(self
45            .get_metadata(keys::STORAGE_SETTINGS)?
46            .and_then(|bytes| serde_json::from_slice(&bytes).ok()))
47    }
48
49    /// Returns the snap synchronization attempt that owns the downloaded state.
50    ///
51    /// Unlike [`Self::storage_settings`], an unreadable record is an error: its state is already
52    /// in the canonical tables, so reporting it absent would let the node adopt it.
53    fn snap_attempt(&self) -> ProviderResult<Option<SnapAttempt>> {
54        let Some(bytes) = self.get_metadata(keys::SNAP_ATTEMPT)? else { return Ok(None) };
55
56        // Read the version first, so a future build's record is reported as unsupported rather
57        // than as a decode failure.
58        let value: serde_json::Value =
59            serde_json::from_slice(&bytes).map_err(ProviderError::other)?;
60        let found = value.get("version").and_then(serde_json::Value::as_u64);
61        if found != Some(SNAP_ATTEMPT_VERSION as u64) {
62            return Err(ProviderError::UnsupportedSnapAttemptVersion {
63                found,
64                supported: SNAP_ATTEMPT_VERSION,
65            })
66        }
67
68        serde_json::from_slice(&bytes).map(Some).map_err(ProviderError::other)
69    }
70}
71
72/// Client trait for writing node metadata to the database.
73pub trait MetadataWriter: Send {
74    /// Write a metadata value
75    fn write_metadata(&self, key: &str, value: Vec<u8>) -> ProviderResult<()>;
76
77    /// Delete a metadata value.
78    fn delete_metadata(&self, _key: &str) -> ProviderResult<()> {
79        Err(ProviderError::UnsupportedProvider)
80    }
81
82    /// Records an unwind, or clears it after every selected stage has committed.
83    fn write_pipeline_unwind(&self, unwind: Option<&PipelineUnwind>) -> ProviderResult<()> {
84        match unwind {
85            Some(unwind) => self.write_metadata(
86                keys::PIPELINE_UNWIND,
87                serde_json::to_vec(unwind).map_err(ProviderError::other)?,
88            ),
89            None => self.delete_metadata(keys::PIPELINE_UNWIND),
90        }
91    }
92
93    /// Write storage settings for this node
94    ///
95    /// Be sure to update provider factory cache with
96    /// [`StorageSettingsCache::set_storage_settings_cache`].
97    fn write_storage_settings(&self, settings: StorageSettings) -> ProviderResult<()> {
98        self.write_metadata(
99            keys::STORAGE_SETTINGS,
100            serde_json::to_vec(&settings).map_err(ProviderError::other)?,
101        )
102    }
103
104    /// Writes the snap synchronization attempt that owns the downloaded state.
105    fn write_snap_attempt(&self, attempt: &SnapAttempt) -> ProviderResult<()> {
106        self.write_metadata(
107            keys::SNAP_ATTEMPT,
108            serde_json::to_vec(attempt).map_err(ProviderError::other)?,
109        )
110    }
111}
112
113/// Trait for caching storage settings on a provider factory.
114pub trait StorageSettingsCache: Send {
115    /// Gets the cached storage settings.
116    fn cached_storage_settings(&self) -> StorageSettings;
117
118    /// Sets the storage settings of this `ProviderFactory`.
119    ///
120    /// IMPORTANT: It does not save settings in storage, that should be done by
121    /// [`MetadataWriter::write_storage_settings`]
122    fn set_storage_settings_cache(&self, settings: StorageSettings);
123}
124
125/// Trait for accessing the database directory path.
126#[cfg(feature = "std")]
127pub trait StoragePath: Send {
128    /// Returns the path to the database directory (e.g. `<datadir>/db`).
129    fn storage_path(&self) -> std::path::PathBuf;
130}