Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write the dag relationship in batch #4304

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 43 additions & 56 deletions flexidag/src/consensusdb/consensus_relations.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
use super::schema::{KeyCodec, ValueCodec};
use super::{
db::DBStorage,
prelude::{BatchDbWriter, CachedDbAccess, DirectDbWriter, StoreError},
prelude::{CachedDbAccess, StoreError},
};
use crate::define_schema;
use rocksdb::WriteBatch;
use bcs_ext::BCSCodec;
use starcoin_crypto::HashValue as Hash;
use starcoin_storage::batch::{WriteBatch, WriteBatchData, WriteBatchWithColumn};
use starcoin_storage::storage::{InnerStore, WriteOp};
use starcoin_types::blockhash::{BlockHashes, BlockLevel};
use std::collections::HashMap;
use std::sync::Arc;

/// Reader API for `RelationsStore`.
Expand Down Expand Up @@ -90,41 +93,6 @@ impl DbRelationsStore {
pub fn clone_with_new_cache(&self, cache_size: usize) -> Self {
Self::new(Arc::clone(&self.db), self.level, cache_size)
}

pub fn insert_batch(
&mut self,
batch: &mut WriteBatch,
hash: Hash,
parents: BlockHashes,
) -> Result<(), StoreError> {
if self.has(hash)? {
return Err(StoreError::KeyAlreadyExists(hash.to_string()));
}

// Insert a new entry for `hash`
self.parents_access
.write(BatchDbWriter::new(batch, &self.db), hash, parents.clone())?;

// The new hash has no children yet
self.children_access.write(
BatchDbWriter::new(batch, &self.db),
hash,
BlockHashes::new(Vec::new()),
)?;

// Update `children` for each parent
for parent in parents.iter().cloned() {
let mut children = (*self.get_children(parent)?).clone();
children.push(hash);
self.children_access.write(
BatchDbWriter::new(batch, &self.db),
parent,
BlockHashes::new(children),
)?;
}

Ok(())
}
}

impl RelationsStoreReader for DbRelationsStore {
Expand All @@ -147,35 +115,54 @@ impl RelationsStoreReader for DbRelationsStore {
}

impl RelationsStore for DbRelationsStore {
/// See `insert_batch` as well
/// TODO: use one function with DbWriter for both this function and insert_batch
fn insert(&self, hash: Hash, parents: BlockHashes) -> Result<(), StoreError> {
if self.has(hash)? {
return Err(StoreError::KeyAlreadyExists(hash.to_string()));
}

// Insert a new entry for `hash`
self.parents_access
.write(DirectDbWriter::new(&self.db), hash, parents.clone())?;

// The new hash has no children yet
self.children_access.write(
DirectDbWriter::new(&self.db),
hash,
BlockHashes::new(Vec::new()),
)?;

// Update `children` for each parent
let mut parent_to_children = HashMap::new();
for parent in parents.iter().cloned() {
let mut children = (*self.get_children(parent)?).clone();
children.push(hash);
self.children_access.write(
DirectDbWriter::new(&self.db),
parent,
BlockHashes::new(children),
)?;
parent_to_children.insert(
parent
.encode()
.map_err(|e| StoreError::EncodeError(e.to_string()))?,
children
.encode()
.map_err(|e| StoreError::EncodeError(e.to_string()))?,
);
}

let batch = WriteBatchWithColumn {
data: vec![
WriteBatchData {
column: PARENTS_CF.to_string(),
row_data: WriteBatch::new_with_rows(vec![(
hash.encode()
.map_err(|e| StoreError::EncodeError(e.to_string()))?,
WriteOp::Value(
parents
.encode()
.map_err(|e| StoreError::EncodeError(e.to_string()))?,
),
)]),
},
WriteBatchData {
column: CHILDREN_CF.to_string(),
row_data: WriteBatch::new_with_rows(
parent_to_children
.into_iter()
.map(|(key, value)| (key, WriteOp::Value(value)))
.collect(),
),
},
],
};
self.db
.write_batch_with_column(batch)
.map_err(|e| StoreError::DBIoError(e.to_string()))?;
jackzhhuang marked this conversation as resolved.
Show resolved Hide resolved

Ok(())
}
}
Expand Down
11 changes: 11 additions & 0 deletions storage/src/batch/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,14 @@ where
Ok(Self::new_with_rows(rows?))
}
}

#[derive(Debug, Default, Clone)]
pub struct WriteBatchData {
pub column: String,
pub row_data: WriteBatch,
}

#[derive(Debug, Default, Clone)]
pub struct WriteBatchWithColumn {
pub data: Vec<WriteBatchData>,
}
28 changes: 27 additions & 1 deletion storage/src/cache_storage/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::batch::GWriteBatch;
use crate::batch::{GWriteBatch, WriteBatchWithColumn};
use crate::{
batch::WriteBatch,
metrics::{record_metrics, StorageMetrics},
Expand Down Expand Up @@ -91,6 +91,32 @@ impl InnerStore for CacheStorage {
})
}

