Skip to content

Commit

Permalink
add batch api to ExplorerDb
Browse files Browse the repository at this point in the history
  • Loading branch information
ecioppettini committed Oct 15, 2021
1 parent 11c9d09 commit 3dda252
Showing 1 changed file with 45 additions and 10 deletions.
55 changes: 45 additions & 10 deletions explorer/src/db/mod.rs
Expand Up @@ -99,6 +99,33 @@ impl NeedsBootstrap {
}
}

pub struct Batch {
txn: schema::MutTxn<()>,
}

impl Batch {
/// Try to add a new block to the indexes, this can fail if the parent of the block is not
/// processed. This doesn't perform any validation on the given block and the previous state,
/// it is assumed that the Block is valid
/// IMPORTANT: this call is blocking, any calls to it should be encapsulated in a threadpool
pub fn apply_block(&mut self, block: Block) -> Result<(), ExplorerError> {
self.txn.add_block(
&block.parent_id().into(),
&block.id().into(),
block.chain_length().into(),
block.header.block_date().into(),
block.fragments(),
)?;

Ok(())
}

/// IMPORTANT: this call is blocking, any calls to it should be encapsulated in a threadpool
pub fn commit(self) -> Result<(), ExplorerError> {
self.txn.commit()
}
}

impl ExplorerDb {
pub fn open() -> Result<OpenDb, ExplorerError> {
let pristine = Pristine::new("explorer-storage")?;
Expand All @@ -123,24 +150,32 @@ impl ExplorerDb {
pub async fn apply_block(&self, block: Block) -> Result<(), ExplorerError> {
let pristine = self.pristine.clone();
tokio::task::spawn_blocking(move || {
let mut mut_tx = pristine.mut_txn_begin()?;
let mut_tx = pristine.mut_txn_begin()?;

mut_tx.add_block(
&block.parent_id().into(),
&block.id().into(),
block.chain_length().into(),
block.header.block_date().into(),
block.fragments(),
)?;
let mut batch = Batch { txn: mut_tx };

mut_tx.commit()?;
batch.apply_block(block)?;

batch.commit()?;

Ok(())
})
.await
.unwrap()
}

pub async fn start_batch(&self) -> Result<Batch, ExplorerError> {
let pristine = self.pristine.clone();

tokio::task::spawn_blocking(move || {
let mut_tx = pristine.mut_txn_begin()?;

Ok(Batch { txn: mut_tx })
})
.await
.unwrap()
}

pub async fn get_txn(&self) -> Result<schema::Txn, ExplorerError> {
let pristine = self.pristine.clone();
tokio::task::spawn_blocking(move || {
Expand All @@ -157,7 +192,7 @@ impl ExplorerDb {
tokio::task::spawn_blocking(move || {
let mut mut_tx = pristine.mut_txn_begin()?;

let status = mut_tx.set_tip(hash.into())?;
let status = mut_tx.set_tip(&hash.into())?;

if status {
mut_tx.commit()?;
Expand Down

0 comments on commit 3dda252

Please sign in to comment.