-
Notifications
You must be signed in to change notification settings - Fork 39
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
435 additions
and
438 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,120 +1,17 @@ | ||
//! This module is responsible for persistent data storage, it provides schema-aware type-safe database access. Currently we use RocksDB, | ||
//! but this crate only exposes an abstraction of a database, so we can easily switch to a different storage engine in the future. | ||
|
||
use anyhow::Context as _; | ||
use concurrency::{ctx, scope, sync::watch}; | ||
use roles::validator::{self, BlockNumber}; | ||
use std::{ | ||
fmt, ops, | ||
path::Path, | ||
sync::{atomic::AtomicU64, RwLock}, | ||
}; | ||
use thiserror::Error; | ||
|
||
mod block_store; | ||
mod buffered; | ||
mod replica; | ||
mod rocksdb; | ||
mod testonly; | ||
#[cfg(test)] | ||
mod tests; | ||
mod traits; | ||
mod types; | ||
|
||
pub use crate::{ | ||
block_store::{BlockStore, WriteBlockStore}, | ||
buffered::{BufferedStorage, ContiguousBlockStore}, | ||
replica::ReplicaStateStore, | ||
types::ReplicaState, | ||
buffered::BufferedStorage, | ||
rocksdb::RocksdbStorage, | ||
traits::{BlockStore, ContiguousBlockStore, ReplicaStateStore, WriteBlockStore}, | ||
types::{ReplicaState, StorageError, StorageResult}, | ||
}; | ||
|
||
/// Storage errors. | ||
#[derive(Debug, Error)] | ||
pub enum StorageError { | ||
/// Operation was canceled by structured concurrency framework. | ||
#[error("operation was canceled by structured concurrency framework")] | ||
Canceled(#[from] ctx::Canceled), | ||
/// Database operation failed. | ||
#[error("database operation failed")] | ||
Database(#[source] anyhow::Error), | ||
} | ||
|
||
/// [`Result`] for fallible storage operations. | ||
pub type StorageResult<T> = Result<T, StorageError>; | ||
|
||
/// Main struct for the Storage module, it just contains the database. Provides a set of high-level | ||
/// atomic operations on the database. It "contains" the following data: | ||
/// | ||
/// - An append-only database of finalized blocks. | ||
/// - A backup of the consensus replica state. | ||
pub struct RocksdbStorage { | ||
/// Wrapped RocksDB instance. We don't need `RwLock` for synchronization *per se*, just to ensure | ||
/// that writes to the DB are linearized. | ||
inner: RwLock<rocksdb::DB>, | ||
/// In-memory cache for the last contiguous block number stored in the DB. The cache is used | ||
/// and updated by `Self::get_last_contiguous_block_number()`. Caching is based on the assumption | ||
/// that blocks are never removed from the DB. | ||
cached_last_contiguous_block_number: AtomicU64, | ||
/// Sender of numbers of written blocks. | ||
block_writes_sender: watch::Sender<BlockNumber>, | ||
} | ||
|
||
impl RocksdbStorage { | ||
/// Create a new Storage. It first tries to open an existing database, and if that fails it just creates a | ||
/// a new one. We need the genesis block of the chain as input. | ||
// TODO(bruno): we want to eventually start pruning old blocks, so having the genesis | ||
// block might be unnecessary. | ||
pub async fn new( | ||
ctx: &ctx::Ctx, | ||
genesis_block: &validator::FinalBlock, | ||
path: &Path, | ||
) -> StorageResult<Self> { | ||
let mut options = rocksdb::Options::default(); | ||
options.create_missing_column_families(true); | ||
options.create_if_missing(true); | ||
|
||
let db = scope::run!(ctx, |_, s| async { | ||
Ok(s.spawn_blocking(|| { | ||
rocksdb::DB::open(&options, path) | ||
.context("Failed opening RocksDB") | ||
.map_err(StorageError::Database) | ||
}) | ||
.join(ctx) | ||
.await?) | ||
}) | ||
.await?; | ||
|
||
let this = Self { | ||
inner: RwLock::new(db), | ||
cached_last_contiguous_block_number: AtomicU64::new(0), | ||
block_writes_sender: watch::channel(genesis_block.block.number).0, | ||
}; | ||
if let Some(stored_genesis_block) = this.block(ctx, genesis_block.block.number).await? { | ||
if stored_genesis_block.block != genesis_block.block { | ||
let err = anyhow::anyhow!("Mismatch between stored and expected genesis block"); | ||
return Err(StorageError::Database(err)); | ||
} | ||
} else { | ||
tracing::debug!( | ||
"Genesis block not present in RocksDB at `{path}`; saving {genesis_block:?}", | ||
path = path.display() | ||
); | ||
this.put_block(ctx, genesis_block).await?; | ||
} | ||
Ok(this) | ||
} | ||
|
||
/// Acquires a read lock on the underlying DB. | ||
fn read(&self) -> impl ops::Deref<Target = rocksdb::DB> + '_ { | ||
self.inner.read().expect("DB lock is poisoned") | ||
} | ||
|
||
/// Acquires a write lock on the underlying DB. | ||
fn write(&self) -> impl ops::Deref<Target = rocksdb::DB> + '_ { | ||
self.inner.write().expect("DB lock is poisoned") | ||
} | ||
} | ||
|
||
impl fmt::Debug for RocksdbStorage { | ||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
formatter.write_str("RocksdbStorage") | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.