fn write_batch_with_column(&self, batch: WriteBatchWithColumn) -> Result<()> {
let rows = batch
.data
.into_iter()
.flat_map(|data| {
data.row_data
.rows
.iter()
.cloned()
.map(|(k, v)| (compose_key(Some(&data.column), k), v))
.collect::<Vec<_>>()
})
.collect();
let batch = WriteBatch { rows };
record_metrics(
"cache",
"write_batch_column_prefix",
"write_batch",
self.metrics.as_ref(),
)
.call(|| {
self.write_batch_inner(batch);
Ok(())
})
}

fn get_len(&self) -> Result<u64, Error> {
Ok(self.cache.lock().len() as u64)
}
Expand Down
26 changes: 25 additions & 1 deletion storage/src/db_storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

use crate::{
batch::WriteBatch,
batch::{WriteBatch, WriteBatchWithColumn},
errors::StorageInitError,
metrics::{record_metrics, StorageMetrics},
storage::{ColumnFamilyName, InnerStore, KeyCodec, RawDBStorage, ValueCodec, WriteOp},
Expand Down Expand Up @@ -414,6 +414,30 @@ impl InnerStore for DBStorage {
})
}

fn write_batch_with_column(&self, batch: WriteBatchWithColumn) -> Result<()> {
let mut db_batch = DBWriteBatch::default();
batch.data.into_iter().for_each(|data| {
let cf_handle = self.get_cf_handle(&data.column);
for (key, write_op) in data.row_data.rows {
match write_op {
WriteOp::Value(value) => db_batch.put_cf(cf_handle, key, value),
WriteOp::Deletion => db_batch.delete_cf(cf_handle, key),
};
}
});
record_metrics(
"db",
"write_batch_column",
"write_batch",
self.metrics.as_ref(),
)
.call(|| {
self.db
.write_opt(db_batch, &Self::default_write_options())?;
Ok(())
})
}
Comment on lines +417 to +439
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Reduce code duplication between batch write methods

The implementations of write_batch_with_column and write_batch_with_column_sync are nearly identical, differing only in the write options used.

Extract the common logic into a private helper method:

+    fn write_batch_with_column_internal(
+        &self,
+        batch: WriteBatchWithColumn,
+        write_opts: WriteOptions,
+    ) -> Result<()> {
+        let mut db_batch = DBWriteBatch::default();
+        batch.data.into_iter().for_each(|data| {
+            let cf_handle = self.get_cf_handle(&data.column);
+            for (key, write_op) in data.row_data.rows {
+                match write_op {
+                    WriteOp::Value(value) => db_batch.put_cf(cf_handle, key, value),
+                    WriteOp::Deletion => db_batch.delete_cf(cf_handle, key),
+                };
+            }
+        });
+        record_metrics(
+            "db",
+            "write_batch_column",
+            "write_batch",
+            self.metrics.as_ref(),
+        )
+        .call(|| {
+            self.db.write_opt(db_batch, &write_opts)?;
+            Ok(())
+        })
+    }
+
     fn write_batch_with_column(&self, batch: WriteBatchWithColumn) -> Result<()> {
-        let mut db_batch = DBWriteBatch::default();
-        // ... existing implementation
+        self.write_batch_with_column_internal(batch, Self::default_write_options())
     }

     fn write_batch_with_column_sync(&self, batch: WriteBatchWithColumn) -> Result<()> {
-        let mut db_batch = DBWriteBatch::default();
-        // ... existing implementation
+        self.write_batch_with_column_internal(batch, Self::sync_write_options())
     }

Also applies to: 441-462


fn get_len(&self) -> Result<u64> {
unimplemented!()
}
Expand Down
14 changes: 14 additions & 0 deletions storage/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

pub use crate::batch::WriteBatch;
use crate::{
batch::WriteBatchWithColumn,
cache_storage::CacheStorage,
db_storage::{DBStorage, SchemaIterator},
upgrade::DBUpgrade,
Expand Down Expand Up @@ -39,6 +40,7 @@ pub trait InnerStore: Send + Sync {
fn contains_key(&self, prefix_name: &str, key: Vec<u8>) -> Result<bool>;
fn remove(&self, prefix_name: &str, key: Vec<u8>) -> Result<()>;
fn write_batch(&self, prefix_name: &str, batch: WriteBatch) -> Result<()>;
fn write_batch_with_column(&self, batch: WriteBatchWithColumn) -> Result<()>;
fn get_len(&self) -> Result<u64>;
fn keys(&self) -> Result<Vec<Vec<u8>>>;
fn put_sync(&self, prefix_name: &str, key: Vec<u8>, value: Vec<u8>) -> Result<()>;
Expand Down Expand Up @@ -201,6 +203,18 @@ impl InnerStore for StorageInstance {
},
}
}

fn write_batch_with_column(&self, batch: WriteBatchWithColumn) -> Result<()> {
match self {
Self::CACHE { cache } => cache.write_batch_with_column(batch),
Self::DB { db } => db.write_batch_with_column(batch),
Self::CacheAndDb { cache, db } => {
db.write_batch_with_column(batch.clone())?;
cache.write_batch_with_column(batch)
}
}
}

fn get_len(&self) -> Result<u64> {
match self {
Self::CACHE { cache } => cache.get_len(),
Expand Down
Loading
Loading